Skip to content

Commit

Permalink
feat: --alphanet flag and config option (#8680)
Browse files Browse the repository at this point in the history
* --alphanet

* fix tests

* fix doc

* anvil support

* better cast and anvil

* fix doc
  • Loading branch information
klkvr authored Aug 16, 2024
1 parent 80fd75b commit f8aa4af
Show file tree
Hide file tree
Showing 21 changed files with 264 additions and 32 deletions.
5 changes: 5 additions & 0 deletions crates/anvil/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ impl NodeArgs {
.with_transaction_block_keeper(self.transaction_block_keeper)
.with_max_persisted_states(self.max_persisted_states)
.with_optimism(self.evm_opts.optimism)
.with_alphanet(self.evm_opts.alphanet)
.with_disable_default_create2_deployer(self.evm_opts.disable_default_create2_deployer)
.with_slots_in_an_epoch(self.slots_in_an_epoch)
.with_memory_limit(self.evm_opts.memory_limit)
Expand Down Expand Up @@ -550,6 +551,10 @@ pub struct AnvilEvmArgs {
/// The memory limit per EVM execution in bytes.
#[arg(long)]
pub memory_limit: Option<u64>,

/// Enable Alphanet features
#[arg(long, visible_alias = "alphanet")]
pub alphanet: bool,
}

/// Resolves an alias passed as fork-url to the matching url defined in the rpc_endpoints section
Expand Down
16 changes: 15 additions & 1 deletion crates/anvil/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ pub struct NodeConfig {
pub memory_limit: Option<u64>,
/// Factory used by `anvil` to extend the EVM's precompiles.
pub precompile_factory: Option<Arc<dyn PrecompileFactory>>,
/// Enable Alphanet features.
pub alphanet: bool,
}

impl NodeConfig {
Expand Down Expand Up @@ -437,6 +439,7 @@ impl Default for NodeConfig {
slots_in_an_epoch: 32,
memory_limit: None,
precompile_factory: None,
alphanet: false,
}
}
}
Expand Down Expand Up @@ -471,8 +474,11 @@ impl NodeConfig {
}
}

/// Returns the base fee to use
/// Returns the hardfork to use
pub fn get_hardfork(&self) -> Hardfork {
if self.alphanet {
return Hardfork::PragueEOF;
}
self.hardfork.unwrap_or_default()
}

Expand Down Expand Up @@ -918,6 +924,13 @@ impl NodeConfig {
self
}

/// Sets whether to enable Alphanet support
#[must_use]
pub fn with_alphanet(mut self, alphanet: bool) -> Self {
self.alphanet = alphanet;
self
}

/// Configures everything related to env, backend and database and returns the
/// [Backend](mem::Backend)
///
Expand Down Expand Up @@ -994,6 +1007,7 @@ impl NodeConfig {
Arc::new(RwLock::new(fork)),
self.enable_steps_tracing,
self.print_logs,
self.alphanet,
self.prune_history,
self.max_persisted_states,
self.transaction_block_keeper,
Expand Down
3 changes: 2 additions & 1 deletion crates/anvil/src/eth/backend/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ pub struct TransactionExecutor<'a, Db: ?Sized, Validator: TransactionValidator>
/// Cumulative blob gas used by all executed transactions
pub blob_gas_used: u128,
pub enable_steps_tracing: bool,
pub alphanet: bool,
pub print_logs: bool,
/// Precompiles to inject to the EVM.
pub precompile_factory: Option<Arc<dyn PrecompileFactory>>,
Expand Down Expand Up @@ -302,7 +303,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator
let nonce = account.nonce;

// records all call and step traces
let mut inspector = Inspector::default().with_tracing();
let mut inspector = Inspector::default().with_tracing().with_alphanet(self.alphanet);
if self.enable_steps_tracing {
inspector = inspector.with_steps_tracing();
}
Expand Down
14 changes: 13 additions & 1 deletion crates/anvil/src/eth/backend/mem/inspector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ pub struct Inspector {
pub tracer: Option<TracingInspector>,
/// collects all `console.sol` logs
pub log_collector: Option<LogCollector>,
/// Whether to enable Alphanet support
pub alphanet: bool,
}

impl Inspector {
Expand Down Expand Up @@ -57,6 +59,12 @@ impl Inspector {
self.log_collector = Some(Default::default());
self
}

/// Enables Alphanet features
pub fn with_alphanet(mut self, yes: bool) -> Self {
self.alphanet = yes;
self
}
}

impl<DB: Database> revm::Inspector<DB> for Inspector {
Expand Down Expand Up @@ -168,7 +176,11 @@ impl<DB: Database> revm::Inspector<DB> for Inspector {
}
}

impl<DB: Database> InspectorExt<DB> for Inspector {}
impl<DB: Database> InspectorExt<DB> for Inspector {
fn is_alphanet(&self) -> bool {
self.alphanet
}
}

/// Prints all the logs
pub fn print_logs(logs: &[Log]) {
Expand Down
7 changes: 6 additions & 1 deletion crates/anvil/src/eth/backend/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ pub struct Backend {
active_snapshots: Arc<Mutex<HashMap<U256, (u64, B256)>>>,
enable_steps_tracing: bool,
print_logs: bool,
alphanet: bool,
/// How to keep history state
prune_state_history_config: PruneStateHistoryConfig,
/// max number of blocks with transactions in memory
Expand All @@ -198,6 +199,7 @@ impl Backend {
fork: Arc<RwLock<Option<ClientFork>>>,
enable_steps_tracing: bool,
print_logs: bool,
alphanet: bool,
prune_state_history_config: PruneStateHistoryConfig,
max_persisted_states: Option<usize>,
transaction_block_keeper: Option<usize>,
Expand Down Expand Up @@ -256,6 +258,7 @@ impl Backend {
active_snapshots: Arc::new(Mutex::new(Default::default())),
enable_steps_tracing,
print_logs,
alphanet,
prune_state_history_config,
transaction_block_keeper,
node_config,
Expand Down Expand Up @@ -908,6 +911,7 @@ impl Backend {
enable_steps_tracing: self.enable_steps_tracing,
print_logs: self.print_logs,
precompile_factory: self.precompile_factory.clone(),
alphanet: self.alphanet,
};

// create a new pending block
Expand Down Expand Up @@ -980,6 +984,7 @@ impl Backend {
blob_gas_used: 0,
enable_steps_tracing: self.enable_steps_tracing,
print_logs: self.print_logs,
alphanet: self.alphanet,
precompile_factory: self.precompile_factory.clone(),
};
let executed_tx = executor.execute();
Expand Down Expand Up @@ -1203,7 +1208,7 @@ impl Backend {

/// Builds [`Inspector`] with the configured options
fn build_inspector(&self) -> Inspector {
let mut inspector = Inspector::default();
let mut inspector = Inspector::default().with_alphanet(self.alphanet);

if self.print_logs {
inspector = inspector.with_log_collector();
Expand Down
47 changes: 40 additions & 7 deletions crates/cast/bin/cmd/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ use foundry_cli::{
};
use foundry_common::ens::NameOrAddress;
use foundry_compilers::artifacts::EvmVersion;
use foundry_config::{find_project_root_path, Config};
use foundry_config::{
figment::{
self,
value::{Dict, Map},
Figment, Metadata, Profile,
},
Config,
};
use foundry_evm::{executors::TracingExecutor, opts::EvmOpts};
use std::str::FromStr;

Expand Down Expand Up @@ -66,6 +73,10 @@ pub struct CallArgs {
#[arg(long, short, help_heading = "Display options")]
json: bool,

/// Enable Alphanet features.
#[arg(long)]
pub alphanet: bool,

#[command(subcommand)]
command: Option<CallSubcommands>,

Expand Down Expand Up @@ -102,6 +113,10 @@ pub enum CallSubcommands {

impl CallArgs {
pub async fn run(self) -> Result<()> {
let figment = Into::<Figment>::into(&self.eth).merge(&self);
let evm_opts = figment.extract::<EvmOpts>()?;
let mut config = Config::try_from(figment)?.sanitized();

let Self {
to,
mut sig,
Expand All @@ -117,13 +132,13 @@ impl CallArgs {
labels,
data,
json,
..
} = self;

if let Some(data) = data {
sig = Some(data);
}

let mut config = Config::from(&eth);
let provider = utils::get_provider(&config)?;
let sender = SenderKind::from_wallet_opts(eth.wallet).await?;
let from = sender.address();
Expand Down Expand Up @@ -160,22 +175,20 @@ impl CallArgs {
.await?;

if trace {
let figment =
Config::figment_with_root(find_project_root_path(None).unwrap()).merge(eth.rpc);
let evm_opts = figment.extract::<EvmOpts>()?;
if let Some(BlockId::Number(BlockNumberOrTag::Number(block_number))) = self.block {
// Override Config `fork_block_number` (if set) with CLI value.
config.fork_block_number = Some(block_number);
}

let (mut env, fork, chain) =
let (mut env, fork, chain, alphanet) =
TracingExecutor::get_fork_material(&config, evm_opts).await?;

// modify settings that usually set in eth_call
env.cfg.disable_block_gas_limit = true;
env.block.gas_limit = U256::MAX;

let mut executor = TracingExecutor::new(env, fork, evm_version, debug, decode_internal);
let mut executor =
TracingExecutor::new(env, fork, evm_version, debug, decode_internal, alphanet);

let value = tx.value.unwrap_or_default();
let input = tx.inner.input.into_input().unwrap_or_default();
Expand All @@ -202,6 +215,26 @@ impl CallArgs {
}
}

impl figment::Provider for CallArgs {
fn metadata(&self) -> Metadata {
Metadata::named("CallArgs")
}

fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
let mut map = Map::new();

if self.alphanet {
map.insert("alphanet".into(), self.alphanet.into());
}

if let Some(evm_version) = self.evm_version {
map.insert("evm_version".into(), figment::value::Value::serialize(evm_version)?);
}

Ok(Map::from([(Config::selected_profile(), map)]))
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
49 changes: 43 additions & 6 deletions crates/cast/bin/cmd/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ use foundry_cli::{
};
use foundry_common::{is_known_system_sender, SYSTEM_TRANSACTION_TYPE};
use foundry_compilers::artifacts::EvmVersion;
use foundry_config::{find_project_root_path, Config};
use foundry_config::{
figment::{
self,
value::{Dict, Map},
Figment, Metadata, Profile,
},
Config,
};
use foundry_evm::{
executors::{EvmError, TracingExecutor},
opts::EvmOpts,
Expand Down Expand Up @@ -75,6 +82,10 @@ pub struct RunArgs {
/// See also, https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second
#[arg(long, value_name = "NO_RATE_LIMITS", visible_alias = "no-rpc-rate-limit")]
pub no_rate_limit: bool,

/// Enables Alphanet features.
#[arg(long)]
pub alphanet: bool,
}

impl RunArgs {
Expand All @@ -84,8 +95,7 @@ impl RunArgs {
///
/// Note: This executes the transaction(s) as is: Cheatcodes are disabled
pub async fn run(self) -> Result<()> {
let figment =
Config::figment_with_root(find_project_root_path(None).unwrap()).merge(self.rpc);
let figment = Into::<Figment>::into(&self.rpc).merge(&self);
let evm_opts = figment.extract::<EvmOpts>()?;
let mut config = Config::try_from(figment)?.sanitized();

Expand Down Expand Up @@ -122,7 +132,8 @@ impl RunArgs {
// we need to fork off the parent block
config.fork_block_number = Some(tx_block_number - 1);

let (mut env, fork, chain) = TracingExecutor::get_fork_material(&config, evm_opts).await?;
let (mut env, fork, chain, alphanet) =
TracingExecutor::get_fork_material(&config, evm_opts).await?;

let mut evm_version = self.evm_version;

Expand All @@ -146,8 +157,14 @@ impl RunArgs {
}
}

let mut executor =
TracingExecutor::new(env.clone(), fork, evm_version, self.debug, self.decode_internal);
let mut executor = TracingExecutor::new(
env.clone(),
fork,
evm_version,
self.debug,
self.decode_internal,
alphanet,
);
let mut env =
EnvWithHandlerCfg::new_with_spec_id(Box::new(env.clone()), executor.spec_id());

Expand Down Expand Up @@ -230,3 +247,23 @@ impl RunArgs {
Ok(())
}
}

impl figment::Provider for RunArgs {
fn metadata(&self) -> Metadata {
Metadata::named("RunArgs")
}

fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
let mut map = Map::new();

if self.alphanet {
map.insert("alphanet".into(), self.alphanet.into());
}

if let Some(evm_version) = self.evm_version {
map.insert("evm_version".into(), figment::value::Value::serialize(evm_version)?);
}

Ok(Map::from([(Config::selected_profile(), map)]))
}
}
9 changes: 9 additions & 0 deletions crates/common/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ pub struct EvmArgs {
#[arg(long)]
#[serde(skip)]
pub isolate: bool,

/// Whether to enable Alphanet features.
#[arg(long)]
#[serde(skip)]
pub alphanet: bool,
}

// Make this set of options a `figment::Provider` so that it can be merged into the `Config`
Expand All @@ -170,6 +175,10 @@ impl Provider for EvmArgs {
dict.insert("isolate".to_string(), self.isolate.into());
}

if self.alphanet {
dict.insert("alphanet".to_string(), self.alphanet.into());
}

if self.always_use_create_2_factory {
dict.insert(
"always_use_create_2_factory".to_string(),
Expand Down
Loading

0 comments on commit f8aa4af

Please sign in to comment.