Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(forge): selectively enable Etherscan trace resolving when a test in ran in a forked environment and return block number in trace on a failed test #7606

Open
wants to merge 52 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
68bfdb8
add has_forks to backend
zerosnacks Apr 8, 2024
7251ef4
Merge branch 'master' into zerosnacks/fix-tracing-regression
zerosnacks Apr 8, 2024
5eca07c
pass down environment, add dynamic enabled / disabled flag on a per t…
zerosnacks Apr 9, 2024
004dc11
add clarifying comment
zerosnacks Apr 9, 2024
46ae039
check has_forks at test runtime
zerosnacks Apr 9, 2024
acba4c4
pass down block number
zerosnacks Apr 9, 2024
f3fc621
fix build issues, cast block number as u64
zerosnacks Apr 9, 2024
d63e4fc
flip order
zerosnacks Apr 9, 2024
0ff4a3f
clarify
zerosnacks Apr 9, 2024
c42c3a6
remove unused code
zerosnacks Apr 9, 2024
f9ad7c0
Merge branch 'master' into zerosnacks/fix-tracing-regression
zerosnacks Apr 10, 2024
c5a4690
simplify by making enable_etherscan flip based on parameter `yes`
zerosnacks Apr 10, 2024
15a9bfd
add environment report formatter, add block on failure
zerosnacks Apr 10, 2024
7e4bb99
add block format to test, looks incorrect, especially in the USDTCall…
zerosnacks Apr 10, 2024
c473f01
fix, has_forks was inverted
zerosnacks Apr 10, 2024
7f1f3c2
Merge branch 'master' into zerosnacks/fix-tracing-regression
zerosnacks Apr 15, 2024
efc05d3
to be able to capture forking state inside of calls (as in vm.createS…
zerosnacks Apr 15, 2024
d2ba46b
filter out block number at genesis, assume non-forked environment in …
zerosnacks Apr 15, 2024
5ae23e5
add basic tests cases
zerosnacks Apr 15, 2024
4edb749
simplify has_forks check, we can simply check `issued_local_forks_ids…
zerosnacks Apr 15, 2024
8fb7445
add specific test for verbose tracing and non verbose tracing for bot…
zerosnacks Apr 15, 2024
676b249
revert simplification
zerosnacks Apr 15, 2024
d48c3b3
add note
zerosnacks Apr 15, 2024
b48a587
pull in latest master
zerosnacks Apr 16, 2024
5404c5c
revert repro_6531, clean up comments
zerosnacks Apr 16, 2024
059decc
make sure to output block number in both test results as well as the …
zerosnacks Apr 16, 2024
5799cc2
Merge branch 'master' into zerosnacks/fix-tracing-regression
zerosnacks Apr 22, 2024
07dde75
merge in master
zerosnacks Apr 23, 2024
07fceb5
remove env passing, to implement an alternative, move etherscan toggl…
zerosnacks Apr 23, 2024
bfca63c
add context capturing, collecting all block changes during execution
zerosnacks Apr 23, 2024
85bb139
fix overflow
zerosnacks Apr 23, 2024
39807c9
fix clippy
zerosnacks Apr 23, 2024
56e1006
add test trace for multiblock fork
zerosnacks Apr 23, 2024
52e2ca5
fix title
zerosnacks Apr 23, 2024
28986ac
add context tracking to setup
zerosnacks Apr 23, 2024
ad74f98
add context tracking support for fuzz and invariant counter example c…
zerosnacks Apr 23, 2024
4fcbdce
enhance with context, move definition to core
zerosnacks Apr 23, 2024
a2ba880
re-add environment with context
zerosnacks Apr 23, 2024
dd2592b
fix clippy
zerosnacks Apr 23, 2024
715d8b2
Merge branch 'master' into zerosnacks/fix-tracing-regression
zerosnacks Apr 25, 2024
f6310ff
appears formatting issue could relate to diff error throw
zerosnacks Apr 25, 2024
00897fa
update trace
zerosnacks Apr 25, 2024
163e337
add fuzz test case, also logs block correctly - avoid pushing genesis…
zerosnacks Apr 25, 2024
e5037d1
remove debug trace
zerosnacks Apr 25, 2024
2b6865f
improve documentation
zerosnacks Apr 25, 2024
b311550
pull in master
zerosnacks Apr 30, 2024
1536799
only rely on context tracing to determine fork status
zerosnacks Apr 30, 2024
af34ff8
remove context as inspector, simply inline
zerosnacks Apr 30, 2024
d42eb2e
remove inspector, only rely on executor env block number at the end o…
zerosnacks Apr 30, 2024
2e5918b
re-add inspector - cleaner than inlining and allows capture of transf…
zerosnacks Apr 30, 2024
c0775aa
add comment on block number modification due to cheat codes
zerosnacks Apr 30, 2024
747e17c
remove wrongly merged funcs file, avoid formatting diff
zerosnacks Apr 30, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion crates/evm/core/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,11 @@ impl Backend {
}
}

/// Returns whether the backend has any active forks
pub fn has_forks(&self) -> bool {
!self.inner.has_forks()
}

/// Returns all snapshots created in this backend
pub fn snapshots(&self) -> &Snapshots<BackendSnapshot<BackendDatabaseSnapshot>> {
&self.inner.snapshots
Expand Down Expand Up @@ -1539,7 +1544,7 @@ pub struct BackendInner {
/// issued _local_ numeric identifier, that remains constant, even if the underlying fork
/// backend changes.
pub issued_local_fork_ids: HashMap<LocalForkId, ForkId>,
/// tracks all the created forks
/// Tracks all the created forks
/// Contains the index of the corresponding `ForkDB` in the `forks` vec
pub created_forks: HashMap<ForkId, ForkLookupIndex>,
/// Holds all created fork databases
Expand Down Expand Up @@ -1598,6 +1603,15 @@ impl BackendInner {
self.ensure_fork_index(self.ensure_fork_id(id)?)
}

/// Returns whether there are any active forks
pub fn has_forks(&self) -> bool {
if !self.created_forks.is_empty() {
return true;
}

self.forks.iter().any(|fork| fork.is_some())
}

/// Returns the underlying fork mapped to the index
#[track_caller]
fn get_fork(&self, idx: ForkLookupIndex) -> &Fork {
Expand Down
15 changes: 15 additions & 0 deletions crates/evm/traces/src/identifier/etherscan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ pub struct EtherscanIdentifier {
invalid_api_key: Arc<AtomicBool>,
pub contracts: BTreeMap<Address, Metadata>,
pub sources: BTreeMap<u32, String>,
// Tracks whether the Etherscan identifier is enabled
// Enabled for forking tests
// Disabled for local tests
pub enabled: bool,
}

impl EtherscanIdentifier {
Expand All @@ -53,9 +57,20 @@ impl EtherscanIdentifier {
invalid_api_key: Arc::new(AtomicBool::new(false)),
contracts: BTreeMap::new(),
sources: BTreeMap::new(),
enabled: true,
}))
}

/// Enables the Etherscan identifier.
pub fn enable(&mut self) {
self.enabled = true;
}

/// Disables the Etherscan identifier.
pub fn disable(&mut self) {
self.enabled = false;
}

/// Goes over the list of contracts we have pulled from the traces, clones their source from
/// Etherscan and compiles them locally, for usage in the debugger.
pub async fn get_compiled_contracts(&self) -> eyre::Result<ContractSources> {
Expand Down
18 changes: 17 additions & 1 deletion crates/evm/traces/src/identifier/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ impl TraceIdentifier for TraceIdentifiers<'_> {
identities.extend(local.identify_addresses(addresses.clone()));
}
if let Some(etherscan) = &mut self.etherscan {
identities.extend(etherscan.identify_addresses(addresses));
if etherscan.enabled {
identities.extend(etherscan.identify_addresses(addresses));
}
}
identities
}
Expand All @@ -86,6 +88,20 @@ impl<'a> TraceIdentifiers<'a> {
Ok(self)
}

/// Enables the Etherscan identifier.
pub fn enable_etherscan(&mut self) {
if let Some(etherscan) = &mut self.etherscan {
etherscan.enable();
}
}

/// Disables the Etherscan identifier.
pub fn disable_etherscan(&mut self) {
if let Some(etherscan) = &mut self.etherscan {
etherscan.disable();
}
}

/// Returns `true` if there are no set identifiers.
pub fn is_empty(&self) -> bool {
self.local.is_none() && self.etherscan.is_none()
Expand Down
11 changes: 11 additions & 0 deletions crates/forge/bin/cmd/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,8 @@ impl TestArgs {
let mut identifier = TraceIdentifiers::new().with_local(&known_contracts);

// Avoid using etherscan for gas report as we decode more traces and this will be expensive.
// Because users can enable forking through cheat codes, we cannot simply disable etherscan
// for non-forking tests here.
if !self.gas_report {
identifier = identifier.with_etherscan(&config, remote_chain_id)?;
}
Expand Down Expand Up @@ -456,6 +458,15 @@ impl TestArgs {
let mut decoded_traces = Vec::with_capacity(result.traces.len());
for (kind, arena) in &result.traces {
if identify_addresses {
if result.is_fork() {
// Enable Etherscan decoding for forking tests.
identifier.enable_etherscan();
} else {
// Disable Etherscan decoding for local tests to avoid unnecessary API
// calls that can slow down execution significantly if rate-limited.
identifier.disable_etherscan();
zerosnacks marked this conversation as resolved.
Show resolved Hide resolved
}

decoder.identify(arena, &mut identifier);
}

Expand Down
33 changes: 32 additions & 1 deletion crates/forge/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,11 @@ impl SuiteResult {
self.test_results.is_empty()
}

/// Whether this test suite has any forked tests.
pub fn has_fork(&self) -> bool {
self.test_results.values().any(|result| result.is_fork())
}

/// The number of tests in this test suite.
pub fn len(&self) -> usize {
self.test_results.len()
Expand Down Expand Up @@ -359,9 +364,12 @@ pub struct TestResult {
/// The decoded DSTest logging events and Hardhat's `console.log` from [logs](Self::logs).
pub decoded_logs: Vec<String>,

/// What kind of test this was
/// What kind of test this was.
pub kind: TestKind,

/// What kind of environment this test was run in.
pub environment: TestEnvironment,

/// Traces
#[serde(skip)]
pub traces: Traces,
Expand Down Expand Up @@ -424,6 +432,11 @@ impl TestResult {
Self { status: TestStatus::Failure, reason: Some(reason), ..Default::default() }
}

/// Returns `true` if this is the result of a forked test
pub fn is_fork(&self) -> bool {
matches!(self.environment, TestEnvironment::Fork { .. })
}

/// Returns `true` if this is the result of a fuzz test
pub fn is_fuzz(&self) -> bool {
matches!(self.kind, TestKind::Fuzz { .. })
Expand Down Expand Up @@ -472,6 +485,24 @@ impl TestKindReport {
}
}

/// Various types of test environments
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TestEnvironment {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this, this makes it easier to add more modes

/// A standard test environment
Standard,
/// A forked test environment
Fork {
/// The block number at which the test was executed
block: u64,
},
}

impl Default for TestEnvironment {
fn default() -> Self {
Self::Standard
}
}

/// Various types of tests
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TestKind {
Expand Down
20 changes: 19 additions & 1 deletion crates/forge/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use crate::{
multi_runner::{is_matching_test, TestContract},
result::{SuiteResult, TestKind, TestResult, TestSetup, TestStatus},
result::{SuiteResult, TestEnvironment, TestKind, TestResult, TestSetup, TestStatus},
TestFilter, TestOptions,
};
use alloy_json_abi::Function;
Expand Down Expand Up @@ -235,6 +235,7 @@ impl<'a> ContractRunner<'a> {
decoded_logs: decode_console_logs(&setup.logs),
logs: setup.logs,
kind: TestKind::Standard(0),
environment: self.get_environment(),
traces: setup.traces,
coverage: setup.coverage,
labeled_addresses: setup.labeled_addresses,
Expand Down Expand Up @@ -393,6 +394,7 @@ impl<'a> ContractRunner<'a> {
traces,
labeled_addresses,
kind: TestKind::Standard(0),
environment: self.get_environment(),
duration: start.elapsed(),
..Default::default()
}
Expand All @@ -405,6 +407,7 @@ impl<'a> ContractRunner<'a> {
traces,
labeled_addresses,
kind: TestKind::Standard(0),
environment: self.get_environment(),
duration: start.elapsed(),
..Default::default()
}
Expand Down Expand Up @@ -432,6 +435,7 @@ impl<'a> ContractRunner<'a> {
decoded_logs: decode_console_logs(&logs),
logs,
kind: TestKind::Standard(gas.overflowing_sub(stipend).0),
environment: self.get_environment(),
traces,
coverage,
labeled_addresses,
Expand Down Expand Up @@ -474,6 +478,7 @@ impl<'a> ContractRunner<'a> {
traces,
labeled_addresses,
kind: TestKind::Invariant { runs: 1, calls: 1, reverts: 1 },
environment: self.get_environment(),
coverage,
duration: start.elapsed(),
..Default::default()
Expand Down Expand Up @@ -504,6 +509,7 @@ impl<'a> ContractRunner<'a> {
traces,
labeled_addresses,
kind: TestKind::Invariant { runs: 0, calls: 0, reverts: 0 },
environment: self.get_environment(),
duration: start.elapsed(),
..Default::default()
}
Expand Down Expand Up @@ -570,6 +576,7 @@ impl<'a> ContractRunner<'a> {
calls: cases.iter().map(|sequence| sequence.cases().len()).sum(),
reverts,
},
environment: self.get_environment(),
coverage,
traces,
labeled_addresses: labeled_addresses.clone(),
Expand Down Expand Up @@ -626,6 +633,7 @@ impl<'a> ContractRunner<'a> {
traces,
labeled_addresses,
kind: TestKind::Standard(0),
environment: self.get_environment(),
debug,
breakpoints,
coverage,
Expand Down Expand Up @@ -698,6 +706,7 @@ impl<'a> ContractRunner<'a> {
decoded_logs: decode_console_logs(&logs),
logs,
kind,
environment: self.get_environment(),
traces,
coverage,
labeled_addresses,
Expand All @@ -707,6 +716,15 @@ impl<'a> ContractRunner<'a> {
gas_report_traces: result.gas_report_traces.into_iter().map(|t| vec![t]).collect(),
}
}

/// Returns the environment of the test runner
fn get_environment(&self) -> TestEnvironment {
self.executor
.backend
.has_forks()
.then(|| TestEnvironment::Fork { block: self.executor.env.block.number.to::<u64>() })
.unwrap_or(TestEnvironment::Standard)
}
}

/// Utility function to merge coverage options
Expand Down