Skip to main content

foundry_evm_traces/decoder/
mod.rs

1use crate::{
2    CallTrace, CallTraceArena, CallTraceNode, DecodedCallData, DecodedCallLog, DecodedCallTrace,
3    DecodedTraceStep,
4    debug::DebugTraceIdentifier,
5    erc8021,
6    identifier::{IdentifiedAddress, LocalTraceIdentifier, SignaturesIdentifier, TraceIdentifier},
7};
8use alloy_dyn_abi::{DynSolValue, EventExt, FunctionExt, JsonAbiExt};
9use alloy_json_abi::{Constructor, Error, Event, Function, JsonAbi};
10use alloy_primitives::{
11    Address, B256, LogData, Selector, U256,
12    map::{AddressHashMap, HashMap, HashSet},
13};
14use alloy_sol_types::SolValue;
15use evm2::interpreter::{InstrStop, opcode::OpCode};
16use foundry_common::{
17    ContractsByArtifact, SELECTOR_LEN,
18    abi::{get_indexed_event, reconstruct_event_params},
19    fmt::format_token,
20    get_contract_name,
21    selectors::SelectorKind,
22    tempo::OUSD_ADDRESS,
23};
24use foundry_config::TracingConfig;
25use foundry_evm_core::{
26    abi::console,
27    constants::{CALLER, CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER, HARDHAT_CONSOLE_ADDRESS},
28    decode::RevertDecoder,
29    precompiles::{
30        BLAKE_2F, BLS12_G1ADD, BLS12_G1MSM, BLS12_G2ADD, BLS12_G2MSM, BLS12_MAP_FP_TO_G1,
31        BLS12_MAP_FP2_TO_G2, BLS12_PAIRING_CHECK, CELO_TRANSFER, EC_ADD, EC_MUL, EC_PAIRING,
32        EC_RECOVER, IDENTITY, MOD_EXP, POINT_EVALUATION, RIPEMD_160, SHA_256,
33    },
34};
35use foundry_evm_hardforks::{ExecutionSpec, FoundryHardfork, TempoHardfork};
36use foundry_evm_networks::{
37    NetworkConfigs, NetworkVariant, TEMPO_PRECOMPILES, celo::transfer::CELO_TRANSFER_LABEL,
38};
39use itertools::Itertools;
40use std::{borrow::Cow, collections::BTreeMap, sync::OnceLock};
41use tempo_contracts::precompiles::{
42    CURRENT_COMMITTEE_ADDRESS, IAccountKeychain, IAddressRegistry, IConfigurableAccount,
43    ICurrentCommittee, IFeeManager, INonce, IReceivePolicyGuard, ISignatureVerifier,
44    IStablecoinDEX, IStorageCredits, ITIP20, ITIP20ChannelReserve, ITIP20Factory, ITIP403Registry,
45    IValidatorConfig, PATH_USD_ADDRESS, RECEIVE_POLICY_GUARD_ADDRESS, TIP403_REGISTRY_ADDRESS,
46};
47
48#[cfg(feature = "base")]
49use base_common_precompiles::{
50    ActivationRegistryStorage, B20FactoryStorage, NonceManagerStorage, PolicyRegistryStorage,
51    TxContextStorage,
52};
53#[cfg(feature = "base")]
54use foundry_evm_hardforks::BaseSpecId;
55#[cfg(feature = "base")]
56use foundry_evm_networks::{active_base_precompiles, is_base_precompile_active_at};
57
58#[cfg(feature = "monad")]
59use foundry_evm_hardforks::MonadHardfork;
60
61#[cfg(feature = "base")]
62mod base;
63#[cfg(feature = "monad")]
64mod monad;
65pub(crate) mod precompiles;
66mod vm;
67
68/// Address-scoped events keyed by signature and indexed input count; anonymous events have no
69/// signature.
70type AddressEvents = HashMap<Address, BTreeMap<(Option<B256>, usize), Vec<Event>>>;
71
72/// A decoded event with both display-formatted parameters and their underlying ABI values.
73#[derive(Debug, Default)]
74pub struct DecodedEvent {
75    /// The event name or canonical signature.
76    pub name: Option<String>,
77    /// Event parameter names, display-formatted values, and decoded ABI values.
78    pub params: Option<Vec<(String, String, DynSolValue)>>,
79}
80
81impl DecodedEvent {
82    fn into_call_log(self) -> DecodedCallLog {
83        DecodedCallLog {
84            name: self.name,
85            params: self.params.map(|params| {
86                params.into_iter().map(|(name, display, _)| (name, display)).collect()
87            }),
88        }
89    }
90}
91
92/// Build a new [CallTraceDecoder].
93#[derive(Default)]
94#[must_use = "builders do nothing unless you call `build` on them"]
95pub struct CallTraceDecoderBuilder {
96    decoder: CallTraceDecoder,
97}
98
99impl CallTraceDecoderBuilder {
100    /// Create a new builder.
101    #[inline]
102    pub fn new() -> Self {
103        Self { decoder: CallTraceDecoder::new().clone() }
104    }
105
106    /// Add known labels to the decoder.
107    #[inline]
108    pub fn with_labels(mut self, labels: impl IntoIterator<Item = (Address, String)>) -> Self {
109        self.decoder.labels.extend(labels);
110        self
111    }
112
113    /// Add known errors to the decoder.
114    #[inline]
115    pub fn with_abi(mut self, abi: &JsonAbi) -> Self {
116        self.decoder.collect_abi(abi, None, true);
117        self
118    }
119
120    /// Add events from an ABI for a specific contract address.
121    #[inline]
122    pub fn with_address_events(mut self, address: Address, abi: &JsonAbi) -> Self {
123        for event in abi.events() {
124            self.decoder.push_address_event(address, event.clone());
125        }
126        self
127    }
128
129    /// Add known contracts to the decoder.
130    #[inline]
131    pub fn with_known_contracts(mut self, contracts: &ContractsByArtifact) -> Self {
132        trace!(target: "evm::traces", len=contracts.len(), "collecting known contract ABIs");
133        for contract in contracts.values() {
134            self.decoder.collect_abi(&contract.abi, None, true);
135        }
136        self
137    }
138
139    /// Add known contracts to the decoder from a `LocalTraceIdentifier`.
140    #[inline]
141    pub fn with_local_identifier_abis(self, identifier: &LocalTraceIdentifier<'_>) -> Self {
142        self.with_known_contracts(identifier.contracts())
143    }
144
145    /// Sets the verbosity level of the decoder.
146    #[inline]
147    pub const fn with_verbosity(mut self, level: u8) -> Self {
148        self.decoder.verbosity = level;
149        self
150    }
151
152    /// Applies trace rendering settings.
153    #[inline]
154    pub fn with_tracing_config(mut self, config: &TracingConfig) -> Self {
155        self.decoder.labels.extend(config.labels.clone());
156        self.decoder.verbosity = config.verbosity;
157        self.decoder.disable_labels = config.disable_labels;
158        self.decoder.compact_labels = config.compact_labels;
159        self
160    }
161
162    /// Sets the signature identifier for events and functions.
163    #[inline]
164    pub fn with_signature_identifier(mut self, identifier: SignaturesIdentifier) -> Self {
165        self.decoder.signature_identifier = Some(identifier);
166        self
167    }
168
169    /// Sets the signature identifier for events and functions.
170    #[inline]
171    pub const fn with_label_disabled(mut self, disable_alias: bool) -> Self {
172        self.decoder.disable_labels = disable_alias;
173        self
174    }
175
176    /// Sets the chain ID for network-specific precompile detection.
177    #[inline]
178    pub const fn with_chain_id(mut self, chain_id: Option<u64>) -> Self {
179        self.decoder.chain_id = chain_id;
180        self
181    }
182
183    /// Sets the execution network used for network-specific precompile detection.
184    #[inline]
185    pub fn with_execution_network(self, network: NetworkVariant) -> Self {
186        self.with_networks(network.into())
187    }
188
189    /// Sets the complete execution profile used for network-specific precompile detection.
190    #[inline]
191    pub const fn with_networks(mut self, networks: NetworkConfigs) -> Self {
192        self.decoder.networks = Some(networks);
193        self
194    }
195
196    /// Sets the hardfork used for network-specific metadata and precompile detection.
197    #[inline]
198    pub const fn with_hardfork(mut self, hardfork: Option<FoundryHardfork>) -> Self {
199        self.decoder.hardfork = hardfork;
200        self
201    }
202
203    /// Hides addresses in trace parameters when a label is available.
204    #[inline]
205    pub const fn with_compact_labels(mut self, compact: bool) -> Self {
206        self.decoder.compact_labels = compact;
207        self
208    }
209
210    /// Sets the debug identifier for the decoder.
211    #[inline]
212    pub fn with_debug_identifier(mut self, identifier: DebugTraceIdentifier) -> Self {
213        self.decoder.debug_identifier = Some(identifier);
214        self
215    }
216
217    /// Build the decoder.
218    #[inline]
219    pub fn build(mut self) -> CallTraceDecoder {
220        self.decoder.base_labels = self.decoder.labels.clone();
221        self.decoder.register_celo_metadata();
222        #[cfg(feature = "monad")]
223        self.decoder.register_monad_metadata();
224        #[cfg(feature = "base")]
225        self.decoder.register_base_metadata();
226        self.decoder
227    }
228}
229
230/// The call trace decoder.
231///
232/// The decoder collects address labels and ABIs from any number of [TraceIdentifier]s, which it
233/// then uses to decode the call trace.
234///
235/// Note that a call trace decoder is required for each new set of traces, since addresses in
236/// different sets might overlap.
237#[derive(Clone, Debug, Default)]
238pub struct CallTraceDecoder {
239    /// Addresses identified to be a specific contract.
240    ///
241    /// The values are in the form `"<artifact>:<contract>"`.
242    pub contracts: HashMap<Address, String>,
243    /// Address labels.
244    pub labels: HashMap<Address, String>,
245    /// Labels configured when the decoder was built.
246    base_labels: HashMap<Address, String>,
247    /// Contract addresses that have a receive function.
248    pub receive_contracts: HashSet<Address>,
249    /// Contract addresses that have fallback functions, mapped to function selectors of that
250    /// contract.
251    pub fallback_contracts: HashMap<Address, HashSet<Selector>>,
252    /// Contract addresses that have do NOT have fallback functions, mapped to function selectors
253    /// of that contract.
254    pub non_fallback_contracts: HashMap<Address, HashSet<Selector>>,
255
256    /// All known functions.
257    pub functions: HashMap<Selector, Vec<Function>>,
258    /// Functions identified for a specific contract address.
259    pub functions_by_address: HashMap<Address, HashMap<Selector, Vec<Function>>>,
260    /// Constructors identified for a specific contract address.
261    pub constructors_by_address: HashMap<Address, Constructor>,
262    /// Creation input offsets where ABI-encoded constructor arguments begin.
263    pub constructor_args_offsets: HashMap<Address, usize>,
264    /// All known events.
265    ///
266    /// Key is: `(topics[0], topics.len() - 1)`.
267    pub events: BTreeMap<(B256, usize), Vec<Event>>,
268    /// Regular and anonymous events identified for a specific contract address.
269    events_by_address: Option<Box<AddressEvents>>,
270    /// Revert decoder. Contains all known custom errors.
271    pub revert_decoder: RevertDecoder,
272
273    /// A signature identifier for events and functions.
274    pub signature_identifier: Option<SignaturesIdentifier>,
275    /// Verbosity level
276    pub verbosity: u8,
277
278    /// Optional identifier of individual trace steps.
279    pub debug_identifier: Option<DebugTraceIdentifier>,
280
281    /// Disable showing of labels.
282    pub disable_labels: bool,
283
284    /// The chain ID, used to determine network-specific precompiles.
285    pub chain_id: Option<u64>,
286
287    /// Execution profile, kept separate from the source chain used for external identification.
288    networks: Option<NetworkConfigs>,
289
290    /// Detailed opcodes for analysis.
291    pub opcodes: Vec<OpCode>,
292
293    /// The hardfork used to determine network-specific metadata and precompiles.
294    hardfork: Option<FoundryHardfork>,
295
296    /// Hide addresses when a label is available, showing only the label.
297    pub compact_labels: bool,
298}
299
300/// The identities a [`CallTraceDecoder`] collected for addresses, see
301/// [`CallTraceDecoder::address_identities`].
302#[derive(Clone, Debug, Default)]
303pub struct AddressIdentities {
304    contracts: HashMap<Address, String>,
305    labels: HashMap<Address, String>,
306    receive_contracts: HashSet<Address>,
307    fallback_contracts: HashMap<Address, HashSet<Selector>>,
308    non_fallback_contracts: HashMap<Address, HashSet<Selector>>,
309    functions_by_address: HashMap<Address, HashMap<Selector, Vec<Function>>>,
310    constructors_by_address: HashMap<Address, Constructor>,
311    constructor_args_offsets: HashMap<Address, usize>,
312    events_by_address: Option<Box<AddressEvents>>,
313}
314
315impl CallTraceDecoder {
316    fn register_celo_metadata(&mut self) {
317        if precompiles::is_known_precompile(
318            CELO_TRANSFER,
319            self.networks,
320            self.chain_id,
321            self.hardfork,
322        ) {
323            self.labels.entry(CELO_TRANSFER).or_insert_with(|| CELO_TRANSFER_LABEL.to_string());
324        }
325    }
326
327    #[cfg(feature = "base")]
328    fn register_base_metadata(&mut self) {
329        if self.networks.is_some_and(|networks| !networks.is_base()) {
330            return;
331        }
332        let Some(upgrade) =
333            self.hardfork.and_then(BaseSpecId::from_foundry_hardfork).map(|spec| spec.upgrade())
334        else {
335            return;
336        };
337
338        for (label, address) in active_base_precompiles(upgrade) {
339            self.labels.entry(address).or_insert_with(|| label.to_string());
340        }
341
342        // Labels alone leave calls showing a raw selector, so register the ABIs too. Each is
343        // scoped to its address and gated on the upgrade that installs it.
344        if is_base_precompile_active_at(ActivationRegistryStorage::ADDRESS, upgrade) {
345            self.register_address_abi(
346                ActivationRegistryStorage::ADDRESS,
347                &base::IActivationRegistry::abi::contract(),
348            );
349        }
350        if is_base_precompile_active_at(PolicyRegistryStorage::ADDRESS, upgrade) {
351            self.register_address_abi(
352                PolicyRegistryStorage::ADDRESS,
353                &base::IPolicyRegistry::abi::contract(),
354            );
355        }
356        if is_base_precompile_active_at(B20FactoryStorage::ADDRESS, upgrade) {
357            self.register_address_abi(
358                B20FactoryStorage::ADDRESS,
359                &base::IB20Factory::abi::contract(),
360            );
361        }
362        if is_base_precompile_active_at(NonceManagerStorage::ADDRESS, upgrade) {
363            self.register_address_abi(
364                NonceManagerStorage::ADDRESS,
365                &base::INonceManager::abi::contract(),
366            );
367        }
368        if is_base_precompile_active_at(TxContextStorage::ADDRESS, upgrade) {
369            self.register_address_abi(
370                TxContextStorage::ADDRESS,
371                &base::ITransactionContext::abi::contract(),
372            );
373        }
374    }
375
376    /// Creates a new call trace decoder.
377    ///
378    /// The call trace decoder always knows how to decode calls to the cheatcode address, as well
379    /// as DSTest-style logs.
380    pub fn new() -> &'static Self {
381        // If you want to take arguments in this function, assign them to the fields of the cloned
382        // lazy instead of removing it
383        static INIT: OnceLock<CallTraceDecoder> = OnceLock::new();
384        INIT.get_or_init(Self::init)
385    }
386
387    /// Returns the hardfork used for network-specific metadata.
388    pub const fn hardfork(&self) -> Option<FoundryHardfork> {
389        self.hardfork
390    }
391
392    /// Rebuilds address-scoped metadata for a new hardfork.
393    ///
394    /// Hardfork changes invalidate previously identified addresses because the set of active
395    /// precompiles can change. Global ABI and signature metadata is preserved.
396    pub fn set_hardfork(&mut self, hardfork: Option<FoundryHardfork>) {
397        if self.hardfork == hardfork {
398            return;
399        }
400        self.hardfork = hardfork;
401        self.clear_addresses();
402    }
403
404    #[instrument(name = "CallTraceDecoder::init", level = "debug")]
405    fn init() -> Self {
406        // Materialized once so the revert decoder can take references below.
407        let tempo_abis = [
408            IFeeManager::abi::contract(),
409            ITIP20::abi::contract(),
410            ITIP403Registry::abi::contract(),
411            ITIP20Factory::abi::contract(),
412            IStablecoinDEX::abi::contract(),
413            IStorageCredits::abi::contract(),
414            INonce::abi::contract(),
415            IValidatorConfig::abi::contract(),
416            IAccountKeychain::abi::contract(),
417            IAddressRegistry::abi::contract(),
418            ITIP20ChannelReserve::abi::contract(),
419            ISignatureVerifier::abi::contract(),
420            IReceivePolicyGuard::abi::contract(),
421            IConfigurableAccount::abi::contract(),
422        ];
423        let mut labels = HashMap::from_iter([
424            (CHEATCODE_ADDRESS, "VM".to_string()),
425            (HARDHAT_CONSOLE_ADDRESS, "console".to_string()),
426            (DEFAULT_CREATE2_DEPLOYER, "Create2Deployer".to_string()),
427            (CALLER, "DefaultSender".to_string()),
428            (EC_RECOVER, "ECRecover".to_string()),
429            (SHA_256, "SHA-256".to_string()),
430            (RIPEMD_160, "RIPEMD-160".to_string()),
431            (IDENTITY, "Identity".to_string()),
432            (MOD_EXP, "ModExp".to_string()),
433            (EC_ADD, "ECAdd".to_string()),
434            (EC_MUL, "ECMul".to_string()),
435            (EC_PAIRING, "ECPairing".to_string()),
436            (BLAKE_2F, "Blake2F".to_string()),
437            (POINT_EVALUATION, "PointEvaluation".to_string()),
438            (BLS12_G1ADD, "BLS12_G1ADD".to_string()),
439            (BLS12_G1MSM, "BLS12_G1MSM".to_string()),
440            (BLS12_G2ADD, "BLS12_G2ADD".to_string()),
441            (BLS12_G2MSM, "BLS12_G2MSM".to_string()),
442            (BLS12_PAIRING_CHECK, "BLS12_PAIRING_CHECK".to_string()),
443            (BLS12_MAP_FP_TO_G1, "BLS12_MAP_FP_TO_G1".to_string()),
444            (BLS12_MAP_FP2_TO_G2, "BLS12_MAP_FP2_TO_G2".to_string()),
445            // Tempo
446            (PATH_USD_ADDRESS, "PathUSD".to_string()),
447            (OUSD_ADDRESS, "OUSD".to_string()),
448        ]);
449        // `CurrentCommittee` is only labeled in an active Tempo T8 context, see `decode_function`.
450        labels.extend(
451            TEMPO_PRECOMPILES
452                .iter()
453                .filter(|(_, address)| *address != CURRENT_COMMITTEE_ADDRESS)
454                .map(|(label, address)| (*address, (*label).to_string())),
455        );
456
457        let functions = console::hh::abi::functions()
458            .into_values()
459            .chain([vm::functions()])
460            .chain(IFeeManager::abi::functions().into_values())
461            // `IStorageCredits` shares the `balanceOf(address)` selector with `ITIP20`, so it
462            // must be chained first to keep `ITIP20`'s `uint256` return as the global fallback.
463            .chain(IStorageCredits::abi::functions().into_values())
464            .chain(ITIP20::abi::functions().into_values())
465            .chain(ITIP403Registry::abi::functions().into_values())
466            .chain(ITIP20Factory::abi::functions().into_values())
467            .chain(IStablecoinDEX::abi::functions().into_values())
468            .chain(INonce::abi::functions().into_values())
469            .chain(IValidatorConfig::abi::functions().into_values())
470            .chain(IAccountKeychain::abi::functions().into_values())
471            .chain(IAddressRegistry::abi::functions().into_values())
472            .chain(ITIP20ChannelReserve::abi::functions().into_values())
473            .chain(ISignatureVerifier::abi::functions().into_values())
474            .chain(IReceivePolicyGuard::abi::functions().into_values())
475            .chain(IConfigurableAccount::abi::functions().into_values())
476            .flatten()
477            // The configurable account shim runs at every registered account's address, so its
478            // functions cannot be scoped to one address. Its Tempo binding has no JSON ABI.
479            .chain(
480                [
481                    "function isValidSignature(bytes32 hash, bytes signature) external view returns (bytes4)",
482                    "function onERC721Received(address operator, address from, uint256 tokenId, bytes data) external view returns (bytes4)",
483                ]
484                .map(|function| Function::parse(function).unwrap()),
485            )
486            .map(|func| (func.selector(), vec![func]))
487            .collect();
488
489        let events = console::ds::abi::events()
490            .into_values()
491            .chain(IFeeManager::abi::events().into_values())
492            .chain(ITIP20::abi::events().into_values())
493            .chain(ITIP403Registry::abi::events().into_values())
494            .chain(ITIP20Factory::abi::events().into_values())
495            .chain(IStablecoinDEX::abi::events().into_values())
496            .chain(INonce::abi::events().into_values())
497            .chain(IValidatorConfig::abi::events().into_values())
498            .chain(IAccountKeychain::abi::events().into_values())
499            .chain(IAddressRegistry::abi::events().into_values())
500            .chain(ITIP20ChannelReserve::abi::events().into_values())
501            .chain(ISignatureVerifier::abi::events().into_values())
502            .chain(IReceivePolicyGuard::abi::events().into_values())
503            .chain(IConfigurableAccount::abi::events().into_values())
504            .flatten()
505            .map(|event| ((event.selector(), indexed_inputs(&event)), vec![event]))
506            .collect();
507
508        Self {
509            contracts: Default::default(),
510            labels,
511            base_labels: Default::default(),
512            receive_contracts: Default::default(),
513            fallback_contracts: Default::default(),
514            non_fallback_contracts: Default::default(),
515            functions,
516            functions_by_address: Default::default(),
517            constructors_by_address: Default::default(),
518            constructor_args_offsets: Default::default(),
519            events,
520            events_by_address: None,
521            // Decode Tempo precompile custom errors by name in traces.
522            revert_decoder: RevertDecoder::new().with_abis(tempo_abis.iter()),
523
524            signature_identifier: None,
525            verbosity: 0,
526
527            debug_identifier: None,
528
529            disable_labels: false,
530
531            chain_id: None,
532            networks: None,
533
534            opcodes: Vec::new(),
535
536            hardfork: None,
537            compact_labels: false,
538        }
539    }
540
541    /// Returns a copy of everything [`Self::clear_addresses`] resets, so that
542    /// [`Self::restore_address_identities`] can bring the decoder back to this point.
543    pub fn address_identities(&self) -> AddressIdentities {
544        AddressIdentities {
545            contracts: self.contracts.clone(),
546            labels: self.labels.clone(),
547            receive_contracts: self.receive_contracts.clone(),
548            fallback_contracts: self.fallback_contracts.clone(),
549            non_fallback_contracts: self.non_fallback_contracts.clone(),
550            functions_by_address: self.functions_by_address.clone(),
551            constructors_by_address: self.constructors_by_address.clone(),
552            constructor_args_offsets: self.constructor_args_offsets.clone(),
553            events_by_address: self.events_by_address.clone(),
554        }
555    }
556
557    /// Restores the identities saved by [`Self::address_identities`].
558    pub fn restore_address_identities(&mut self, identities: &AddressIdentities) {
559        self.contracts.clone_from(&identities.contracts);
560        self.labels.clone_from(&identities.labels);
561        self.receive_contracts.clone_from(&identities.receive_contracts);
562        self.fallback_contracts.clone_from(&identities.fallback_contracts);
563        self.non_fallback_contracts.clone_from(&identities.non_fallback_contracts);
564        self.functions_by_address.clone_from(&identities.functions_by_address);
565        self.constructors_by_address.clone_from(&identities.constructors_by_address);
566        self.constructor_args_offsets.clone_from(&identities.constructor_args_offsets);
567        self.events_by_address.clone_from(&identities.events_by_address);
568    }
569
570    /// Clears all known addresses.
571    pub fn clear_addresses(&mut self) {
572        self.contracts.clear();
573
574        if self.base_labels.is_empty() {
575            self.labels.clone_from(&Self::new().labels);
576        } else {
577            self.labels.clone_from(&self.base_labels);
578        }
579
580        self.receive_contracts.clear();
581        self.fallback_contracts.clear();
582        self.non_fallback_contracts.clear();
583        self.functions_by_address.clear();
584        self.events_by_address = None;
585        self.constructors_by_address.clear();
586        self.constructor_args_offsets.clear();
587
588        self.register_celo_metadata();
589        #[cfg(feature = "monad")]
590        self.register_monad_metadata();
591        #[cfg(feature = "base")]
592        self.register_base_metadata();
593    }
594
595    /// Returns labels for precompiles active in this decoder's chain context.
596    pub fn precompile_labels(&self) -> AddressHashMap<String> {
597        self.labels
598            .iter()
599            .filter(|(address, _)| {
600                precompiles::is_known_precompile(
601                    **address,
602                    self.networks,
603                    self.chain_id,
604                    self.hardfork,
605                )
606            })
607            .map(|(address, label)| (*address, label.clone()))
608            .collect()
609    }
610
611    /// Identify unknown addresses in the specified call trace using the specified identifier.
612    ///
613    /// Unknown contracts are contracts that either lack a label or an ABI.
614    pub fn identify(&mut self, arena: &CallTraceArena, identifier: &mut impl TraceIdentifier) {
615        self.collect_identified_addresses(self.identify_addresses(arena, identifier), true);
616    }
617
618    /// Identifies unknown addresses without re-registering their ABIs globally, and returns
619    /// whether it identified any address.
620    ///
621    /// The identified ABIs must already be registered in this decoder.
622    pub fn identify_scoped(
623        &mut self,
624        arena: &CallTraceArena,
625        identifier: &mut impl TraceIdentifier,
626    ) -> bool {
627        let identified = self.identify_addresses(arena, identifier);
628        let any = !identified.is_empty();
629        self.collect_identified_addresses(identified, false);
630        any
631    }
632
633    /// Identify unknown addresses in the specified call trace using the specified identifier.
634    ///
635    /// Unknown contracts are contracts that either lack a label or an ABI.
636    pub fn identify_addresses<'a>(
637        &self,
638        arena: &CallTraceArena,
639        identifier: &'a mut impl TraceIdentifier,
640    ) -> Vec<IdentifiedAddress<'a>> {
641        let nodes = arena.nodes().iter().filter(|node| {
642            // Skip precompile addresses, they will never resolve externally.
643            if node.is_precompile()
644                || precompiles::is_known_precompile_call(
645                    &node.trace,
646                    self.networks,
647                    self.chain_id,
648                    self.hardfork,
649                )
650            {
651                return false;
652            }
653            let address = &node.trace.address;
654            !self.labels.contains_key(address) || !self.contracts.contains_key(address)
655        });
656        identifier.identify_addresses(&nodes.collect::<Vec<_>>())
657    }
658
659    /// Adds a single event to the decoder.
660    pub fn push_event(&mut self, event: Event) {
661        push_unique(
662            self.events.entry((event.selector(), indexed_inputs(&event))).or_default(),
663            Cow::Owned(event),
664        );
665    }
666
667    /// Adds a single event to the decoder for a specific contract address.
668    pub fn push_address_event(&mut self, address: Address, event: Event) {
669        let events = self
670            .events_by_address
671            .get_or_insert_with(Default::default)
672            .entry(address)
673            .or_default()
674            .entry(((!event.anonymous).then(|| event.selector()), indexed_inputs(&event)))
675            .or_default();
676        push_unique(events, Cow::Owned(event));
677    }
678
679    /// Adds a single function to the decoder.
680    pub fn push_function(&mut self, function: Function) {
681        self.push_function_with_selector(function.selector(), Cow::Owned(function));
682    }
683
684    fn push_function_with_selector(&mut self, selector: Selector, function: Cow<'_, Function>) {
685        let functions = self.functions.entry(selector).or_default();
686
687        if push_unique(functions, function) && functions.len() > 1 {
688            let function = functions.last().expect("function was just inserted");
689            let signature = function.signature();
690            trace!(target: "evm::traces", %selector, new=%signature, "duplicate function selector");
691        }
692    }
693
694    /// Adds a single function to the decoder for a specific contract address.
695    pub fn push_address_function(&mut self, address: Address, function: Function) {
696        let functions = self
697            .functions_by_address
698            .entry(address)
699            .or_default()
700            .entry(function.selector())
701            .or_default();
702        push_unique(functions, Cow::Owned(function));
703    }
704
705    /// Returns the functions registered for `selector` at `address`.
706    ///
707    /// Address-scoped and caller-supplied metadata takes precedence over network fallbacks.
708    pub fn functions_for_selector(
709        &self,
710        address: Address,
711        selector: &Selector,
712    ) -> Option<&[Function]> {
713        if self.is_current_committee_active(address) {
714            static FUNCTIONS: OnceLock<HashMap<Selector, Vec<Function>>> = OnceLock::new();
715            if let Some(functions) = FUNCTIONS
716                .get_or_init(|| {
717                    ICurrentCommittee::abi::functions()
718                        .into_values()
719                        .flatten()
720                        .map(|function| (function.selector(), vec![function]))
721                        .collect()
722                })
723                .get(selector)
724            {
725                return Some(functions);
726            }
727        }
728        if let Some(functions) =
729            self.functions_by_address.get(&address).and_then(|functions| functions.get(selector))
730        {
731            return Some(functions);
732        }
733        #[cfg(feature = "base")]
734        let base_functions = self.base_functions_for_selector(selector);
735        // Tempo's function with this selector has no output, while B20 returns a bool.
736        #[cfg(feature = "base")]
737        if let Some(functions) = base_functions
738            && functions.first().is_some_and(|function| function.name == "transferWithMemo")
739        {
740            if let Some(global) = self.functions.get(selector) {
741                let tempo_fallback = global.first().is_some_and(|function| {
742                    function.name == "transferWithMemo" && function.outputs.is_empty()
743                });
744                if !tempo_fallback {
745                    return Some(global);
746                }
747                if global.len() > 1 {
748                    return Some(&global[1..]);
749                }
750            }
751            return Some(functions);
752        }
753        let functions = self.functions.get(selector);
754        #[cfg(feature = "base")]
755        let functions = functions.or(base_functions);
756        functions.map(Vec::as_slice)
757    }
758
759    #[cfg(feature = "base")]
760    fn is_base_context(&self) -> bool {
761        self.networks.map_or_else(
762            || self.hardfork.and_then(BaseSpecId::from_foundry_hardfork).is_some(),
763            |networks| networks.is_base(),
764        )
765    }
766
767    #[cfg(feature = "base")]
768    fn base_functions_for_selector(&self, selector: &Selector) -> Option<&'static Vec<Function>> {
769        if !self.is_base_context() {
770            return None;
771        }
772        static FUNCTIONS: OnceLock<HashMap<Selector, Vec<Function>>> = OnceLock::new();
773        FUNCTIONS
774            .get_or_init(|| {
775                base::IB20Extensions::abi::functions()
776                    .into_values()
777                    .flatten()
778                    .map(|function| (function.selector(), vec![function]))
779                    .collect()
780            })
781            .get(selector)
782    }
783
784    #[cfg(feature = "base")]
785    fn base_events(&self) -> Option<&'static BTreeMap<(B256, usize), Vec<Event>>> {
786        if !self.is_base_context() {
787            return None;
788        }
789        static EVENTS: OnceLock<BTreeMap<(B256, usize), Vec<Event>>> = OnceLock::new();
790        Some(EVENTS.get_or_init(|| {
791            base::IB20Extensions::abi::events()
792                .into_values()
793                .flatten()
794                .map(|event| ((event.selector(), indexed_inputs(&event)), vec![event]))
795                .collect()
796        }))
797    }
798
799    #[cfg(feature = "base")]
800    fn base_revert_decoder(&self, address: Address) -> Option<&'static RevertDecoder> {
801        let upgrade =
802            self.hardfork.and_then(BaseSpecId::from_foundry_hardfork).map(|spec| spec.upgrade())?;
803        if !self.is_base_context() || !is_base_precompile_active_at(address, upgrade) {
804            return None;
805        }
806
807        static DECODERS: OnceLock<HashMap<Address, RevertDecoder>> = OnceLock::new();
808        DECODERS
809            .get_or_init(|| {
810                HashMap::from_iter([
811                    (
812                        ActivationRegistryStorage::ADDRESS,
813                        RevertDecoder::new().with_abi(&base::IActivationRegistry::abi::contract()),
814                    ),
815                    (
816                        PolicyRegistryStorage::ADDRESS,
817                        RevertDecoder::new().with_abi(&base::IPolicyRegistry::abi::contract()),
818                    ),
819                    (
820                        B20FactoryStorage::ADDRESS,
821                        RevertDecoder::new().with_abi(&base::IB20Factory::abi::contract()),
822                    ),
823                    (
824                        NonceManagerStorage::ADDRESS,
825                        RevertDecoder::new().with_abi(&base::INonceManager::abi::contract()),
826                    ),
827                    (
828                        TxContextStorage::ADDRESS,
829                        RevertDecoder::new().with_abi(&base::ITransactionContext::abi::contract()),
830                    ),
831                ])
832            })
833            .get(&address)
834    }
835
836    #[cfg(feature = "monad")]
837    fn register_monad_metadata(&mut self) {
838        if self.networks.is_some_and(|networks| !networks.is_monad()) {
839            return;
840        }
841        let Some(hardfork) = self.hardfork.and_then(MonadHardfork::from_foundry_hardfork) else {
842            return;
843        };
844
845        self.labels
846            .entry(foundry_evm_core::constants::MONAD_CHEATCODE_ADDRESS)
847            .or_insert_with(|| "MonadVM".to_string());
848        self.register_address_abi(
849            monad_evm2::staking::STAKING_ADDRESS,
850            &monad::IMonadStaking::abi::contract(),
851        );
852        self.register_address_abi(
853            monad_evm2::staking::STAKING_ADDRESS,
854            &monad::IMonadStakingSyscalls::abi::contract(),
855        );
856        self.labels
857            .entry(monad_evm2::staking::STAKING_ADDRESS)
858            .or_insert_with(|| "Staking".to_string());
859
860        if foundry_evm_networks::is_monad_precompile_active_at(
861            monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
862            hardfork,
863        ) {
864            self.register_address_abi(
865                monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
866                &monad::IReserveBalance::abi::contract(),
867            );
868            self.labels
869                .entry(monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS)
870                .or_insert_with(|| "ReserveBalance".to_string());
871        }
872    }
873
874    #[cfg(any(feature = "base", feature = "monad"))]
875    fn register_address_abi(&mut self, address: Address, abi: &JsonAbi) {
876        for function in abi.functions() {
877            self.push_address_function(address, function.clone());
878        }
879        for event in abi.events() {
880            self.push_address_event(address, event.clone());
881        }
882    }
883
884    fn is_current_committee_active(&self, address: Address) -> bool {
885        address == CURRENT_COMMITTEE_ADDRESS
886            && self
887                .hardfork
888                .and_then(TempoHardfork::from_foundry_hardfork)
889                .is_some_and(|hardfork| hardfork.is_t8())
890            && precompiles::is_known_precompile(
891                address,
892                self.networks,
893                self.chain_id,
894                self.hardfork,
895            )
896    }
897
898    /// Selects the appropriate function from a list of functions with the same selector by
899    /// checking which one decodes the calldata.
900    ///
901    /// Address-scoped function lookup should happen before this to avoid using ABI metadata from a
902    /// different contract when multiple functions have the same input types.
903    fn select_contract_function<'a>(
904        &self,
905        functions: &'a [Function],
906        trace: &CallTrace,
907    ) -> &'a [Function] {
908        // Suffixed calldata must start with the exact ABI encoding of the function inputs, so
909        // packed calldata isn't decoded as a function with fewer inputs. Cheatcode calls are
910        // always decoded to redact sensitive inputs.
911        if trace.address != CHEATCODE_ADDRESS
912            && let Some(args) = suffixed_abi_args(&trace.data)
913        {
914            return functions
915                .iter()
916                .position(|func| is_abi_encoded_input(func, args))
917                .map_or(&[], |i| &functions[i..=i]);
918        }
919
920        // When there are selector collisions, try to decode the calldata with each function
921        // to determine which one is actually being called. The correct function should
922        // decode successfully while the wrong ones will fail due to parameter type mismatches.
923        if functions.len() > 1 {
924            for (i, func) in functions.iter().enumerate() {
925                if trace.data.len() >= SELECTOR_LEN
926                    && func.abi_decode_input(&trace.data[SELECTOR_LEN..]).is_ok()
927                {
928                    return &functions[i..i + 1];
929                }
930            }
931        }
932        functions
933    }
934
935    /// Adds a single error to the decoder.
936    pub fn push_error(&mut self, error: Error) {
937        self.revert_decoder.push_error(error);
938    }
939
940    pub const fn without_label(&mut self, disable: bool) {
941        self.disable_labels = disable;
942    }
943
944    fn collect_identified_addresses(
945        &mut self,
946        mut addrs: Vec<IdentifiedAddress<'_>>,
947        global: bool,
948    ) {
949        addrs.sort_by_key(|identity| identity.address);
950        addrs.dedup_by_key(|identity| identity.address);
951        if addrs.is_empty() {
952            return;
953        }
954
955        trace!(target: "evm::traces", len=addrs.len(), "collecting address identities");
956        for IdentifiedAddress {
957            address,
958            label,
959            contract,
960            abi,
961            constructor_args_offset,
962            artifact_id: _,
963        } in addrs
964        {
965            let _span = trace_span!(target: "evm::traces", "identity", ?contract, ?label).entered();
966
967            if let Some(contract) = contract {
968                self.contracts.entry(address).or_insert(contract);
969            }
970
971            if let Some(label) = label.filter(|s| !s.is_empty()) {
972                self.labels.entry(address).or_insert(label);
973            }
974
975            if let Some(abi) = abi {
976                self.collect_abi(&abi, Some(address), global);
977            }
978
979            if let Some(offset) = constructor_args_offset {
980                self.constructor_args_offsets.entry(address).or_insert(offset);
981            }
982        }
983    }
984
985    fn collect_abi(&mut self, abi: &JsonAbi, address: Option<Address>, global: bool) {
986        let len = abi.len();
987        if len == 0 {
988            return;
989        }
990        trace!(target: "evm::traces", len, ?address, "collecting ABI");
991        let mut selectors = HashSet::default();
992        for function in abi.functions() {
993            let selector = function.selector();
994            if let Some(address) = address {
995                let functions = self
996                    .functions_by_address
997                    .entry(address)
998                    .or_default()
999                    .entry(selector)
1000                    .or_default();
1001                push_unique(functions, Cow::Borrowed(function));
1002                selectors.insert(selector);
1003            }
1004            if global {
1005                self.push_function_with_selector(selector, Cow::Borrowed(function));
1006            }
1007        }
1008        if let Some(address) = address
1009            && let Some(constructor) = abi.constructor()
1010        {
1011            self.constructors_by_address.entry(address).or_insert_with(|| constructor.clone());
1012        }
1013        if global {
1014            for event in abi.events() {
1015                push_unique(
1016                    self.events.entry((event.selector(), indexed_inputs(event))).or_default(),
1017                    Cow::Borrowed(event),
1018                );
1019            }
1020            for error in abi.errors() {
1021                self.push_error(error.clone());
1022            }
1023        }
1024        if let Some(address) = address {
1025            if abi.receive.is_some() {
1026                self.receive_contracts.insert(address);
1027            }
1028
1029            if abi.fallback.is_some() {
1030                self.fallback_contracts.insert(address, selectors);
1031            } else {
1032                self.non_fallback_contracts.insert(address, selectors);
1033            }
1034        }
1035    }
1036
1037    /// Populates the traces with decoded data by mutating the
1038    /// [CallTrace] in place. See [CallTraceDecoder::decode_function] and
1039    /// [CallTraceDecoder::decode_event] for more details.
1040    pub async fn populate_traces(&self, traces: &mut Vec<CallTraceNode>) {
1041        for node in traces {
1042            if !self.opcodes.is_empty() {
1043                for step in &mut node.trace.steps {
1044                    if step.decoded.is_some() || !self.opcodes.contains(&step.op) {
1045                        continue;
1046                    }
1047                    let res = match &step.storage_change {
1048                        Some(change) if step.op == OpCode::SSTORE => {
1049                            if let Some(had_value) = change.had_value {
1050                                format!(
1051                                    "[{}] {} {:#x}: {:#x} → {:#x}",
1052                                    step.gas_cost, step.op, change.key, had_value, change.value
1053                                )
1054                            } else {
1055                                format!(
1056                                    "[{}] {} {:#x} → ({:#x})",
1057                                    step.gas_cost, step.op, change.key, change.value
1058                                )
1059                            }
1060                        }
1061                        Some(change) => format!(
1062                            "[{}] {} {:#x} → ({:#x})",
1063                            step.gas_cost, step.op, change.key, change.value
1064                        ),
1065                        None => format!("[{}] {}", step.gas_cost, step.op),
1066                    };
1067
1068                    step.decoded = Some(Box::new(DecodedTraceStep::Line(res)));
1069                }
1070            }
1071
1072            node.trace.decoded = Some(Box::new(self.decode_function(&node.trace).await));
1073            self.redact_raw_cheatcode_secrets(&mut node.trace);
1074            for log in &mut node.logs {
1075                log.decoded =
1076                    Some(Box::new(self.decode_event_with_address(log.address, &log.raw_log).await));
1077            }
1078
1079            if let Some(debug) = self.debug_identifier.as_ref()
1080                && let Some(identified) = self.contracts.get(&node.trace.address)
1081            {
1082                debug.identify_node_steps(node, get_contract_name(identified))
1083            }
1084        }
1085    }
1086
1087    /// Returns the same function signature as [`Self::decode_function`] without formatting
1088    /// arguments and return values when the ABI identifies a single function.
1089    pub async fn decode_function_signature(&self, trace: &CallTrace) -> Option<String> {
1090        if !trace.kind.is_any_create()
1091            && trace.address != DEFAULT_CREATE2_DEPLOYER
1092            && !precompiles::is_known_precompile_call(
1093                trace,
1094                self.networks,
1095                self.chain_id,
1096                self.hardfork,
1097            )
1098            && is_abi_call_data(&trace.data)
1099            // Suffixed calldata is only decoded if it matches the function inputs.
1100            && suffixed_abi_args(&trace.data).is_none()
1101            && let Some(selector) = trace.data.first_chunk().map(Selector::from)
1102            && let Some([function]) = self.functions_for_selector(trace.address, &selector)
1103            && self
1104                .fallback_contracts
1105                .get(&trace.address)
1106                .is_none_or(|selectors| selectors.contains(&selector))
1107        {
1108            return Some(function.signature());
1109        }
1110
1111        self.decode_function(trace).await.call_data.map(|data| data.signature)
1112    }
1113
1114    /// Decodes a call trace.
1115    pub async fn decode_function(&self, trace: &CallTrace) -> DecodedCallTrace {
1116        let label = if self.disable_labels {
1117            None
1118        } else if let Some(label) = self.labels.get(&trace.address) {
1119            Some(label.clone())
1120        } else if self.is_current_committee_active(trace.address) {
1121            Some("CurrentCommittee".to_string())
1122        } else {
1123            None
1124        };
1125
1126        if trace.kind.is_any_create() {
1127            return DecodedCallTrace {
1128                label,
1129                call_data: self.decode_constructor_input(trace),
1130                return_data: None,
1131            };
1132        }
1133
1134        if let Some(trace) = precompiles::decode(trace, self.networks, self.chain_id, self.hardfork)
1135        {
1136            return trace;
1137        }
1138
1139        let cdata = &trace.data;
1140        if trace.address == DEFAULT_CREATE2_DEPLOYER {
1141            return DecodedCallTrace {
1142                label,
1143                call_data: Some(DecodedCallData { signature: "create2".to_string(), args: vec![] }),
1144                return_data: self.default_return_data(trace).await,
1145            };
1146        }
1147
1148        if is_abi_call_data(cdata) {
1149            let selector = Selector::try_from(&cdata[..SELECTOR_LEN]).unwrap();
1150            let mut identified_functions = Vec::new();
1151            let functions = match self.functions_for_selector(trace.address, &selector) {
1152                Some(functions) => functions,
1153                None => {
1154                    if let Some(identifier) = &self.signature_identifier
1155                        && let Some(function) = identifier.identify_function(selector).await
1156                    {
1157                        identified_functions.push(function);
1158                    }
1159                    &identified_functions
1160                }
1161            };
1162
1163            let contract_functions = self.select_contract_function(functions, trace);
1164
1165            // Check if unsupported fn selector: calldata dooes NOT point to one of its selectors +
1166            // non-fallback contract + no receive. Skip delegate calls: library ABIs omit external
1167            // functions with storage parameters.
1168            if !trace.kind.is_delegate()
1169                && let Some(contract_selectors) = self.non_fallback_contracts.get(&trace.address)
1170                && !contract_selectors.contains(&selector)
1171                && (!cdata.is_empty() || !self.receive_contracts.contains(&trace.address))
1172            {
1173                let return_data = if trace.success {
1174                    None
1175                } else {
1176                    let revert_msg =
1177                        self.decode_revert_at(trace.address, &trace.output, trace.status).await;
1178
1179                    if trace.output.is_empty() || revert_msg.contains("EvmError: Revert") {
1180                        Some(format!(
1181                            "unrecognized function selector {} for contract {}, which has no fallback function.",
1182                            selector, trace.address
1183                        ))
1184                    } else {
1185                        Some(revert_msg)
1186                    }
1187                };
1188
1189                return if let Some(func) = contract_functions.first() {
1190                    DecodedCallTrace {
1191                        label,
1192                        call_data: Some(self.decode_function_input(trace, func)),
1193                        return_data,
1194                    }
1195                } else {
1196                    DecodedCallTrace {
1197                        label,
1198                        call_data: self.fallback_call_data(trace),
1199                        return_data,
1200                    }
1201                };
1202            }
1203
1204            let [func, ..] = contract_functions else {
1205                return DecodedCallTrace {
1206                    label,
1207                    call_data: self.fallback_call_data(trace),
1208                    return_data: self.default_return_data(trace).await,
1209                };
1210            };
1211
1212            // If traced contract is a fallback contract, check if it has the decoded function.
1213            // If not, then replace call data signature with `fallback`.
1214            let mut call_data = self.decode_function_input(trace, func);
1215            if let Some(fallback_functions) = self.fallback_contracts.get(&trace.address)
1216                && !fallback_functions.contains(&selector)
1217                && let Some(cd) = self.fallback_call_data(trace)
1218            {
1219                call_data.signature = cd.signature;
1220            }
1221
1222            DecodedCallTrace {
1223                label,
1224                call_data: Some(call_data),
1225                return_data: self.decode_function_output(trace, contract_functions).await,
1226            }
1227        } else {
1228            // Calls to the cheatcode address with a known selector must not fall back to raw
1229            // calldata rendering: even malformed calldata can contain sensitive inputs like
1230            // private keys that the custom cheatcode decoding redacts.
1231            if trace.address == CHEATCODE_ADDRESS
1232                && let Some(selector) = cdata.first_chunk().map(Selector::from)
1233                && let Some([func, ..]) = self.functions_for_selector(trace.address, &selector)
1234            {
1235                return DecodedCallTrace {
1236                    label,
1237                    call_data: Some(self.decode_function_input(trace, func)),
1238                    return_data: self.default_return_data(trace).await,
1239                };
1240            }
1241            DecodedCallTrace {
1242                label,
1243                call_data: self.fallback_call_data(trace),
1244                return_data: self.default_return_data(trace).await,
1245            }
1246        }
1247    }
1248
1249    /// Decodes a function's input into the given trace.
1250    fn decode_function_input(&self, trace: &CallTrace, func: &Function) -> DecodedCallData {
1251        let mut args = None;
1252        if trace.data.len() >= SELECTOR_LEN {
1253            if trace.address == CHEATCODE_ADDRESS {
1254                // Try to decode cheatcode inputs in a more custom way
1255                if let Some(v) = self.decode_cheatcode_inputs(func, &trace.data) {
1256                    args = Some(v);
1257                }
1258            }
1259
1260            if args.is_none()
1261                && let Ok(decoded) = func.abi_decode_input(&trace.data[SELECTOR_LEN..])
1262            {
1263                args = Some(
1264                    decoded
1265                        .iter()
1266                        .zip(&func.inputs)
1267                        .map(|(value, input)| {
1268                            self.format_param_value(
1269                                Some(trace.address),
1270                                &func.name,
1271                                &input.name,
1272                                &input.ty,
1273                                value,
1274                            )
1275                        })
1276                        .collect(),
1277                );
1278            }
1279        }
1280
1281        DecodedCallData { signature: func.signature(), args: args.unwrap_or_default() }
1282    }
1283
1284    /// Decodes constructor input from a creation trace.
1285    fn decode_constructor_input(&self, trace: &CallTrace) -> Option<DecodedCallData> {
1286        let constructor = self.constructors_by_address.get(&trace.address)?;
1287        let offset = *self.constructor_args_offsets.get(&trace.address)?;
1288        let data = trace.data.get(offset..)?;
1289        let decoded = constructor.abi_decode_input(data).ok()?;
1290        let args = decoded
1291            .iter()
1292            .zip(&constructor.inputs)
1293            .map(|(value, input)| {
1294                self.format_param_value(
1295                    Some(trace.address),
1296                    "constructor",
1297                    &input.name,
1298                    &input.ty,
1299                    value,
1300                )
1301            })
1302            .collect();
1303
1304        Some(DecodedCallData { signature: constructor_signature(constructor), args })
1305    }
1306
1307    /// Custom decoding for cheatcode inputs.
1308    fn decode_cheatcode_inputs(&self, func: &Function, data: &[u8]) -> Option<Vec<String>> {
1309        if let Some(redacted) = self.redact_cheatcode_secret_inputs(func, data) {
1310            return Some(redacted);
1311        }
1312        match func.name.as_str() {
1313            "expectRevert" => {
1314                let decoded =
1315                    data.get(SELECTOR_LEN..).and_then(|data| func.abi_decode_input(data).ok());
1316                let Some(decoded) = decoded else {
1317                    return Some(vec![self.revert_decoder.decode(data, None)]);
1318                };
1319                let Some(first) = decoded.first() else {
1320                    return Some(vec![self.revert_decoder.decode(data, None)]);
1321                };
1322                let expected_revert = match first {
1323                    DynSolValue::Bytes(bytes) => bytes.as_slice(),
1324                    DynSolValue::FixedBytes(word, size) => &word[..*size],
1325                    _ => return None,
1326                };
1327                Some(
1328                    std::iter::once(self.revert_decoder.decode(expected_revert, None))
1329                        .chain(decoded.iter().skip(1).map(|value| self.format_value(value)))
1330                        .collect(),
1331                )
1332            }
1333            "parseJson" |
1334            "parseJsonUint" |
1335            "parseJsonUintArray" |
1336            "parseJsonInt" |
1337            "parseJsonIntArray" |
1338            "parseJsonString" |
1339            "parseJsonStringArray" |
1340            "parseJsonAddress" |
1341            "parseJsonAddressArray" |
1342            "parseJsonBool" |
1343            "parseJsonBoolArray" |
1344            "parseJsonBytes" |
1345            "parseJsonBytesArray" |
1346            "parseJsonBytes32" |
1347            "parseJsonBytes32Array" |
1348            "writeJson" |
1349            // `keyExists` is being deprecated in favor of `keyExistsJson`. It will be removed in future versions.
1350            "keyExists" |
1351            "keyExistsJson" |
1352            "serializeBool" |
1353            "serializeUint" |
1354            "serializeUintToHex" |
1355            "serializeInt" |
1356            "serializeAddress" |
1357            "serializeBytes32" |
1358            "serializeString" |
1359            "serializeBytes" => {
1360                if self.verbosity >= 5 {
1361                    None
1362                } else {
1363                    let mut decoded = func.abi_decode_input(&data[SELECTOR_LEN..]).ok()?;
1364                    let token = if func.name.as_str() == "parseJson" ||
1365                        // `keyExists` is being deprecated in favor of `keyExistsJson`. It will be removed in future versions.
1366                        func.name.as_str() == "keyExists" ||
1367                        func.name.as_str() == "keyExistsJson"
1368                    {
1369                        "<JSON file>"
1370                    } else {
1371                        "<stringified JSON>"
1372                    };
1373                    decoded[0] = DynSolValue::String(token.to_string());
1374                    Some(decoded.iter().map(format_token).collect())
1375                }
1376            }
1377            s if s.contains("Toml") => {
1378                if self.verbosity >= 5 {
1379                    None
1380                } else {
1381                    let mut decoded = func.abi_decode_input(&data[SELECTOR_LEN..]).ok()?;
1382                    let token = if func.name.as_str() == "parseToml" ||
1383                        func.name.as_str() == "keyExistsToml"
1384                    {
1385                        "<TOML file>"
1386                    } else {
1387                        "<stringified TOML>"
1388                    };
1389                    decoded[0] = DynSolValue::String(token.to_string());
1390                    Some(decoded.iter().map(format_token).collect())
1391                }
1392            }
1393            "sign" | "signCompact" => {
1394                // Digest-only and signer-address overloads carry no key material.
1395                let decoded = func.abi_decode_input(data.get(SELECTOR_LEN..)?).ok()?;
1396                Some(decoded.iter().map(|value| self.format_value(value)).collect())
1397            }
1398            "createFork" | "createSelectFork" | "rpc" => {
1399                // RPC URLs are redacted above; aliases are shown as-is.
1400                let decoded = func.abi_decode_input(data.get(SELECTOR_LEN..)?).ok()?;
1401                (func.inputs.first()?.ty == "string")
1402                    .then(|| decoded.iter().map(format_token).collect())
1403            }
1404            _ => None,
1405        }
1406    }
1407
1408    /// Redacts the inputs of cheatcode calls that carry secrets, such as private keys or RPC
1409    /// URLs.
1410    ///
1411    /// Returns `None` when the call carries no secret. This is the single source of truth for
1412    /// both the decoded arguments and [`Self::redact_raw_cheatcode_secrets`].
1413    fn redact_cheatcode_secret_inputs(&self, func: &Function, data: &[u8]) -> Option<Vec<String>> {
1414        match func.name.as_str() {
1415            "addr" | "createEd25519Key" | "createWallet" | "deriveKey" | "publicKeyEd25519"
1416            | "publicKeyP256" | "rememberKey" | "rememberKeys" => {
1417                // Redact private key in all cases
1418                Some(vec!["<pk>".to_string()])
1419            }
1420            "broadcast" | "startBroadcast" => {
1421                // Redact private key if defined
1422                // broadcast(uint256) / startBroadcast(uint256)
1423                (!func.inputs.is_empty() && func.inputs[0].ty == "uint256")
1424                    .then(|| vec!["<pk>".to_string()])
1425            }
1426            "getNonce" => {
1427                // Redact private key if defined
1428                // getNonce(Wallet)
1429                (!func.inputs.is_empty() && func.inputs[0].ty == "tuple")
1430                    .then(|| vec!["<pk>".to_string()])
1431            }
1432            "sign"
1433            | "signCompact"
1434            | "signP256"
1435            | "signKeychain"
1436            | "signKeychainAdmin"
1437            | "signConfigurableAccount"
1438            | "signKeychainConfigurableAccount"
1439                if !matches!(
1440                    func.inputs.first().map(|input| input.ty.as_str()),
1441                    Some("bytes32" | "address")
1442                ) =>
1443            {
1444                // Fail closed: when the arguments of a key-taking cheatcode cannot be
1445                // decoded, redact everything instead of deferring to generic rendering.
1446                let Ok(mut decoded) = func.abi_decode_input(&data[SELECTOR_LEN..]) else {
1447                    return Some(vec!["<redacted>".to_string()]);
1448                };
1449
1450                // Redact private key and replace in trace: the first parameter is a raw
1451                // private key (uint256), a Wallet struct (tuple), or a list of owner keys
1452                // (uint256[] or OwnerKey[]).
1453                decoded[0] = DynSolValue::String("<pk>".to_string());
1454                Some(decoded.iter().map(|value| self.format_value(value)).collect())
1455            }
1456            "signWithNonceUnsafe" => {
1457                let Ok(mut decoded) = func.abi_decode_input(&data[SELECTOR_LEN..]) else {
1458                    return Some(vec!["<redacted>".to_string()]);
1459                };
1460                // Redact private key and nonce and replace in trace for
1461                // signWithNonceUnsafe(uint256 privateKey, bytes32 digest, uint256 nonce).
1462                // The nonce is the raw ECDSA k value: together with the digest and the
1463                // returned signature it allows recovering the private key.
1464                decoded[0] = DynSolValue::String("<pk>".to_string());
1465                decoded[2] = DynSolValue::String("<nonce>".to_string());
1466                Some(decoded.iter().map(|value| self.format_value(value)).collect())
1467            }
1468            "signEd25519" => {
1469                let Ok(mut decoded) = func.abi_decode_input(&data[SELECTOR_LEN..]) else {
1470                    return Some(vec!["<redacted>".to_string()]);
1471                };
1472                // Redact private key and replace in trace for
1473                // signEd25519(bytes namespace, bytes message, bytes32 privateKey)
1474                decoded[2] = DynSolValue::String("<pk>".to_string());
1475                Some(decoded.iter().map(|value| self.format_value(value)).collect())
1476            }
1477            "signDelegation" | "signAndAttachDelegation" => {
1478                let Ok(mut decoded) = func.abi_decode_input(&data[SELECTOR_LEN..]) else {
1479                    return Some(vec!["<redacted>".to_string()]);
1480                };
1481                // Redact private key and replace in trace for
1482                // signAndAttachDelegation(address implementation, uint256 privateKey)
1483                // signDelegation(address implementation, uint256 privateKey)
1484                decoded[1] = DynSolValue::String("<pk>".to_string());
1485                Some(decoded.iter().map(format_token).collect())
1486            }
1487            "createFork" | "createSelectFork" | "rpc" => {
1488                // Redact RPC URL except if referenced by an alias.
1489                let mut decoded = func.abi_decode_input(data.get(SELECTOR_LEN..)?).ok()?;
1490                if func.inputs.first()?.ty != "string" {
1491                    return None;
1492                }
1493                let url_or_alias = decoded[0].as_str().unwrap_or_default();
1494                if !url_or_alias.starts_with("http") && !url_or_alias.starts_with("ws") {
1495                    return None;
1496                }
1497                decoded[0] = DynSolValue::String("<rpc url>".to_string());
1498                Some(decoded.iter().map(format_token).collect())
1499            }
1500            _ => None,
1501        }
1502    }
1503
1504    /// Decodes a function's output into the given trace.
1505    async fn decode_function_output(
1506        &self,
1507        trace: &CallTrace,
1508        funcs: &[Function],
1509    ) -> Option<String> {
1510        if !trace.success {
1511            return self.default_return_data(trace).await;
1512        }
1513
1514        if trace.address == CHEATCODE_ADDRESS
1515            && let Some(decoded) = funcs.iter().find_map(|func| self.decode_cheatcode_outputs(func))
1516        {
1517            return Some(decoded);
1518        }
1519
1520        if let Some(values) =
1521            funcs.iter().find_map(|func| func.abi_decode_output(&trace.output).ok())
1522        {
1523            // Functions coming from an external database do not have any outputs specified,
1524            // and will lead to returning an empty list of values.
1525            if values.is_empty() {
1526                return None;
1527            }
1528
1529            return Some(
1530                values.iter().map(|value| self.format_value(value)).format(", ").to_string(),
1531            );
1532        }
1533
1534        None
1535    }
1536
1537    /// Custom decoding for cheatcode outputs.
1538    fn decode_cheatcode_outputs(&self, func: &Function) -> Option<String> {
1539        redact_cheatcode_secret_output(func)
1540            .or(match func.name.as_str() {
1541                "parseJson" if self.verbosity < 5 => Some("<encoded JSON value>"),
1542                "readFile" if self.verbosity < 5 => Some("<file>"),
1543                _ => None,
1544            })
1545            .map(Into::into)
1546    }
1547
1548    /// Strips the raw calldata and return data of a cheatcode call that carries secrets, so that
1549    /// serialized traces apply the same redaction as the decoded view.
1550    ///
1551    /// The selector is kept so the call can still be identified. Decode the trace before calling
1552    /// this, since decoding it again afterwards cannot recover the stripped arguments.
1553    pub fn redact_raw_cheatcode_secrets(&self, trace: &mut CallTrace) {
1554        if trace.address != CHEATCODE_ADDRESS {
1555            return;
1556        }
1557        let Some(selector) = trace.data.first_chunk::<SELECTOR_LEN>().copied() else { return };
1558        let Some(funcs) = self.functions_for_selector(trace.address, &selector.into()) else {
1559            return;
1560        };
1561        if funcs.iter().any(|func| self.redact_cheatcode_secret_inputs(func, &trace.data).is_some())
1562        {
1563            trace.data.truncate(SELECTOR_LEN);
1564        }
1565        // Like the decoded view, keep revert data so failed calls keep their diagnostics.
1566        if trace.success && funcs.iter().any(|func| redact_cheatcode_secret_output(func).is_some())
1567        {
1568            trace.output.clear();
1569        }
1570    }
1571
1572    #[track_caller]
1573    fn fallback_call_data(&self, trace: &CallTrace) -> Option<DecodedCallData> {
1574        let cdata = &trace.data;
1575        let signature = if cdata.is_empty() && self.receive_contracts.contains(&trace.address) {
1576            "receive()"
1577        } else if self.fallback_contracts.contains_key(&trace.address) {
1578            "fallback()"
1579        } else {
1580            return None;
1581        }
1582        .to_string();
1583        let args = if cdata.is_empty() { Vec::new() } else { vec![cdata.to_string()] };
1584        Some(DecodedCallData { signature, args })
1585    }
1586
1587    /// The default decoded return data for a trace.
1588    async fn default_return_data(&self, trace: &CallTrace) -> Option<String> {
1589        // For calls with status None or successful status, don't decode revert data.
1590        if trace.status.is_none_or(InstrStop::is_success) || trace.success {
1591            return None;
1592        }
1593        Some(self.decode_revert_at(trace.address, &trace.output, trace.status).await)
1594    }
1595
1596    /// Decodes revert data into a human-readable representation.
1597    ///
1598    /// If the revert decoder does not know the custom error, tries identifying the error selector
1599    /// with the signatures identifier, like unknown function and event signatures. This resolves
1600    /// errors from the local signatures cache populated by `forge build`, or from remote signature
1601    /// databases.
1602    async fn decode_revert(&self, output: &[u8], status: Option<InstrStop>) -> String {
1603        if let Some(reason) = self.revert_decoder.maybe_decode_known(output) {
1604            return reason;
1605        }
1606        if let Some(identifier) = &self.signature_identifier
1607            && let Some((selector, data)) = output.split_first_chunk::<SELECTOR_LEN>()
1608            && let Some(error) = identifier.identify_error(Selector::from(*selector)).await
1609            && let Ok(decoded) = error.abi_decode_input(data)
1610        {
1611            return format!("{}({})", error.name, decoded.iter().map(format_token).format(", "));
1612        }
1613        self.revert_decoder.decode(output, status)
1614    }
1615
1616    async fn decode_revert_at(
1617        &self,
1618        address: Address,
1619        output: &[u8],
1620        status: Option<InstrStop>,
1621    ) -> String {
1622        #[cfg(feature = "base")]
1623        if let Some(reason) =
1624            self.base_revert_decoder(address).and_then(|decoder| decoder.maybe_decode_known(output))
1625        {
1626            return reason;
1627        }
1628        if self.is_current_committee_active(address) {
1629            static DECODER: OnceLock<RevertDecoder> = OnceLock::new();
1630            let decoder = DECODER
1631                .get_or_init(|| RevertDecoder::new().with_abi(&ICurrentCommittee::abi::contract()));
1632            if let Some(reason) = decoder.maybe_decode_known(output) {
1633                return reason;
1634            }
1635        }
1636        self.decode_revert(output, status).await
1637    }
1638
1639    /// Decodes an event.
1640    pub async fn decode_event(&self, log: &LogData) -> DecodedCallLog {
1641        self.decode_event_inner(None, log, false).await.into_call_log()
1642    }
1643
1644    /// Decodes an event emitted by a known address.
1645    pub async fn decode_event_with_address(
1646        &self,
1647        address: Address,
1648        log: &LogData,
1649    ) -> DecodedCallLog {
1650        self.decode_event_inner(Some(address), log, false).await.into_call_log()
1651    }
1652
1653    /// Decodes an event emitted by a known address, using its canonical signature as the name.
1654    pub async fn decode_event_with_address_signature(
1655        &self,
1656        address: Address,
1657        log: &LogData,
1658    ) -> DecodedEvent {
1659        self.decode_event_inner(Some(address), log, true).await
1660    }
1661
1662    async fn decode_event_inner(
1663        &self,
1664        address: Option<Address>,
1665        log: &LogData,
1666        canonical_signature: bool,
1667    ) -> DecodedEvent {
1668        let key = log.topics().first().map(|&topic| (topic, log.topics().len() - 1));
1669        let events = address.and_then(|address| self.events_by_address.as_deref()?.get(&address));
1670        let address_events = key.and_then(|(topic, count)| events?.get(&(Some(topic), count)));
1671        let global_events = key.and_then(|key| self.events.get(&key));
1672        #[cfg(feature = "base")]
1673        let base_events = key.and_then(|key| self.base_events()?.get(&key));
1674        #[cfg(not(feature = "base"))]
1675        let base_events: Option<&Vec<Event>> = None;
1676        let fallback_events = global_events.or(base_events);
1677        let regular_events = address_events.or(fallback_events);
1678        let anonymous_events = events.and_then(|events| events.get(&(None, log.topics().len())));
1679
1680        let decoded = if canonical_signature && address_events.is_none() {
1681            // Topic zero does not encode indexed parameter placement, so global metadata is only
1682            // a hint. Try every compatible layout and reject ambiguity.
1683            let mut events = fallback_events
1684                .into_iter()
1685                .flatten()
1686                .flat_map(|event| indexed_event_candidates(event.clone(), log))
1687                .collect::<Vec<_>>();
1688            events.extend(anonymous_events.into_iter().flatten().cloned());
1689            self.decode_unique_event_candidates(address, log, &events, true)
1690        } else if canonical_signature || anonymous_events.is_some() {
1691            self.decode_unique_event_candidates(
1692                address,
1693                log,
1694                regular_events.into_iter().flatten().chain(anonymous_events.into_iter().flatten()),
1695                canonical_signature,
1696            )
1697        } else {
1698            self.decode_event_candidates(address, log, regular_events.into_iter().flatten(), false)
1699        };
1700        if let Some(decoded) = decoded {
1701            return decoded;
1702        }
1703
1704        if regular_events.is_some() || anonymous_events.is_some() {
1705            return DecodedEvent::default();
1706        }
1707
1708        if let Some(&topic) = log.topics().first()
1709            && let Some(identifier) = &self.signature_identifier
1710            && let Some(event) = identifier.identify_event(topic).await
1711        {
1712            if !canonical_signature {
1713                let event = get_indexed_event(event, log);
1714                return self
1715                    .decode_event_candidates(address, log, [&event], false)
1716                    .unwrap_or_default();
1717            }
1718            let mut decoded = indexed_event_candidates(event, log)
1719                .filter_map(|event| self.decode_event_candidates(address, log, [&event], true));
1720            let event = decoded.next();
1721            if event.is_some() && decoded.next().is_some() {
1722                return DecodedEvent::default();
1723            }
1724            if let Some(decoded) = event {
1725                return decoded;
1726            }
1727        }
1728
1729        DecodedEvent::default()
1730    }
1731
1732    fn decode_event_candidates<'a>(
1733        &self,
1734        address: Option<Address>,
1735        log: &LogData,
1736        events: impl IntoIterator<Item = &'a Event>,
1737        canonical_signature: bool,
1738    ) -> Option<DecodedEvent> {
1739        for event in events {
1740            if let Ok(decoded) = event.decode_log(log) {
1741                let params = reconstruct_event_params(event, &decoded);
1742                let params = params
1743                    .into_iter()
1744                    .zip(event.inputs.iter())
1745                    .map(|(param, input)| {
1746                        // Undo patched names.
1747                        let name = input.name.clone();
1748                        let display = self.format_param_value(
1749                            address,
1750                            &event.name,
1751                            &input.name,
1752                            &input.ty,
1753                            &param,
1754                        );
1755                        (name, display, param)
1756                    })
1757                    .collect();
1758                return Some(DecodedEvent {
1759                    name: Some(if canonical_signature {
1760                        event.signature()
1761                    } else {
1762                        event.name.clone()
1763                    }),
1764                    params: Some(params),
1765                });
1766            }
1767        }
1768        None
1769    }
1770
1771    fn decode_unique_event_candidates<'a>(
1772        &self,
1773        address: Option<Address>,
1774        log: &LogData,
1775        events: impl IntoIterator<Item = &'a Event>,
1776        canonical_signature: bool,
1777    ) -> Option<DecodedEvent> {
1778        let mut decoded = events.into_iter().filter_map(|event| {
1779            self.decode_event_candidates(address, log, [event], canonical_signature)
1780        });
1781        let event = decoded.next()?;
1782        decoded.next().is_none().then_some(event)
1783    }
1784
1785    /// Prefetches function and event signatures into the identifier cache
1786    pub async fn prefetch_signatures(&self, nodes: &[CallTraceNode]) {
1787        let Some(identifier) = &self.signature_identifier else { return };
1788        let events = nodes
1789            .iter()
1790            .flat_map(|node| {
1791                node.logs
1792                    .iter()
1793                    .map(|log| log.raw_log.topics())
1794                    .filter(|&topics| {
1795                        if let Some(&first) = topics.first()
1796                            && self.events.contains_key(&(first, topics.len() - 1))
1797                        {
1798                            return false;
1799                        }
1800                        true
1801                    })
1802                    .filter_map(|topics| topics.first())
1803            })
1804            .copied();
1805        let functions = nodes
1806            .iter()
1807            .filter(|&n| {
1808                // Ignore known addresses.
1809                if n.trace.address == DEFAULT_CREATE2_DEPLOYER
1810                    || n.is_precompile()
1811                    || precompiles::is_known_precompile_call(
1812                        &n.trace,
1813                        self.networks,
1814                        self.chain_id,
1815                        self.hardfork,
1816                    )
1817                {
1818                    return false;
1819                }
1820                // Ignore non-ABI calldata.
1821                if n.trace.kind.is_any_create() || !is_abi_call_data(&n.trace.data) {
1822                    return false;
1823                }
1824                true
1825            })
1826            .filter_map(|n| n.trace.data.first_chunk().map(Selector::from))
1827            .filter(|selector| !self.functions.contains_key(selector));
1828        let errors = nodes
1829            .iter()
1830            .filter(|&n| {
1831                // Only consider reverted traces whose output the revert decoder cannot decode.
1832                n.trace.status.is_some_and(|s| !s.is_success())
1833                    && !n.trace.success
1834                    && self.revert_decoder.maybe_decode_known(&n.trace.output).is_none()
1835            })
1836            .filter_map(|n| n.trace.output.first_chunk().map(Selector::from));
1837        let selectors = events
1838            .map(SelectorKind::Event)
1839            .chain(functions.map(SelectorKind::Function))
1840            .chain(errors.map(SelectorKind::Error))
1841            .unique()
1842            .collect::<Vec<_>>();
1843        let _ = identifier.identify(&selectors).await;
1844    }
1845
1846    /// Pretty-prints a value.
1847    fn format_value(&self, value: &DynSolValue) -> String {
1848        if let DynSolValue::Address(addr) = value
1849            && !self.disable_labels
1850            && let Some(label) = self.labels.get(addr)
1851        {
1852            if self.compact_labels {
1853                return label.clone();
1854            }
1855            return format!("{label}: [{addr}]");
1856        }
1857        format_token(value)
1858    }
1859
1860    fn format_param_value(
1861        &self,
1862        address: Option<Address>,
1863        context_name: &str,
1864        input_name: &str,
1865        input_ty: &str,
1866        value: &DynSolValue,
1867    ) -> String {
1868        self.format_claim_receipt_bytes(address, context_name, input_name, input_ty, value)
1869            .map(|value| self.format_value(&value))
1870            .unwrap_or_else(|| self.format_value(value))
1871    }
1872
1873    fn format_claim_receipt_bytes(
1874        &self,
1875        address: Option<Address>,
1876        context_name: &str,
1877        input_name: &str,
1878        input_ty: &str,
1879        value: &DynSolValue,
1880    ) -> Option<DynSolValue> {
1881        if !matches!(address, Some(RECEIVE_POLICY_GUARD_ADDRESS | TIP403_REGISTRY_ADDRESS)) {
1882            return None;
1883        }
1884        if input_name != "receipt" || input_ty != "bytes" {
1885            return None;
1886        }
1887        if !matches!(context_name, "balanceOf" | "claim" | "burnBlockedReceipt" | "TransferBlocked")
1888        {
1889            return None;
1890        }
1891        let DynSolValue::Bytes(bytes) = value else { return None };
1892        let decoded = IReceivePolicyGuard::ClaimReceiptV1::abi_decode(bytes).ok()?;
1893
1894        Some(DynSolValue::CustomStruct {
1895            name: "ClaimReceiptV1".to_string(),
1896            prop_names: vec![
1897                "version".to_string(),
1898                "token".to_string(),
1899                "recoveryAuthority".to_string(),
1900                "originator".to_string(),
1901                "recipient".to_string(),
1902                "blockedAt".to_string(),
1903                "blockedNonce".to_string(),
1904                "blockedReason".to_string(),
1905                "kind".to_string(),
1906                "memo".to_string(),
1907            ],
1908            tuple: vec![
1909                DynSolValue::Uint(U256::from(decoded.version), 8),
1910                DynSolValue::Address(decoded.token),
1911                DynSolValue::Address(decoded.recoveryAuthority),
1912                DynSolValue::Address(decoded.originator),
1913                DynSolValue::Address(decoded.recipient),
1914                DynSolValue::Uint(U256::from(decoded.blockedAt), 64),
1915                DynSolValue::Uint(U256::from(decoded.blockedNonce), 64),
1916                DynSolValue::Uint(U256::from(decoded.blockedReason), 8),
1917                DynSolValue::Uint(U256::from(decoded.kind as u8), 8),
1918                DynSolValue::FixedBytes(decoded.memo, 32),
1919            ],
1920        })
1921    }
1922}
1923
1924/// Returns `true` if the given function calldata (including function selector) is ABI-encoded.
1925///
1926/// This is a simple heuristic to avoid fetching non ABI-encoded selectors. A trailing ERC-8021
1927/// attribution suffix is ignored.
1928fn is_abi_call_data(data: &[u8]) -> bool {
1929    let data = erc8021::strip_suffix(data);
1930    match data.len().cmp(&SELECTOR_LEN) {
1931        std::cmp::Ordering::Less => false,
1932        std::cmp::Ordering::Equal => true,
1933        std::cmp::Ordering::Greater => {
1934            is_abi_data(&data[SELECTOR_LEN..]) || suffixed_abi_args(data).is_some()
1935        }
1936    }
1937}
1938
1939/// Returns `true` if the given data is ABI-encoded.
1940///
1941/// See [`is_abi_call_data`] for more details.
1942fn is_abi_data(data: &[u8]) -> bool {
1943    let rem = data.len() % 32;
1944    if rem == 0 || data.is_empty() {
1945        return true;
1946    }
1947    // If the length is not a multiple of 32, also accept when the last remainder bytes are all 0.
1948    data[data.len() - rem..].iter().all(|byte| *byte == 0)
1949}
1950
1951/// Returns the word-aligned arguments of the given function calldata if they are followed by a
1952/// non-zero suffix shorter than a word, such as tracking bytes appended by routers. A trailing
1953/// ERC-8021 attribution suffix is removed first.
1954///
1955/// The first argument word must be left-padded like an address, integer, boolean or offset, which
1956/// packed calldata rarely is.
1957fn suffixed_abi_args(data: &[u8]) -> Option<&[u8]> {
1958    let args = erc8021::strip_suffix(data).get(SELECTOR_LEN..)?;
1959    let (args, suffix) = args.split_at(args.len() - args.len() % 32);
1960    (args.starts_with(&[0; 12]) && suffix.iter().any(|byte| *byte != 0)).then_some(args)
1961}
1962
1963/// Returns `true` if `args` is exactly the ABI encoding of the function inputs.
1964fn is_abi_encoded_input(func: &Function, args: &[u8]) -> bool {
1965    func.abi_decode_input(args)
1966        .and_then(|values| func.abi_encode_input_raw(&values))
1967        .is_ok_and(|encoded| encoded == args)
1968}
1969
1970fn indexed_inputs(event: &Event) -> usize {
1971    event.inputs.iter().filter(|param| param.indexed).count()
1972}
1973
1974fn indexed_event_candidates(mut event: Event, log: &LogData) -> impl Iterator<Item = Event> {
1975    for (index, input) in event.inputs.iter_mut().enumerate() {
1976        if input.name.is_empty() {
1977            input.name = format!("param{index}");
1978        }
1979        input.indexed = false;
1980    }
1981    (0..event.inputs.len()).combinations(log.topics().len() - 1).map(move |indexed| {
1982        let mut event = event.clone();
1983        for index in indexed {
1984            event.inputs[index].indexed = true;
1985        }
1986        event
1987    })
1988}
1989
1990fn constructor_signature(constructor: &Constructor) -> String {
1991    format!(
1992        "constructor({})",
1993        constructor.inputs.iter().map(|input| input.selector_type()).format(",")
1994    )
1995}
1996
1997/// Appends `item` unless an equal value is already present, and returns whether it was appended.
1998fn push_unique<T: Clone + PartialEq>(items: &mut Vec<T>, item: Cow<'_, T>) -> bool {
1999    if items.contains(&item) {
2000        false
2001    } else {
2002        items.push(item.into_owned());
2003        true
2004    }
2005}
2006
2007/// Returns the placeholder for the output of a cheatcode that returns secrets, such as
2008/// environment variable values, private keys, or RPC URLs.
2009fn redact_cheatcode_secret_output(func: &Function) -> Option<&'static str> {
2010    match func.name.as_str() {
2011        s if s.starts_with("env") => Some("<env var value>"),
2012        "createEd25519Key" | "createWallet" | "deriveKey" => Some("<pk>"),
2013        "promptSecret" | "promptSecretUint" => Some("<secret>"),
2014        "rpcUrl" | "rpcUrls" | "rpcUrlStructs" => Some("<rpc url>"),
2015        _ => None,
2016    }
2017}
2018
2019#[cfg(test)]
2020mod tests {
2021    use super::*;
2022    use crate::CallKind;
2023    use alloy_primitives::{address, aliases::U96, bytes, hex};
2024    use alloy_sol_types::{SolCall, SolError, SolEvent};
2025    use foundry_evm_core::{abi::Vm, precompiles::P256_VERIFY, tempo::TEMPO_PRECOMPILE_ADDRESSES};
2026    use tempo_contracts::precompiles::{
2027        ACCOUNT_KEYCHAIN_ADDRESS, CONFIGURABLE_ACCOUNT_ADDRESS, IConfigurableAccountShim,
2028        SIGNATURE_VERIFIER_ADDRESS, STORAGE_CREDITS_ADDRESS, TIP_FEE_MANAGER_ADDRESS,
2029        TIP20_CHANNEL_RESERVE_ADDRESS, TIP20_FACTORY_ADDRESS, VALIDATOR_CONFIG_V2_ADDRESS,
2030    };
2031
2032    #[cfg(feature = "base")]
2033    use foundry_evm_hardforks::BaseUpgrade;
2034
2035    #[cfg(feature = "monad")]
2036    use monad_evm2::{
2037        reserve_balance::IReserveBalance::dippedIntoReserveCall,
2038        staking::interface::IMonadStaking::getEpochCall,
2039    };
2040
2041    #[cfg(feature = "monad")]
2042    fn function_abi_items(functions: impl IntoIterator<Item = Function>) -> Vec<(String, String)> {
2043        let mut items = functions
2044            .into_iter()
2045            .map(|function| (function.selector().to_string(), function.signature()))
2046            .collect::<Vec<_>>();
2047        items.sort();
2048        items
2049    }
2050
2051    #[cfg(feature = "monad")]
2052    fn event_abi_items(events: impl IntoIterator<Item = Event>) -> Vec<(String, usize, String)> {
2053        let mut items = events
2054            .into_iter()
2055            .map(|event| (event.selector().to_string(), indexed_inputs(&event), event.signature()))
2056            .collect::<Vec<_>>();
2057        items.sort();
2058        items
2059    }
2060
2061    #[cfg(feature = "monad")]
2062    fn typed_call_abi_item<C: SolCall>() -> (String, String) {
2063        (Selector::from(C::SELECTOR).to_string(), C::SIGNATURE.to_string())
2064    }
2065
2066    #[cfg(feature = "monad")]
2067    fn typed_event_abi_item<E: SolEvent>() -> (String, usize, String) {
2068        let signature_topics = usize::from(!E::ANONYMOUS);
2069        let indexed_inputs = <E::TopicList as alloy_sol_types::TopicList>::COUNT - signature_topics;
2070        (E::SIGNATURE_HASH.to_string(), indexed_inputs, E::SIGNATURE.to_string())
2071    }
2072
2073    #[cfg(feature = "monad")]
2074    fn monad_decoder(hardfork: MonadHardfork) -> CallTraceDecoder {
2075        CallTraceDecoderBuilder::new()
2076            .with_execution_network(NetworkVariant::Monad)
2077            .with_chain_id(Some(143))
2078            .with_hardfork(Some(hardfork.into()))
2079            .build()
2080    }
2081
2082    #[test]
2083    #[cfg(feature = "monad")]
2084    fn test_monad_decoder_abis_match_monad_evm2() {
2085        use monad_evm2::{
2086            reserve_balance::IReserveBalance as CanonicalReserveBalance,
2087            staking::interface::IMonadStaking as CanonicalMonadStaking,
2088        };
2089
2090        let local_staking_functions = monad::IMonadStaking::abi::functions()
2091            .into_values()
2092            .chain(monad::IMonadStakingSyscalls::abi::functions().into_values())
2093            .flatten();
2094        let mut canonical_staking_functions = vec![
2095            typed_call_abi_item::<CanonicalMonadStaking::addValidatorCall>(),
2096            typed_call_abi_item::<CanonicalMonadStaking::delegateCall>(),
2097            typed_call_abi_item::<CanonicalMonadStaking::undelegateCall>(),
2098            typed_call_abi_item::<CanonicalMonadStaking::withdrawCall>(),
2099            typed_call_abi_item::<CanonicalMonadStaking::compoundCall>(),
2100            typed_call_abi_item::<CanonicalMonadStaking::claimRewardsCall>(),
2101            typed_call_abi_item::<CanonicalMonadStaking::changeCommissionCall>(),
2102            typed_call_abi_item::<CanonicalMonadStaking::externalRewardCall>(),
2103            typed_call_abi_item::<CanonicalMonadStaking::getEpochCall>(),
2104            typed_call_abi_item::<CanonicalMonadStaking::getProposerValIdCall>(),
2105            typed_call_abi_item::<CanonicalMonadStaking::getValidatorCall>(),
2106            typed_call_abi_item::<CanonicalMonadStaking::getDelegatorCall>(),
2107            typed_call_abi_item::<CanonicalMonadStaking::getWithdrawalRequestCall>(),
2108            typed_call_abi_item::<CanonicalMonadStaking::getConsensusValidatorSetCall>(),
2109            typed_call_abi_item::<CanonicalMonadStaking::getSnapshotValidatorSetCall>(),
2110            typed_call_abi_item::<CanonicalMonadStaking::getExecutionValidatorSetCall>(),
2111            typed_call_abi_item::<CanonicalMonadStaking::getDelegationsCall>(),
2112            typed_call_abi_item::<CanonicalMonadStaking::getDelegatorsCall>(),
2113            typed_call_abi_item::<CanonicalMonadStaking::syscallOnEpochChangeCall>(),
2114            typed_call_abi_item::<CanonicalMonadStaking::syscallRewardCall>(),
2115            typed_call_abi_item::<CanonicalMonadStaking::syscallSnapshotCall>(),
2116        ];
2117        canonical_staking_functions.sort();
2118        assert_eq!(
2119            function_abi_items(local_staking_functions),
2120            canonical_staking_functions,
2121            "Monad staking function selectors drifted from monad_evm2",
2122        );
2123
2124        let mut canonical_staking_events = vec![
2125            typed_event_abi_item::<CanonicalMonadStaking::ClaimRewards>(),
2126            typed_event_abi_item::<CanonicalMonadStaking::CommissionChanged>(),
2127            typed_event_abi_item::<CanonicalMonadStaking::Delegate>(),
2128            typed_event_abi_item::<CanonicalMonadStaking::EpochChanged>(),
2129            typed_event_abi_item::<CanonicalMonadStaking::Undelegate>(),
2130            typed_event_abi_item::<CanonicalMonadStaking::ValidatorCreated>(),
2131            typed_event_abi_item::<CanonicalMonadStaking::ValidatorRewarded>(),
2132            typed_event_abi_item::<CanonicalMonadStaking::ValidatorStatusChanged>(),
2133            typed_event_abi_item::<CanonicalMonadStaking::Withdraw>(),
2134        ];
2135        canonical_staking_events.sort();
2136        assert_eq!(
2137            event_abi_items(monad::IMonadStaking::abi::events().into_values().flatten()),
2138            canonical_staking_events,
2139            "Monad staking event selectors drifted from monad_evm2",
2140        );
2141
2142        assert_eq!(
2143            function_abi_items(monad::IReserveBalance::abi::functions().into_values().flatten()),
2144            vec![typed_call_abi_item::<CanonicalReserveBalance::dippedIntoReserveCall>()],
2145            "Monad reserve-balance function selectors drifted from monad_evm2",
2146        );
2147
2148        assert_eq!(
2149            event_abi_items(monad::IReserveBalance::abi::events().into_values().flatten()),
2150            Vec::<(String, usize, String)>::new(),
2151            "Monad reserve-balance event selectors drifted from monad_evm2",
2152        );
2153    }
2154
2155    #[tokio::test]
2156    async fn function_signature_matches_full_decoding() {
2157        let address = Address::repeat_byte(0x11);
2158        let fallback = Address::repeat_byte(0x22);
2159        let no_fallback = Address::repeat_byte(0x33);
2160        let scoped = Address::repeat_byte(0x44);
2161        let known_fallback = Address::repeat_byte(0x55);
2162        let mut decoder = CallTraceDecoder::new().clone();
2163        let function = Function::parse("roundTrip(uint256[]) returns (uint256[])").unwrap();
2164        let data = function
2165            .abi_encode_input(&[DynSolValue::Array(vec![DynSolValue::Uint(U256::MAX, 256)])])
2166            .unwrap();
2167        decoder.push_function(function.clone());
2168        decoder.push_address_function(scoped, function.clone());
2169        decoder.fallback_contracts.insert(fallback, HashSet::default());
2170        decoder
2171            .fallback_contracts
2172            .insert(known_fallback, HashSet::from_iter([function.selector()]));
2173        decoder.receive_contracts.insert(fallback);
2174        decoder.non_fallback_contracts.insert(no_fallback, HashSet::default());
2175        decoder
2176            .constructors_by_address
2177            .insert(address, Constructor::parse("constructor()").unwrap());
2178        decoder.constructor_args_offsets.insert(address, 0);
2179
2180        // A global collision still resolves through the existing calldata checks.
2181        let transfer = Function::parse("transferFrom(address,address,uint256)").unwrap();
2182        let collision = Function::parse("gasprice_bit_ether(int128)").unwrap();
2183        assert_eq!(transfer.selector(), collision.selector());
2184        let collision_data =
2185            [collision.selector().as_slice(), B256::with_last_byte(1).as_slice()].concat();
2186        decoder.push_function(transfer.clone());
2187        decoder.push_function(collision);
2188        decoder.push_address_function(scoped, transfer);
2189
2190        for address in [
2191            address,
2192            fallback,
2193            no_fallback,
2194            scoped,
2195            known_fallback,
2196            IDENTITY,
2197            DEFAULT_CREATE2_DEPLOYER,
2198        ] {
2199            for kind in [CallKind::Call, CallKind::DelegateCall, CallKind::Create] {
2200                for success in [true, false] {
2201                    for data in [
2202                        vec![],
2203                        vec![1, 2, 3],
2204                        vec![0xff; SELECTOR_LEN],
2205                        function.selector().to_vec(),
2206                        [function.selector().as_slice(), &[0xff; 32]].concat(),
2207                        data.clone(),
2208                        collision_data.clone(),
2209                    ] {
2210                        let trace = CallTrace {
2211                            address,
2212                            kind,
2213                            success,
2214                            status: (!success).then_some(InstrStop::Revert),
2215                            data: data.into(),
2216                            output: vec![0xff; 64].into(),
2217                            ..Default::default()
2218                        };
2219                        assert_eq!(
2220                            decoder.decode_function_signature(&trace).await,
2221                            decoder
2222                                .decode_function(&trace)
2223                                .await
2224                                .call_data
2225                                .map(|data| data.signature),
2226                            "{address} {kind:?} success={success} calldata={}",
2227                            trace.data,
2228                        );
2229                    }
2230                }
2231            }
2232        }
2233    }
2234
2235    #[test]
2236    fn test_selector_collision_resolution() {
2237        // Create two functions with the same selector but different signatures
2238        let func1 = Function::parse("transferFrom(address,address,uint256)").unwrap();
2239        let func2 = Function::parse("gasprice_bit_ether(int128)").unwrap();
2240
2241        // Verify they have the same selector (this is the collision)
2242        assert_eq!(func1.selector(), func2.selector());
2243
2244        let functions = vec![func1, func2];
2245
2246        // Create a mock trace with calldata that matches func1
2247        let trace = CallTrace {
2248            address: Address::repeat_byte(0x12),
2249            data: bytes!(
2250                "23b872dd000000000000000000000000000000000000000000000000000000000000012300000000000000000000000000000000000000000000000000000000000004560000000000000000000000000000000000000000000000000000000000000064"
2251            ),
2252            ..Default::default()
2253        };
2254
2255        let decoder = CallTraceDecoder::new();
2256        let result = decoder.select_contract_function(&functions, &trace);
2257
2258        // Should return only the function that can decode the calldata (func1)
2259        assert_eq!(result.len(), 1);
2260        assert_eq!(result[0].signature(), "transferFrom(address,address,uint256)");
2261    }
2262
2263    #[test]
2264    fn test_selector_collision_resolution_second_function() {
2265        // Create two functions with the same selector but different signatures
2266        let func1 = Function::parse("transferFrom(address,address,uint256)").unwrap();
2267        let func2 = Function::parse("gasprice_bit_ether(int128)").unwrap();
2268
2269        let functions = vec![func1, func2];
2270
2271        // Create a mock trace with calldata that matches func2
2272        let trace = CallTrace {
2273            address: Address::repeat_byte(0x12),
2274            data: bytes!(
2275                "23b872dd0000000000000000000000000000000000000000000000000000000000000064"
2276            ),
2277            ..Default::default()
2278        };
2279
2280        let decoder = CallTraceDecoder::new();
2281        let result = decoder.select_contract_function(&functions, &trace);
2282
2283        // Should return only the function that can decode the calldata (func2)
2284        assert_eq!(result.len(), 1);
2285        assert_eq!(result[0].signature(), "gasprice_bit_ether(int128)");
2286    }
2287
2288    #[test]
2289    fn test_is_abi_call_data() {
2290        let call_data = |args: &[&[u8]]| [&[0x07, 0xed, 0x23, 0x79][..], &args.concat()].concat();
2291        let address = Address::repeat_byte(0x11);
2292        let word = address.into_word();
2293        let suffix = hex!("2a6f45f2");
2294
2295        assert!(is_abi_call_data(&call_data(&[&word[..]])));
2296        assert!(is_abi_call_data(&call_data(&[&word[..], &[0; 4]])));
2297        assert!(is_abi_call_data(&call_data(&[&word[..], &suffix])));
2298        // Packed arguments and suffixes without a whole ABI-encoded word.
2299        assert!(!is_abi_call_data(&call_data(&[&address[..], &word[..]])));
2300        assert!(!is_abi_call_data(&call_data(&[&suffix])));
2301        // ERC-8021 attribution suffixes are removed exactly, whatever the first word.
2302        let erc8021 = hex!("a161776a6364705f666163696c31000e0280218021802180218021802180218021");
2303        assert!(is_abi_call_data(&call_data(&[&B256::repeat_byte(0x11)[..], &erc8021])));
2304    }
2305
2306    #[tokio::test]
2307    async fn test_decode_call_data_with_suffix() {
2308        let abi = JsonAbi::parse([
2309            "function execute(bytes commands, bytes[] inputs, uint256 deadline)",
2310            "function chargeFee()",
2311        ])
2312        .unwrap();
2313        let identifier = SignaturesIdentifier::new_offline_with_abis([&abi]).unwrap();
2314        let mut decoder =
2315            CallTraceDecoderBuilder::new().with_signature_identifier(identifier).build();
2316        let tag = hex!("756e6978000001a0ee8a61e9800089610000006d0100");
2317        let trace = |data: &[&[u8]]| CallTrace {
2318            address: Address::repeat_byte(0x12),
2319            data: data.concat().into(),
2320            success: true,
2321            ..Default::default()
2322        };
2323
2324        let execute = abi.function("execute").unwrap().first().unwrap();
2325        let data = execute
2326            .abi_encode_input(&[
2327                DynSolValue::Bytes(vec![0x0b]),
2328                DynSolValue::Array(vec![DynSolValue::Bytes(vec![0x01; 3])]),
2329                DynSolValue::Uint(U256::ONE, 256),
2330            ])
2331            .unwrap();
2332        let call_data = decoder.decode_function(&trace(&[&data, &tag])).await.call_data.unwrap();
2333        assert_eq!(call_data.signature, "execute(bytes,bytes[],uint256)");
2334        assert_eq!(call_data.args, ["0x0b", "[0x010101]", "1"]);
2335
2336        // A trailing ERC-8021 attribution suffix of any length is removed before the tag.
2337        let erc8021 = hex!(
2338            "72616e67655f7661756c742c63656c6f5f6533386364643332313061361d0080218021802180218021802180218021"
2339        );
2340        let decoded = decoder.decode_function(&trace(&[&data, &tag, &erc8021])).await;
2341        assert_eq!(decoded.call_data.unwrap().args, call_data.args);
2342
2343        // Packed arguments are not decoded as a function with fewer inputs, including on a known
2344        // contract without a fallback that lacks the selector.
2345        let charge_fee = abi.function("chargeFee").unwrap().first().unwrap();
2346        let word = Address::repeat_byte(0x11).into_word();
2347        let packed = trace(&[&charge_fee.selector()[..], &word[..], &tag]);
2348        assert!(decoder.decode_function(&packed).await.call_data.is_none());
2349        decoder.non_fallback_contracts.insert(packed.address, HashSet::default());
2350        assert!(decoder.decode_function(&packed).await.call_data.is_none());
2351    }
2352
2353    #[cfg(feature = "base")]
2354    #[tokio::test]
2355    async fn base_fallback_does_not_shadow_ethereum_abi() {
2356        let abi = JsonAbi::parse(["function pause(uint8[] features) returns (bool)"]).unwrap();
2357        let function = abi.functions().next().unwrap();
2358        let trace = CallTrace {
2359            address: Address::repeat_byte(0x12),
2360            data: function
2361                .abi_encode_input(&[DynSolValue::Array(vec![DynSolValue::Uint(U256::ZERO, 8)])])
2362                .unwrap()
2363                .into(),
2364            output: function.abi_encode_output(&[DynSolValue::Bool(true)]).unwrap().into(),
2365            success: true,
2366            ..Default::default()
2367        };
2368
2369        let ethereum = CallTraceDecoderBuilder::new()
2370            .with_execution_network(NetworkVariant::Ethereum)
2371            .with_abi(&abi)
2372            .build();
2373        let decoded = ethereum.decode_function(&trace).await;
2374        assert_eq!(decoded.call_data.unwrap().signature, "pause(uint8[])");
2375        assert_eq!(decoded.return_data.as_deref(), Some("true"));
2376
2377        let base =
2378            CallTraceDecoderBuilder::new().with_execution_network(NetworkVariant::Base).build();
2379        let decoded = base.decode_function(&trace).await;
2380        assert_eq!(decoded.call_data.unwrap().signature, "pause(uint8[])");
2381        assert_eq!(decoded.return_data, None);
2382    }
2383
2384    #[tokio::test]
2385    async fn identified_event_does_not_shadow_builtin_metadata() {
2386        let address = Address::repeat_byte(0x12);
2387        let mut decoder = CallTraceDecoder::new().clone();
2388        let abi = JsonAbi::parse(["event log_string(string)"]).unwrap();
2389        decoder.collect_abi(&abi, Some(address), true);
2390
2391        let event = Event::parse("event log_string(string val)").unwrap();
2392        let log = LogData::new_unchecked(
2393            vec![event.selector()],
2394            ("script ran".to_string(),).abi_encode().into(),
2395        );
2396        let decoded = decoder.decode_event_with_address(address, &log).await;
2397
2398        assert_eq!(decoded.name.as_deref(), Some("log_string"));
2399        assert_eq!(decoded.params.unwrap()[0].0, "val");
2400    }
2401
2402    #[tokio::test]
2403    async fn address_scoped_abis_decode_all_registered_events() {
2404        let address = Address::repeat_byte(0x12);
2405        let proxy = JsonAbi::parse(["event ProxyEvent()"]).unwrap();
2406        let implementation = JsonAbi::parse(["event ImplementationEvent()"]).unwrap();
2407        let decoder = CallTraceDecoderBuilder::new()
2408            .with_address_events(address, &implementation)
2409            .with_address_events(address, &proxy)
2410            .build();
2411
2412        for event in proxy.events().chain(implementation.events()) {
2413            let log = LogData::new_unchecked(vec![event.selector()], Default::default());
2414            let decoded = decoder.decode_event_with_address(address, &log).await;
2415            assert_eq!(decoded.name.as_deref(), Some(event.name.as_str()));
2416            assert!(decoder.decode_event_with_address(Address::ZERO, &log).await.name.is_none());
2417        }
2418    }
2419
2420    #[tokio::test]
2421    async fn clearing_addresses_removes_regular_and_anonymous_events() {
2422        let address = Address::repeat_byte(0x12);
2423        let abi = JsonAbi::parse([
2424            "event ScopedValue(uint256 value)",
2425            "event AnonymousValue(uint256 value) anonymous",
2426        ])
2427        .unwrap();
2428        let mut decoder = CallTraceDecoderBuilder::new()
2429            .with_address_events(address, &abi)
2430            .with_address_events(address, &abi)
2431            .build();
2432        let global = Event::parse("event GlobalValue()").unwrap();
2433        let global_log = LogData::new_unchecked(vec![global.selector()], Default::default());
2434        decoder.push_event(global);
2435
2436        for event in abi.events() {
2437            let topics = if event.anonymous { vec![] } else { vec![event.selector()] };
2438            let log = LogData::new_unchecked(topics, (U256::from(7),).abi_encode().into());
2439            assert_eq!(
2440                decoder.decode_event_with_address(address, &log).await.name.as_deref(),
2441                Some(event.name.as_str())
2442            );
2443
2444            let mut cleared = decoder.clone();
2445            cleared.clear_addresses();
2446            assert!(cleared.decode_event_with_address(address, &log).await.name.is_none());
2447            assert_eq!(
2448                cleared.decode_event(&global_log).await.name.as_deref(),
2449                Some("GlobalValue")
2450            );
2451        }
2452    }
2453
2454    #[tokio::test]
2455    async fn canonical_address_events_require_a_unique_match() {
2456        let address = Address::repeat_byte(0x12);
2457        let implementation =
2458            JsonAbi::parse(["event Value(address indexed who, uint256 amount)"]).unwrap();
2459        let proxy = JsonAbi::parse(["event Value(address who, uint256 indexed amount)"]).unwrap();
2460        let event = proxy.events().next().unwrap();
2461        let log = LogData::new_unchecked(
2462            vec![event.selector(), U256::from(42).into()],
2463            (Address::repeat_byte(0x34),).abi_encode().into(),
2464        );
2465        let decoder = CallTraceDecoderBuilder::new()
2466            .with_address_events(address, &implementation)
2467            .with_address_events(address, &proxy)
2468            .build();
2469
2470        let decoded = decoder.decode_event_with_address_signature(address, &log).await;
2471        assert!(decoded.name.is_none());
2472        assert!(decoded.params.is_none());
2473    }
2474
2475    #[tokio::test]
2476    async fn canonical_global_events_require_a_unique_indexed_placement() {
2477        let known = Event::parse(
2478            "event AmbiguousLayout(address indexed from, address indexed to, uint256 amount)",
2479        )
2480        .unwrap();
2481        let emitted = Event::parse(
2482            "event AmbiguousLayout(address from, address indexed to, uint256 indexed amount)",
2483        )
2484        .unwrap();
2485        assert_eq!(known.selector(), emitted.selector());
2486
2487        let address = Address::repeat_byte(0x12);
2488        let from = Address::repeat_byte(0x34);
2489        let to = Address::repeat_byte(0x56);
2490        let amount = U256::from(42);
2491        let log = LogData::new_unchecked(
2492            vec![emitted.selector(), to.into_word(), amount.into()],
2493            (from,).abi_encode().into(),
2494        );
2495        let mut decoder = CallTraceDecoder::new().clone();
2496        decoder.push_event(known);
2497
2498        let decoded = decoder.decode_event_with_address_signature(address, &log).await;
2499        assert!(decoded.name.is_none());
2500        assert!(decoded.params.is_none());
2501
2502        decoder.push_address_event(address, emitted);
2503        let decoded = decoder.decode_event_with_address_signature(address, &log).await;
2504        assert_eq!(decoded.name.as_deref(), Some("AmbiguousLayout(address,address,uint256)"));
2505        let params = decoded.params.unwrap();
2506        assert_eq!(params[0].2, DynSolValue::Address(from));
2507        assert_eq!(params[1].2, DynSolValue::Address(to));
2508        assert_eq!(params[2].2, DynSolValue::Uint(amount, 256));
2509    }
2510
2511    #[tokio::test]
2512    async fn identified_events_preserve_legacy_indexed_placement_for_traces() {
2513        let event = Event::parse(
2514            "event DecoderAmbiguousIndexedPlacement(address indexed owner, uint256 id)",
2515        )
2516        .unwrap();
2517        let mut abi = JsonAbi::new();
2518        abi.events.insert(event.name.clone(), vec![event.clone()]);
2519        let log = LogData::new_unchecked(
2520            vec![event.selector(), U256::from(42).into()],
2521            (Address::repeat_byte(0x34),).abi_encode().into(),
2522        );
2523        let identifier = SignaturesIdentifier::new_offline_with_abis([&abi]).unwrap();
2524        let decoder = CallTraceDecoderBuilder::new().with_signature_identifier(identifier).build();
2525
2526        let decoded = decoder.decode_event(&log).await;
2527        assert_eq!(decoded.name.as_deref(), Some("DecoderAmbiguousIndexedPlacement"));
2528
2529        let decoded = decoder.decode_event_with_address_signature(Address::ZERO, &log).await;
2530        assert!(decoded.name.is_none());
2531        assert!(decoded.params.is_none());
2532    }
2533
2534    #[tokio::test]
2535    async fn address_scoped_anonymous_events_require_a_unique_match() {
2536        let address = Address::repeat_byte(0x12);
2537        let abi = JsonAbi::parse(["event AnonymousValue(uint256 value) anonymous"]).unwrap();
2538        let log = LogData::new_unchecked(Vec::new(), (U256::from(7),).abi_encode().into());
2539        let decoded = CallTraceDecoderBuilder::new()
2540            .with_address_events(address, &abi)
2541            .build()
2542            .decode_event_with_address(address, &log)
2543            .await;
2544        assert_eq!(decoded.name.as_deref(), Some("AnonymousValue"));
2545
2546        let abi = JsonAbi::parse([
2547            "event AnonymousValue(uint256 value) anonymous",
2548            "event AnonymousAmount(uint256 amount) anonymous",
2549        ])
2550        .unwrap();
2551        let decoder = CallTraceDecoderBuilder::new().with_address_events(address, &abi).build();
2552
2553        let decoded = decoder.decode_event_with_address(address, &log).await;
2554
2555        assert!(decoded.name.is_none());
2556        assert!(decoded.params.is_none());
2557
2558        let abi = JsonAbi::parse([
2559            "event RegularValue(uint256 value)",
2560            "event AnonymousValue(uint256 indexed value) anonymous",
2561        ])
2562        .unwrap();
2563        let regular = abi.events().find(|event| !event.anonymous).unwrap();
2564        let log = LogData::new_unchecked(vec![regular.selector()], Default::default());
2565        let decoded = CallTraceDecoderBuilder::new()
2566            .with_address_events(address, &abi)
2567            .build()
2568            .decode_event_with_address_signature(address, &log)
2569            .await;
2570        assert_eq!(decoded.name.as_deref(), Some("AnonymousValue(uint256)"));
2571
2572        let abi = JsonAbi::parse([
2573            "event RegularValue()",
2574            "event AnonymousValue(bytes32 indexed value) anonymous",
2575        ])
2576        .unwrap();
2577        let regular = abi.events().find(|event| !event.anonymous).unwrap();
2578        let log = LogData::new_unchecked(vec![regular.selector()], Default::default());
2579        let decoder = CallTraceDecoderBuilder::new().with_address_events(address, &abi).build();
2580        let decoded = decoder.decode_event_with_address_signature(address, &log).await;
2581        assert!(decoded.name.is_none());
2582        assert!(decoded.params.is_none());
2583        let decoded = decoder.decode_event_with_address(address, &log).await;
2584        assert!(decoded.name.is_none());
2585        assert!(decoded.params.is_none());
2586    }
2587
2588    #[test]
2589    fn compact_labels_hide_address_in_trace_parameters() {
2590        let address = Address::with_last_byte(1);
2591        let value = DynSolValue::Address(address);
2592        let tracing = TracingConfig {
2593            labels: AddressHashMap::from_iter([(address, "Alice".to_string())]),
2594            ..Default::default()
2595        };
2596        let decoder = CallTraceDecoderBuilder::new().with_tracing_config(&tracing).build();
2597        assert_eq!(decoder.format_value(&value), format!("Alice: [{address}]"));
2598
2599        let tracing = TracingConfig { compact_labels: true, ..tracing };
2600        let decoder = CallTraceDecoderBuilder::new().with_tracing_config(&tracing).build();
2601        assert_eq!(decoder.format_value(&value), "Alice");
2602
2603        let tracing = TracingConfig { disable_labels: true, ..tracing };
2604        let decoder = CallTraceDecoderBuilder::new().with_tracing_config(&tracing).build();
2605        assert_eq!(decoder.format_value(&value), address.to_string());
2606    }
2607
2608    #[test]
2609    fn configured_labels_survive_address_reset() {
2610        let configured = address!("0x0000000000000000000000000000000000000100");
2611        let discovered = address!("0x0000000000000000000000000000000000000200");
2612        let tracing = TracingConfig {
2613            labels: AddressHashMap::from_iter([(configured, "configured".to_string())]),
2614            ..Default::default()
2615        };
2616        let mut decoder = CallTraceDecoderBuilder::new().with_tracing_config(&tracing).build();
2617        decoder.labels.insert(discovered, "discovered".to_string());
2618
2619        decoder.clear_addresses();
2620
2621        assert_eq!(decoder.labels.get(&configured).map(String::as_str), Some("configured"));
2622        assert!(!decoder.labels.contains_key(&discovered));
2623    }
2624
2625    #[tokio::test]
2626    async fn test_decode_constructor_input() {
2627        let address = Address::repeat_byte(0x12);
2628        let constructor = Constructor::parse("constructor(uint256 amount, address owner)").unwrap();
2629        let args = constructor
2630            .abi_encode_input(&[
2631                DynSolValue::Uint(U256::from(42), 256),
2632                DynSolValue::Address(Address::repeat_byte(0x34)),
2633            ])
2634            .unwrap();
2635        let mut data = vec![0x60, 0x80, 0x60, 0x40];
2636        let offset = data.len();
2637        data.extend_from_slice(&args);
2638        let trace = CallTrace {
2639            address,
2640            kind: crate::CallKind::Create,
2641            data: data.into(),
2642            ..Default::default()
2643        };
2644        let mut decoder = CallTraceDecoder::new().clone();
2645        decoder.constructors_by_address.insert(address, constructor);
2646        decoder.constructor_args_offsets.insert(address, offset);
2647
2648        let decoded = decoder.decode_function(&trace).await;
2649        let call_data = decoded.call_data.expect("constructor input should decode");
2650
2651        assert_eq!(call_data.signature, "constructor(uint256,address)");
2652        assert_eq!(call_data.args[0], "42");
2653        assert_eq!(call_data.args[1], format!("{}", Address::repeat_byte(0x34)));
2654    }
2655
2656    #[test]
2657    fn test_should_redact() {
2658        let mut decoder = CallTraceDecoder::new().clone();
2659        decoder.labels.insert(Address::repeat_byte(0x22), "signer".to_string());
2660
2661        let expected_revert_bytes4 = vec![0xde, 0xad, 0xbe, 0xef];
2662        let expect_revert_bytes4_data = Function::parse("expectRevert(bytes4)")
2663            .unwrap()
2664            .abi_encode_input(&[DynSolValue::FixedBytes(
2665                B256::right_padding_from(expected_revert_bytes4.as_slice()),
2666                4,
2667            )])
2668            .unwrap();
2669
2670        let expected_revert_bytes = hex!(
2671            "08c379a000000000000000000000000000000000000000000000000000000000\
2672             0000002000000000000000000000000000000000000000000000000000000000\
2673             00000004626f6f6d000000000000000000000000000000000000000000000000"
2674        )
2675        .to_vec();
2676        let expect_revert_bytes_data = Function::parse("expectRevert(bytes)")
2677            .unwrap()
2678            .abi_encode_input(&[DynSolValue::Bytes(expected_revert_bytes.clone())])
2679            .unwrap();
2680
2681        let reverter = Address::repeat_byte(0x11);
2682        let expect_revert_bytes4_address_data = Function::parse("expectRevert(bytes4,address)")
2683            .unwrap()
2684            .abi_encode_input(&[
2685                DynSolValue::FixedBytes(
2686                    B256::right_padding_from(expected_revert_bytes4.as_slice()),
2687                    4,
2688                ),
2689                DynSolValue::Address(reverter),
2690            ])
2691            .unwrap();
2692
2693        let count = 42_u64;
2694        let expect_revert_bytes_count_data = Function::parse("expectRevert(bytes,uint64)")
2695            .unwrap()
2696            .abi_encode_input(&[
2697                DynSolValue::Bytes(expected_revert_bytes.clone()),
2698                DynSolValue::Uint(alloy_primitives::U256::from(count), 64),
2699            ])
2700            .unwrap();
2701
2702        let expect_revert_bytes_address_count_data =
2703            Function::parse("expectRevert(bytes,address,uint64)")
2704                .unwrap()
2705                .abi_encode_input(&[
2706                    DynSolValue::Bytes(expected_revert_bytes.clone()),
2707                    DynSolValue::Address(reverter),
2708                    DynSolValue::Uint(alloy_primitives::U256::from(count), 64),
2709                ])
2710                .unwrap();
2711
2712        let expect_revert_runtime_data = expected_revert_bytes4.clone();
2713
2714        // [function_signature, data, expected]
2715        let cheatcode_input_test_cases = vec![
2716            // Should decode the expected revert payload, not full cheatcode calldata:
2717            (
2718                "expectRevert(bytes4)",
2719                expect_revert_bytes4_data,
2720                Some(vec![decoder.revert_decoder.decode(expected_revert_bytes4.as_slice(), None)]),
2721            ),
2722            (
2723                "expectRevert(bytes)",
2724                expect_revert_bytes_data,
2725                Some(vec![decoder.revert_decoder.decode(expected_revert_bytes.as_slice(), None)]),
2726            ),
2727            (
2728                "expectRevert(bytes4)",
2729                expect_revert_runtime_data.clone(),
2730                Some(vec![
2731                    decoder.revert_decoder.decode(expect_revert_runtime_data.as_slice(), None),
2732                ]),
2733            ),
2734            (
2735                "expectRevert(bytes4,address)",
2736                expect_revert_bytes4_address_data,
2737                Some(vec![
2738                    decoder.revert_decoder.decode(expected_revert_bytes4.as_slice(), None),
2739                    decoder.format_value(&DynSolValue::Address(reverter)),
2740                ]),
2741            ),
2742            (
2743                "expectRevert(bytes,uint64)",
2744                expect_revert_bytes_count_data,
2745                Some(vec![
2746                    decoder.revert_decoder.decode(expected_revert_bytes.as_slice(), None),
2747                    decoder
2748                        .format_value(&DynSolValue::Uint(alloy_primitives::U256::from(count), 64)),
2749                ]),
2750            ),
2751            (
2752                "expectRevert(bytes,address,uint64)",
2753                expect_revert_bytes_address_count_data,
2754                Some(vec![
2755                    decoder.revert_decoder.decode(expected_revert_bytes.as_slice(), None),
2756                    decoder.format_value(&DynSolValue::Address(reverter)),
2757                    decoder
2758                        .format_value(&DynSolValue::Uint(alloy_primitives::U256::from(count), 64)),
2759                ]),
2760            ),
2761            (
2762                "expectRevert()",
2763                expect_revert_runtime_data.clone(),
2764                Some(vec![
2765                    decoder.revert_decoder.decode(expect_revert_runtime_data.as_slice(), None),
2766                ]),
2767            ),
2768            // Should redact private key from traces in all cases:
2769            ("addr(uint256)", vec![], Some(vec!["<pk>".to_string()])),
2770            ("createEd25519Key(bytes32)", vec![], Some(vec!["<pk>".to_string()])),
2771            ("createWallet(string)", vec![], Some(vec!["<pk>".to_string()])),
2772            ("createWallet(uint256)", vec![], Some(vec!["<pk>".to_string()])),
2773            ("deriveKey(string,uint32)", vec![], Some(vec!["<pk>".to_string()])),
2774            ("deriveKey(string,string,uint32)", vec![], Some(vec!["<pk>".to_string()])),
2775            ("deriveKey(string,uint32,string)", vec![], Some(vec!["<pk>".to_string()])),
2776            ("deriveKey(string,string,uint32,string)", vec![], Some(vec!["<pk>".to_string()])),
2777            ("publicKeyEd25519(bytes32)", vec![], Some(vec!["<pk>".to_string()])),
2778            ("publicKeyP256(uint256)", vec![], Some(vec!["<pk>".to_string()])),
2779            ("rememberKey(uint256)", vec![], Some(vec!["<pk>".to_string()])),
2780            ("rememberKeys(string,string,uint32)", vec![], Some(vec!["<pk>".to_string()])),
2781            ("rememberKeys(string,string,string,uint32)", vec![], Some(vec!["<pk>".to_string()])),
2782            //
2783            // Should redact private key from traces in specific cases with exceptions:
2784            ("broadcast(uint256)", vec![], Some(vec!["<pk>".to_string()])),
2785            ("broadcast()", vec![], None), // Ignore: `private key` is not passed.
2786            ("startBroadcast(uint256)", vec![], Some(vec!["<pk>".to_string()])),
2787            ("startBroadcast()", vec![], None), // Ignore: `private key` is not passed.
2788            ("getNonce((address,uint256,uint256,uint256))", vec![], Some(vec!["<pk>".to_string()])),
2789            ("getNonce(address)", vec![], None), // Ignore: `address` is public.
2790            //
2791            // Should redact private key and replace in trace in cases:
2792            (
2793                "sign(uint256,bytes32)",
2794                hex!(
2795                    "
2796                    e341eaa4
2797                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
2798                    0000000000000000000000000000000000000000000000000000000000000000
2799                "
2800                )
2801                .to_vec(),
2802                Some(vec![
2803                    "\"<pk>\"".to_string(),
2804                    "0x0000000000000000000000000000000000000000000000000000000000000000"
2805                        .to_string(),
2806                ]),
2807            ),
2808            (
2809                "signP256(uint256,bytes32)",
2810                hex!(
2811                    "
2812                    83211b40
2813                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
2814                    0000000000000000000000000000000000000000000000000000000000000000
2815                "
2816                )
2817                .to_vec(),
2818                Some(vec![
2819                    "\"<pk>\"".to_string(),
2820                    "0x0000000000000000000000000000000000000000000000000000000000000000"
2821                        .to_string(),
2822                ]),
2823            ),
2824            (
2825                "signCompact(uint256,bytes32)",
2826                hex!(
2827                    "
2828                    cc2a781f
2829                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
2830                    0000000000000000000000000000000000000000000000000000000000000000
2831                "
2832                )
2833                .to_vec(),
2834                Some(vec![
2835                    "\"<pk>\"".to_string(),
2836                    "0x0000000000000000000000000000000000000000000000000000000000000000"
2837                        .to_string(),
2838                ]),
2839            ),
2840            (
2841                // signCompact(Wallet,bytes32)
2842                "signCompact((address,uint256,uint256,uint256),bytes32)",
2843                hex!(
2844                    "
2845                    3d0e292f
2846                    0000000000000000000000001111111111111111111111111111111111111111
2847                    0000000000000000000000000000000000000000000000000000000000000001
2848                    0000000000000000000000000000000000000000000000000000000000000002
2849                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
2850                    0000000000000000000000000000000000000000000000000000000000000000
2851                "
2852                )
2853                .to_vec(),
2854                Some(vec![
2855                    "\"<pk>\"".to_string(),
2856                    "0x0000000000000000000000000000000000000000000000000000000000000000"
2857                        .to_string(),
2858                ]),
2859            ),
2860            (
2861                // Ignore: `private key` is not passed, digest is signed by the script signer.
2862                "signCompact(bytes32)",
2863                hex!(
2864                    "
2865                    a282dc4b
2866                    0000000000000000000000000000000000000000000000000000000000000000
2867                "
2868                )
2869                .to_vec(),
2870                Some(vec![
2871                    "0x0000000000000000000000000000000000000000000000000000000000000000"
2872                        .to_string(),
2873                ]),
2874            ),
2875            (
2876                // Ignore: `signer` is a public address.
2877                "signCompact(address,bytes32)",
2878                hex!(
2879                    "
2880                    8e2f97bf
2881                    0000000000000000000000001111111111111111111111111111111111111111
2882                    0000000000000000000000000000000000000000000000000000000000000000
2883                "
2884                )
2885                .to_vec(),
2886                Some(vec![
2887                    "0x1111111111111111111111111111111111111111".to_string(),
2888                    "0x0000000000000000000000000000000000000000000000000000000000000000"
2889                        .to_string(),
2890                ]),
2891            ),
2892            (
2893                "signWithNonceUnsafe(uint256,bytes32,uint256)",
2894                hex!(
2895                    "
2896                    2012783a
2897                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
2898                    0000000000000000000000000000000000000000000000000000000000000000
2899                    0000000000000000000000000000000000000000000000000000000000000001
2900                "
2901                )
2902                .to_vec(),
2903                Some(vec![
2904                    "\"<pk>\"".to_string(),
2905                    "0x0000000000000000000000000000000000000000000000000000000000000000"
2906                        .to_string(),
2907                    "\"<nonce>\"".to_string(),
2908                ]),
2909            ),
2910            (
2911                "signKeychain(uint256,address,bytes32)",
2912                hex!(
2913                    "
2914                    5804c690
2915                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
2916                    0000000000000000000000001111111111111111111111111111111111111111
2917                    0000000000000000000000000000000000000000000000000000000000000000
2918                "
2919                )
2920                .to_vec(),
2921                Some(vec![
2922                    "\"<pk>\"".to_string(),
2923                    "0x1111111111111111111111111111111111111111".to_string(),
2924                    "0x0000000000000000000000000000000000000000000000000000000000000000"
2925                        .to_string(),
2926                ]),
2927            ),
2928            (
2929                "signKeychainAdmin(uint256,address,bytes32)",
2930                hex!(
2931                    "
2932                    bc5fb2f7
2933                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
2934                    0000000000000000000000001111111111111111111111111111111111111111
2935                    0000000000000000000000000000000000000000000000000000000000000000
2936                "
2937                )
2938                .to_vec(),
2939                Some(vec![
2940                    "\"<pk>\"".to_string(),
2941                    "0x1111111111111111111111111111111111111111".to_string(),
2942                    "0x0000000000000000000000000000000000000000000000000000000000000000"
2943                        .to_string(),
2944                ]),
2945            ),
2946            (
2947                // Owner key lists are redacted as a whole.
2948                "signConfigurableAccount(uint256[],address,(bytes32,uint64,uint8,(address,uint8)[]),bytes32)",
2949                hex!(
2950                    "
2951                    9f493d1c
2952                    0000000000000000000000000000000000000000000000000000000000000080
2953                    0000000000000000000000002222222222222222222222222222222222222222
2954                    00000000000000000000000000000000000000000000000000000000000000c0
2955                    0000000000000000000000000000000000000000000000000000000000000000
2956                    0000000000000000000000000000000000000000000000000000000000000001
2957                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
2958                    000000000000000000000000000000000000000000000000000000000000005a
2959                    0000000000000000000000000000000000000000000000000000000000000000
2960                    0000000000000000000000000000000000000000000000000000000000000001
2961                    0000000000000000000000000000000000000000000000000000000000000080
2962                    0000000000000000000000000000000000000000000000000000000000000001
2963                    0000000000000000000000001111111111111111111111111111111111111111
2964                    0000000000000000000000000000000000000000000000000000000000000001
2965                "
2966                )
2967                .to_vec(),
2968                Some(vec![
2969                    "\"<pk>\"".to_string(),
2970                    "signer: [0x2222222222222222222222222222222222222222]".to_string(),
2971                    "(0x000000000000000000000000000000000000000000000000000000000000005a, 0, 1, [(0x1111111111111111111111111111111111111111, 1)])".to_string(),
2972                    "0x0000000000000000000000000000000000000000000000000000000000000000".to_string(),
2973                ]),
2974            ),
2975            (
2976                "signKeychainConfigurableAccount((uint8,uint256)[],address,(bytes32,uint64,uint8,(address,uint8)[]),address,bytes32)",
2977                hex!(
2978                    "
2979                    b6468902
2980                    00000000000000000000000000000000000000000000000000000000000000a0
2981                    0000000000000000000000002222222222222222222222222222222222222222
2982                    0000000000000000000000000000000000000000000000000000000000000100
2983                    0000000000000000000000003333333333333333333333333333333333333333
2984                    0000000000000000000000000000000000000000000000000000000000000000
2985                    0000000000000000000000000000000000000000000000000000000000000001
2986                    0000000000000000000000000000000000000000000000000000000000000002
2987                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
2988                    000000000000000000000000000000000000000000000000000000000000005a
2989                    0000000000000000000000000000000000000000000000000000000000000000
2990                    0000000000000000000000000000000000000000000000000000000000000001
2991                    0000000000000000000000000000000000000000000000000000000000000080
2992                    0000000000000000000000000000000000000000000000000000000000000001
2993                    0000000000000000000000001111111111111111111111111111111111111111
2994                    0000000000000000000000000000000000000000000000000000000000000001
2995                "
2996                )
2997                .to_vec(),
2998                Some(vec![
2999                    "\"<pk>\"".to_string(),
3000                    "signer: [0x2222222222222222222222222222222222222222]".to_string(),
3001                    "(0x000000000000000000000000000000000000000000000000000000000000005a, 0, 1, [(0x1111111111111111111111111111111111111111, 1)])".to_string(),
3002                    "0x3333333333333333333333333333333333333333".to_string(),
3003                    "0x0000000000000000000000000000000000000000000000000000000000000000".to_string(),
3004                ]),
3005            ),
3006            (
3007                // Labels are applied to address arguments while the key is redacted.
3008                "signKeychain(uint256,address,bytes32)",
3009                hex!(
3010                    "
3011                    5804c690
3012                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
3013                    0000000000000000000000002222222222222222222222222222222222222222
3014                    0000000000000000000000000000000000000000000000000000000000000000
3015                "
3016                )
3017                .to_vec(),
3018                Some(vec![
3019                    "\"<pk>\"".to_string(),
3020                    "signer: [0x2222222222222222222222222222222222222222]".to_string(),
3021                    "0x0000000000000000000000000000000000000000000000000000000000000000"
3022                        .to_string(),
3023                ]),
3024            ),
3025            (
3026                // cast calldata "signEd25519(bytes,bytes,bytes32)" "0x6e73" "0x6d7367"
3027                // 0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
3028                "signEd25519(bytes,bytes,bytes32)",
3029                hex!(
3030                    "
3031                    ef609c65
3032                    0000000000000000000000000000000000000000000000000000000000000060
3033                    00000000000000000000000000000000000000000000000000000000000000a0
3034                    7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6
3035                    0000000000000000000000000000000000000000000000000000000000000002
3036                    6e73000000000000000000000000000000000000000000000000000000000000
3037                    0000000000000000000000000000000000000000000000000000000000000003
3038                    6d73670000000000000000000000000000000000000000000000000000000000
3039                "
3040                )
3041                .to_vec(),
3042                Some(vec!["0x6e73".to_string(), "0x6d7367".to_string(), "\"<pk>\"".to_string()]),
3043            ),
3044            (
3045                // cast calldata "createFork(string)" "https://eth-mainnet.g.alchemy.com/v2/api_key"
3046                "createFork(string)",
3047                hex!(
3048                    "
3049                    31ba3498
3050                    0000000000000000000000000000000000000000000000000000000000000020
3051                    000000000000000000000000000000000000000000000000000000000000002c
3052                    68747470733a2f2f6574682d6d61696e6e65742e672e616c6368656d792e636f
3053                    6d2f76322f6170695f6b65790000000000000000000000000000000000000000
3054                    "
3055                )
3056                .to_vec(),
3057                Some(vec!["\"<rpc url>\"".to_string()]),
3058            ),
3059            (
3060                // cast calldata "createFork(string)" "wss://eth-mainnet.g.alchemy.com/v2/api_key"
3061                "createFork(string)",
3062                hex!(
3063                    "
3064                    31ba3498
3065                    0000000000000000000000000000000000000000000000000000000000000020
3066                    000000000000000000000000000000000000000000000000000000000000002a
3067                    7773733a2f2f6574682d6d61696e6e65742e672e616c6368656d792e636f6d2f
3068                    76322f6170695f6b657900000000000000000000000000000000000000000000
3069                    "
3070                )
3071                .to_vec(),
3072                Some(vec!["\"<rpc url>\"".to_string()]),
3073            ),
3074            (
3075                // cast calldata "createFork(string)" "mainnet"
3076                "createFork(string)",
3077                hex!(
3078                    "
3079                    31ba3498
3080                    0000000000000000000000000000000000000000000000000000000000000020
3081                    0000000000000000000000000000000000000000000000000000000000000007
3082                    6d61696e6e657400000000000000000000000000000000000000000000000000
3083                    "
3084                )
3085                .to_vec(),
3086                Some(vec!["\"mainnet\"".to_string()]),
3087            ),
3088            (
3089                // cast calldata "createFork(string,uint256)" "https://eth-mainnet.g.alchemy.com/v2/api_key" 1
3090                "createFork(string,uint256)",
3091                hex!(
3092                    "
3093                    6ba3ba2b
3094                    0000000000000000000000000000000000000000000000000000000000000040
3095                    0000000000000000000000000000000000000000000000000000000000000001
3096                    000000000000000000000000000000000000000000000000000000000000002c
3097                    68747470733a2f2f6574682d6d61696e6e65742e672e616c6368656d792e636f
3098                    6d2f76322f6170695f6b65790000000000000000000000000000000000000000
3099                "
3100                )
3101                .to_vec(),
3102                Some(vec!["\"<rpc url>\"".to_string(), "1".to_string()]),
3103            ),
3104            (
3105                // cast calldata "createFork(string,uint256)" "mainnet" 1
3106                "createFork(string,uint256)",
3107                hex!(
3108                    "
3109                    6ba3ba2b
3110                    0000000000000000000000000000000000000000000000000000000000000040
3111                    0000000000000000000000000000000000000000000000000000000000000001
3112                    0000000000000000000000000000000000000000000000000000000000000007
3113                    6d61696e6e657400000000000000000000000000000000000000000000000000
3114                "
3115                )
3116                .to_vec(),
3117                Some(vec!["\"mainnet\"".to_string(), "1".to_string()]),
3118            ),
3119            (
3120                // cast calldata "createFork(string,bytes32)" "https://eth-mainnet.g.alchemy.com/v2/api_key" 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
3121                "createFork(string,bytes32)",
3122                hex!(
3123                    "
3124                    7ca29682
3125                    0000000000000000000000000000000000000000000000000000000000000040
3126                    ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
3127                    000000000000000000000000000000000000000000000000000000000000002c
3128                    68747470733a2f2f6574682d6d61696e6e65742e672e616c6368656d792e636f
3129                    6d2f76322f6170695f6b65790000000000000000000000000000000000000000
3130                "
3131                )
3132                .to_vec(),
3133                Some(vec![
3134                    "\"<rpc url>\"".to_string(),
3135                    "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
3136                        .to_string(),
3137                ]),
3138            ),
3139            (
3140                // cast calldata "createFork(string,bytes32)" "mainnet"
3141                // 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
3142                "createFork(string,bytes32)",
3143                hex!(
3144                    "
3145                    7ca29682
3146                    0000000000000000000000000000000000000000000000000000000000000040
3147                    ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
3148                    0000000000000000000000000000000000000000000000000000000000000007
3149                    6d61696e6e657400000000000000000000000000000000000000000000000000
3150                "
3151                )
3152                .to_vec(),
3153                Some(vec![
3154                    "\"mainnet\"".to_string(),
3155                    "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
3156                        .to_string(),
3157                ]),
3158            ),
3159            (
3160                // cast calldata "createSelectFork(string)" "https://eth-mainnet.g.alchemy.com/v2/api_key"
3161                "createSelectFork(string)",
3162                hex!(
3163                    "
3164                    98680034
3165                    0000000000000000000000000000000000000000000000000000000000000020
3166                    000000000000000000000000000000000000000000000000000000000000002c
3167                    68747470733a2f2f6574682d6d61696e6e65742e672e616c6368656d792e636f
3168                    6d2f76322f6170695f6b65790000000000000000000000000000000000000000
3169                    "
3170                )
3171                .to_vec(),
3172                Some(vec!["\"<rpc url>\"".to_string()]),
3173            ),
3174            (
3175                // cast calldata "createSelectFork(string)" "mainnet"
3176                "createSelectFork(string)",
3177                hex!(
3178                    "
3179                    98680034
3180                    0000000000000000000000000000000000000000000000000000000000000020
3181                    0000000000000000000000000000000000000000000000000000000000000007
3182                    6d61696e6e657400000000000000000000000000000000000000000000000000
3183                    "
3184                )
3185                .to_vec(),
3186                Some(vec!["\"mainnet\"".to_string()]),
3187            ),
3188            (
3189                // cast calldata "createSelectFork(string,uint256)" "https://eth-mainnet.g.alchemy.com/v2/api_key" 1
3190                "createSelectFork(string,uint256)",
3191                hex!(
3192                    "
3193                    71ee464d
3194                    0000000000000000000000000000000000000000000000000000000000000040
3195                    0000000000000000000000000000000000000000000000000000000000000001
3196                    000000000000000000000000000000000000000000000000000000000000002c
3197                    68747470733a2f2f6574682d6d61696e6e65742e672e616c6368656d792e636f
3198                    6d2f76322f6170695f6b65790000000000000000000000000000000000000000
3199                "
3200                )
3201                .to_vec(),
3202                Some(vec!["\"<rpc url>\"".to_string(), "1".to_string()]),
3203            ),
3204            (
3205                // cast calldata "createSelectFork(string,uint256)" "mainnet" 1
3206                "createSelectFork(string,uint256)",
3207                hex!(
3208                    "
3209                    71ee464d
3210                    0000000000000000000000000000000000000000000000000000000000000040
3211                    0000000000000000000000000000000000000000000000000000000000000001
3212                    0000000000000000000000000000000000000000000000000000000000000007
3213                    6d61696e6e657400000000000000000000000000000000000000000000000000
3214                "
3215                )
3216                .to_vec(),
3217                Some(vec!["\"mainnet\"".to_string(), "1".to_string()]),
3218            ),
3219            (
3220                // cast calldata "createSelectFork(string,bytes32)" "https://eth-mainnet.g.alchemy.com/v2/api_key" 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
3221                "createSelectFork(string,bytes32)",
3222                hex!(
3223                    "
3224                    84d52b7a
3225                    0000000000000000000000000000000000000000000000000000000000000040
3226                    ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
3227                    000000000000000000000000000000000000000000000000000000000000002c
3228                    68747470733a2f2f6574682d6d61696e6e65742e672e616c6368656d792e636f
3229                    6d2f76322f6170695f6b65790000000000000000000000000000000000000000
3230                "
3231                )
3232                .to_vec(),
3233                Some(vec![
3234                    "\"<rpc url>\"".to_string(),
3235                    "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
3236                        .to_string(),
3237                ]),
3238            ),
3239            (
3240                // cast calldata "createSelectFork(string,bytes32)" "mainnet"
3241                // 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
3242                "createSelectFork(string,bytes32)",
3243                hex!(
3244                    "
3245                    84d52b7a
3246                    0000000000000000000000000000000000000000000000000000000000000040
3247                    ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
3248                    0000000000000000000000000000000000000000000000000000000000000007
3249                    6d61696e6e657400000000000000000000000000000000000000000000000000
3250                "
3251                )
3252                .to_vec(),
3253                Some(vec![
3254                    "\"mainnet\"".to_string(),
3255                    "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
3256                        .to_string(),
3257                ]),
3258            ),
3259            (
3260                // cast calldata "rpc(string,string,string)" "https://eth-mainnet.g.alchemy.com/v2/api_key" "eth_getBalance" "[\"0x551e7784778ef8e048e495df49f2614f84a4f1dc\",\"0x0\"]"
3261                "rpc(string,string,string)",
3262                hex!(
3263                    "
3264                    0199a220
3265                    0000000000000000000000000000000000000000000000000000000000000060
3266                    00000000000000000000000000000000000000000000000000000000000000c0
3267                    0000000000000000000000000000000000000000000000000000000000000100
3268                    000000000000000000000000000000000000000000000000000000000000002c
3269                    68747470733a2f2f6574682d6d61696e6e65742e672e616c6368656d792e636f
3270                    6d2f76322f6170695f6b65790000000000000000000000000000000000000000
3271                    000000000000000000000000000000000000000000000000000000000000000e
3272                    6574685f67657442616c616e6365000000000000000000000000000000000000
3273                    0000000000000000000000000000000000000000000000000000000000000034
3274                    5b22307835353165373738343737386566386530343865343935646634396632
3275                    363134663834613466316463222c22307830225d000000000000000000000000
3276                "
3277                )
3278                .to_vec(),
3279                Some(vec![
3280                    "\"<rpc url>\"".to_string(),
3281                    "\"eth_getBalance\"".to_string(),
3282                    "\"[\\\"0x551e7784778ef8e048e495df49f2614f84a4f1dc\\\",\\\"0x0\\\"]\""
3283                        .to_string(),
3284                ]),
3285            ),
3286            (
3287                // cast calldata "rpc(string,string,string)" "mainnet" "eth_getBalance"
3288                // "[\"0x551e7784778ef8e048e495df49f2614f84a4f1dc\",\"0x0\"]"
3289                "rpc(string,string,string)",
3290                hex!(
3291                    "
3292                    0199a220
3293                    0000000000000000000000000000000000000000000000000000000000000060
3294                    00000000000000000000000000000000000000000000000000000000000000a0
3295                    00000000000000000000000000000000000000000000000000000000000000e0
3296                    0000000000000000000000000000000000000000000000000000000000000007
3297                    6d61696e6e657400000000000000000000000000000000000000000000000000
3298                    000000000000000000000000000000000000000000000000000000000000000e
3299                    6574685f67657442616c616e6365000000000000000000000000000000000000
3300                    0000000000000000000000000000000000000000000000000000000000000034
3301                    5b22307835353165373738343737386566386530343865343935646634396632
3302                    363134663834613466316463222c22307830225d000000000000000000000000
3303                "
3304                )
3305                .to_vec(),
3306                Some(vec![
3307                    "\"mainnet\"".to_string(),
3308                    "\"eth_getBalance\"".to_string(),
3309                    "\"[\\\"0x551e7784778ef8e048e495df49f2614f84a4f1dc\\\",\\\"0x0\\\"]\""
3310                        .to_string(),
3311                ]),
3312            ),
3313        ];
3314
3315        // [function_signature, expected]
3316        let cheatcode_output_test_cases = vec![
3317            // Should redact private key on output in all cases:
3318            ("createEd25519Key(bytes32)", Some("<pk>".to_string())),
3319            ("createWallet(string)", Some("<pk>".to_string())),
3320            ("deriveKey(string,uint32)", Some("<pk>".to_string())),
3321            // Should redact RPC URL if defined, except if referenced by an alias:
3322            ("rpcUrl(string)", Some("<rpc url>".to_string())),
3323            ("rpcUrls()", Some("<rpc url>".to_string())),
3324            ("rpcUrlStructs()", Some("<rpc url>".to_string())),
3325        ];
3326
3327        for (function_signature, data, expected) in cheatcode_input_test_cases {
3328            let function = Function::parse(function_signature).unwrap();
3329            let result = decoder.decode_cheatcode_inputs(&function, &data);
3330            assert_eq!(result, expected, "Input case failed for: {function_signature}");
3331        }
3332
3333        for (function_signature, expected) in cheatcode_output_test_cases {
3334            let function = Function::parse(function_signature).unwrap();
3335            let result = Some(decoder.decode_cheatcode_outputs(&function).unwrap_or_default());
3336            assert_eq!(result, expected, "Output case failed for: {function_signature}");
3337        }
3338    }
3339
3340    #[tokio::test]
3341    async fn test_should_redact_end_to_end() {
3342        let decoder = CallTraceDecoder::new();
3343        let pk_hex = "7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6";
3344        let pk = hex!("7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6");
3345        let cheatcode_trace = |data: Vec<u8>| CallTrace {
3346            address: CHEATCODE_ADDRESS,
3347            data: data.into(),
3348            success: true,
3349            ..Default::default()
3350        };
3351
3352        // Well-formed sign(uint256,bytes32) resolves through selector lookup and redacts the
3353        // private key.
3354        let call = Vm::sign_1Call { privateKey: U256::from_be_bytes(pk), digest: B256::ZERO };
3355        let decoded = decoder.decode_function(&cheatcode_trace(call.abi_encode())).await;
3356        let call_data = decoded.call_data.expect("sign should decode");
3357        assert_eq!(call_data.signature, "sign(uint256,bytes32)");
3358        assert_eq!(call_data.args[0], "\"<pk>\"");
3359        assert!(!call_data.args.join(",").contains(pk_hex));
3360
3361        // Raw calldata of key-taking overloads is stripped to the selector, while digest-only
3362        // overloads keep theirs.
3363        let mut trace = cheatcode_trace(call.abi_encode());
3364        decoder.redact_raw_cheatcode_secrets(&mut trace);
3365        assert_eq!(trace.data[..], Vm::sign_1Call::SELECTOR);
3366        let data = Vm::sign_2Call { digest: B256::from(pk) }.abi_encode();
3367        let mut trace = cheatcode_trace(data.clone());
3368        decoder.redact_raw_cheatcode_secrets(&mut trace);
3369        assert_eq!(trace.data[..], data[..]);
3370
3371        // Return data of secret-returning cheatcodes is cleared on success, while revert data
3372        // keeps the failure diagnostic.
3373        let env_call = Vm::envUint_0Call { name: "PRIVATE_KEY".to_string() }.abi_encode();
3374        let mut trace = cheatcode_trace(env_call.clone());
3375        trace.output = U256::from_be_bytes(pk).abi_encode().into();
3376        decoder.redact_raw_cheatcode_secrets(&mut trace);
3377        assert!(trace.output.is_empty());
3378        let revert = b"environment variable \"PRIVATE_KEY\" not found".abi_encode();
3379        let mut trace = CallTrace { success: false, ..cheatcode_trace(env_call) };
3380        trace.output = revert.clone().into();
3381        decoder.redact_raw_cheatcode_secrets(&mut trace);
3382        assert_eq!(trace.output[..], revert[..]);
3383
3384        // signEd25519 redacts the trailing private key argument.
3385        let call = Vm::signEd25519Call {
3386            namespace: b"ns".into(),
3387            message: b"msg".into(),
3388            privateKey: B256::from(pk),
3389        };
3390        let decoded = decoder.decode_function(&cheatcode_trace(call.abi_encode())).await;
3391        let call_data = decoded.call_data.expect("signEd25519 should decode");
3392        assert_eq!(call_data.signature, "signEd25519(bytes,bytes,bytes32)");
3393        assert_eq!(call_data.args[2], "\"<pk>\"");
3394        assert!(!call_data.args.join(",").contains(pk_hex));
3395
3396        // Malformed calldata (nonzero trailing byte fails the ABI shape heuristic) must not
3397        // fall back to raw calldata rendering.
3398        let call = Vm::sign_1Call { privateKey: U256::from_be_bytes(pk), digest: B256::ZERO };
3399        let mut data = call.abi_encode();
3400        data.push(0xff);
3401        let decoded = decoder.decode_function(&cheatcode_trace(data)).await;
3402        let call_data = decoded.call_data.expect("malformed calldata must not fall back to raw");
3403        assert_eq!(call_data.signature, "sign(uint256,bytes32)");
3404        assert!(!call_data.args.join(",").contains(pk_hex));
3405
3406        // Suffixed calldata that isn't the exact ABI encoding (dirty string padding) must not
3407        // fall back to raw calldata rendering either.
3408        let call = Vm::deriveKey_0Call {
3409            mnemonic: "test test test test test test test test test test test junk".to_string(),
3410            index: 0,
3411        };
3412        let mut data = call.abi_encode();
3413        *data.last_mut().unwrap() = 0xff;
3414        data.push(0xff);
3415        let decoded = decoder.decode_function(&cheatcode_trace(data)).await;
3416        let call_data = decoded.call_data.expect("suffixed calldata must not fall back to raw");
3417        assert_eq!(call_data.args, vec!["<pk>".to_string()]);
3418
3419        // Truncated calldata cannot be decoded at all and fails closed.
3420        let data = Vm::sign_1Call::SELECTOR.iter().copied().chain(pk).collect::<Vec<u8>>();
3421        let decoded = decoder.decode_function(&cheatcode_trace(data)).await;
3422        let call_data = decoded.call_data.expect("truncated calldata must not fall back to raw");
3423        assert_eq!(call_data.signature, "sign(uint256,bytes32)");
3424        assert_eq!(call_data.args, vec!["<redacted>".to_string()]);
3425    }
3426
3427    #[tokio::test]
3428    async fn test_tempo_decode_preserves_existing_labels() {
3429        let decoder = CallTraceDecoder::new();
3430        let trace = CallTrace { address: PATH_USD_ADDRESS, success: true, ..Default::default() };
3431
3432        let decoded = decoder.decode_function(&trace).await;
3433        assert_eq!(decoded.label.as_deref(), Some("PathUSD"));
3434    }
3435
3436    #[tokio::test]
3437    async fn test_tempo_decode_labels_ousd() {
3438        let decoder = CallTraceDecoder::new();
3439        let transfer = ITIP20::transferCall {
3440            to: address!("0x0000000000000000000000000000000000000def"),
3441            amount: U256::from(1_000_000u64),
3442        };
3443        let trace = CallTrace {
3444            address: OUSD_ADDRESS,
3445            data: transfer.abi_encode().into(),
3446            success: true,
3447            ..Default::default()
3448        };
3449
3450        let decoded = decoder.decode_function(&trace).await;
3451        assert_eq!(decoded.label.as_deref(), Some("OUSD"));
3452        let call_data = decoded.call_data.expect("OUSD transfer should decode");
3453        assert_eq!(call_data.signature, "transfer(address,uint256)");
3454    }
3455
3456    #[tokio::test]
3457    async fn test_t5_decode_does_not_synthesize_general_target_label() {
3458        let mut decoder = CallTraceDecoder::new().clone();
3459        decoder.chain_id = Some(4217);
3460        let trace = CallTrace {
3461            address: address!("0x0000000000000000000000000000000000000123"),
3462            depth: 0,
3463            success: true,
3464            ..Default::default()
3465        };
3466
3467        let decoded = decoder.decode_function(&trace).await;
3468        assert_eq!(decoded.label, None);
3469    }
3470
3471    #[tokio::test]
3472    async fn test_t5_tip20_logo_uri_calls_and_events_decode() {
3473        let decoder = CallTraceDecoder::new();
3474
3475        let call = ITIP20::setLogoURICall { newLogoURI: "https://example.com/logo.png".into() };
3476        let trace = CallTrace {
3477            address: PATH_USD_ADDRESS,
3478            data: call.abi_encode().into(),
3479            success: true,
3480            ..Default::default()
3481        };
3482        let decoded = decoder.decode_function(&trace).await;
3483        let call_data = decoded.call_data.expect("setLogoURI should decode");
3484        assert_eq!(call_data.signature, "setLogoURI(string)");
3485        assert_eq!(call_data.args, vec!["\"https://example.com/logo.png\"".to_string()]);
3486
3487        let call = ITIP20::logoURICall {};
3488        let trace = CallTrace {
3489            address: PATH_USD_ADDRESS,
3490            data: call.abi_encode().into(),
3491            success: true,
3492            ..Default::default()
3493        };
3494        let decoded = decoder.decode_function(&trace).await;
3495        assert_eq!(decoded.call_data.expect("logoURI should decode").signature, "logoURI()");
3496
3497        let event = ITIP20::LogoURIUpdated {
3498            updater: address!("0x0000000000000000000000000000000000000abc"),
3499            newLogoURI: "ipfs://logo".into(),
3500        };
3501        let decoded = decoder.decode_event(&event.encode_log_data()).await;
3502        assert_eq!(decoded.name.as_deref(), Some("LogoURIUpdated"));
3503        let params = decoded.params.expect("LogoURIUpdated params should decode");
3504        assert_eq!(params[0].0, "updater");
3505        assert!(
3506            params[0].1.to_ascii_lowercase().contains("0000000000000000000000000000000000000abc")
3507        );
3508        assert_eq!(params[1], ("newLogoURI".into(), "\"ipfs://logo\"".into()));
3509    }
3510
3511    #[tokio::test]
3512    async fn test_t5_tip20_factory_create_token_with_logo_decodes() {
3513        let decoder = CallTraceDecoder::new();
3514        let call = ITIP20Factory::createToken_1Call {
3515            name: "Example USD".into(),
3516            symbol: "xUSD".into(),
3517            currency: "USD".into(),
3518            quoteToken: PATH_USD_ADDRESS,
3519            admin: address!("0x0000000000000000000000000000000000000abc"),
3520            salt: B256::repeat_byte(0x11),
3521            logoURI: "https://example.com/xusd.png".into(),
3522        };
3523        let trace = CallTrace {
3524            address: TIP20_FACTORY_ADDRESS,
3525            data: call.abi_encode().into(),
3526            success: true,
3527            ..Default::default()
3528        };
3529        let decoded = decoder.decode_function(&trace).await;
3530        let call_data = decoded.call_data.expect("createToken overload should decode");
3531        assert_eq!(
3532            call_data.signature,
3533            "createToken(string,string,string,address,address,bytes32,string)"
3534        );
3535        assert_eq!(call_data.args[6], "\"https://example.com/xusd.png\"");
3536    }
3537
3538    #[tokio::test]
3539    async fn test_t5_stablecoin_dex_order_flipped_event_decodes() {
3540        let decoder = CallTraceDecoder::new();
3541        let event = IStablecoinDEX::OrderFlipped {
3542            orderId: 42,
3543            maker: address!("0x0000000000000000000000000000000000000abc"),
3544            token: PATH_USD_ADDRESS,
3545            amount: 1_000_000,
3546            isBid: false,
3547            tick: 100,
3548            flipTick: 100,
3549        };
3550        let decoded = decoder.decode_event(&event.encode_log_data()).await;
3551        assert_eq!(decoded.name.as_deref(), Some("OrderFlipped"));
3552        let params = decoded.params.expect("OrderFlipped params should decode");
3553        assert_eq!(params[0], ("orderId".into(), "42".into()));
3554        assert_eq!(params[4], ("isBid".into(), "false".into()));
3555        assert_eq!(params[5], ("tick".into(), "100".into()));
3556        assert_eq!(params[6], ("flipTick".into(), "100".into()));
3557    }
3558
3559    #[tokio::test]
3560    async fn test_t5_channel_reserve_call_and_event_decode() {
3561        let mut decoder = CallTraceDecoder::new().clone();
3562        decoder.chain_id = Some(4217);
3563
3564        let open = ITIP20ChannelReserve::openCall {
3565            payee: address!("0x0000000000000000000000000000000000000abc"),
3566            operator: Address::ZERO,
3567            token: PATH_USD_ADDRESS,
3568            deposit: U96::from(1_000_000u64),
3569            salt: B256::repeat_byte(0x22),
3570            authorizedSigner: Address::ZERO,
3571        };
3572        let trace = CallTrace {
3573            address: TIP20_CHANNEL_RESERVE_ADDRESS,
3574            data: open.abi_encode().into(),
3575            depth: 0,
3576            success: true,
3577            ..Default::default()
3578        };
3579        let decoded = decoder.decode_function(&trace).await;
3580        assert_eq!(decoded.label.as_deref(), Some("TIP20ChannelReserve"));
3581        assert_eq!(
3582            decoded.call_data.expect("open should decode").signature,
3583            "open(address,address,address,uint96,bytes32,address)"
3584        );
3585
3586        let transfer = ITIP20::transferCall {
3587            to: address!("0x0000000000000000000000000000000000000def"),
3588            amount: U256::from(1_000_000u64),
3589        };
3590        let trace = CallTrace {
3591            address: PATH_USD_ADDRESS,
3592            data: transfer.abi_encode().into(),
3593            depth: 0,
3594            success: true,
3595            ..Default::default()
3596        };
3597        let decoded = decoder.decode_function(&trace).await;
3598        assert_eq!(decoded.label.as_deref(), Some("PathUSD"));
3599        let json = serde_json::to_string(&decoded).expect("decoded trace serializes");
3600        assert!(json.contains(r#""label":"PathUSD""#));
3601        assert!(!json.contains("payment-lane"));
3602
3603        let balance_of = ITIP20::balanceOfCall {
3604            account: address!("0x0000000000000000000000000000000000000def"),
3605        };
3606        let trace = CallTrace {
3607            address: PATH_USD_ADDRESS,
3608            data: balance_of.abi_encode().into(),
3609            depth: 0,
3610            success: true,
3611            ..Default::default()
3612        };
3613        let decoded = decoder.decode_function(&trace).await;
3614        assert_eq!(decoded.label.as_deref(), Some("PathUSD"));
3615
3616        let event = ITIP20ChannelReserve::ChannelOpened {
3617            channelId: B256::repeat_byte(0x33),
3618            payer: address!("0x0000000000000000000000000000000000000123"),
3619            payee: address!("0x0000000000000000000000000000000000000abc"),
3620            operator: Address::ZERO,
3621            token: PATH_USD_ADDRESS,
3622            authorizedSigner: Address::ZERO,
3623            salt: B256::repeat_byte(0x22),
3624            expiringNonceHash: B256::repeat_byte(0x44),
3625            deposit: U96::from(1_000_000u64),
3626        };
3627        let decoded = decoder.decode_event(&event.encode_log_data()).await;
3628        assert_eq!(decoded.name.as_deref(), Some("ChannelOpened"));
3629        let params = decoded.params.expect("ChannelOpened params should decode");
3630        assert_eq!(params[0].0, "channelId");
3631        assert_eq!(params[8].0, "deposit");
3632        assert!(params[8].1.starts_with("1000000"));
3633    }
3634
3635    #[tokio::test]
3636    #[cfg(feature = "monad")]
3637    async fn test_decodes_monad_staking_precompile_call() {
3638        let trace = CallTrace {
3639            address: monad_evm2::staking::STAKING_ADDRESS,
3640            data: getEpochCall::SELECTOR.into(),
3641            output:
3642                monad_evm2::staking::interface::IMonadStaking::getEpochCall::abi_encode_returns(
3643                    &monad_evm2::staking::interface::IMonadStaking::getEpochReturn {
3644                        epoch: 42,
3645                        inEpochDelayPeriod: true,
3646                    },
3647                )
3648                .into(),
3649            success: true,
3650            ..Default::default()
3651        };
3652
3653        let decoded = monad_decoder(MonadHardfork::MonadEight).decode_function(&trace).await;
3654
3655        assert_eq!(decoded.label.as_deref(), Some("Staking"));
3656        let call_data = decoded.call_data.expect("call data");
3657        assert_eq!(call_data.signature, "getEpoch()");
3658        assert!(call_data.args.is_empty());
3659        assert_eq!(decoded.return_data.as_deref(), Some("42, true"));
3660    }
3661
3662    #[tokio::test]
3663    #[cfg(feature = "monad")]
3664    async fn test_decodes_monad_staking_syscall() {
3665        let block_author = Address::repeat_byte(0x42);
3666        let trace = CallTrace {
3667            address: monad_evm2::staking::STAKING_ADDRESS,
3668            data: monad::IMonadStakingSyscalls::syscallRewardCall { blockAuthor: block_author }
3669                .abi_encode()
3670                .into(),
3671            success: true,
3672            ..Default::default()
3673        };
3674
3675        let decoder = monad_decoder(MonadHardfork::MonadEight);
3676        let expected_author = decoder.format_value(&DynSolValue::Address(block_author));
3677        let decoded = decoder.decode_function(&trace).await;
3678
3679        assert_eq!(decoded.label.as_deref(), Some("Staking"));
3680        let call_data = decoded.call_data.expect("call data");
3681        assert_eq!(call_data.signature, "syscallReward(address)");
3682        assert_eq!(call_data.args, vec![expected_author]);
3683    }
3684
3685    #[tokio::test]
3686    #[cfg(feature = "monad")]
3687    async fn test_decodes_monad_reserve_balance_precompile_call() {
3688        let trace = CallTrace {
3689            address: monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
3690            data: dippedIntoReserveCall::SELECTOR.into(),
3691            output: true.abi_encode().into(),
3692            success: true,
3693            ..Default::default()
3694        };
3695
3696        let decoded = monad_decoder(MonadHardfork::MonadNine).decode_function(&trace).await;
3697
3698        assert_eq!(decoded.label.as_deref(), Some("ReserveBalance"));
3699        let call_data = decoded.call_data.expect("call data");
3700        assert_eq!(call_data.signature, "dippedIntoReserve()");
3701        assert!(call_data.args.is_empty());
3702        assert_eq!(decoded.return_data.as_deref(), Some("true"));
3703    }
3704
3705    #[tokio::test]
3706    #[cfg(feature = "monad")]
3707    async fn test_decodes_monad_staking_precompile_event() {
3708        let event = Event::parse(
3709            "event Delegate(uint64 indexed validatorId,address indexed delegator,uint256 amount,uint64 activationEpoch)",
3710        )
3711        .unwrap();
3712        let delegator = Address::repeat_byte(0x11);
3713        let log = LogData::new_unchecked(
3714            vec![event.selector(), topic_from_u64(7), topic_from_address(delegator)],
3715            (U256::from(1000), 9_u64).abi_encode().into(),
3716        );
3717
3718        let decoder = monad_decoder(MonadHardfork::MonadEight);
3719        let decoded =
3720            decoder.decode_event_with_address(monad_evm2::staking::STAKING_ADDRESS, &log).await;
3721
3722        assert_eq!(decoded.name.as_deref(), Some("Delegate"));
3723        let params = decoded.params.expect("params");
3724        assert_eq!(params[0], ("validatorId".to_string(), "7".to_string()));
3725        assert_eq!(params[1].0, "delegator");
3726        assert_eq!(params[2], ("amount".to_string(), "1000".to_string()));
3727        assert_eq!(params[3], ("activationEpoch".to_string(), "9".to_string()));
3728
3729        let collision = decoder
3730            .decode_event_with_address(monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS, &log)
3731            .await;
3732        assert_eq!(collision.name, None);
3733    }
3734
3735    #[tokio::test]
3736    #[cfg(feature = "monad")]
3737    async fn test_monad_metadata_is_not_registered_for_ethereum() {
3738        let decoder = CallTraceDecoderBuilder::new().with_chain_id(Some(1)).build();
3739        for address in [
3740            foundry_evm_core::constants::MONAD_CHEATCODE_ADDRESS,
3741            monad_evm2::staking::STAKING_ADDRESS,
3742            monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
3743        ] {
3744            assert!(!decoder.labels.contains_key(&address));
3745        }
3746
3747        let staking_trace = CallTrace {
3748            address: monad_evm2::staking::STAKING_ADDRESS,
3749            data: getEpochCall::SELECTOR.into(),
3750            output:
3751                monad_evm2::staking::interface::IMonadStaking::getEpochCall::abi_encode_returns(
3752                    &monad_evm2::staking::interface::IMonadStaking::getEpochReturn {
3753                        epoch: 42,
3754                        inEpochDelayPeriod: true,
3755                    },
3756                )
3757                .into(),
3758            success: true,
3759            ..Default::default()
3760        };
3761        let staking = decoder.decode_function(&staking_trace).await;
3762        assert_ne!(
3763            staking.call_data.as_ref().map(|call| call.signature.as_str()),
3764            Some("getEpoch()")
3765        );
3766
3767        let reserve_trace = CallTrace {
3768            address: monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
3769            data: dippedIntoReserveCall::SELECTOR.into(),
3770            output: true.abi_encode().into(),
3771            success: true,
3772            ..Default::default()
3773        };
3774        let reserve = decoder.decode_function(&reserve_trace).await;
3775        assert_ne!(
3776            reserve.call_data.as_ref().map(|call| call.signature.as_str()),
3777            Some("dippedIntoReserve()")
3778        );
3779
3780        let event = Event::parse(
3781            "event Delegate(uint64 indexed validatorId,address indexed delegator,uint256 amount,uint64 activationEpoch)",
3782        )
3783        .unwrap();
3784        let log = LogData::new_unchecked(
3785            vec![
3786                event.selector(),
3787                topic_from_u64(7),
3788                topic_from_address(Address::repeat_byte(0x11)),
3789            ],
3790            (U256::from(1000), 9_u64).abi_encode().into(),
3791        );
3792        for address in [
3793            monad_evm2::staking::STAKING_ADDRESS,
3794            monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
3795        ] {
3796            let decoded = decoder.decode_event_with_address(address, &log).await;
3797            assert_eq!(decoded.name, None);
3798        }
3799    }
3800
3801    #[tokio::test]
3802    #[cfg(feature = "monad")]
3803    async fn test_monad_reserve_metadata_starts_at_monad_nine() {
3804        let mut monad_eight = monad_decoder(MonadHardfork::MonadEight);
3805        monad_eight.clear_addresses();
3806        assert_eq!(
3807            monad_eight
3808                .labels
3809                .get(&foundry_evm_core::constants::MONAD_CHEATCODE_ADDRESS)
3810                .map(String::as_str),
3811            Some("MonadVM")
3812        );
3813        assert_eq!(
3814            monad_eight.labels.get(&monad_evm2::staking::STAKING_ADDRESS).map(String::as_str),
3815            Some("Staking")
3816        );
3817        assert!(
3818            !monad_eight.labels.contains_key(&monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS)
3819        );
3820
3821        let trace = CallTrace {
3822            address: monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
3823            data: dippedIntoReserveCall::SELECTOR.into(),
3824            output: true.abi_encode().into(),
3825            success: true,
3826            ..Default::default()
3827        };
3828        let before = monad_eight.decode_function(&trace).await;
3829        assert_ne!(
3830            before.call_data.as_ref().map(|call| call.signature.as_str()),
3831            Some("dippedIntoReserve()")
3832        );
3833
3834        let mut monad_nine = monad_decoder(MonadHardfork::MonadNine);
3835        monad_nine.clear_addresses();
3836        assert_eq!(
3837            monad_nine
3838                .labels
3839                .get(&monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS)
3840                .map(String::as_str),
3841            Some("ReserveBalance")
3842        );
3843        let after = monad_nine.decode_function(&trace).await;
3844        assert_eq!(
3845            after.call_data.as_ref().map(|call| call.signature.as_str()),
3846            Some("dippedIntoReserve()")
3847        );
3848    }
3849
3850    #[tokio::test]
3851    #[cfg(feature = "monad")]
3852    async fn test_monad_metadata_refreshes_across_hardforks() {
3853        let trace = CallTrace {
3854            address: monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
3855            data: dippedIntoReserveCall::SELECTOR.into(),
3856            output: true.abi_encode().into(),
3857            success: true,
3858            ..Default::default()
3859        };
3860        let mut decoder = monad_decoder(MonadHardfork::MonadEight);
3861
3862        decoder.set_hardfork(Some(MonadHardfork::MonadNine.into()));
3863        assert_eq!(decoder.hardfork(), Some(MonadHardfork::MonadNine.into()));
3864        assert_eq!(
3865            decoder
3866                .labels
3867                .get(&monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS)
3868                .map(String::as_str),
3869            Some("ReserveBalance")
3870        );
3871        let monad_nine = decoder.decode_function(&trace).await;
3872        assert_eq!(
3873            monad_nine.call_data.as_ref().map(|call| call.signature.as_str()),
3874            Some("dippedIntoReserve()")
3875        );
3876
3877        decoder.set_hardfork(Some(MonadHardfork::MonadEight.into()));
3878        assert_eq!(decoder.hardfork(), Some(MonadHardfork::MonadEight.into()));
3879        assert!(
3880            !decoder.labels.contains_key(&monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS)
3881        );
3882        assert_eq!(
3883            decoder.labels.get(&monad_evm2::staking::STAKING_ADDRESS).map(String::as_str),
3884            Some("Staking")
3885        );
3886        let monad_eight = decoder.decode_function(&trace).await;
3887        assert_ne!(
3888            monad_eight.call_data.as_ref().map(|call| call.signature.as_str()),
3889            Some("dippedIntoReserve()")
3890        );
3891    }
3892
3893    #[cfg(feature = "monad")]
3894    fn topic_from_u64(value: u64) -> B256 {
3895        let mut topic = [0u8; 32];
3896        topic[24..].copy_from_slice(&value.to_be_bytes());
3897        B256::from(topic)
3898    }
3899
3900    #[cfg(feature = "monad")]
3901    fn topic_from_address(address: Address) -> B256 {
3902        let mut topic = [0u8; 32];
3903        topic[12..].copy_from_slice(address.as_slice());
3904        B256::from(topic)
3905    }
3906
3907    #[tokio::test]
3908    async fn test_t7_storage_credits_call_and_error_decode() {
3909        let mut decoder = CallTraceDecoder::new().clone();
3910        decoder.chain_id = Some(4217);
3911
3912        // A write call decodes to its signature and the precompile address is labeled.
3913        let set_mode = IStorageCredits::setModeCall { newMode: IStorageCredits::Mode::Direct };
3914        let trace = CallTrace {
3915            address: STORAGE_CREDITS_ADDRESS,
3916            data: set_mode.abi_encode().into(),
3917            depth: 0,
3918            success: true,
3919            ..Default::default()
3920        };
3921        let decoded = decoder.decode_function(&trace).await;
3922        assert_eq!(decoded.label.as_deref(), Some("StorageCredits"));
3923        assert_eq!(decoded.call_data.expect("setMode should decode").signature, "setMode(uint8)");
3924
3925        // A view call unique to this precompile also decodes.
3926        let mode_of = IStorageCredits::modeOfCall { account: Address::repeat_byte(0x11) };
3927        let trace = CallTrace {
3928            address: STORAGE_CREDITS_ADDRESS,
3929            data: mode_of.abi_encode().into(),
3930            depth: 0,
3931            success: true,
3932            ..Default::default()
3933        };
3934        let decoded = decoder.decode_function(&trace).await;
3935        assert_eq!(decoded.call_data.expect("modeOf should decode").signature, "modeOf(address)");
3936
3937        // The precompile's custom errors decode by name in reverts.
3938        let revert = decoder
3939            .revert_decoder
3940            .decode(IStorageCredits::InvalidMode {}.abi_encode().as_slice(), None);
3941        assert!(revert.contains("InvalidMode"), "{revert}");
3942
3943        // `balanceOf(address)` collides with `ITIP20`'s selector; the global map must keep
3944        // `ITIP20`'s `uint256` return so ordinary token balances above `u64::MAX` still decode.
3945        let selector = IStorageCredits::balanceOfCall::SELECTOR;
3946        let funcs = decoder.functions.get(&selector).expect("balanceOf selector is registered");
3947        assert!(
3948            funcs.iter().any(|f| f.outputs.first().is_some_and(|o| o.ty == "uint256")),
3949            "global balanceOf must return uint256"
3950        );
3951    }
3952
3953    // A mock identifier that records which addresses it was asked to identify.
3954    struct RecordingIdentifier {
3955        queried: Vec<Address>,
3956    }
3957    impl TraceIdentifier for RecordingIdentifier {
3958        fn identify_addresses(&mut self, nodes: &[&CallTraceNode]) -> Vec<IdentifiedAddress<'_>> {
3959            self.queried.extend(nodes.iter().map(|n| n.trace.address));
3960            Vec::new()
3961        }
3962    }
3963
3964    struct AbiIdentifier {
3965        abi: JsonAbi,
3966    }
3967
3968    impl TraceIdentifier for AbiIdentifier {
3969        fn identify_addresses(&mut self, nodes: &[&CallTraceNode]) -> Vec<IdentifiedAddress<'_>> {
3970            nodes
3971                .iter()
3972                .map(|node| IdentifiedAddress {
3973                    address: node.trace.address,
3974                    label: Some("Scoped".to_string()),
3975                    contract: Some("Scoped".to_string()),
3976                    abi: Some(Cow::Borrowed(&self.abi)),
3977                    constructor_args_offset: None,
3978                    artifact_id: None,
3979                })
3980                .collect()
3981        }
3982    }
3983
3984    #[test]
3985    fn scoped_identification_reuses_global_abi() {
3986        let abi = JsonAbi::parse(["function scoped(uint256)"]).unwrap();
3987        let function = abi.functions().next().unwrap().clone();
3988        let selector = function.selector();
3989        let mut decoder = CallTraceDecoderBuilder::new().with_abi(&abi).build();
3990        let global_functions = decoder.functions.get(&selector).unwrap().len();
3991
3992        let address = Address::repeat_byte(0x42);
3993        let mut arena = CallTraceArena::default();
3994        arena.nodes_mut()[0].trace.address = address;
3995        decoder.identify_scoped(&arena, &mut AbiIdentifier { abi });
3996
3997        assert_eq!(decoder.functions.get(&selector).unwrap().len(), global_functions);
3998        assert_eq!(decoder.functions_by_address[&address][&selector], [function]);
3999    }
4000
4001    #[test]
4002    fn repeated_identification_does_not_duplicate_global_events() {
4003        let abi = JsonAbi::parse(["event Scoped(uint256 value)"]).unwrap();
4004        let event = abi.events().next().unwrap().clone();
4005        let mut decoder = CallTraceDecoder::new().clone();
4006
4007        let mut arena = CallTraceArena::default();
4008        for byte in [0x42, 0x43] {
4009            arena.nodes_mut()[0].trace.address = Address::repeat_byte(byte);
4010            decoder.identify(&arena, &mut AbiIdentifier { abi: abi.clone() });
4011        }
4012
4013        assert_eq!(decoder.events[&(event.selector(), 0)], [event]);
4014    }
4015
4016    #[tokio::test]
4017    async fn inactive_p256_address_uses_contract_identity() {
4018        let abi = JsonAbi::parse(["function ordinaryCode()"]).unwrap();
4019        let function = abi.functions().next().unwrap();
4020        let mut arena = CallTraceArena::default();
4021        arena.nodes_mut()[0].trace = CallTrace {
4022            address: P256_VERIFY,
4023            maybe_precompile: Some(false),
4024            data: function.selector().into(),
4025            success: true,
4026            ..Default::default()
4027        };
4028
4029        let mut decoder = CallTraceDecoder::new().clone();
4030        decoder.identify(&arena, &mut AbiIdentifier { abi });
4031        let decoded = decoder.decode_function(&arena.nodes()[0].trace).await;
4032
4033        assert_eq!(decoded.label.as_deref(), Some("Scoped"));
4034        assert_eq!(decoded.call_data.unwrap().signature, "ordinaryCode()");
4035    }
4036
4037    #[test]
4038    fn p256_is_not_an_unconditional_precompile_label() {
4039        assert!(!CallTraceDecoder::new().precompile_labels().contains_key(&P256_VERIFY));
4040    }
4041
4042    #[test]
4043    fn test_identify_addresses_skips_evm_precompiles() {
4044        let decoder = CallTraceDecoder::new();
4045
4046        let mut arena = CallTraceArena::default();
4047        let regular_addr = Address::repeat_byte(0x42);
4048        arena.nodes_mut()[0].trace.address = regular_addr;
4049
4050        // Standard EVM precompile flagged by the inspector.
4051        arena.nodes_mut().push(CallTraceNode {
4052            trace: CallTrace {
4053                address: SHA_256,
4054                depth: 1,
4055                maybe_precompile: Some(true),
4056                ..Default::default()
4057            },
4058            idx: 1,
4059            ..Default::default()
4060        });
4061
4062        // Standard EVM precompile NOT flagged, caught by is_known_precompile.
4063        arena.nodes_mut().push(CallTraceNode {
4064            trace: CallTrace {
4065                address: SHA_256,
4066                depth: 1,
4067                maybe_precompile: None,
4068                ..Default::default()
4069            },
4070            idx: 2,
4071            ..Default::default()
4072        });
4073
4074        let mut identifier = RecordingIdentifier { queried: Vec::new() };
4075        decoder.identify_addresses(&arena, &mut identifier);
4076
4077        assert_eq!(identifier.queried, vec![regular_addr]);
4078    }
4079
4080    #[test]
4081    fn test_identify_addresses_skips_tempo_precompiles() {
4082        // Decoder with Tempo chain ID (4217).
4083        let decoder = CallTraceDecoderBuilder::new()
4084            .with_chain_id(Some(4217))
4085            .with_hardfork(Some(TempoHardfork::T5.into()))
4086            .build();
4087
4088        assert_eq!(
4089            decoder.labels.get(&TIP20_CHANNEL_RESERVE_ADDRESS),
4090            Some(&"TIP20ChannelReserve".to_string())
4091        );
4092
4093        let mut arena = CallTraceArena::default();
4094        let regular_addr = Address::repeat_byte(0x42);
4095        arena.nodes_mut()[0].trace.address = regular_addr;
4096
4097        // Tempo precompile — not flagged by inspector, caught by is_known_precompile
4098        // only when chain_id is a Tempo chain.
4099        let tempo_precompile = TEMPO_PRECOMPILE_ADDRESSES[0];
4100        arena.nodes_mut().push(CallTraceNode {
4101            trace: CallTrace {
4102                address: tempo_precompile,
4103                depth: 1,
4104                maybe_precompile: None,
4105                ..Default::default()
4106            },
4107            idx: 1,
4108            ..Default::default()
4109        });
4110
4111        let mut identifier = RecordingIdentifier { queried: Vec::new() };
4112        decoder.identify_addresses(&arena, &mut identifier);
4113
4114        // On a Tempo chain, the Tempo precompile should be filtered out.
4115        assert_eq!(identifier.queried, vec![regular_addr]);
4116    }
4117
4118    #[test]
4119    fn test_precompile_labels_follow_tempo_hardfork_activation_boundaries() {
4120        let labels_for_hardfork = |hardfork: TempoHardfork| {
4121            CallTraceDecoderBuilder::new()
4122                .with_hardfork(Some(hardfork.into()))
4123                .build()
4124                .precompile_labels()
4125        };
4126
4127        let t4_labels = labels_for_hardfork(TempoHardfork::T4);
4128        assert_eq!(t4_labels.get(&TIP_FEE_MANAGER_ADDRESS), Some(&"FeeManager".to_string()));
4129        assert!(!t4_labels.contains_key(&TIP20_CHANNEL_RESERVE_ADDRESS));
4130        assert!(!t4_labels.contains_key(&RECEIVE_POLICY_GUARD_ADDRESS));
4131        assert!(!t4_labels.contains_key(&STORAGE_CREDITS_ADDRESS));
4132
4133        let t5_labels = labels_for_hardfork(TempoHardfork::T5);
4134        assert_eq!(t5_labels.get(&TIP_FEE_MANAGER_ADDRESS), Some(&"FeeManager".to_string()));
4135        assert_eq!(
4136            t5_labels.get(&TIP20_CHANNEL_RESERVE_ADDRESS),
4137            Some(&"TIP20ChannelReserve".to_string())
4138        );
4139        assert!(!t5_labels.contains_key(&RECEIVE_POLICY_GUARD_ADDRESS));
4140        assert!(!t5_labels.contains_key(&STORAGE_CREDITS_ADDRESS));
4141
4142        let t6_labels = labels_for_hardfork(TempoHardfork::T6);
4143        assert_eq!(
4144            t6_labels.get(&TIP20_CHANNEL_RESERVE_ADDRESS),
4145            Some(&"TIP20ChannelReserve".to_string())
4146        );
4147        assert_eq!(
4148            t6_labels.get(&RECEIVE_POLICY_GUARD_ADDRESS),
4149            Some(&"ReceivePolicyGuard".to_string())
4150        );
4151        assert!(!t6_labels.contains_key(&STORAGE_CREDITS_ADDRESS));
4152
4153        let t7_labels = labels_for_hardfork(TempoHardfork::T7);
4154        assert_eq!(
4155            t7_labels.get(&RECEIVE_POLICY_GUARD_ADDRESS),
4156            Some(&"ReceivePolicyGuard".to_string())
4157        );
4158        assert_eq!(t7_labels.get(&STORAGE_CREDITS_ADDRESS), Some(&"StorageCredits".to_string()));
4159
4160        assert!(
4161            !labels_for_hardfork(TempoHardfork::T13).contains_key(&CONFIGURABLE_ACCOUNT_ADDRESS)
4162        );
4163        assert_eq!(
4164            labels_for_hardfork(TempoHardfork::T14).get(&CONFIGURABLE_ACCOUNT_ADDRESS),
4165            Some(&"ConfigurableAccount".to_string())
4166        );
4167
4168        let ethereum_labels = CallTraceDecoderBuilder::new()
4169            .with_execution_network(NetworkVariant::Ethereum)
4170            .with_chain_id(Some(4217))
4171            .with_hardfork(Some(TempoHardfork::T7.into()))
4172            .build()
4173            .precompile_labels();
4174        assert!(!ethereum_labels.contains_key(&TIP20_CHANNEL_RESERVE_ADDRESS));
4175        assert!(!ethereum_labels.contains_key(&RECEIVE_POLICY_GUARD_ADDRESS));
4176        assert!(!ethereum_labels.contains_key(&STORAGE_CREDITS_ADDRESS));
4177    }
4178
4179    #[test]
4180    fn celo_profile_is_authoritative_for_custom_precompile_labels() {
4181        let mut custom_celo = CallTraceDecoderBuilder::new()
4182            .with_networks(NetworkConfigs::with_celo())
4183            .with_chain_id(Some(98_765_432))
4184            .build();
4185        assert_eq!(
4186            custom_celo.precompile_labels().get(&CELO_TRANSFER),
4187            Some(&CELO_TRANSFER_LABEL.to_string())
4188        );
4189        custom_celo.clear_addresses();
4190        assert_eq!(
4191            custom_celo.precompile_labels().get(&CELO_TRANSFER),
4192            Some(&CELO_TRANSFER_LABEL.to_string())
4193        );
4194
4195        let explicit_ethereum = CallTraceDecoderBuilder::new()
4196            .with_networks(NetworkConfigs::default())
4197            .with_chain_id(Some(42_220))
4198            .build();
4199        assert!(!explicit_ethereum.precompile_labels().contains_key(&CELO_TRANSFER));
4200
4201        let inferred_celo = CallTraceDecoderBuilder::new().with_chain_id(Some(42_220)).build();
4202        assert_eq!(
4203            inferred_celo.precompile_labels().get(&CELO_TRANSFER),
4204            Some(&CELO_TRANSFER_LABEL.to_string())
4205        );
4206    }
4207
4208    #[cfg(feature = "base")]
4209    #[test]
4210    fn test_precompile_labels_follow_base_upgrade_boundaries() {
4211        let labels_for_upgrade = |upgrade| {
4212            CallTraceDecoderBuilder::new()
4213                .with_chain_id(Some(8453))
4214                .with_hardfork(Some(FoundryHardfork::Base(upgrade)))
4215                .build()
4216                .precompile_labels()
4217        };
4218        let base_precompiles = NetworkConfigs::with_base().precompiles(None);
4219        let base_label_count = |labels: &AddressHashMap<String>| {
4220            base_precompiles.values().filter(|address| labels.contains_key(*address)).count()
4221        };
4222
4223        assert_eq!(base_label_count(&labels_for_upgrade(BaseUpgrade::Azul)), 0);
4224        assert_eq!(base_label_count(&labels_for_upgrade(BaseUpgrade::Beryl)), 3);
4225        assert_eq!(base_label_count(&labels_for_upgrade(BaseUpgrade::Cobalt)), 5);
4226    }
4227
4228    #[tokio::test]
4229    async fn test_current_committee_decoding_is_durable_and_context_gated() {
4230        let abi = ICurrentCommittee::abi::contract();
4231        let function = abi.functions.get("getCommitteeMembers").unwrap().first().unwrap();
4232        let output = function
4233            .abi_encode_output(&[
4234                DynSolValue::Uint(U256::from(7), 64),
4235                DynSolValue::Array(vec![DynSolValue::FixedBytes(B256::with_last_byte(1), 32)]),
4236            ])
4237            .unwrap();
4238        let trace = CallTrace {
4239            address: CURRENT_COMMITTEE_ADDRESS,
4240            data: function.selector().into(),
4241            output: output.into(),
4242            success: true,
4243            ..Default::default()
4244        };
4245
4246        let mut decoder = CallTraceDecoderBuilder::new()
4247            .with_chain_id(Some(4217))
4248            .with_hardfork(Some(TempoHardfork::T8.into()))
4249            .build();
4250        decoder.clear_addresses();
4251        let decoded = decoder.decode_function(&trace).await;
4252        assert_eq!(decoded.label.as_deref(), Some("CurrentCommittee"));
4253        assert_eq!(decoded.call_data.unwrap().signature, "getCommitteeMembers()");
4254        assert_eq!(
4255            decoded.return_data.unwrap(),
4256            "7, [0x0000000000000000000000000000000000000000000000000000000000000001]"
4257        );
4258
4259        for decoder in [
4260            CallTraceDecoderBuilder::new()
4261                .with_chain_id(Some(4217))
4262                .with_hardfork(Some(TempoHardfork::T7.into()))
4263                .build(),
4264            CallTraceDecoderBuilder::new()
4265                .with_chain_id(Some(1))
4266                .with_hardfork(Some(TempoHardfork::T8.into()))
4267                .build(),
4268        ] {
4269            let decoded = decoder.decode_function(&trace).await;
4270            assert_ne!(decoded.label.as_deref(), Some("CurrentCommittee"));
4271            assert!(decoded.call_data.is_none());
4272        }
4273    }
4274
4275    #[tokio::test]
4276    async fn test_current_committee_unauthorized_is_address_scoped() {
4277        let output = ICurrentCommittee::Unauthorized {}.abi_encode();
4278        let trace = CallTrace {
4279            address: CURRENT_COMMITTEE_ADDRESS,
4280            output: output.clone().into(),
4281            success: false,
4282            status: Some(InstrStop::Revert),
4283            ..Default::default()
4284        };
4285        let decoder = CallTraceDecoderBuilder::new()
4286            .with_chain_id(Some(4217))
4287            .with_hardfork(Some(TempoHardfork::T8.into()))
4288            .build();
4289        assert_eq!(
4290            decoder.decode_function(&trace).await.return_data.as_deref(),
4291            Some("Unauthorized()")
4292        );
4293
4294        let unrelated = CallTrace { address: Address::ZERO, ..trace };
4295        let baseline = CallTraceDecoder::new().decode_function(&unrelated).await;
4296        assert_eq!(decoder.decode_function(&unrelated).await.return_data, baseline.return_data);
4297    }
4298
4299    #[test]
4300    fn test_precompile_labels_skip_tempo_precompiles_on_other_chains() {
4301        let decoder = CallTraceDecoderBuilder::new()
4302            .with_chain_id(Some(1))
4303            .with_hardfork(Some(TempoHardfork::T6.into()))
4304            .build();
4305
4306        let labels = decoder.precompile_labels();
4307        assert!(!labels.contains_key(&TIP_FEE_MANAGER_ADDRESS));
4308        assert!(!labels.contains_key(&RECEIVE_POLICY_GUARD_ADDRESS));
4309        assert!(!labels.contains_key(&STORAGE_CREDITS_ADDRESS));
4310    }
4311
4312    #[test]
4313    fn test_tempo_hardfork_labels_do_not_clobber_user_labels() {
4314        let reserve_label = "UserReserve".to_string();
4315        let guard_label = "UserGuard".to_string();
4316        let decoder = CallTraceDecoderBuilder::new()
4317            .with_labels([
4318                (TIP20_CHANNEL_RESERVE_ADDRESS, reserve_label.clone()),
4319                (RECEIVE_POLICY_GUARD_ADDRESS, guard_label.clone()),
4320            ])
4321            .with_hardfork(Some(TempoHardfork::T6.into()))
4322            .build();
4323
4324        assert_eq!(decoder.labels.get(&TIP20_CHANNEL_RESERVE_ADDRESS), Some(&reserve_label));
4325        assert_eq!(decoder.labels.get(&RECEIVE_POLICY_GUARD_ADDRESS), Some(&guard_label));
4326    }
4327
4328    #[test]
4329    fn test_tempo_hardfork_transitions_rebuild_address_metadata() {
4330        let user_address = address!("0000000000000000000000000000000000001234");
4331        let user_label = "UserLabel".to_string();
4332        let mut decoder = CallTraceDecoderBuilder::new()
4333            .with_execution_network(NetworkVariant::Tempo)
4334            .with_labels([(user_address, user_label.clone())])
4335            .with_hardfork(Some(TempoHardfork::T4.into()))
4336            .build();
4337
4338        let labels = decoder.precompile_labels();
4339        assert!(labels.contains_key(&TIP_FEE_MANAGER_ADDRESS));
4340        assert!(!labels.contains_key(&TIP20_CHANNEL_RESERVE_ADDRESS));
4341        assert!(!labels.contains_key(&RECEIVE_POLICY_GUARD_ADDRESS));
4342
4343        decoder.set_hardfork(Some(TempoHardfork::T6.into()));
4344        let labels = decoder.precompile_labels();
4345        assert!(labels.contains_key(&TIP_FEE_MANAGER_ADDRESS));
4346        assert!(labels.contains_key(&TIP20_CHANNEL_RESERVE_ADDRESS));
4347        assert!(labels.contains_key(&RECEIVE_POLICY_GUARD_ADDRESS));
4348        assert_eq!(decoder.labels.get(&user_address), Some(&user_label));
4349
4350        decoder.set_hardfork(Some(TempoHardfork::T4.into()));
4351        let labels = decoder.precompile_labels();
4352        assert!(labels.contains_key(&TIP_FEE_MANAGER_ADDRESS));
4353        assert!(!labels.contains_key(&TIP20_CHANNEL_RESERVE_ADDRESS));
4354        assert!(!labels.contains_key(&RECEIVE_POLICY_GUARD_ADDRESS));
4355        assert_eq!(decoder.labels.get(&user_address), Some(&user_label));
4356
4357        decoder.set_hardfork(None);
4358        assert_eq!(decoder.labels.get(&user_address), Some(&user_label));
4359    }
4360
4361    #[test]
4362    fn test_tempo_hardfork_none_does_not_remove_user_reserve_label() {
4363        let reserve_label = "UserReserve".to_string();
4364        let decoder = CallTraceDecoderBuilder::new()
4365            .with_labels([(TIP20_CHANNEL_RESERVE_ADDRESS, reserve_label.clone())])
4366            .with_hardfork(None)
4367            .build();
4368
4369        assert_eq!(decoder.labels.get(&TIP20_CHANNEL_RESERVE_ADDRESS), Some(&reserve_label));
4370    }
4371
4372    #[tokio::test]
4373    async fn test_labels_validator_config_v2() {
4374        let decoder = CallTraceDecoderBuilder::new()
4375            .with_execution_network(NetworkVariant::Tempo)
4376            .with_hardfork(Some(TempoHardfork::T8.into()))
4377            .build();
4378        let trace = CallTrace { address: VALIDATOR_CONFIG_V2_ADDRESS, ..Default::default() };
4379
4380        assert_eq!(
4381            decoder.decode_function(&trace).await.label.as_deref(),
4382            Some("ValidatorConfigV2")
4383        );
4384        assert_eq!(
4385            decoder.precompile_labels().get(&VALIDATOR_CONFIG_V2_ADDRESS).map(String::as_str),
4386            Some("ValidatorConfigV2")
4387        );
4388    }
4389
4390    #[tokio::test]
4391    async fn test_decode_receive_policy_guard_at_t6() {
4392        let function = Function::parse("claim(address,bytes)").unwrap();
4393        let data = function
4394            .abi_encode_input(&[
4395                DynSolValue::Address(Address::repeat_byte(0x11)),
4396                DynSolValue::Bytes(vec![0x12, 0x34]),
4397            ])
4398            .unwrap();
4399        let trace = CallTrace {
4400            address: RECEIVE_POLICY_GUARD_ADDRESS,
4401            data: data.into(),
4402            success: true,
4403            ..Default::default()
4404        };
4405
4406        let decoder = CallTraceDecoderBuilder::new()
4407            .with_chain_id(Some(4217))
4408            .with_hardfork(Some(TempoHardfork::T6.into()))
4409            .build();
4410        let decoded = decoder.decode_function(&trace).await;
4411
4412        assert_eq!(decoded.label, Some("ReceivePolicyGuard".to_string()));
4413        assert_eq!(decoded.call_data.unwrap().signature, "claim(address,bytes)");
4414    }
4415
4416    #[tokio::test]
4417    async fn test_t6_receive_policy_calls_decode() {
4418        let decoder = CallTraceDecoderBuilder::new()
4419            .with_chain_id(Some(4217))
4420            .with_hardfork(Some(TempoHardfork::T6.into()))
4421            .build();
4422
4423        let set_policy = ITIP403Registry::setReceivePolicyCall {
4424            senderPolicyId: 7,
4425            tokenFilterId: 9,
4426            recoveryAuthority: address!("0x0000000000000000000000000000000000000abc"),
4427        };
4428        let decoded = decoder
4429            .decode_function(&CallTrace {
4430                address: TIP403_REGISTRY_ADDRESS,
4431                data: set_policy.abi_encode().into(),
4432                success: true,
4433                ..Default::default()
4434            })
4435            .await;
4436        let call_data = decoded.call_data.expect("setReceivePolicy should decode");
4437        assert_eq!(decoded.label.as_deref(), Some("TIP403Registry"));
4438        assert_eq!(call_data.signature, "setReceivePolicy(uint64,uint64,address)");
4439        assert_eq!(call_data.args[0], "7");
4440        assert_eq!(call_data.args[1], "9");
4441
4442        let validate = ITIP403Registry::validateReceivePolicyCall {
4443            token: PATH_USD_ADDRESS,
4444            sender: address!("0x0000000000000000000000000000000000000def"),
4445            receiver: address!("0x0000000000000000000000000000000000000123"),
4446        };
4447        let decoded = decoder
4448            .decode_function(&CallTrace {
4449                address: TIP403_REGISTRY_ADDRESS,
4450                data: validate.abi_encode().into(),
4451                success: true,
4452                ..Default::default()
4453            })
4454            .await;
4455        let call_data = decoded.call_data.expect("validateReceivePolicy should decode");
4456        assert_eq!(call_data.signature, "validateReceivePolicy(address,address,address)");
4457        assert!(call_data.args[0].contains("PathUSD"));
4458    }
4459
4460    #[tokio::test]
4461    async fn test_t6_admin_key_calls_decode() {
4462        let decoder = CallTraceDecoderBuilder::new()
4463            .with_chain_id(Some(4217))
4464            .with_hardfork(Some(TempoHardfork::T6.into()))
4465            .build();
4466        let account = address!("0x0000000000000000000000000000000000000abc");
4467        let key = address!("0x0000000000000000000000000000000000000def");
4468        let signature = vec![0x04, 0xaa, 0xbb];
4469
4470        let cases = [
4471            (
4472                ACCOUNT_KEYCHAIN_ADDRESS,
4473                IAccountKeychain::authorizeAdminKeyCall {
4474                    keyId: key,
4475                    signatureType: IAccountKeychain::SignatureType::Secp256k1,
4476                    witness: B256::repeat_byte(0x11),
4477                }
4478                .abi_encode()
4479                .into(),
4480                "authorizeAdminKey(address,uint8,bytes32)",
4481            ),
4482            (
4483                ACCOUNT_KEYCHAIN_ADDRESS,
4484                IAccountKeychain::isAdminKeyCall { account, keyId: key }.abi_encode().into(),
4485                "isAdminKey(address,address)",
4486            ),
4487            (
4488                SIGNATURE_VERIFIER_ADDRESS,
4489                ISignatureVerifier::verifyKeychainCall {
4490                    account,
4491                    hash: B256::repeat_byte(0x22),
4492                    signature: signature.clone().into(),
4493                }
4494                .abi_encode()
4495                .into(),
4496                "verifyKeychain(address,bytes32,bytes)",
4497            ),
4498            (
4499                SIGNATURE_VERIFIER_ADDRESS,
4500                ISignatureVerifier::verifyKeychainAdminCall {
4501                    account,
4502                    hash: B256::repeat_byte(0x33),
4503                    signature: signature.into(),
4504                }
4505                .abi_encode()
4506                .into(),
4507                "verifyKeychainAdmin(address,bytes32,bytes)",
4508            ),
4509        ];
4510
4511        for (address, data, signature) in cases {
4512            let decoded = decoder
4513                .decode_function(&CallTrace { address, data, success: true, ..Default::default() })
4514                .await;
4515            assert_eq!(
4516                decoded.call_data.expect("T6 keychain call should decode").signature,
4517                signature
4518            );
4519        }
4520    }
4521
4522    #[tokio::test]
4523    async fn test_t6_receive_policy_and_admin_events_decode() {
4524        let decoder = CallTraceDecoder::new();
4525        let account = address!("0x0000000000000000000000000000000000000abc");
4526        let key = address!("0x0000000000000000000000000000000000000def");
4527
4528        let events = [
4529            (
4530                ITIP403Registry::ReceivePolicyUpdated {
4531                    account,
4532                    senderPolicyId: 7,
4533                    tokenFilterId: 9,
4534                    recoveryAuthority: key,
4535                }
4536                .encode_log_data(),
4537                "ReceivePolicyUpdated",
4538            ),
4539            (
4540                IAccountKeychain::AdminKeyAuthorized { account, publicKey: key }.encode_log_data(),
4541                "AdminKeyAuthorized",
4542            ),
4543            (
4544                IReceivePolicyGuard::ReceiptClaimed {
4545                    token: PATH_USD_ADDRESS,
4546                    receiver: account,
4547                    blockedNonce: 11,
4548                    blockedAt: 12,
4549                    receiptVersion: 1,
4550                    originator: key,
4551                    recipient: account,
4552                    recoveryAuthority: key,
4553                    caller: key,
4554                    to: account,
4555                    amount: U256::from(123),
4556                }
4557                .encode_log_data(),
4558                "ReceiptClaimed",
4559            ),
4560            (
4561                IReceivePolicyGuard::ReceiptBurned {
4562                    token: PATH_USD_ADDRESS,
4563                    receiver: account,
4564                    blockedNonce: 11,
4565                    blockedAt: 12,
4566                    receiptVersion: 1,
4567                    originator: key,
4568                    recipient: account,
4569                    recoveryAuthority: key,
4570                    caller: key,
4571                    amount: U256::from(123),
4572                }
4573                .encode_log_data(),
4574                "ReceiptBurned",
4575            ),
4576        ];
4577
4578        for (log, expected_name) in events {
4579            let decoded = decoder.decode_event(&log).await;
4580            assert_eq!(decoded.name.as_deref(), Some(expected_name));
4581            assert!(decoded.params.expect("event params should decode").len() >= 2);
4582        }
4583    }
4584
4585    #[tokio::test]
4586    async fn test_t6_claim_receipt_bytes_decode_in_calls_and_transfer_blocked_event() {
4587        let decoder = CallTraceDecoder::new();
4588        let recovery = address!("0x0000000000000000000000000000000000000abc");
4589        let originator = address!("0x0000000000000000000000000000000000000def");
4590        let recipient = address!("0x0000000000000000000000000000000000000123");
4591        let receipt = IReceivePolicyGuard::ClaimReceiptV1::new(
4592            PATH_USD_ADDRESS,
4593            recovery,
4594            originator,
4595            recipient,
4596            12,
4597            34,
4598            ITIP403Registry::BlockedReason::RECEIVE_POLICY as u8,
4599            IReceivePolicyGuard::InboundKind::TRANSFER,
4600            B256::repeat_byte(0x44),
4601        )
4602        .abi_encode();
4603
4604        let claim =
4605            IReceivePolicyGuard::claimCall { to: recipient, receipt: receipt.clone().into() };
4606        let decoded = decoder
4607            .decode_function(&CallTrace {
4608                address: RECEIVE_POLICY_GUARD_ADDRESS,
4609                data: claim.abi_encode().into(),
4610                success: true,
4611                ..Default::default()
4612            })
4613            .await;
4614        let call_data = decoded.call_data.expect("claim should decode");
4615        assert_eq!(call_data.signature, "claim(address,bytes)");
4616        assert!(call_data.args[1].contains("ClaimReceiptV1"));
4617        assert!(call_data.args[1].contains("blockedNonce: 34"));
4618        assert!(call_data.args[1].contains(&originator.to_string()));
4619
4620        let decoded = decoder
4621            .decode_function(&CallTrace {
4622                address: Address::repeat_byte(0x77),
4623                data: claim.abi_encode().into(),
4624                success: true,
4625                ..Default::default()
4626            })
4627            .await;
4628        let call_data = decoded.call_data.expect("matching claim selector should decode");
4629        assert_eq!(call_data.signature, "claim(address,bytes)");
4630        assert!(!call_data.args[1].contains("ClaimReceiptV1"));
4631        assert!(call_data.args[1].starts_with("0x"));
4632
4633        let blocked = IReceivePolicyGuard::TransferBlocked {
4634            token: PATH_USD_ADDRESS,
4635            receiver: recipient,
4636            blockedNonce: 34,
4637            amount: U256::from(123),
4638            receiptVersion: 1,
4639            receipt: receipt.into(),
4640        };
4641        let blocked_log = blocked.encode_log_data();
4642        let decoded =
4643            decoder.decode_event_with_address(RECEIVE_POLICY_GUARD_ADDRESS, &blocked_log).await;
4644        assert_eq!(decoded.name.as_deref(), Some("TransferBlocked"));
4645        let params = decoded.params.expect("TransferBlocked params should decode");
4646        let receipt = params.iter().find(|(name, _)| name == "receipt").unwrap();
4647        assert!(receipt.1.contains("ClaimReceiptV1"));
4648        assert!(receipt.1.contains("blockedReason: 2"));
4649        assert!(receipt.1.contains("kind: 0"));
4650
4651        let decoded =
4652            decoder.decode_event_with_address(Address::repeat_byte(0x77), &blocked_log).await;
4653        assert_eq!(decoded.name.as_deref(), Some("TransferBlocked"));
4654        let params = decoded.params.expect("TransferBlocked params should decode");
4655        let receipt = params.iter().find(|(name, _)| name == "receipt").unwrap();
4656        assert!(!receipt.1.contains("ClaimReceiptV1"));
4657        assert!(receipt.1.starts_with("0x"));
4658    }
4659
4660    #[tokio::test]
4661    async fn test_t14_configurable_account_decode() {
4662        let decoder = CallTraceDecoderBuilder::new()
4663            .with_chain_id(Some(4217))
4664            .with_hardfork(Some(TempoHardfork::T14.into()))
4665            .build();
4666        let account = address!("0x0000000000000000000000000000000000000abc");
4667        let owner = address!("0x0000000000000000000000000000000000000def");
4668        let owners = vec![IConfigurableAccount::ConfigurableAccountOwner { owner, weight: 2 }];
4669        let hash = B256::repeat_byte(0x22);
4670
4671        let update = IConfigurableAccount::updateConfigCall {
4672            current: IConfigurableAccount::ConfigurableAccountConfig {
4673                salt: B256::ZERO,
4674                version: 3,
4675                threshold: 1,
4676                owners: owners.clone(),
4677            },
4678            threshold: 2,
4679            owners: owners.clone(),
4680        };
4681        let decoded = decoder
4682            .decode_function(&CallTrace {
4683                address: CONFIGURABLE_ACCOUNT_ADDRESS,
4684                data: update.abi_encode().into(),
4685                output: IConfigurableAccount::UnauthorizedConfigurableAccountCaller {}
4686                    .abi_encode()
4687                    .into(),
4688                status: Some(InstrStop::Revert),
4689                ..Default::default()
4690            })
4691            .await;
4692        assert_eq!(decoded.label.as_deref(), Some("ConfigurableAccount"));
4693        let call_data = decoded.call_data.expect("updateConfig should decode");
4694        assert_eq!(
4695            call_data.signature,
4696            "updateConfig((bytes32,uint64,uint8,(address,uint8)[]),uint8,(address,uint8)[])"
4697        );
4698        assert_eq!(
4699            call_data.args,
4700            [
4701                format!("(0x{}, 3, 1, [({owner}, 2)])", "0".repeat(64)),
4702                "2".to_string(),
4703                format!("[({owner}, 2)]"),
4704            ]
4705        );
4706        assert_eq!(decoded.return_data.as_deref(), Some("UnauthorizedConfigurableAccountCaller()"));
4707
4708        // The shim runs at the account's own address, not at the precompile.
4709        let decoded = decoder
4710            .decode_function(&CallTrace {
4711                address: account,
4712                data: IConfigurableAccountShim::isValidSignatureCall {
4713                    hash,
4714                    signature: vec![0x05, 0xaa].into(),
4715                }
4716                .abi_encode()
4717                .into(),
4718                output: IConfigurableAccountShim::isValidSignatureCall::abi_encode_returns(
4719                    &IConfigurableAccountShim::isValidSignatureCall::SELECTOR.into(),
4720                )
4721                .into(),
4722                success: true,
4723                ..Default::default()
4724            })
4725            .await;
4726        assert_eq!(decoded.label, None);
4727        let call_data = decoded.call_data.expect("isValidSignature should decode");
4728        assert_eq!(call_data.signature, "isValidSignature(bytes32,bytes)");
4729        assert_eq!(call_data.args, [hash.to_string(), "0x05aa".to_string()]);
4730        assert_eq!(decoded.return_data.as_deref(), Some("0x1626ba7e"));
4731
4732        let decoded = decoder
4733            .decode_function(&CallTrace {
4734                address: SIGNATURE_VERIFIER_ADDRESS,
4735                data: ISignatureVerifier::verifyConfigurableAccountCall {
4736                    account,
4737                    hash,
4738                    signature: vec![0x05].into(),
4739                }
4740                .abi_encode()
4741                .into(),
4742                output: true.abi_encode().into(),
4743                success: true,
4744                ..Default::default()
4745            })
4746            .await;
4747        assert_eq!(decoded.label.as_deref(), Some("SignatureVerifier"));
4748        assert_eq!(
4749            decoded.call_data.expect("verifyConfigurableAccount should decode").signature,
4750            "verifyConfigurableAccount(address,bytes32,bytes)"
4751        );
4752        assert_eq!(decoded.return_data.as_deref(), Some("true"));
4753
4754        let events = [
4755            (
4756                IConfigurableAccount::ConfigurableAccountConfigUpdated {
4757                    account,
4758                    salt: B256::ZERO,
4759                    version: 4,
4760                    threshold: 2,
4761                    owners: owners.clone(),
4762                }
4763                .encode_log_data(),
4764                "ConfigurableAccountConfigUpdated",
4765            ),
4766            (
4767                IConfigurableAccount::AccountUpgraded {
4768                    account,
4769                    commitment: B256::repeat_byte(0x33),
4770                    salt: B256::ZERO,
4771                    threshold: 2,
4772                    owners,
4773                }
4774                .encode_log_data(),
4775                "AccountUpgraded",
4776            ),
4777        ];
4778        for (log, name) in events {
4779            let decoded =
4780                decoder.decode_event_with_address(CONFIGURABLE_ACCOUNT_ADDRESS, &log).await;
4781            assert_eq!(decoded.name.as_deref(), Some(name));
4782            let params = decoded.params.expect("event params should decode");
4783            assert_eq!(params[0], ("account".to_string(), account.to_string()));
4784            assert_eq!(params.last().unwrap(), &("owners".to_string(), format!("[({owner}, 2)]")));
4785        }
4786    }
4787
4788    #[test]
4789    fn test_identify_addresses_does_not_skip_future_tempo_precompiles() {
4790        let decoder = CallTraceDecoderBuilder::new()
4791            .with_chain_id(Some(4217))
4792            .with_hardfork(Some(TempoHardfork::T4.into()))
4793            .build();
4794
4795        let mut arena = CallTraceArena::default();
4796        let regular_addr = Address::repeat_byte(0x42);
4797        arena.nodes_mut()[0].trace.address = regular_addr;
4798
4799        arena.nodes_mut().push(CallTraceNode {
4800            trace: CallTrace {
4801                address: TIP20_CHANNEL_RESERVE_ADDRESS,
4802                depth: 1,
4803                maybe_precompile: None,
4804                ..Default::default()
4805            },
4806            idx: 1,
4807            ..Default::default()
4808        });
4809
4810        let mut identifier = RecordingIdentifier { queried: Vec::new() };
4811        decoder.identify_addresses(&arena, &mut identifier);
4812
4813        assert_eq!(identifier.queried, vec![regular_addr, TIP20_CHANNEL_RESERVE_ADDRESS]);
4814    }
4815
4816    #[test]
4817    fn test_identify_addresses_does_not_skip_tempo_precompiles_on_other_chains() {
4818        // Decoder with Ethereum mainnet chain ID (1).
4819        let mut decoder = CallTraceDecoder::new().clone();
4820        decoder.chain_id = Some(1);
4821
4822        let mut arena = CallTraceArena::default();
4823        let regular_addr = Address::repeat_byte(0x42);
4824        arena.nodes_mut()[0].trace.address = regular_addr;
4825
4826        let tempo_precompile = TEMPO_PRECOMPILE_ADDRESSES[0];
4827        arena.nodes_mut().push(CallTraceNode {
4828            trace: CallTrace {
4829                address: tempo_precompile,
4830                depth: 1,
4831                maybe_precompile: None,
4832                ..Default::default()
4833            },
4834            idx: 1,
4835            ..Default::default()
4836        });
4837
4838        let mut identifier = RecordingIdentifier { queried: Vec::new() };
4839        decoder.identify_addresses(&arena, &mut identifier);
4840
4841        // On Ethereum, Tempo precompile addresses are regular contracts — should NOT be filtered.
4842        assert_eq!(identifier.queried, vec![regular_addr, tempo_precompile]);
4843    }
4844
4845    #[test]
4846    #[cfg(feature = "monad")]
4847    fn test_identify_addresses_skips_monad_precompiles() {
4848        let decoder = monad_decoder(MonadHardfork::MonadNine);
4849
4850        let mut arena = CallTraceArena::default();
4851        let regular_addr = Address::repeat_byte(0x42);
4852        arena.nodes_mut()[0].trace.address = regular_addr;
4853
4854        arena.nodes_mut().push(CallTraceNode {
4855            trace: CallTrace {
4856                address: monad_evm2::staking::STAKING_ADDRESS,
4857                depth: 1,
4858                maybe_precompile: None,
4859                ..Default::default()
4860            },
4861            idx: 1,
4862            ..Default::default()
4863        });
4864        arena.nodes_mut().push(CallTraceNode {
4865            trace: CallTrace {
4866                address: monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
4867                depth: 1,
4868                maybe_precompile: None,
4869                ..Default::default()
4870            },
4871            idx: 2,
4872            ..Default::default()
4873        });
4874
4875        let mut identifier = RecordingIdentifier { queried: Vec::new() };
4876        decoder.identify_addresses(&arena, &mut identifier);
4877
4878        assert_eq!(identifier.queried, vec![regular_addr]);
4879    }
4880
4881    #[test]
4882    #[cfg(feature = "monad")]
4883    fn test_identify_addresses_does_not_skip_monad_precompiles_on_other_chains() {
4884        let decoder = CallTraceDecoderBuilder::new().with_chain_id(Some(1)).build();
4885
4886        let mut arena = CallTraceArena::default();
4887        let regular_addr = Address::repeat_byte(0x42);
4888        arena.nodes_mut()[0].trace.address = regular_addr;
4889
4890        arena.nodes_mut().push(CallTraceNode {
4891            trace: CallTrace {
4892                address: monad_evm2::staking::STAKING_ADDRESS,
4893                depth: 1,
4894                maybe_precompile: None,
4895                ..Default::default()
4896            },
4897            idx: 1,
4898            ..Default::default()
4899        });
4900        arena.nodes_mut().push(CallTraceNode {
4901            trace: CallTrace {
4902                address: monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
4903                depth: 1,
4904                maybe_precompile: None,
4905                ..Default::default()
4906            },
4907            idx: 2,
4908            ..Default::default()
4909        });
4910
4911        let mut identifier = RecordingIdentifier { queried: Vec::new() };
4912        decoder.identify_addresses(&arena, &mut identifier);
4913
4914        assert_eq!(
4915            identifier.queried,
4916            vec![
4917                regular_addr,
4918                monad_evm2::staking::STAKING_ADDRESS,
4919                monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
4920            ]
4921        );
4922    }
4923
4924    #[test]
4925    #[cfg(feature = "monad")]
4926    fn execution_network_overrides_nested_source_monad_precompile_detection() {
4927        assert!(!precompiles::is_known_precompile(
4928            monad_evm2::reserve_balance::RESERVE_BALANCE_ADDRESS,
4929            Some(NetworkVariant::Ethereum.into()),
4930            Some(143),
4931            Some(MonadHardfork::MonadNine.into()),
4932        ));
4933    }
4934}