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

feat(forge, cast): add cast --with_local_artifacts/forge selectors cache to trace with local artifacts #7359

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion crates/cast/bin/cmd/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ pub struct CallArgs {

#[command(flatten)]
eth: EthereumOpts,

/// Use current project artifacts for trace decoding.
#[arg(long, visible_alias = "la")]
pub with_local_artifacts: bool,
}

#[derive(Debug, Parser)]
Expand Down Expand Up @@ -127,6 +131,7 @@ impl CallArgs {
decode_internal,
labels,
data,
with_local_artifacts,
..
} = self;

Expand Down Expand Up @@ -195,7 +200,16 @@ impl CallArgs {
),
};

handle_traces(trace, &config, chain, labels, debug, decode_internal, false).await?;
handle_traces(
trace,
&config,
chain,
labels,
with_local_artifacts,
debug,
decode_internal,
)
.await?;

return Ok(());
}
Expand Down
8 changes: 6 additions & 2 deletions crates/cast/bin/cmd/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use foundry_cli::{
opts::{EtherscanOpts, RpcOpts},
utils::{handle_traces, init_progress, TraceResult},
};
use foundry_common::{is_known_system_sender, shell, SYSTEM_TRANSACTION_TYPE};
use foundry_common::{is_known_system_sender, SYSTEM_TRANSACTION_TYPE};
use foundry_compilers::artifacts::EvmVersion;
use foundry_config::{
figment::{
Expand Down Expand Up @@ -87,6 +87,10 @@ pub struct RunArgs {
/// Enables Alphanet features.
#[arg(long, alias = "odyssey")]
pub alphanet: bool,

/// Use current project artifacts for trace decoding.
#[arg(long, visible_alias = "la")]
pub with_local_artifacts: bool,
}

impl RunArgs {
Expand Down Expand Up @@ -251,9 +255,9 @@ impl RunArgs {
&config,
chain,
self.label,
self.with_local_artifacts,
self.debug,
self.decode_internal,
shell::verbosity() > 0,
)
.await?;

Expand Down
98 changes: 69 additions & 29 deletions crates/cli/src/utils/cmd.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use alloy_json_abi::JsonAbi;
use alloy_primitives::Address;
use eyre::{Result, WrapErr};
use foundry_common::{fs, TestFunctionExt};
use foundry_common::{compile::ProjectCompiler, fs, shell, ContractsByArtifact, TestFunctionExt};
use foundry_compilers::{
artifacts::{CompactBytecode, Settings},
cache::{CacheEntry, CompilerCache},
Expand All @@ -14,9 +14,9 @@ use foundry_evm::{
executors::{DeployResult, EvmError, RawCallResult},
opts::EvmOpts,
traces::{
debug::DebugTraceIdentifier,
debug::{ContractSources, DebugTraceIdentifier},
decode_trace_arena,
identifier::{EtherscanIdentifier, SignaturesIdentifier},
identifier::{CachedSignatures, SignaturesIdentifier, TraceIdentifiers},
render_trace_arena_with_bytecodes, CallTraceDecoder, CallTraceDecoderBuilder, TraceKind,
Traces,
},
Expand Down Expand Up @@ -383,10 +383,25 @@ pub async fn handle_traces(
config: &Config,
chain: Option<Chain>,
labels: Vec<String>,
with_local_artifacts: bool,
debug: bool,
decode_internal: bool,
verbose: bool,
) -> Result<()> {
let (known_contracts, local_sources) = if with_local_artifacts {
let _ = sh_println!("Compiling project to generate artifacts");
let project = config.project()?;
let compiler = ProjectCompiler::new().quiet(true);
let output = compiler.compile(&project)?;
(
Some(ContractsByArtifact::new(
output.artifact_ids().map(|(id, artifact)| (id, artifact.clone().into())),
)),
Some(ContractSources::from_project_output(&output, project.root(), None)?),
)
} else {
(None, None)
};

let labels = labels.iter().filter_map(|label_str| {
let mut iter = label_str.split(':');

Expand All @@ -398,45 +413,48 @@ pub async fn handle_traces(
None
});
let config_labels = config.labels.clone().into_iter();
let mut decoder = CallTraceDecoderBuilder::new()

let mut builder = CallTraceDecoderBuilder::new()
.with_labels(labels.chain(config_labels))
.with_signature_identifier(SignaturesIdentifier::new(
Config::foundry_cache_dir(),
config.offline,
)?)
.build();
)?);
let mut identifier = TraceIdentifiers::new().with_etherscan(config, chain)?;
if let Some(contracts) = &known_contracts {
builder = builder.with_known_contracts(contracts);
identifier = identifier.with_local(contracts);
}

let mut etherscan_identifier = EtherscanIdentifier::new(config, chain)?;
if let Some(etherscan_identifier) = &mut etherscan_identifier {
for (_, trace) in result.traces.as_deref_mut().unwrap_or_default() {
decoder.identify(trace, etherscan_identifier);
}
let mut decoder = builder.build();

for (_, trace) in result.traces.as_deref_mut().unwrap_or_default() {
decoder.identify(trace, &mut identifier);
}

if decode_internal {
let sources = if let Some(etherscan_identifier) = &etherscan_identifier {
if decode_internal || debug {
let sources = if let Some(local_sources) = local_sources {
local_sources
} else if let Some(ref etherscan_identifier) = identifier.etherscan {
etherscan_identifier.get_compiled_contracts().await?
} else {
Default::default()
};

if debug {
let mut debugger = Debugger::builder()
.traces(result.traces.expect("missing traces"))
.decoder(&decoder)
.sources(sources)
.build();
debugger.try_run_tui()?;
return Ok(())
}

decoder.debug_identifier = Some(DebugTraceIdentifier::new(sources));
}

if debug {
let sources = if let Some(etherscan_identifier) = etherscan_identifier {
etherscan_identifier.get_compiled_contracts().await?
} else {
Default::default()
};
let mut debugger = Debugger::builder()
.traces(result.traces.expect("missing traces"))
.decoder(&decoder)
.sources(sources)
.build();
debugger.try_run_tui()?;
} else {
print_traces(&mut result, &decoder, verbose).await?;
}
print_traces(&mut result, &decoder, shell::verbosity() > 0).await?;

Ok(())
}
Expand Down Expand Up @@ -464,3 +482,25 @@ pub async fn print_traces(
sh_println!("Gas used: {}", result.gas_used)?;
Ok(())
}

/// Traverse the artifacts in the project to generate local signatures and merge them into the cache
/// file.
pub fn cache_local_signatures(output: &ProjectCompileOutput, cache_path: PathBuf) -> Result<()> {
let path = cache_path.join("signatures");
let mut cached_signatures = CachedSignatures::load(cache_path);
output.artifacts().for_each(|(_, artifact)| {
if let Some(abi) = &artifact.abi {
for func in abi.functions() {
cached_signatures.functions.insert(func.selector().to_string(), func.signature());
}
for event in abi.events() {
cached_signatures
.events
.insert(event.selector().to_string(), event.full_signature());
}
}
});

fs::write_json_file(&path, &cached_signatures)?;
Ok(())
}
2 changes: 1 addition & 1 deletion crates/evm/traces/src/identifier/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ mod etherscan;
pub use etherscan::EtherscanIdentifier;

mod signatures;
pub use signatures::{SignaturesIdentifier, SingleSignaturesIdentifier};
pub use signatures::{CachedSignatures, SignaturesIdentifier, SingleSignaturesIdentifier};

/// An address identity
pub struct AddressIdentity<'a> {
Expand Down
35 changes: 22 additions & 13 deletions crates/evm/traces/src/identifier/signatures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,29 @@ use tokio::sync::RwLock;
pub type SingleSignaturesIdentifier = Arc<RwLock<SignaturesIdentifier>>;

#[derive(Debug, Default, Serialize, Deserialize)]
struct CachedSignatures {
events: BTreeMap<String, String>,
functions: BTreeMap<String, String>,
pub struct CachedSignatures {
pub events: BTreeMap<String, String>,
pub functions: BTreeMap<String, String>,
}

impl CachedSignatures {
#[instrument(target = "evm::traces")]
pub fn load(cache_path: PathBuf) -> Self {
let path = cache_path.join("signatures");
if path.is_file() {
fs::read_json_file(&path)
.map_err(
|err| warn!(target: "evm::traces", ?path, ?err, "failed to read cache file"),
)
.unwrap_or_default()
} else {
if let Err(err) = std::fs::create_dir_all(cache_path) {
warn!(target: "evm::traces", "could not create signatures cache dir: {:?}", err);
}
Self::default()
}
}
}
/// An identifier that tries to identify functions and events using signatures found at
/// `https://openchain.xyz` or a local cache.
#[derive(Debug)]
Expand All @@ -42,16 +60,7 @@ impl SignaturesIdentifier {
let identifier = if let Some(cache_path) = cache_path {
let path = cache_path.join("signatures");
trace!(target: "evm::traces", ?path, "reading signature cache");
let cached = if path.is_file() {
fs::read_json_file(&path)
.map_err(|err| warn!(target: "evm::traces", ?path, ?err, "failed to read cache file"))
.unwrap_or_default()
} else {
if let Err(err) = std::fs::create_dir_all(cache_path) {
warn!(target: "evm::traces", "could not create signatures cache dir: {:?}", err);
}
CachedSignatures::default()
};
let cached = CachedSignatures::load(cache_path);
Self { cached, cached_path: Some(path), unavailable: HashSet::default(), client }
} else {
Self {
Expand Down
26 changes: 25 additions & 1 deletion crates/forge/bin/cmd/selectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ use comfy_table::Table;
use eyre::Result;
use foundry_cli::{
opts::{CompilerArgs, CoreBuildArgs, ProjectPathsArgs},
utils::FoundryPathExt,
utils::{cache_local_signatures, FoundryPathExt},
};
use foundry_common::{
compile::{compile_target, ProjectCompiler},
selectors::{import_selectors, SelectorImportData},
};
use foundry_compilers::{artifacts::output_selection::ContractOutputSelection, info::ContractInfo};
use foundry_config::Config;
use std::fs::canonicalize;

/// CLI arguments for `forge selectors`.
Expand Down Expand Up @@ -67,11 +68,34 @@ pub enum SelectorsSubcommands {
#[command(flatten)]
project_paths: ProjectPathsArgs,
},

/// Cache project selectors (enables trace with local contracts functions and events).
#[command(visible_alias = "c")]
Cache {
#[command(flatten)]
project_paths: ProjectPathsArgs,
},
}

impl SelectorsSubcommands {
pub async fn run(self) -> Result<()> {
match self {
Self::Cache { project_paths } => {
sh_println!("Caching selectors for contracts in the project...")?;
let build_args = CoreBuildArgs {
project_paths,
compiler: CompilerArgs {
extra_output: vec![ContractOutputSelection::Abi],
..Default::default()
},
..Default::default()
};

// compile the project to get the artifacts/abis
let project = build_args.project()?;
let outcome = ProjectCompiler::new().quiet(true).compile(&project)?;
cache_local_signatures(&outcome, Config::foundry_cache_dir().unwrap())?
}
Self::Upload { contract, all, project_paths } => {
let build_args = CoreBuildArgs {
project_paths: project_paths.clone(),
Expand Down
Loading