Skip to content

Commit

Permalink
use zkforge module, fix deployed smart contract address computation
Browse files Browse the repository at this point in the history
  • Loading branch information
nbaztec committed Dec 12, 2023
1 parent 59e7ea9 commit 23e5a34
Show file tree
Hide file tree
Showing 22 changed files with 90 additions and 87 deletions.
2 changes: 1 addition & 1 deletion crates/zkforge/bin/cmd/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ foundry_config::merge_impl_figment_convert!(BuildArgs, args);
/// # Example
///
/// ```
/// use foundry_cli::cmd::forge::build::BuildArgs;
/// use foundry_cli::cmd::zkforge::build::BuildArgs;
/// use foundry_config::Config;
/// # fn t(args: BuildArgs) {
/// let config = Config::from(&args);
Expand Down
24 changes: 12 additions & 12 deletions crates/zkforge/bin/cmd/coverage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,6 @@ use super::{install, test::FilterArgs};
use alloy_primitives::{Address, Bytes, U256};
use clap::{Parser, ValueEnum, ValueHint};
use eyre::{Context, Result};
use forge::{
coverage::{
analysis::SourceAnalyzer, anchors::find_anchors, ContractId, CoverageReport,
CoverageReporter, DebugReporter, ItemAnchor, LcovReporter, SummaryReporter,
},
inspectors::CheatsConfig,
opts::EvmOpts,
result::SuiteResult,
revm::primitives::SpecId,
utils::{build_ic_pc_map, ICPCMap},
MultiContractRunnerBuilder, TestOptions,
};
use foundry_cli::{
opts::CoreBuildArgs,
p_println,
Expand All @@ -29,6 +17,18 @@ use foundry_config::{Config, SolcReq};
use semver::Version;
use std::{collections::HashMap, path::PathBuf, sync::mpsc::channel};
use yansi::Paint;
use zkforge::{
coverage::{
analysis::SourceAnalyzer, anchors::find_anchors, ContractId, CoverageReport,
CoverageReporter, DebugReporter, ItemAnchor, LcovReporter, SummaryReporter,
},
inspectors::CheatsConfig,
opts::EvmOpts,
result::SuiteResult,
revm::primitives::SpecId,
utils::{build_ic_pc_map, ICPCMap},
MultiContractRunnerBuilder, TestOptions,
};

/// A map, keyed by contract ID, to a tuple of the deployment source map and the runtime source map.
type SourceMaps = HashMap<ContractId, (SourceMap, SourceMap)>;
Expand Down
4 changes: 2 additions & 2 deletions crates/zkforge/bin/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
//!
//! ```
//! use clap::Parser;
//! use forge::executor::opts::EvmOpts;
//! use foundry_cli::cmd::forge::build::BuildArgs;
//! use foundry_cli::cmd::zkforge::build::BuildArgs;
//! use foundry_common::evm::EvmArgs;
//! use foundry_config::{figment::Figment, *};
//! use zkforge::executor::opts::EvmOpts;
//!
//! // A new clap subcommand that accepts both `EvmArgs` and `BuildArgs`
//! #[derive(Debug, Clone, Parser)]
Expand Down
2 changes: 1 addition & 1 deletion crates/zkforge/bin/cmd/script/broadcast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ impl ScriptArgs {
let from = tx.from().expect("no sender");

if sequential_broadcast {
let nonce = forge::next_nonce((*from).to_alloy(), fork_url, None)
let nonce = zkforge::next_nonce((*from).to_alloy(), fork_url, None)
.await
.map_err(|_| eyre::eyre!("Not able to query the EOA nonce."))?;

Expand Down
2 changes: 1 addition & 1 deletion crates/zkforge/bin/cmd/script/build.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use super::*;
use alloy_primitives::{Address, Bytes};
use eyre::{Context, ContextCompat, Result};
use forge::link::{link_with_nonce_or_address, PostLinkInput, ResolvedDependency};
use foundry_cli::utils::get_cached_entry_by_name;
use foundry_common::{
compact_to_contract,
Expand All @@ -16,6 +15,7 @@ use foundry_compilers::{
ArtifactId, Project, ProjectCompileOutput,
};
use std::{collections::BTreeMap, str::FromStr};
use zkforge::link::{link_with_nonce_or_address, PostLinkInput, ResolvedDependency};

impl ScriptArgs {
/// Compiles the file or project and the verify metadata.
Expand Down
4 changes: 2 additions & 2 deletions crates/zkforge/bin/cmd/script/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl ScriptArgs {
if let Some(ref fork_url) = script_config.evm_opts.fork_url {
// when forking, override the sender's nonce to the onchain value
script_config.sender_nonce =
forge::next_nonce(script_config.evm_opts.sender, fork_url, None).await?
zkforge::next_nonce(script_config.evm_opts.sender, fork_url, None).await?
} else {
// if not forking, then ignore any pre-deployed library addresses
script_config.config.libraries = Default::default();
Expand Down Expand Up @@ -300,7 +300,7 @@ impl ScriptArgs {
) -> Result<(Libraries, ArtifactContracts<ContractBytecodeSome>)> {
// if we had a new sender that requires relinking, we need to
// get the nonce mainnet for accurate addresses for predeploy libs
let nonce = forge::next_nonce(
let nonce = zkforge::next_nonce(
new_sender,
script_config.evm_opts.fork_url.as_ref().ok_or_else(|| {
eyre::eyre!("You must provide an RPC URL (see --fork-url) when broadcasting.")
Expand Down
14 changes: 7 additions & 7 deletions crates/zkforge/bin/cmd/script/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ use super::{
use alloy_primitives::{Address, Bytes, U256};
use ethers_core::types::transaction::eip2718::TypedTransaction;
use eyre::Result;
use forge::{
backend::Backend,
executors::ExecutorBuilder,
inspectors::{cheatcodes::BroadcastableTransactions, CheatsConfig},
traces::{CallTraceDecoder, Traces},
utils::CallKind,
};
use foundry_cli::utils::{ensure_clean_constructor, needs_setup};
use foundry_common::{shell, types::ToEthers, RpcUrl};
use foundry_compilers::artifacts::CompactContractBytecode;
use futures::future::join_all;
use parking_lot::RwLock;
use std::{collections::VecDeque, sync::Arc};
use zkforge::{
backend::Backend,
executors::ExecutorBuilder,
inspectors::{cheatcodes::BroadcastableTransactions, CheatsConfig},
traces::{CallTraceDecoder, Traces},
utils::CallKind,
};

/// Helper alias type for the processed result of a runner onchain simulation.
type RunnerResult = (Option<TransactionWithMetadata>, Traces);
Expand Down
22 changes: 11 additions & 11 deletions crates/zkforge/bin/cmd/script/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,6 @@ use ethers_core::types::{
use ethers_providers::{Http, Middleware};
use ethers_signers::LocalWallet;
use eyre::{ContextCompat, Result, WrapErr};
use forge::{
backend::Backend,
debug::DebugArena,
decode::decode_console_logs,
opts::EvmOpts,
traces::{
identifier::{EtherscanIdentifier, LocalTraceIdentifier, SignaturesIdentifier},
CallTraceDecoder, CallTraceDecoderBuilder, TraceCallData, TraceKind, TraceRetData, Traces,
},
utils::CallKind,
};
use foundry_cli::opts::MultiWallet;
use foundry_common::{
abi::{encode_function_args, get_func},
Expand Down Expand Up @@ -56,6 +45,17 @@ use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use yansi::Paint;
use zkforge::{
backend::Backend,
debug::DebugArena,
decode::decode_console_logs,
opts::EvmOpts,
traces::{
identifier::{EtherscanIdentifier, LocalTraceIdentifier, SignaturesIdentifier},
CallTraceDecoder, CallTraceDecoderBuilder, TraceCallData, TraceKind, TraceRetData, Traces,
},
utils::CallKind,
};

mod artifacts;
mod broadcast;
Expand Down
2 changes: 1 addition & 1 deletion crates/zkforge/bin/cmd/script/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::*;
use alloy_primitives::{Address, Bytes, U256};
use ethers_core::types::NameOrAddress;
use eyre::Result;
use forge::{
use zkforge::{
constants::CALLER,
executors::{CallResult, DeployResult, EvmError, ExecutionErr, Executor, RawCallResult},
revm::interpreter::{return_ok, InstructionResult},
Expand Down
2 changes: 1 addition & 1 deletion crates/zkforge/bin/cmd/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use super::{
use alloy_primitives::U256;
use clap::{builder::RangedU64ValueParser, Parser, ValueHint};
use eyre::{Context, Result};
use forge::result::TestKindReport;
use foundry_cli::utils::STATIC_FUZZ_SEED;
use once_cell::sync::Lazy;
use regex::Regex;
Expand All @@ -19,6 +18,7 @@ use std::{
};
use watchexec::config::{InitConfig, RuntimeConfig};
use yansi::Paint;
use zkforge::result::TestKindReport;

/// A regex that matches a basic snapshot entry like
/// `Test:testDeposit() (gas: 58804)`
Expand Down
2 changes: 1 addition & 1 deletion crates/zkforge/bin/cmd/test/filter.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use clap::Parser;
use forge::TestFilter;
use foundry_cli::utils::FoundryPathExt;
use foundry_common::glob::GlobMatcher;
use foundry_compilers::{FileFilter, ProjectPathsConfig};
use foundry_config::Config;
use std::{fmt, path::Path};
use zkforge::TestFilter;

/// The filter to use during testing.
///
Expand Down
30 changes: 15 additions & 15 deletions crates/zkforge/bin/cmd/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,6 @@ use super::{install, test::filter::ProjectPathsAwareFilter, watch::WatchArgs};
use alloy_primitives::U256;
use clap::Parser;
use eyre::Result;
use forge::{
decode::decode_console_logs,
gas_report::GasReport,
inspectors::CheatsConfig,
result::{SuiteResult, TestResult, TestStatus},
traces::{
identifier::{EtherscanIdentifier, LocalTraceIdentifier, SignaturesIdentifier},
CallTraceDecoderBuilder, TraceKind,
},
MultiContractRunner, MultiContractRunnerBuilder, TestOptions, TestOptionsBuilder,
};
use foundry_cli::{
opts::CoreBuildArgs,
utils::{self, LoadConfig},
Expand All @@ -34,6 +23,17 @@ use regex::Regex;
use std::{collections::BTreeMap, fs, sync::mpsc::channel, time::Duration};
use watchexec::config::{InitConfig, RuntimeConfig};
use yansi::Paint;
use zkforge::{
decode::decode_console_logs,
gas_report::GasReport,
inspectors::CheatsConfig,
result::{SuiteResult, TestResult, TestStatus},
traces::{
identifier::{EtherscanIdentifier, LocalTraceIdentifier, SignaturesIdentifier},
CallTraceDecoderBuilder, TraceKind,
},
MultiContractRunner, MultiContractRunnerBuilder, TestOptions, TestOptionsBuilder,
};

mod filter;
mod summary;
Expand Down Expand Up @@ -129,7 +129,7 @@ impl TestArgs {
}

pub async fn run(self) -> Result<TestOutcome> {
trace!(target: "forge::test", "executing test command");
trace!(target: "zkforge::test", "executing test command");
shell::set_shell(shell::Shell::from_args(self.opts.silent, self.json))?;
self.execute_tests().await
}
Expand Down Expand Up @@ -348,14 +348,14 @@ impl TestArgs {
return Ok(TestOutcome::new(results, self.allow_failure))
}

trace!(target: "forge::test", "running all tests");
trace!(target: "zkforge::test", "running all tests");

if runner.matching_test_function_count(filter) == 0 {
let filter_str = filter.to_string();
if filter_str.is_empty() {
println!(
"\nNo tests found in project! \
Forge looks for functions that starts with `test`."
ZKForge looks for functions that starts with `test`."
);
} else {
println!("\nNo tests match the provided pattern:\n{filter_str}");
Expand Down Expand Up @@ -541,7 +541,7 @@ impl TestArgs {
}
}

trace!(target: "forge::test", "received {} results", results.len());
trace!(target: "zkforge::test", "received {} results", results.len());

Ok(TestOutcome::new(results, self.allow_failure))
}
Expand Down
2 changes: 1 addition & 1 deletion crates/zkforge/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ fn main() -> Result<()> {
clap_complete::generate(
clap_complete_fig::Fig,
&mut Opts::command(),
"forge",
"zkforge",
&mut std::io::stdout(),
);
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions crates/zkforge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,11 @@ impl TestOptions {
};

if let Some(ref fuzz_seed) = self.fuzz.seed {
trace!(target: "forge::test", "building deterministic fuzzer with seed {}", fuzz_seed);
trace!(target: "zkforge::test", "building deterministic fuzzer with seed {}", fuzz_seed);
let rng = TestRng::from_seed(RngAlgorithm::ChaCha, &B256::from(*fuzz_seed).0);
TestRunner::new_with_rng(cfg, rng)
} else {
trace!(target: "forge::test", "building stochastic fuzzer");
trace!(target: "zkforge::test", "building stochastic fuzzer");
TestRunner::new(cfg)
}
}
Expand Down
37 changes: 20 additions & 17 deletions crates/zkforge/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,24 +115,27 @@ impl<'a> ContractRunner<'a> {
}
}

let sender_nonce = self.executor.get_nonce(self.sender)?;
let address = self.sender.create(sender_nonce);

// Set the contracts initial balance before deployment, so it is available during
// construction
self.executor.set_balance(address, self.initial_balance)?;
// TODO: Look into generating address via zksync's scheme and set the balance before deploy
// let sender_nonce = self.executor.get_nonce(self.sender)?;
// let address = self.sender.create(sender_nonce);

// Deploy the test contract
match self.executor.deploy(self.sender, self.code.clone(), U256::ZERO, self.errors) {
Ok(d) => {
logs.extend(d.logs);
traces.extend(d.traces.map(|traces| (TraceKind::Deployment, traces)));
d.address
}
Err(e) => {
return Ok(TestSetup::from_evm_error_with(e, logs, traces, Default::default()))
}
};
let address =
match self.executor.deploy(self.sender, self.code.clone(), U256::ZERO, self.errors) {
Ok(d) => {
logs.extend(d.logs);
traces.extend(d.traces.map(|traces| (TraceKind::Deployment, traces)));
d.address
}
Err(e) => {
return Ok(TestSetup::from_evm_error_with(e, logs, traces, Default::default()))
}
};

// TODO: Move this before deploy to be consistent with upstream once the addresses are
// predictable Set the contracts initial balance before deployment, so it is
// available during construction
self.executor.set_balance(address, self.initial_balance)?;

// Reset `self.sender`s and `CALLER`s balance to the initial balance we want
self.executor.set_balance(self.sender, self.initial_balance)?;
Expand Down Expand Up @@ -427,7 +430,7 @@ impl<'a> ContractRunner<'a> {
known_contracts: Option<&ContractsByArtifact>,
identified_contracts: &ContractsByAddress,
) -> TestResult {
trace!(target: "forge::test::fuzz", "executing invariant test for {:?}", func.name);
trace!(target: "zkforge::test::fuzz", "executing invariant test for {:?}", func.name);
let empty = ContractsByArtifact::default();
let project_contracts = known_contracts.unwrap_or(&empty);
let TestSetup { address, logs, traces, labeled_addresses, coverage, .. } = setup;
Expand Down
8 changes: 4 additions & 4 deletions crates/zkforge/tests/it/config.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
//! Test config.
use crate::test_helpers::{COMPILED, EVM_OPTS, PROJECT};
use forge::{
result::{SuiteResult, TestStatus},
MultiContractRunner, MultiContractRunnerBuilder, TestOptions, TestOptionsBuilder,
};
use foundry_config::{
fs_permissions::PathPermission, Config, FsPermissions, FuzzConfig, FuzzDictionaryConfig,
InvariantConfig, RpcEndpoint, RpcEndpoints,
Expand All @@ -15,6 +11,10 @@ use foundry_evm::{
use foundry_test_utils::{init_tracing, Filter};
use itertools::Itertools;
use std::{collections::BTreeMap, path::Path};
use zkforge::{
result::{SuiteResult, TestStatus},
MultiContractRunner, MultiContractRunnerBuilder, TestOptions, TestOptionsBuilder,
};

/// How to execute a test run.
pub struct TestConfig {
Expand Down
2 changes: 1 addition & 1 deletion crates/zkforge/tests/it/core.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! Forge tests for core functionality.
use crate::config::*;
use forge::result::SuiteResult;
use foundry_evm::traces::TraceKind;
use foundry_test_utils::Filter;
use std::{collections::BTreeMap, env};
use zkforge::result::SuiteResult;

#[tokio::test(flavor = "multi_thread")]
async fn test_core() {
Expand Down
2 changes: 1 addition & 1 deletion crates/zkforge/tests/it/fork.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ use crate::{
config::*,
test_helpers::{PROJECT, RE_PATH_SEPARATOR},
};
use forge::result::SuiteResult;
use foundry_config::{fs_permissions::PathPermission, Config, FsPermissions};
use foundry_test_utils::Filter;
use zkforge::result::SuiteResult;

/// Executes reverting fork test
#[tokio::test(flavor = "multi_thread")]
Expand Down
Loading

0 comments on commit 23e5a34

Please sign in to comment.