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: add support for binary_mappings and network_family configs #9505

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 6 additions & 1 deletion crates/anvil/src/anvil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ fn main() {
fn run() -> Result<()> {
utils::load_dotenv();

if let Some(to) = utils::should_redirect_to() {
utils::redirect_execution(to)?;
return Ok(());
}

let mut args = Anvil::parse();
args.global.init()?;
args.node.evm_opts.resolve_rpc_alias();
Expand All @@ -69,7 +74,7 @@ fn run() -> Result<()> {
&mut std::io::stdout(),
),
}
return Ok(())
return Ok(());
}

let _ = fdlimit::raise_fd_limit();
Expand Down
5 changes: 5 additions & 0 deletions crates/cast/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ fn run() -> Result<()> {
utils::subscriber();
utils::enable_paint();

if let Some(to) = utils::should_redirect_to() {
utils::redirect_execution(to)?;
return Ok(());
}

let args = CastArgs::parse();
args.global.init()?;
main_args(args)
Expand Down
19 changes: 12 additions & 7 deletions crates/chisel/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@ fn run() -> eyre::Result<()> {
utils::subscriber();
utils::load_dotenv();

if let Some(to) = utils::should_redirect_to() {
utils::redirect_execution(to)?;
return Ok(());
}

let args = Chisel::parse();
args.global.init()?;
main_args(args)
Expand Down Expand Up @@ -158,15 +163,15 @@ async fn main_args(args: Chisel) -> eyre::Result<()> {
DispatchResult::CommandFailed(e) => sh_err!("{e}")?,
_ => panic!("Unexpected result: Please report this bug."),
}
return Ok(())
return Ok(());
}
Some(ChiselSubcommand::Load { id }) | Some(ChiselSubcommand::View { id }) => {
// For both of these subcommands, we need to attempt to load the session from cache
match dispatcher.dispatch_command(ChiselCommand::Load, &[id]).await {
DispatchResult::CommandSuccess(_) => { /* Continue */ }
DispatchResult::CommandFailed(e) => {
sh_err!("{e}")?;
return Ok(())
return Ok(());
}
_ => panic!("Unexpected result! Please report this bug."),
}
Expand All @@ -179,7 +184,7 @@ async fn main_args(args: Chisel) -> eyre::Result<()> {
}
_ => panic!("Unexpected result! Please report this bug."),
}
return Ok(())
return Ok(());
}
}
Some(ChiselSubcommand::ClearCache) => {
Expand All @@ -188,11 +193,11 @@ async fn main_args(args: Chisel) -> eyre::Result<()> {
DispatchResult::CommandFailed(e) => sh_err!("{e}")?,
_ => panic!("Unexpected result! Please report this bug."),
}
return Ok(())
return Ok(());
}
Some(ChiselSubcommand::Eval { command }) => {
dispatch_repl_line(&mut dispatcher, command).await?;
return Ok(())
return Ok(());
}
None => { /* No chisel subcommand present; Continue */ }
}
Expand Down Expand Up @@ -234,7 +239,7 @@ async fn main_args(args: Chisel) -> eyre::Result<()> {
}
Err(ReadlineError::Interrupted) => {
if interrupt {
break
break;
} else {
sh_println!("(To exit, press Ctrl+C again)")?;
interrupt = true;
Expand All @@ -243,7 +248,7 @@ async fn main_args(args: Chisel) -> eyre::Result<()> {
Err(ReadlineError::Eof) => break,
Err(err) => {
sh_err!("{err:?}")?;
break
break;
}
}
}
Expand Down
27 changes: 27 additions & 0 deletions crates/cli/src/utils/bin_redirect.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::path::PathBuf;

/// Loads config and checks if there is a binary remapping for the current binary.
/// If there is a remapping, returns the path to the binary that should be executed.
/// Returns `None` if the binary is not remapped _or_ if the current binary is not found in the
/// config.
pub fn should_redirect_to() -> Option<PathBuf> {
let current_exe = std::env::current_exe().ok()?;
let binary_name = current_exe.file_stem()?.to_str()?;
let config = foundry_config::Config::load();
config.binary_mappings().redirect_for(binary_name).cloned()
}

/// Launches the `to` binary with the same arguments as the current binary.
/// E.g. if user runs `forge build --arg1 --arg2`, and `to` is `/path/to/custom/forge`, then
/// this function will run `/path/to/custom/forge build --arg1 --arg2`.
pub fn redirect_execution(to: PathBuf) -> eyre::Result<()> {
let args = std::env::args().skip(1).collect::<Vec<_>>();
let status = std::process::Command::new(to)
.args(args)
.status()
.map_err(|e| eyre::eyre!("Failed to run command: {}", e))?;
if !status.success() {
eyre::bail!("Command failed with status: {}", status);
}
Ok(())
}
3 changes: 3 additions & 0 deletions crates/cli/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ pub use suggestions::*;
mod abi;
pub use abi::*;

mod bin_redirect;
pub use bin_redirect::*;

// reexport all `foundry_config::utils`
#[doc(hidden)]
pub use foundry_config::utils::*;
Expand Down
109 changes: 109 additions & 0 deletions crates/config/src/binary_mappings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
use std::{
collections::HashMap,
path::{Path, PathBuf},
};

use serde::{Deserialize, Serialize};

/// Binaries that can be remapped.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BinaryName {
Forge,
Anvil,
Cast,
Chisel,
}

impl TryFrom<&str> for BinaryName {
type Error = eyre::Error;

fn try_from(value: &str) -> eyre::Result<Self> {
match value {
"forge" => Ok(Self::Forge),
"anvil" => Ok(Self::Anvil),
"cast" => Ok(Self::Cast),
"chisel" => Ok(Self::Chisel),
_ => eyre::bail!("Invalid binary name: {value}"),
}
}
}

/// Contains the config for binary remappings,
/// e.g. ability to redirect any of the foundry binaries to some other binary.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct BinaryMappings {
/// The mappings from binary name to the path of the binary.
#[serde(flatten)]
pub mappings: HashMap<BinaryName, PathBuf>,
}

impl BinaryMappings {
/// Tells if the binary name is remapped to some other binary.
/// This function will return `None` if the binary name cannot be parsed or if
/// the binary name is not remapped.
pub fn redirect_for(&self, binary_name: &str) -> Option<&PathBuf> {
// Sanitize the path so that it
let binary_name = Path::new(binary_name).file_stem()?.to_str()?;
let binary_name = BinaryName::try_from(binary_name).ok()?;
self.mappings.get(&binary_name)
}
}

impl<T> From<T> for BinaryMappings
where
T: Into<HashMap<BinaryName, PathBuf>>,
{
fn from(mappings: T) -> Self {
Self { mappings: mappings.into() }
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn binary_names() {
assert_eq!(BinaryName::try_from("forge").unwrap(), BinaryName::Forge);
assert_eq!(BinaryName::try_from("anvil").unwrap(), BinaryName::Anvil);
assert_eq!(BinaryName::try_from("cast").unwrap(), BinaryName::Cast);
assert_eq!(BinaryName::try_from("chisel").unwrap(), BinaryName::Chisel);
}

#[test]
fn binary_names_serde() {
let test_vector = [
(BinaryName::Forge, r#""forge""#),
(BinaryName::Anvil, r#""anvil""#),
(BinaryName::Cast, r#""cast""#),
(BinaryName::Chisel, r#""chisel""#),
];

for (binary_name, expected) in test_vector.iter() {
let serialized = serde_json::to_string(binary_name).unwrap();
assert_eq!(serialized, *expected);

let deserialized: BinaryName = serde_json::from_str(expected).unwrap();
assert_eq!(deserialized, *binary_name);
}
}

#[test]
fn redirect_to() {
let mappings = BinaryMappings::from([
(BinaryName::Forge, PathBuf::from("forge-zksync")),
(BinaryName::Anvil, PathBuf::from("anvil-zksync")),
(BinaryName::Cast, PathBuf::from("cast-zksync")),
(BinaryName::Chisel, PathBuf::from("chisel-zksync")),
]);

assert_eq!(mappings.redirect_for("forge"), Some(&PathBuf::from("forge-zksync")));
assert_eq!(mappings.redirect_for("anvil"), Some(&PathBuf::from("anvil-zksync")));
assert_eq!(mappings.redirect_for("cast"), Some(&PathBuf::from("cast-zksync")));
assert_eq!(mappings.redirect_for("chisel"), Some(&PathBuf::from("chisel-zksync")));
assert_eq!(mappings.redirect_for("invalid"), None);
assert_eq!(mappings.redirect_for("/usr/bin/forge"), Some(&PathBuf::from("forge-zksync")));
assert_eq!(mappings.redirect_for("anvil.exe"), Some(&PathBuf::from("anvil-zksync")));
}
}
88 changes: 88 additions & 0 deletions crates/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ use foundry_compilers::{
ArtifactOutput, ConfigurableArtifacts, Graph, Project, ProjectPathsConfig,
RestrictionsWithVersion, VyperLanguage,
};
use network_family::NetworkFamily;
use regex::Regex;
use revm_primitives::{map::AddressHashMap, FixedBytes, SpecId};
use semver::Version;
Expand Down Expand Up @@ -122,6 +123,11 @@ use bind_json::BindJsonConfig;
mod compilation;
use compilation::{CompilationRestrictions, SettingsOverrides};

mod binary_mappings;
use binary_mappings::BinaryMappings;

mod network_family;

/// Foundry configuration
///
/// # Defaults
Expand Down Expand Up @@ -512,6 +518,17 @@ pub struct Config {
#[serde(default)]
pub compilation_restrictions: Vec<CompilationRestrictions>,

/// Configuration for alternative versions of foundry tools to be used.
#[serde(default)]
pub binary_mappings: Option<BinaryMappings>,

/// Network family configuration.
/// If specified, network family can be used to change certain defaults (such as
/// binary mappings). Note, however, that network family only changes _defaults_,
/// so if the configuration is explicitly provided, it takes precedence.
#[serde(default)]
pub network_family: NetworkFamily,

/// PRIVATE: This structure may grow, As such, constructing this structure should
/// _always_ be done using a public constructor or update syntax:
///
Expand Down Expand Up @@ -1990,6 +2007,11 @@ impl Config {
}
}

/// Returns the binary mappings.
pub fn binary_mappings(&self) -> BinaryMappings {
self.binary_mappings.clone().unwrap_or_else(|| self.network_family.binary_mappings())
}

/// The path provided to this function should point to a cached chain folder.
fn get_cached_blocks(chain_path: &Path) -> eyre::Result<Vec<(String, u64)>> {
let mut blocks = vec![];
Expand Down Expand Up @@ -2379,6 +2401,8 @@ impl Default for Config {
additional_compiler_profiles: Default::default(),
compilation_restrictions: Default::default(),
eof: false,
binary_mappings: Default::default(),
network_family: NetworkFamily::Ethereum,
_non_exhaustive: (),
}
}
Expand Down Expand Up @@ -4834,4 +4858,68 @@ mod tests {
Ok(())
});
}

#[test]
fn test_binary_mappings() {
figment::Jail::expect_with(|jail| {
// No mappings by default.
let config = Config::load();
assert_eq!(config.binary_mappings(), BinaryMappings::default());

// Load specified mappings.
jail.create_file(
"foundry.toml",
r#"
[profile.default]
binary_mappings = { "forge" = "forge-zksync", "anvil" = "anvil-zksync" }
"#,
)?;
let config = Config::load();
assert_eq!(
config.binary_mappings(),
BinaryMappings::from([
(binary_mappings::BinaryName::Forge, PathBuf::from("forge-zksync")),
(binary_mappings::BinaryName::Anvil, PathBuf::from("anvil-zksync"))
])
);

// Override via network family.
jail.create_file(
"foundry.toml",
r#"
[profile.default]
network_family = "zksync"
"#,
)?;
let config = Config::load();
assert_eq!(
config.binary_mappings(),
BinaryMappings::from([
(binary_mappings::BinaryName::Forge, PathBuf::from("forge-zksync")),
(binary_mappings::BinaryName::Cast, PathBuf::from("cast-zksync")),
(binary_mappings::BinaryName::Anvil, PathBuf::from("anvil-zksync"))
])
);

// Config precedence.
jail.create_file(
"foundry.toml",
r#"
[profile.default]
binary_mappings = { "forge" = "something-custom", "anvil" = "something-else" }
network_family = "zksync"
"#,
)?;
let config = Config::load();
assert_eq!(
config.binary_mappings(),
BinaryMappings::from([
(binary_mappings::BinaryName::Forge, PathBuf::from("something-custom")),
(binary_mappings::BinaryName::Anvil, PathBuf::from("something-else"))
])
);

Ok(())
});
}
}
Loading
Loading