1use 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#[derive(Clone, Debug)]
92pub struct Executor {
93 backend: Backend,
99 env: Env,
101 inspector: InspectorStack,
103 gas_limit: u64,
105 legacy_assertions: bool,
107}
108
109impl Executor {
110 #[inline]
112 pub fn builder() -> ExecutorBuilder {
113 ExecutorBuilder::new()
114 }
115
116 #[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 backend.insert_account_info(
128 CHEATCODE_ADDRESS,
129 revm::state::AccountInfo {
130 code: Some(Bytecode::new_raw(Bytes::from_static(&[0]))),
131 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 pub fn backend(&self) -> &Backend {
153 &self.backend
154 }
155
156 pub fn backend_mut(&mut self) -> &mut Backend {
158 &mut self.backend
159 }
160
161 pub fn env(&self) -> &Env {
163 &self.env
164 }
165
166 pub fn env_mut(&mut self) -> &mut Env {
168 &mut self.env
169 }
170
171 pub fn inspector(&self) -> &InspectorStack {
173 &self.inspector
174 }
175
176 pub fn inspector_mut(&mut self) -> &mut InspectorStack {
178 &mut self.inspector
179 }
180
181 pub fn spec_id(&self) -> SpecId {
183 self.env.evm_env.cfg_env.spec
184 }
185
186 pub fn set_spec_id(&mut self, spec_id: SpecId) {
188 self.env.evm_env.cfg_env.spec = spec_id;
189 }
190
191 pub fn gas_limit(&self) -> u64 {
196 self.gas_limit
197 }
198
199 pub fn set_gas_limit(&mut self, gas_limit: u64) {
201 self.gas_limit = gas_limit;
202 }
203
204 pub fn legacy_assertions(&self) -> bool {
207 self.legacy_assertions
208 }
209
210 pub fn set_legacy_assertions(&mut self, legacy_assertions: bool) {
213 self.legacy_assertions = legacy_assertions;
214 }
215
216 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 create2_deployer_account.code.is_none_or(|code| code.is_empty()) {
226 let creator = DEFAULT_CREATE2_DEPLOYER_DEPLOYER;
227
228 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 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 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 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 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 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 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 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 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 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 #[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 self.backend_mut().add_persistent_account(address);
369
370 debug!(%address, "deployed contract");
371
372 Ok(DeployResult { raw: result, address })
373 }
374
375 #[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 self.env_mut().evm_env.block_env = res.env.evm_env.block_env.clone();
398 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 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 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 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 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 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 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 #[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 #[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 #[instrument(name = "commit", level = "debug", skip_all)]
523 fn commit(&mut self, result: &mut RawCallResult) {
524 self.backend_mut().commit(result.state_changeset.clone());
526
527 self.inspector_mut().cheatcodes = result.cheatcodes.take();
529 if let Some(cheats) = self.inspector_mut().cheatcodes.as_mut() {
530 cheats.broadcastable_transactions.clear();
532 cheats.ignored_traces.ignored.clear();
533
534 if let Some(last_pause_call) = cheats.ignored_traces.last_pause_call.as_mut() {
537 *last_pause_call = (0, 0);
538 }
539 }
540
541 self.inspector_mut().set_env(&result.env);
543 }
544
545 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 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 return should_fail;
576 }
577 self.is_success(address, call_result.reverted, state_changeset, should_fail)
578 }
579
580 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 if reverted {
621 return false;
622 }
623
624 if self.backend().has_state_snapshot_failure() {
626 return false;
627 }
628
629 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 {
648 let mut backend = self.backend().clone_empty();
650
651 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 backend.commit(state_changeset.into_owned());
663
664 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 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 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 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#[derive(Debug, thiserror::Error)]
729#[error("execution reverted: {reason} (gas: {})", raw.gas_used)]
730pub struct ExecutionErr {
731 pub raw: RawCallResult,
733 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(transparent)]
757 Execution(#[from] Box<ExecutionErr>),
758 #[error(transparent)]
760 Abi(#[from] alloy_dyn_abi::Error),
761 #[error("{0}")]
763 Skip(SkipReason),
764 #[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#[derive(Debug)]
787pub struct DeployResult {
788 pub raw: RawCallResult,
790 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#[derive(Debug)]
818pub struct RawCallResult {
819 pub exit_reason: Option<InstructionResult>,
821 pub reverted: bool,
823 pub has_state_snapshot_failure: bool,
828 pub result: Bytes,
830 pub gas_used: u64,
832 pub gas_refunded: u64,
834 pub stipend: u64,
836 pub logs: Vec<Log>,
838 pub labels: AddressHashMap<String>,
840 pub traces: Option<SparsedTraceArena>,
842 pub line_coverage: Option<HitMaps>,
844 pub edge_coverage: Option<Vec<u8>>,
846 pub transactions: Option<BroadcastableTransactions>,
848 pub state_changeset: StateChangeset,
850 pub env: Env,
852 pub cheatcodes: Option<Box<Cheatcodes>>,
854 pub out: Option<Output>,
856 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 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 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 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 pub fn into_execution_error(self, reason: String) -> ExecutionErr {
916 ExecutionErr { raw: self, reason }
917 }
918
919 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 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 DynSolValue::Tuple(result)
943 };
944 Ok(CallResult { raw: self, decoded_result })
945 }
946
947 pub fn transactions(&self) -> Option<&BroadcastableTransactions> {
949 self.cheatcodes.as_ref().map(|c| &c.broadcastable_transactions)
950 }
951
952 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 for (curr, hist) in std::iter::zip(x, history_map) {
961 if *curr > 0 {
963 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 *hist < bucket {
978 if *hist == 0 {
979 is_edge = true;
981 }
982 *hist = bucket;
983 new_coverage = true;
984 }
985
986 *curr = 0;
988 }
989 }
990 }
991 (new_coverage, is_edge)
992 }
993}
994
995pub struct CallResult<T = DynSolValue> {
997 pub raw: RawCallResult,
999 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
1019fn 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 (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
1095pub struct FuzzTestTimer {
1097 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 pub fn is_enabled(&self) -> bool {
1108 self.inner.is_some()
1109 }
1110
1111 pub fn is_timed_out(&self) -> bool {
1113 self.inner.is_some_and(|(start, duration)| start.elapsed() > duration)
1114 }
1115}
1116
1117#[derive(Clone)]
1119pub struct FailFast {
1120 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 pub fn is_enabled(&self) -> bool {
1132 self.inner.is_some()
1133 }
1134
1135 pub fn record_fail(&self) {
1137 if let Some(fail_fast) = &self.inner {
1138 fail_fast.store(true, Ordering::Relaxed);
1139 }
1140 }
1141
1142 pub fn should_stop(&self) -> bool {
1144 self.inner.as_ref().map(|flag| flag.load(Ordering::Relaxed)).unwrap_or(false)
1145 }
1146}