Skip to content

Commit

Permalink
use standard strategy traits
Browse files Browse the repository at this point in the history
  • Loading branch information
nbaztec committed Dec 19, 2024
1 parent d7e6f1d commit e5ccd9e
Show file tree
Hide file tree
Showing 17 changed files with 63 additions and 99 deletions.
6 changes: 3 additions & 3 deletions crates/cheatcodes/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::Result;
use crate::{
strategy::{CheatcodeInspectorStrategyExt, EvmCheatcodeInspectorStrategy},
strategy::{CheatcodeInspectorStrategy, EvmCheatcodeInspectorStrategy},
Vm::Rpc,
};
use alloy_primitives::{map::AddressHashMap, U256};
Expand Down Expand Up @@ -57,7 +57,7 @@ pub struct CheatsConfig {
/// Version of the script/test contract which is currently running.
pub running_version: Option<Version>,
/// The behavior strategy.
pub strategy: Box<dyn CheatcodeInspectorStrategyExt>,
pub strategy: Box<dyn CheatcodeInspectorStrategy>,
/// Whether to enable legacy (non-reverting) assertions.
pub assertions_revert: bool,
/// Optional seed for the RNG algorithm.
Expand All @@ -73,7 +73,7 @@ impl CheatsConfig {
available_artifacts: Option<ContractsByArtifact>,
running_contract: Option<String>,
running_version: Option<Version>,
strategy: Box<dyn CheatcodeInspectorStrategyExt>,
strategy: Box<dyn CheatcodeInspectorStrategy>,
) -> Self {
let mut allowed_paths = vec![config.root.0.clone()];
allowed_paths.extend(config.libs.clone());
Expand Down
8 changes: 4 additions & 4 deletions crates/cheatcodes/src/inspector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
DealRecord, GasRecord,
},
script::{Broadcast, Wallets},
strategy::CheatcodeInspectorStrategyExt,
strategy::CheatcodeInspectorStrategy,
test::{
assume::AssumeNoRevert,
expect::{self, ExpectedEmit, ExpectedRevert, ExpectedRevertKind},
Expand Down Expand Up @@ -69,7 +69,7 @@ pub use utils::CommonCreateInput;

pub type Ecx<'a, 'b, 'c> = &'a mut EvmContext<&'b mut (dyn DatabaseExt + 'c)>;
pub type InnerEcx<'a, 'b, 'c> = &'a mut InnerEvmContext<&'b mut (dyn DatabaseExt + 'c)>;
pub type Strategy<'a> = &'a mut dyn CheatcodeInspectorStrategyExt;
pub type Strategy<'a> = &'a mut dyn CheatcodeInspectorStrategy;

/// Helper trait for obtaining complete [revm::Inspector] instance from mutable reference to
/// [Cheatcodes].
Expand Down Expand Up @@ -528,7 +528,7 @@ pub struct Cheatcodes {
pub wallets: Option<Wallets>,

/// The behavior strategy.
pub strategy: Option<Box<dyn CheatcodeInspectorStrategyExt>>,
pub strategy: Option<Box<dyn CheatcodeInspectorStrategy>>,
}

impl Clone for Cheatcodes {
Expand Down Expand Up @@ -568,7 +568,7 @@ impl Clone for Cheatcodes {
arbitrary_storage: self.arbitrary_storage.clone(),
deprecated: self.deprecated.clone(),
wallets: self.wallets.clone(),
strategy: self.strategy.as_ref().map(|s| s.new_cloned_ext()),
strategy: self.strategy.as_ref().map(|s| s.new_cloned()),
}
}
}
Expand Down
22 changes: 5 additions & 17 deletions crates/cheatcodes/src/strategy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::{
CheatsConfig, CheatsCtxt, Result,
};

pub trait CheatcodeInspectorStrategy: Debug + Send + Sync {
pub trait CheatcodeInspectorStrategy: Debug + Send + Sync + CheatcodeInspectorStrategyExt {
fn name(&self) -> &'static str;

fn new_cloned(&self) -> Box<dyn CheatcodeInspectorStrategy>;
Expand Down Expand Up @@ -182,9 +182,7 @@ pub trait CheatcodeInspectorStrategy: Debug + Send + Sync {
}

/// We define this in our fork
pub trait CheatcodeInspectorStrategyExt: CheatcodeInspectorStrategy {
fn new_cloned_ext(&self) -> Box<dyn CheatcodeInspectorStrategyExt>;

pub trait CheatcodeInspectorStrategyExt {
fn zksync_cheatcode_skip_zkvm(&mut self) -> Result {
Ok(Default::default())
}
Expand Down Expand Up @@ -223,10 +221,10 @@ pub trait CheatcodeInspectorStrategyExt: CheatcodeInspectorStrategy {

fn zksync_set_deployer_call_input(&mut self, _call: &mut CallInputs) {}

fn zksync_try_create(
fn zksync_try_create<'c>(
&mut self,
_state: &mut Cheatcodes,
_ecx: Ecx,
_ecx: Ecx<'_, '_, 'c>,
_input: &dyn CommonCreateInput,
_executor: &mut dyn CheatcodesExecutor,
) -> Option<CreateOutcome> {
Expand Down Expand Up @@ -328,23 +326,13 @@ impl CheatcodeInspectorStrategy for EvmCheatcodeInspectorStrategy {
}
}

impl CheatcodeInspectorStrategyExt for EvmCheatcodeInspectorStrategy {
fn new_cloned_ext(&self) -> Box<dyn CheatcodeInspectorStrategyExt> {
Box::new(self.clone())
}
}
impl CheatcodeInspectorStrategyExt for EvmCheatcodeInspectorStrategy {}

impl Clone for Box<dyn CheatcodeInspectorStrategy> {
fn clone(&self) -> Self {
self.new_cloned()
}
}

impl Clone for Box<dyn CheatcodeInspectorStrategyExt> {
fn clone(&self) -> Self {
self.new_cloned_ext()
}
}

struct _ObjectSafe0(dyn CheatcodeInspectorStrategy);
struct _ObjectSafe1(dyn CheatcodeInspectorStrategyExt);
4 changes: 2 additions & 2 deletions crates/cli/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use foundry_common::{
shell,
};
use foundry_config::{Chain, Config};
use foundry_evm::executors::strategy::{EvmExecutorStrategy, ExecutorStrategyExt};
use foundry_evm::executors::strategy::{EvmExecutorStrategy, ExecutorStrategy};
use foundry_strategy_zksync::ZksyncExecutorStrategy;
use serde::de::DeserializeOwned;
use std::{
Expand Down Expand Up @@ -93,7 +93,7 @@ pub fn get_provider(config: &Config) -> Result<RetryProvider> {
get_provider_builder(config)?.build()
}

pub fn get_executor_strategy(config: &Config) -> Box<dyn ExecutorStrategyExt> {
pub fn get_executor_strategy(config: &Config) -> Box<dyn ExecutorStrategy> {
if config.zksync.should_compile() {
info!("using zksync strategy");
Box::new(ZksyncExecutorStrategy::default())
Expand Down
4 changes: 2 additions & 2 deletions crates/evm/core/src/backend/cow.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! A wrapper around `Backend` that is clone-on-write used for fuzzing.
use super::{strategy::BackendStrategyExt, BackendError, ForkInfo};
use super::{strategy::BackendStrategy, BackendError, ForkInfo};
use crate::{
backend::{
diagnostic::RevertDiagnostic, Backend, DatabaseExt, LocalForkId, RevertStateSnapshotAction,
Expand Down Expand Up @@ -92,7 +92,7 @@ impl DatabaseExt for CowBackend<'_> {
self.backend.to_mut().get_fork_info(id)
}

fn get_strategy(&mut self) -> &mut dyn BackendStrategyExt {
fn get_strategy(&mut self) -> &mut dyn BackendStrategy {
self.backend.to_mut().strategy.as_mut()
}

Expand Down
25 changes: 12 additions & 13 deletions crates/evm/core/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use std::{
collections::{BTreeMap, HashSet},
time::Instant,
};
use strategy::{BackendStrategyExt, BackendStrategyForkInfo};
use strategy::{BackendStrategy, BackendStrategyForkInfo};

mod diagnostic;
pub use diagnostic::RevertDiagnostic;
Expand Down Expand Up @@ -102,7 +102,7 @@ pub trait DatabaseExt: Database<Error = DatabaseError> + DatabaseCommit {
fn get_fork_info(&mut self, id: LocalForkId) -> eyre::Result<ForkInfo>;

/// Retrieve the strategy.
fn get_strategy(&mut self) -> &mut dyn BackendStrategyExt;
fn get_strategy(&mut self) -> &mut dyn BackendStrategy;

/// Reverts the snapshot if it exists
///
Expand Down Expand Up @@ -460,7 +460,7 @@ struct _ObjectSafe(dyn DatabaseExt);
#[must_use]
pub struct Backend {
/// The behavior strategy.
pub strategy: Box<dyn BackendStrategyExt>,
pub strategy: Box<dyn BackendStrategy>,

/// The access point for managing forks
forks: MultiFork,
Expand Down Expand Up @@ -496,7 +496,7 @@ pub struct Backend {
impl Clone for Backend {
fn clone(&self) -> Self {
Self {
strategy: self.strategy.new_cloned_ext(),
strategy: self.strategy.new_cloned(),
forks: self.forks.clone(),
mem_db: self.mem_db.clone(),
fork_init_journaled_state: self.fork_init_journaled_state.clone(),
Expand All @@ -512,7 +512,7 @@ impl Backend {
///
/// If `fork` is `Some` this will use a `fork` database, otherwise with an in-memory
/// database.
pub fn spawn(fork: Option<CreateFork>, strategy: Box<dyn BackendStrategyExt>) -> Self {
pub fn spawn(fork: Option<CreateFork>, strategy: Box<dyn BackendStrategy>) -> Self {
Self::new(MultiFork::spawn(), fork, strategy)
}

Expand All @@ -525,7 +525,7 @@ impl Backend {
pub fn new(
forks: MultiFork,
fork: Option<CreateFork>,
strategy: Box<dyn BackendStrategyExt>,
strategy: Box<dyn BackendStrategy>,
) -> Self {
trace!(target: "backend", forking_mode=?fork.is_some(), "creating executor backend");
// Note: this will take of registering the `fork`
Expand Down Expand Up @@ -568,7 +568,7 @@ impl Backend {
id: &ForkId,
fork: Fork,
journaled_state: JournaledState,
strategy: Box<dyn BackendStrategyExt>,
strategy: Box<dyn BackendStrategy>,
) -> Self {
let mut backend = Self::spawn(None, strategy);
let fork_ids = backend.inner.insert_new_fork(id.clone(), fork.db, journaled_state);
Expand All @@ -586,7 +586,7 @@ impl Backend {
active_fork_ids: None,
inner: Default::default(),
fork_url_type: Default::default(),
strategy: self.strategy.new_cloned_ext(),
strategy: self.strategy.new_cloned(),
}
}

Expand Down Expand Up @@ -938,7 +938,7 @@ impl DatabaseExt for Backend {
Ok(ForkInfo { fork_type, fork_env })
}

fn get_strategy(&mut self) -> &mut dyn BackendStrategyExt {
fn get_strategy(&mut self) -> &mut dyn BackendStrategy {
self.strategy.as_mut()
}

Expand Down Expand Up @@ -1808,7 +1808,7 @@ impl BackendInner {
id: LocalForkId,
new_fork_id: ForkId,
backend: SharedBackend,
strategy: &mut dyn BackendStrategyExt,
strategy: &mut dyn BackendStrategy,
) -> eyre::Result<ForkLookupIndex> {
let fork_id = self.ensure_fork_id(id)?;
let idx = self.ensure_fork_index(fork_id)?;
Expand Down Expand Up @@ -1937,7 +1937,7 @@ fn commit_transaction(
fork_id: &ForkId,
persistent_accounts: &HashSet<Address>,
inspector: &mut dyn InspectorExt,
strategy: &mut dyn BackendStrategyExt,
strategy: &mut dyn BackendStrategy,
) -> eyre::Result<()> {
// TODO: Remove after https://github.com/foundry-rs/foundry/pull/9131
// if the tx has the blob_versioned_hashes field, we assume it's a Cancun block
Expand All @@ -1952,8 +1952,7 @@ fn commit_transaction(
let fork = fork.clone();
let journaled_state = journaled_state.clone();
let depth = journaled_state.depth;
let mut db =
Backend::new_with_fork(fork_id, fork, journaled_state, strategy.new_cloned_ext());
let mut db = Backend::new_with_fork(fork_id, fork, journaled_state, strategy.new_cloned());

let mut evm = crate::utils::new_evm_with_inspector(&mut db as _, env, inspector);
// Adjust inner EVM depth to ensure that inspectors receive accurate data.
Expand Down
11 changes: 3 additions & 8 deletions crates/evm/core/src/backend/strategy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub struct BackendStrategyForkInfo<'a> {
pub target_type: ForkType,
}

pub trait BackendStrategy: Debug + Send + Sync {
pub trait BackendStrategy: Debug + Send + Sync + BackendStrategyExt {
fn name(&self) -> &'static str;

fn new_cloned(&self) -> Box<dyn BackendStrategy>;
Expand All @@ -37,8 +37,7 @@ pub trait BackendStrategy: Debug + Send + Sync {
fn merge_db_account_data(&self, addr: Address, active: &ForkDB, fork_db: &mut ForkDB);
}

pub trait BackendStrategyExt: BackendStrategy {
fn new_cloned_ext(&self) -> Box<dyn BackendStrategyExt>;
pub trait BackendStrategyExt {
/// Saves the storage keys for immutable variables per address.
///
/// These are required during fork to help merge the persisted addresses, as they are stored
Expand Down Expand Up @@ -97,11 +96,7 @@ impl BackendStrategy for EvmBackendStrategy {
}
}

impl BackendStrategyExt for EvmBackendStrategy {
fn new_cloned_ext(&self) -> Box<dyn BackendStrategyExt> {
Box::new(self.clone())
}
}
impl BackendStrategyExt for EvmBackendStrategy {}

impl EvmBackendStrategy {
/// Merges the state of all `accounts` from the currently active db into the given `fork`
Expand Down
4 changes: 2 additions & 2 deletions crates/evm/evm/src/executors/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{executors::Executor, inspectors::InspectorStackBuilder};
use foundry_evm_core::backend::Backend;
use revm::primitives::{Env, EnvWithHandlerCfg, SpecId};

use super::strategy::ExecutorStrategyExt;
use super::strategy::ExecutorStrategy;

/// The builder that allows to configure an evm [`Executor`] which a stack of optional
/// [`revm::Inspector`]s, such as [`Cheatcodes`].
Expand Down Expand Up @@ -76,7 +76,7 @@ impl ExecutorBuilder {

/// Builds the executor as configured.
#[inline]
pub fn build(self, env: Env, db: Backend, strategy: Box<dyn ExecutorStrategyExt>) -> Executor {
pub fn build(self, env: Env, db: Backend, strategy: Box<dyn ExecutorStrategy>) -> Executor {
let Self { mut stack, gas_limit, spec_id, legacy_assertions } = self;
if stack.block.is_none() {
stack.block = Some(env.block.clone());
Expand Down
14 changes: 7 additions & 7 deletions crates/evm/evm/src/executors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ use revm::{
},
};
use std::borrow::Cow;
use strategy::ExecutorStrategyExt;
use strategy::ExecutorStrategy;

mod builder;
pub use builder::ExecutorBuilder;
Expand Down Expand Up @@ -93,7 +93,7 @@ pub struct Executor {
/// Whether `failed()` should be called on the test contract to determine if the test failed.
legacy_assertions: bool,

strategy: Option<Box<dyn ExecutorStrategyExt>>,
strategy: Option<Box<dyn ExecutorStrategy>>,
}

impl Clone for Executor {
Expand All @@ -104,7 +104,7 @@ impl Clone for Executor {
inspector: self.inspector.clone(),
gas_limit: self.gas_limit,
legacy_assertions: self.legacy_assertions,
strategy: self.strategy.as_ref().map(|s| s.new_cloned_ext()),
strategy: self.strategy.as_ref().map(|s| s.new_cloned()),
}
}
}
Expand All @@ -124,7 +124,7 @@ impl Executor {
inspector: InspectorStack,
gas_limit: u64,
legacy_assertions: bool,
strategy: Box<dyn ExecutorStrategyExt>,
strategy: Box<dyn ExecutorStrategy>,
) -> Self {
// Need to create a non-empty contract on the cheatcodes address so `extcodesize` checks
// do not fail.
Expand All @@ -150,7 +150,7 @@ impl Executor {
self.inspector().clone(),
self.gas_limit,
self.legacy_assertions,
self.strategy.as_ref().map(|s| s.new_cloned_ext()).expect("failed acquiring strategy"),
self.strategy.as_ref().map(|s| s.new_cloned()).expect("failed acquiring strategy"),
)
}

Expand Down Expand Up @@ -216,7 +216,7 @@ impl Executor {

pub fn with_strategy<F, R>(&mut self, mut f: F) -> R
where
F: FnMut(&mut dyn ExecutorStrategyExt, &mut Self) -> R,
F: FnMut(&mut dyn ExecutorStrategy, &mut Self) -> R,
{
let mut strategy = self.strategy.take();
let result = f(strategy.as_mut().expect("failed acquiring strategy").as_mut(), self);
Expand Down Expand Up @@ -461,7 +461,7 @@ impl Executor {
.strategy
.as_ref()
.expect("failed acquiring strategy")
.new_cloned_ext()
.new_cloned()
.call_inspect(&mut backend, &mut env, &mut inspector)?;

convert_executed_result(
Expand Down
Loading

0 comments on commit e5ccd9e

Please sign in to comment.