foundry_evm/executors/
mod.rs

1//! EVM executor abstractions, which can execute calls.
2//!
3//! Used for running tests, scripts, and interacting with the inner backend which holds the state.
4
5// TODO: The individual executors in this module should be moved into the respective crates, and the
6// `Executor` struct should be accessed using a trait defined in `foundry-evm-core` instead of
7// the concrete `Executor` type.
8
9use crate::{
10    Env,
11    inspectors::{
12        Cheatcodes, InspectorData, InspectorStack, cheatcodes::BroadcastableTransactions,
13    },
14};
15use alloy_dyn_abi::{DynSolValue, FunctionExt, JsonAbiExt};
16use alloy_json_abi::Function;
17use alloy_primitives::{
18    Address, Bytes, Log, TxKind, U256, keccak256,
19    map::{AddressHashMap, HashMap},
20};
21use alloy_sol_types::{SolCall, sol};
22use foundry_evm_core::{
23    EvmEnv,
24    backend::{Backend, BackendError, BackendResult, CowBackend, DatabaseExt, GLOBAL_FAIL_SLOT},
25    constants::{
26        CALLER, CHEATCODE_ADDRESS, CHEATCODE_CONTRACT_HASH, DEFAULT_CREATE2_DEPLOYER,
27        DEFAULT_CREATE2_DEPLOYER_CODE, DEFAULT_CREATE2_DEPLOYER_DEPLOYER,
28    },
29    decode::{RevertDecoder, SkipReason},
30    utils::StateChangeset,
31};
32use foundry_evm_coverage::HitMaps;
33use foundry_evm_traces::{SparsedTraceArena, TraceMode};
34use revm::{
35    bytecode::Bytecode,
36    context::{BlockEnv, TxEnv},
37    context_interface::{
38        result::{ExecutionResult, Output, ResultAndState},
39        transaction::SignedAuthorization,
40    },
41    database::{DatabaseCommit, DatabaseRef},
42    interpreter::{InstructionResult, return_ok},
43    primitives::hardfork::SpecId,
44};
45use std::{
46    borrow::Cow,
47    sync::{
48        Arc,
49        atomic::{AtomicBool, Ordering},
50    },
51    time::{Duration, Instant},
52};
53
54mod builder;
55pub use builder::ExecutorBuilder;
56
57pub mod fuzz;
58pub use fuzz::FuzzedExecutor;
59
60pub mod invariant;
61pub use invariant::InvariantExecutor;
62
63mod corpus;
64mod trace;
65
66pub use trace::TracingExecutor;
67
68const DURATION_BETWEEN_METRICS_REPORT: Duration = Duration::from_secs(5);
69
70sol! {
71    interface ITest {
72        function setUp() external;
73        function failed() external view returns (bool failed);
74
75        #[derive(Default)]
76        function beforeTestSetup(bytes4 testSelector) public view returns (bytes[] memory beforeTestCalldata);
77    }
78}
79
80/// EVM executor.
81///
82/// The executor can be configured with various `revm::Inspector`s, like `Cheatcodes`.
83///
84/// There are multiple ways of interacting the EVM:
85/// - `call`: executes a transaction, but does not persist any state changes; similar to `eth_call`,
86///   where the EVM state is unchanged after the call.
87/// - `transact`: executes a transaction and persists the state changes
88/// - `deploy`: a special case of `transact`, specialized for persisting the state of a contract
89///   deployment
90/// - `setup`: a special case of `transact`, used to set up the environment for a test
91#[derive(Clone, Debug)]
92pub struct Executor {
93    /// The underlying `revm::Database` that contains the EVM storage.
94    // Note: We do not store an EVM here, since we are really
95    // only interested in the database. REVM's `EVM` is a thin
96    // wrapper around spawning a new EVM on every call anyway,
97    // so the performance difference should be negligible.
98    backend: Backend,
99    /// The EVM environment.
100    env: Env,
101    /// The Revm inspector stack.
102    inspector: InspectorStack,
103    /// The gas limit for calls and deployments.
104    gas_limit: u64,
105    /// Whether `failed()` should be called on the test contract to determine if the test failed.
106    legacy_assertions: bool,
107}
108
109impl Executor {
110    /// Creates a new `ExecutorBuilder`.
111    #[inline]
112    pub fn builder() -> ExecutorBuilder {
113        ExecutorBuilder::new()
114    }
115
116    /// Creates a new `Executor` with the given arguments.
117    #[inline]
118    pub fn new(
119        mut backend: Backend,
120        env: Env,
121        inspector: InspectorStack,
122        gas_limit: u64,
123        legacy_assertions: bool,
124    ) -> Self {
125        // Need to create a non-empty contract on the cheatcodes address so `extcodesize` checks
126        // do not fail.
127        backend.insert_account_info(
128            CHEATCODE_ADDRESS,
129            revm::state::AccountInfo {
130                code: Some(Bytecode::new_raw(Bytes::from_static(&[0]))),
131                // Also set the code hash manually so that it's not computed later.
132                // The code hash value does not matter, as long as it's not zero or `KECCAK_EMPTY`.
133                code_hash: CHEATCODE_CONTRACT_HASH,
134                ..Default::default()
135            },
136        );
137
138        Self { backend, env, inspector, gas_limit, legacy_assertions }
139    }
140
141    fn clone_with_backend(&self, backend: Backend) -> Self {
142        let env = Env::new_with_spec_id(
143            self.env.evm_env.cfg_env.clone(),
144            self.env.evm_env.block_env.clone(),
145            self.env.tx.clone(),
146            self.spec_id(),
147        );
148        Self::new(backend, env, self.inspector().clone(), self.gas_limit, self.legacy_assertions)
149    }
150
151    /// Returns a reference to the EVM backend.
152    pub fn backend(&self) -> &Backend {
153        &self.backend
154    }
155
156    /// Returns a mutable reference to the EVM backend.
157    pub fn backend_mut(&mut self) -> &mut Backend {
158        &mut self.backend
159    }
160
161    /// Returns a reference to the EVM environment.
162    pub fn env(&self) -> &Env {
163        &self.env
164    }
165
166    /// Returns a mutable reference to the EVM environment.
167    pub fn env_mut(&mut self) -> &mut Env {
168        &mut self.env
169    }
170
171    /// Returns a reference to the EVM inspector.
172    pub fn inspector(&self) -> &InspectorStack {
173        &self.inspector
174    }
175
176    /// Returns a mutable reference to the EVM inspector.
177    pub fn inspector_mut(&mut self) -> &mut InspectorStack {
178        &mut self.inspector
179    }
180
181    /// Returns the EVM spec ID.
182    pub fn spec_id(&self) -> SpecId {
183        self.env.evm_env.cfg_env.spec
184    }
185
186    /// Sets the EVM spec ID.
187    pub fn set_spec_id(&mut self, spec_id: SpecId) {
188        self.env.evm_env.cfg_env.spec = spec_id;
189    }
190
191    /// Returns the gas limit for calls and deployments.
192    ///
193    /// This is different from the gas limit imposed by the passed in environment, as those limits
194    /// are used by the EVM for certain opcodes like `gaslimit`.
195    pub fn gas_limit(&self) -> u64 {
196        self.gas_limit
197    }
198
199    /// Sets the gas limit for calls and deployments.
200    pub fn set_gas_limit(&mut self, gas_limit: u64) {
201        self.gas_limit = gas_limit;
202    }
203
204    /// Returns whether `failed()` should be called on the test contract to determine if the test
205    /// failed.
206    pub fn legacy_assertions(&self) -> bool {
207        self.legacy_assertions
208    }
209
210    /// Sets whether `failed()` should be called on the test contract to determine if the test
211    /// failed.
212    pub fn set_legacy_assertions(&mut self, legacy_assertions: bool) {
213        self.legacy_assertions = legacy_assertions;
214    }
215
216    /// Creates the default CREATE2 Contract Deployer for local tests and scripts.
217    pub fn deploy_create2_deployer(&mut self) -> eyre::Result<()> {
218        trace!("deploying local create2 deployer");
219        let create2_deployer_account = self
220            .backend()
221            .basic_ref(DEFAULT_CREATE2_DEPLOYER)?
222            .ok_or_else(|| BackendError::MissingAccount(DEFAULT_CREATE2_DEPLOYER))?;
223
224        // If the deployer is not currently deployed, deploy the default one.
225        if create2_deployer_account.code.is_none_or(|code| code.is_empty()) {
226            let creator = DEFAULT_CREATE2_DEPLOYER_DEPLOYER;
227
228            // Probably 0, but just in case.
229            let initial_balance = self.get_balance(creator)?;
230            self.set_balance(creator, U256::MAX)?;
231
232            let res =
233                self.deploy(creator, DEFAULT_CREATE2_DEPLOYER_CODE.into(), U256::ZERO, None)?;
234            trace!(create2=?res.address, "deployed local create2 deployer");
235
236            self.set_balance(creator, initial_balance)?;
237        }
238        Ok(())
239    }
240
241    /// Set the balance of an account.
242    pub fn set_balance(&mut self, address: Address, amount: U256) -> BackendResult<()> {
243        trace!(?address, ?amount, "setting account balance");
244        let mut account = self.backend().basic_ref(address)?.unwrap_or_default();
245        account.balance = amount;
246        self.backend_mut().insert_account_info(address, account);
247        Ok(())
248    }
249
250    /// Gets the balance of an account
251    pub fn get_balance(&self, address: Address) -> BackendResult<U256> {
252        Ok(self.backend().basic_ref(address)?.map(|acc| acc.balance).unwrap_or_default())
253    }
254
255    /// Set the nonce of an account.
256    pub fn set_nonce(&mut self, address: Address, nonce: u64) -> BackendResult<()> {
257        let mut account = self.backend().basic_ref(address)?.unwrap_or_default();
258        account.nonce = nonce;
259        self.backend_mut().insert_account_info(address, account);
260        self.env_mut().tx.nonce = nonce;
261        Ok(())
262    }
263
264    /// Returns the nonce of an account.
265    pub fn get_nonce(&self, address: Address) -> BackendResult<u64> {
266        Ok(self.backend().basic_ref(address)?.map(|acc| acc.nonce).unwrap_or_default())
267    }
268
269    /// Set the code of an account.
270    pub fn set_code(&mut self, address: Address, code: Bytecode) -> BackendResult<()> {
271        let mut account = self.backend().basic_ref(address)?.unwrap_or_default();
272        account.code_hash = keccak256(code.original_byte_slice());
273        account.code = Some(code);
274        self.backend_mut().insert_account_info(address, account);
275        Ok(())
276    }
277
278    /// Set the storage of an account.
279    pub fn set_storage(
280        &mut self,
281        address: Address,
282        storage: HashMap<U256, U256>,
283    ) -> BackendResult<()> {
284        self.backend_mut().replace_account_storage(address, storage)?;
285        Ok(())
286    }
287
288    /// Set a storage slot of an account.
289    pub fn set_storage_slot(
290        &mut self,
291        address: Address,
292        slot: U256,
293        value: U256,
294    ) -> BackendResult<()> {
295        self.backend_mut().insert_account_storage(address, slot, value)?;
296        Ok(())
297    }
298
299    /// Returns `true` if the account has no code.
300    pub fn is_empty_code(&self, address: Address) -> BackendResult<bool> {
301        Ok(self.backend().basic_ref(address)?.map(|acc| acc.is_empty_code_hash()).unwrap_or(true))
302    }
303
304    #[inline]
305    pub fn set_tracing(&mut self, mode: TraceMode) -> &mut Self {
306        self.inspector_mut().tracing(mode);
307        self
308    }
309
310    #[inline]
311    pub fn set_script_execution(&mut self, script_address: Address) {
312        self.inspector_mut().script(script_address);
313    }
314
315    #[inline]
316    pub fn set_trace_printer(&mut self, trace_printer: bool) -> &mut Self {
317        self.inspector_mut().print(trace_printer);
318        self
319    }
320
321    #[inline]
322    pub fn create2_deployer(&self) -> Address {
323        self.inspector().create2_deployer
324    }
325
326    /// Deploys a contract and commits the new state to the underlying database.
327    ///
328    /// Executes a CREATE transaction with the contract `code` and persistent database state
329    /// modifications.
330    pub fn deploy(
331        &mut self,
332        from: Address,
333        code: Bytes,
334        value: U256,
335        rd: Option<&RevertDecoder>,
336    ) -> Result<DeployResult, EvmError> {
337        let env = self.build_test_env(from, TxKind::Create, code, value);
338        self.deploy_with_env(env, rd)
339    }
340
341    /// Deploys a contract using the given `env` and commits the new state to the underlying
342    /// database.
343    ///
344    /// # Panics
345    ///
346    /// Panics if `env.tx.kind` is not `TxKind::Create(_)`.
347    #[instrument(name = "deploy", level = "debug", skip_all)]
348    pub fn deploy_with_env(
349        &mut self,
350        env: Env,
351        rd: Option<&RevertDecoder>,
352    ) -> Result<DeployResult, EvmError> {
353        assert!(
354            matches!(env.tx.kind, TxKind::Create),
355            "Expected create transaction, got {:?}",
356            env.tx.kind
357        );
358        trace!(sender=%env.tx.caller, "deploying contract");
359
360        let mut result = self.transact_with_env(env)?;
361        result = result.into_result(rd)?;
362        let Some(Output::Create(_, Some(address))) = result.out else {
363            panic!("Deployment succeeded, but no address was returned: {result:#?}");
364        };
365
366        // also mark this library as persistent, this will ensure that the state of the library is
367        // persistent across fork swaps in forking mode
368        self.backend_mut().add_persistent_account(address);
369
370        debug!(%address, "deployed contract");
371
372        Ok(DeployResult { raw: result, address })
373    }
374
375    /// Calls the `setUp()` function on a contract.
376    ///
377    /// This will commit any state changes to the underlying database.
378    ///
379    /// Ayn changes made during the setup call to env's block environment are persistent, for
380    /// example `vm.chainId()` will change the `block.chainId` for all subsequent test calls.
381    #[instrument(name = "setup", level = "debug", skip_all)]
382    pub fn setup(
383        &mut self,
384        from: Option<Address>,
385        to: Address,
386        rd: Option<&RevertDecoder>,
387    ) -> Result<RawCallResult, EvmError> {
388        trace!(?from, ?to, "setting up contract");
389
390        let from = from.unwrap_or(CALLER);
391        self.backend_mut().set_test_contract(to).set_caller(from);
392        let calldata = Bytes::from_static(&ITest::setUpCall::SELECTOR);
393        let mut res = self.transact_raw(from, to, calldata, U256::ZERO)?;
394        res = res.into_result(rd)?;
395
396        // record any changes made to the block's environment during setup
397        self.env_mut().evm_env.block_env = res.env.evm_env.block_env.clone();
398        // and also the chainid, which can be set manually
399        self.env_mut().evm_env.cfg_env.chain_id = res.env.evm_env.cfg_env.chain_id;
400
401        let success =
402            self.is_raw_call_success(to, Cow::Borrowed(&res.state_changeset), &res, false);
403        if !success {
404            return Err(res.into_execution_error("execution error".to_string()).into());
405        }
406
407        Ok(res)
408    }
409
410    /// Performs a call to an account on the current state of the VM.
411    pub fn call(
412        &self,
413        from: Address,
414        to: Address,
415        func: &Function,
416        args: &[DynSolValue],
417        value: U256,
418        rd: Option<&RevertDecoder>,
419    ) -> Result<CallResult, EvmError> {
420        let calldata = Bytes::from(func.abi_encode_input(args)?);
421        let result = self.call_raw(from, to, calldata, value)?;
422        result.into_decoded_result(func, rd)
423    }
424
425    /// Performs a call to an account on the current state of the VM.
426    pub fn call_sol<C: SolCall>(
427        &self,
428        from: Address,
429        to: Address,
430        args: &C,
431        value: U256,
432        rd: Option<&RevertDecoder>,
433    ) -> Result<CallResult<C::Return>, EvmError> {
434        let calldata = Bytes::from(args.abi_encode());
435        let mut raw = self.call_raw(from, to, calldata, value)?;
436        raw = raw.into_result(rd)?;
437        Ok(CallResult { decoded_result: C::abi_decode_returns(&raw.result)?, raw })
438    }
439
440    /// Performs a call to an account on the current state of the VM.
441    pub fn transact(
442        &mut self,
443        from: Address,
444        to: Address,
445        func: &Function,
446        args: &[DynSolValue],
447        value: U256,
448        rd: Option<&RevertDecoder>,
449    ) -> Result<CallResult, EvmError> {
450        let calldata = Bytes::from(func.abi_encode_input(args)?);
451        let result = self.transact_raw(from, to, calldata, value)?;
452        result.into_decoded_result(func, rd)
453    }
454
455    /// Performs a raw call to an account on the current state of the VM.
456    pub fn call_raw(
457        &self,
458        from: Address,
459        to: Address,
460        calldata: Bytes,
461        value: U256,
462    ) -> eyre::Result<RawCallResult> {
463        let env = self.build_test_env(from, TxKind::Call(to), calldata, value);
464        self.call_with_env(env)
465    }
466
467    /// Performs a raw call to an account on the current state of the VM with an EIP-7702
468    /// authorization list.
469    pub fn call_raw_with_authorization(
470        &mut self,
471        from: Address,
472        to: Address,
473        calldata: Bytes,
474        value: U256,
475        authorization_list: Vec<SignedAuthorization>,
476    ) -> eyre::Result<RawCallResult> {
477        let mut env = self.build_test_env(from, to.into(), calldata, value);
478        env.tx.set_signed_authorization(authorization_list);
479        env.tx.tx_type = 4;
480        self.call_with_env(env)
481    }
482
483    /// Performs a raw call to an account on the current state of the VM.
484    pub fn transact_raw(
485        &mut self,
486        from: Address,
487        to: Address,
488        calldata: Bytes,
489        value: U256,
490    ) -> eyre::Result<RawCallResult> {
491        let env = self.build_test_env(from, TxKind::Call(to), calldata, value);
492        self.transact_with_env(env)
493    }
494
495    /// Execute the transaction configured in `env.tx`.
496    ///
497    /// The state after the call is **not** persisted.
498    #[instrument(name = "call", level = "debug", skip_all)]
499    pub fn call_with_env(&self, mut env: Env) -> eyre::Result<RawCallResult> {
500        let mut stack = self.inspector().clone();
501        let mut backend = CowBackend::new_borrowed(self.backend());
502        let result = backend.inspect(&mut env, stack.as_inspector())?;
503        convert_executed_result(env, stack, result, backend.has_state_snapshot_failure())
504    }
505
506    /// Execute the transaction configured in `env.tx`.
507    #[instrument(name = "transact", level = "debug", skip_all)]
508    pub fn transact_with_env(&mut self, mut env: Env) -> eyre::Result<RawCallResult> {
509        let mut stack = self.inspector().clone();
510        let backend = self.backend_mut();
511        let result = backend.inspect(&mut env, stack.as_inspector())?;
512        let mut result =
513            convert_executed_result(env, stack, result, backend.has_state_snapshot_failure())?;
514        self.commit(&mut result);
515        Ok(result)
516    }
517
518    /// Commit the changeset to the database and adjust `self.inspector_config` values according to
519    /// the executed call result.
520    ///
521    /// This should not be exposed to the user, as it should be called only by `transact*`.
522    #[instrument(name = "commit", level = "debug", skip_all)]
523    fn commit(&mut self, result: &mut RawCallResult) {
524        // Persist changes to db.
525        self.backend_mut().commit(result.state_changeset.clone());
526
527        // Persist cheatcode state.
528        self.inspector_mut().cheatcodes = result.cheatcodes.take();
529        if let Some(cheats) = self.inspector_mut().cheatcodes.as_mut() {
530            // Clear broadcastable transactions
531            cheats.broadcastable_transactions.clear();
532            cheats.ignored_traces.ignored.clear();
533
534            // if tracing was paused but never unpaused, we should begin next frame with tracing
535            // still paused
536            if let Some(last_pause_call) = cheats.ignored_traces.last_pause_call.as_mut() {
537                *last_pause_call = (0, 0);
538            }
539        }
540
541        // Persist the changed environment.
542        self.inspector_mut().set_env(&result.env);
543    }
544
545    /// Returns `true` if a test can be considered successful.
546    ///
547    /// This is the same as [`Self::is_success`], but will consume the `state_changeset` map to use
548    /// internally when calling `failed()`.
549    pub fn is_raw_call_mut_success(
550        &self,
551        address: Address,
552        call_result: &mut RawCallResult,
553        should_fail: bool,
554    ) -> bool {
555        self.is_raw_call_success(
556            address,
557            Cow::Owned(std::mem::take(&mut call_result.state_changeset)),
558            call_result,
559            should_fail,
560        )
561    }
562
563    /// Returns `true` if a test can be considered successful.
564    ///
565    /// This is the same as [`Self::is_success`], but intended for outcomes of [`Self::call_raw`].
566    pub fn is_raw_call_success(
567        &self,
568        address: Address,
569        state_changeset: Cow<'_, StateChangeset>,
570        call_result: &RawCallResult,
571        should_fail: bool,
572    ) -> bool {
573        if call_result.has_state_snapshot_failure {
574            // a failure occurred in a reverted snapshot, which is considered a failed test
575            return should_fail;
576        }
577        self.is_success(address, call_result.reverted, state_changeset, should_fail)
578    }
579
580    /// Returns `true` if a test can be considered successful.
581    ///
582    /// If the call succeeded, we also have to check the global and local failure flags.
583    ///
584    /// These are set by the test contract itself when an assertion fails, using the internal `fail`
585    /// function. The global flag is located in [`CHEATCODE_ADDRESS`] at slot [`GLOBAL_FAIL_SLOT`],
586    /// and the local flag is located in the test contract at an unspecified slot.
587    ///
588    /// This behavior is inherited from Dapptools, where initially only a public
589    /// `failed` variable was used to track test failures, and later, a global failure flag was
590    /// introduced to track failures across multiple contracts in
591    /// [ds-test#30](https://github.com/dapphub/ds-test/pull/30).
592    ///
593    /// The assumption is that the test runner calls `failed` on the test contract to determine if
594    /// it failed. However, we want to avoid this as much as possible, as it is relatively
595    /// expensive to set up an EVM call just for checking a single boolean flag.
596    ///
597    /// See:
598    /// - Newer DSTest: <https://github.com/dapphub/ds-test/blob/e282159d5170298eb2455a6c05280ab5a73a4ef0/src/test.sol#L47-L63>
599    /// - Older DSTest: <https://github.com/dapphub/ds-test/blob/9ca4ecd48862b40d7b0197b600713f64d337af12/src/test.sol#L38-L49>
600    /// - forge-std: <https://github.com/foundry-rs/forge-std/blob/19891e6a0b5474b9ea6827ddb90bb9388f7acfc0/src/StdAssertions.sol#L38-L44>
601    pub fn is_success(
602        &self,
603        address: Address,
604        reverted: bool,
605        state_changeset: Cow<'_, StateChangeset>,
606        should_fail: bool,
607    ) -> bool {
608        let success = self.is_success_raw(address, reverted, state_changeset);
609        should_fail ^ success
610    }
611
612    #[instrument(name = "is_success", level = "debug", skip_all)]
613    fn is_success_raw(
614        &self,
615        address: Address,
616        reverted: bool,
617        state_changeset: Cow<'_, StateChangeset>,
618    ) -> bool {
619        // The call reverted.
620        if reverted {
621            return false;
622        }
623
624        // A failure occurred in a reverted snapshot, which is considered a failed test.
625        if self.backend().has_state_snapshot_failure() {
626            return false;
627        }
628
629        // Check the global failure slot.
630        if let Some(acc) = state_changeset.get(&CHEATCODE_ADDRESS)
631            && let Some(failed_slot) = acc.storage.get(&GLOBAL_FAIL_SLOT)
632            && !failed_slot.present_value().is_zero()
633        {
634            return false;
635        }
636        if let Ok(failed_slot) = self.backend().storage_ref(CHEATCODE_ADDRESS, GLOBAL_FAIL_SLOT)
637            && !failed_slot.is_zero()
638        {
639            return false;
640        }
641
642        if !self.legacy_assertions {
643            return true;
644        }
645
646        // Finally, resort to calling `DSTest::failed`.
647        {
648            // Construct a new bare-bones backend to evaluate success.
649            let mut backend = self.backend().clone_empty();
650
651            // We only clone the test contract and cheatcode accounts,
652            // that's all we need to evaluate success.
653            for address in [address, CHEATCODE_ADDRESS] {
654                let Ok(acc) = self.backend().basic_ref(address) else { return false };
655                backend.insert_account_info(address, acc.unwrap_or_default());
656            }
657
658            // If this test failed any asserts, then this changeset will contain changes
659            // `false -> true` for the contract's `failed` variable and the `globalFailure` flag
660            // in the state of the cheatcode address,
661            // which are both read when we call `"failed()(bool)"` in the next step.
662            backend.commit(state_changeset.into_owned());
663
664            // Check if a DSTest assertion failed
665            let executor = self.clone_with_backend(backend);
666            let call = executor.call_sol(CALLER, address, &ITest::failedCall {}, U256::ZERO, None);
667            match call {
668                Ok(CallResult { raw: _, decoded_result: failed }) => {
669                    trace!(failed, "DSTest::failed()");
670                    !failed
671                }
672                Err(err) => {
673                    trace!(%err, "failed to call DSTest::failed()");
674                    true
675                }
676            }
677        }
678    }
679
680    /// Creates the environment to use when executing a transaction in a test context
681    ///
682    /// If using a backend with cheatcodes, `tx.gas_price` and `block.number` will be overwritten by
683    /// the cheatcode state in between calls.
684    fn build_test_env(&self, caller: Address, kind: TxKind, data: Bytes, value: U256) -> Env {
685        Env {
686            evm_env: EvmEnv {
687                cfg_env: {
688                    let mut cfg = self.env().evm_env.cfg_env.clone();
689                    cfg.spec = self.spec_id();
690                    cfg
691                },
692                // We always set the gas price to 0 so we can execute the transaction regardless of
693                // network conditions - the actual gas price is kept in `self.block` and is applied
694                // by the cheatcode handler if it is enabled
695                block_env: BlockEnv {
696                    basefee: 0,
697                    gas_limit: self.gas_limit,
698                    ..self.env().evm_env.block_env.clone()
699                },
700            },
701            tx: TxEnv {
702                caller,
703                kind,
704                data,
705                value,
706                // As above, we set the gas price to 0.
707                gas_price: 0,
708                gas_priority_fee: None,
709                gas_limit: self.gas_limit,
710                chain_id: Some(self.env().evm_env.cfg_env.chain_id),
711                ..self.env().tx.clone()
712            },
713        }
714    }
715
716    pub fn call_sol_default<C: SolCall>(&self, to: Address, args: &C) -> C::Return
717    where
718        C::Return: Default,
719    {
720        self.call_sol(CALLER, to, args, U256::ZERO, None)
721            .map(|c| c.decoded_result)
722            .inspect_err(|e| warn!(target: "forge::test", "failed calling {:?}: {e}", C::SIGNATURE))
723            .unwrap_or_default()
724    }
725}
726
727/// Represents the context after an execution error occurred.
728#[derive(Debug, thiserror::Error)]
729#[error("execution reverted: {reason} (gas: {})", raw.gas_used)]
730pub struct ExecutionErr {
731    /// The raw result of the call.
732    pub raw: RawCallResult,
733    /// The revert reason.
734    pub reason: String,
735}
736
737impl std::ops::Deref for ExecutionErr {
738    type Target = RawCallResult;
739
740    #[inline]
741    fn deref(&self) -> &Self::Target {
742        &self.raw
743    }
744}
745
746impl std::ops::DerefMut for ExecutionErr {
747    #[inline]
748    fn deref_mut(&mut self) -> &mut Self::Target {
749        &mut self.raw
750    }
751}
752
753#[derive(Debug, thiserror::Error)]
754pub enum EvmError {
755    /// Error which occurred during execution of a transaction.
756    #[error(transparent)]
757    Execution(#[from] Box<ExecutionErr>),
758    /// Error which occurred during ABI encoding/decoding.
759    #[error(transparent)]
760    Abi(#[from] alloy_dyn_abi::Error),
761    /// Error caused which occurred due to calling the `skip` cheatcode.
762    #[error("{0}")]
763    Skip(SkipReason),
764    /// Any other error.
765    #[error("{0}")]
766    Eyre(
767        #[from]
768        #[source]
769        eyre::Report,
770    ),
771}
772
773impl From<ExecutionErr> for EvmError {
774    fn from(err: ExecutionErr) -> Self {
775        Self::Execution(Box::new(err))
776    }
777}
778
779impl From<alloy_sol_types::Error> for EvmError {
780    fn from(err: alloy_sol_types::Error) -> Self {
781        Self::Abi(err.into())
782    }
783}
784
785/// The result of a deployment.
786#[derive(Debug)]
787pub struct DeployResult {
788    /// The raw result of the deployment.
789    pub raw: RawCallResult,
790    /// The address of the deployed contract
791    pub address: Address,
792}
793
794impl std::ops::Deref for DeployResult {
795    type Target = RawCallResult;
796
797    #[inline]
798    fn deref(&self) -> &Self::Target {
799        &self.raw
800    }
801}
802
803impl std::ops::DerefMut for DeployResult {
804    #[inline]
805    fn deref_mut(&mut self) -> &mut Self::Target {
806        &mut self.raw
807    }
808}
809
810impl From<DeployResult> for RawCallResult {
811    fn from(d: DeployResult) -> Self {
812        d.raw
813    }
814}
815
816/// The result of a raw call.
817#[derive(Debug)]
818pub struct RawCallResult {
819    /// The status of the call
820    pub exit_reason: Option<InstructionResult>,
821    /// Whether the call reverted or not
822    pub reverted: bool,
823    /// Whether the call includes a snapshot failure
824    ///
825    /// This is tracked separately from revert because a snapshot failure can occur without a
826    /// revert, since assert failures are stored in a global variable (ds-test legacy)
827    pub has_state_snapshot_failure: bool,
828    /// The raw result of the call.
829    pub result: Bytes,
830    /// The gas used for the call
831    pub gas_used: u64,
832    /// Refunded gas
833    pub gas_refunded: u64,
834    /// The initial gas stipend for the transaction
835    pub stipend: u64,
836    /// The logs emitted during the call
837    pub logs: Vec<Log>,
838    /// The labels assigned to addresses during the call
839    pub labels: AddressHashMap<String>,
840    /// The traces of the call
841    pub traces: Option<SparsedTraceArena>,
842    /// The line coverage info collected during the call
843    pub line_coverage: Option<HitMaps>,
844    /// The edge coverage info collected during the call
845    pub edge_coverage: Option<Vec<u8>>,
846    /// Scripted transactions generated from this call
847    pub transactions: Option<BroadcastableTransactions>,
848    /// The changeset of the state.
849    pub state_changeset: StateChangeset,
850    /// The `revm::Env` after the call
851    pub env: Env,
852    /// The cheatcode states after execution
853    pub cheatcodes: Option<Box<Cheatcodes>>,
854    /// The raw output of the execution
855    pub out: Option<Output>,
856    /// The chisel state
857    pub chisel_state: Option<(Vec<U256>, Vec<u8>, Option<InstructionResult>)>,
858    pub reverter: Option<Address>,
859}
860
861impl Default for RawCallResult {
862    fn default() -> Self {
863        Self {
864            exit_reason: None,
865            reverted: false,
866            has_state_snapshot_failure: false,
867            result: Bytes::new(),
868            gas_used: 0,
869            gas_refunded: 0,
870            stipend: 0,
871            logs: Vec::new(),
872            labels: HashMap::default(),
873            traces: None,
874            line_coverage: None,
875            edge_coverage: None,
876            transactions: None,
877            state_changeset: HashMap::default(),
878            env: Env::default(),
879            cheatcodes: Default::default(),
880            out: None,
881            chisel_state: None,
882            reverter: None,
883        }
884    }
885}
886
887impl RawCallResult {
888    /// Unpacks an EVM result.
889    pub fn from_evm_result(r: Result<Self, EvmError>) -> eyre::Result<(Self, Option<String>)> {
890        match r {
891            Ok(r) => Ok((r, None)),
892            Err(EvmError::Execution(e)) => Ok((e.raw, Some(e.reason))),
893            Err(e) => Err(e.into()),
894        }
895    }
896
897    /// Unpacks an execution result.
898    pub fn from_execution_result(r: Result<Self, ExecutionErr>) -> (Self, Option<String>) {
899        match r {
900            Ok(r) => (r, None),
901            Err(e) => (e.raw, Some(e.reason)),
902        }
903    }
904
905    /// Converts the result of the call into an `EvmError`.
906    pub fn into_evm_error(self, rd: Option<&RevertDecoder>) -> EvmError {
907        if let Some(reason) = SkipReason::decode(&self.result) {
908            return EvmError::Skip(reason);
909        }
910        let reason = rd.unwrap_or_default().decode(&self.result, self.exit_reason);
911        EvmError::Execution(Box::new(self.into_execution_error(reason)))
912    }
913
914    /// Converts the result of the call into an `ExecutionErr`.
915    pub fn into_execution_error(self, reason: String) -> ExecutionErr {
916        ExecutionErr { raw: self, reason }
917    }
918
919    /// Returns an `EvmError` if the call failed, otherwise returns `self`.
920    pub fn into_result(self, rd: Option<&RevertDecoder>) -> Result<Self, EvmError> {
921        if let Some(reason) = self.exit_reason
922            && reason.is_ok()
923        {
924            Ok(self)
925        } else {
926            Err(self.into_evm_error(rd))
927        }
928    }
929
930    /// Decodes the result of the call with the given function.
931    pub fn into_decoded_result(
932        mut self,
933        func: &Function,
934        rd: Option<&RevertDecoder>,
935    ) -> Result<CallResult, EvmError> {
936        self = self.into_result(rd)?;
937        let mut result = func.abi_decode_output(&self.result)?;
938        let decoded_result = if result.len() == 1 {
939            result.pop().unwrap()
940        } else {
941            // combine results into a tuple
942            DynSolValue::Tuple(result)
943        };
944        Ok(CallResult { raw: self, decoded_result })
945    }
946
947    /// Returns the transactions generated from this call.
948    pub fn transactions(&self) -> Option<&BroadcastableTransactions> {
949        self.cheatcodes.as_ref().map(|c| &c.broadcastable_transactions)
950    }
951
952    /// Update provided history map with edge coverage info collected during this call.
953    /// Uses AFL binning algo <https://github.com/h0mbre/Lucid/blob/3026e7323c52b30b3cf12563954ac1eaa9c6981e/src/coverage.rs#L57-L85>
954    pub fn merge_edge_coverage(&mut self, history_map: &mut [u8]) -> (bool, bool) {
955        let mut new_coverage = false;
956        let mut is_edge = false;
957        if let Some(x) = &mut self.edge_coverage {
958            // Iterate over the current map and the history map together and update
959            // the history map, if we discover some new coverage, report true
960            for (curr, hist) in std::iter::zip(x, history_map) {
961                // If we got a hitcount of at least 1
962                if *curr > 0 {
963                    // Convert hitcount into bucket count
964                    let bucket = match *curr {
965                        0 => 0,
966                        1 => 1,
967                        2 => 2,
968                        3 => 4,
969                        4..=7 => 8,
970                        8..=15 => 16,
971                        16..=31 => 32,
972                        32..=127 => 64,
973                        128..=255 => 128,
974                    };
975
976                    // If the old record for this edge pair is lower, update
977                    if *hist < bucket {
978                        if *hist == 0 {
979                            // Counts as an edge the first time we see it, otherwise it's a feature.
980                            is_edge = true;
981                        }
982                        *hist = bucket;
983                        new_coverage = true;
984                    }
985
986                    // Zero out the current map for next iteration.
987                    *curr = 0;
988                }
989            }
990        }
991        (new_coverage, is_edge)
992    }
993}
994
995/// The result of a call.
996pub struct CallResult<T = DynSolValue> {
997    /// The raw result of the call.
998    pub raw: RawCallResult,
999    /// The decoded result of the call.
1000    pub decoded_result: T,
1001}
1002
1003impl std::ops::Deref for CallResult {
1004    type Target = RawCallResult;
1005
1006    #[inline]
1007    fn deref(&self) -> &Self::Target {
1008        &self.raw
1009    }
1010}
1011
1012impl std::ops::DerefMut for CallResult {
1013    #[inline]
1014    fn deref_mut(&mut self) -> &mut Self::Target {
1015        &mut self.raw
1016    }
1017}
1018
1019/// Converts the data aggregated in the `inspector` and `call` to a `RawCallResult`
1020fn convert_executed_result(
1021    env: Env,
1022    inspector: InspectorStack,
1023    ResultAndState { result, state: state_changeset }: ResultAndState,
1024    has_state_snapshot_failure: bool,
1025) -> eyre::Result<RawCallResult> {
1026    let (exit_reason, gas_refunded, gas_used, out, exec_logs) = match result {
1027        ExecutionResult::Success { reason, gas_used, gas_refunded, output, logs, .. } => {
1028            (reason.into(), gas_refunded, gas_used, Some(output), logs)
1029        }
1030        ExecutionResult::Revert { gas_used, output } => {
1031            // Need to fetch the unused gas
1032            (InstructionResult::Revert, 0_u64, gas_used, Some(Output::Call(output)), vec![])
1033        }
1034        ExecutionResult::Halt { reason, gas_used } => {
1035            (reason.into(), 0_u64, gas_used, None, vec![])
1036        }
1037    };
1038    let gas = revm::interpreter::gas::calculate_initial_tx_gas(
1039        env.evm_env.cfg_env.spec,
1040        &env.tx.data,
1041        env.tx.kind.is_create(),
1042        env.tx.access_list.len().try_into()?,
1043        0,
1044        0,
1045    );
1046
1047    let result = match &out {
1048        Some(Output::Call(data)) => data.clone(),
1049        _ => Bytes::new(),
1050    };
1051
1052    let InspectorData {
1053        mut logs,
1054        labels,
1055        traces,
1056        line_coverage,
1057        edge_coverage,
1058        cheatcodes,
1059        chisel_state,
1060        reverter,
1061    } = inspector.collect();
1062
1063    if logs.is_empty() {
1064        logs = exec_logs;
1065    }
1066
1067    let transactions = cheatcodes
1068        .as_ref()
1069        .map(|c| c.broadcastable_transactions.clone())
1070        .filter(|txs| !txs.is_empty());
1071
1072    Ok(RawCallResult {
1073        exit_reason: Some(exit_reason),
1074        reverted: !matches!(exit_reason, return_ok!()),
1075        has_state_snapshot_failure,
1076        result,
1077        gas_used,
1078        gas_refunded,
1079        stipend: gas.initial_gas,
1080        logs,
1081        labels,
1082        traces,
1083        line_coverage,
1084        edge_coverage,
1085        transactions,
1086        state_changeset,
1087        env,
1088        cheatcodes,
1089        out,
1090        chisel_state,
1091        reverter,
1092    })
1093}
1094
1095/// Timer for a fuzz test.
1096pub struct FuzzTestTimer {
1097    /// Inner fuzz test timer - (test start time, test duration).
1098    inner: Option<(Instant, Duration)>,
1099}
1100
1101impl FuzzTestTimer {
1102    pub fn new(timeout: Option<u32>) -> Self {
1103        Self { inner: timeout.map(|timeout| (Instant::now(), Duration::from_secs(timeout.into()))) }
1104    }
1105
1106    /// Whether the fuzz test timer is enabled.
1107    pub fn is_enabled(&self) -> bool {
1108        self.inner.is_some()
1109    }
1110
1111    /// Whether the current fuzz test timed out and should be stopped.
1112    pub fn is_timed_out(&self) -> bool {
1113        self.inner.is_some_and(|(start, duration)| start.elapsed() > duration)
1114    }
1115}
1116
1117/// Helper struct to enable fail fast behavior: when one test fails, all other tests stop early.
1118#[derive(Clone)]
1119pub struct FailFast {
1120    /// Shared atomic flag set to `true` when a failure occurs.
1121    /// None if fail-fast is disabled.
1122    inner: Option<Arc<AtomicBool>>,
1123}
1124
1125impl FailFast {
1126    pub fn new(fail_fast: bool) -> Self {
1127        Self { inner: fail_fast.then_some(Arc::new(AtomicBool::new(false))) }
1128    }
1129
1130    /// Returns `true` if fail-fast is enabled.
1131    pub fn is_enabled(&self) -> bool {
1132        self.inner.is_some()
1133    }
1134
1135    /// Sets the failure flag. Used by other tests to stop early.
1136    pub fn record_fail(&self) {
1137        if let Some(fail_fast) = &self.inner {
1138            fail_fast.store(true, Ordering::Relaxed);
1139        }
1140    }
1141
1142    /// Whether a failure has been recorded and test should stop.
1143    pub fn should_stop(&self) -> bool {
1144        self.inner.as_ref().map(|flag| flag.load(Ordering::Relaxed)).unwrap_or(false)
1145    }
1146}