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

refactor: split cheatcode definitions into a separate crate #6202

Merged
merged 6 commits into from
Nov 3, 2023
Merged
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
2 changes: 1 addition & 1 deletion .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[alias]
cheats = "test -p foundry-cheatcodes --features schema tests::"
cheats = "test -p foundry-cheatcodes-defs --features schema tests::"

[target.x86_64-pc-windows-msvc]
rustflags = [
Expand Down
15 changes: 12 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ members = [
"crates/binder/",
"crates/cast/",
"crates/cheatcodes/",
"crates/cheatcodes/defs/",
"crates/chisel/",
"crates/cli/",
"crates/common/",
Expand Down Expand Up @@ -116,6 +117,7 @@ forge-fmt = { path = "crates/fmt" }
foundry-abi = { path = "crates/abi" }
foundry-binder = { path = "crates/binder" }
foundry-cheatcodes = { path = "crates/cheatcodes" }
foundry-cheatcodes-defs = { path = "crates/cheatcodes/defs" }
foundry-cli = { path = "crates/cli" }
foundry-common = { path = "crates/common" }
foundry-config = { path = "crates/config" }
Expand Down
70 changes: 20 additions & 50 deletions crates/cheatcodes/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,56 +12,26 @@ repository.workspace = true
exclude.workspace = true

[dependencies]
foundry-macros.workspace = true

foundry-cheatcodes-defs.workspace = true
foundry-common.workspace = true
foundry-compilers.workspace = true
foundry-config.workspace = true
foundry-evm-core.workspace = true
foundry-utils.workspace = true

alloy-dyn-abi.workspace = true
alloy-json-abi.workspace = true
alloy-primitives.workspace = true
alloy-sol-types.workspace = true

serde.workspace = true
ethers-core.workspace = true
ethers-providers.workspace = true
ethers-signers.workspace = true

eyre.workspace = true
hex.workspace = true
itertools.workspace = true
jsonpath_lib.workspace = true
revm.workspace = true
serde_json.workspace = true

# schema
schemars = { version = "0.8.15", optional = true }

# impls
foundry-common = { workspace = true, optional = true }
foundry-compilers = { workspace = true, optional = true }
foundry-config = { workspace = true, optional = true }
foundry-evm-core = { workspace = true, optional = true }
foundry-utils = { workspace = true, optional = true }

alloy-dyn-abi = { workspace = true, optional = true }
alloy-json-abi = { workspace = true, optional = true }
ethers-core = { workspace = true, optional = true }
ethers-signers = { workspace = true, optional = true }
ethers-providers = { workspace = true, optional = true }

eyre = { workspace = true, optional = true }
hex = { workspace = true, optional = true }
itertools = { workspace = true, optional = true }
jsonpath_lib = { workspace = true, optional = true }
revm = { workspace = true, optional = true }
tracing = { workspace = true, optional = true }
walkdir = { version = "2", optional = true }

[features]
schema = ["dep:schemars"]
impls = [
"dep:foundry-common",
"dep:foundry-compilers",
"dep:foundry-config",
"dep:foundry-evm-core",
"dep:foundry-utils",
"dep:alloy-dyn-abi",
"dep:alloy-json-abi",
"dep:ethers-core",
"dep:ethers-providers",
"dep:ethers-signers",
"dep:eyre",
"dep:hex",
"dep:itertools",
"dep:jsonpath_lib",
"dep:revm",
"dep:tracing",
"dep:walkdir",
]
tracing.workspace = true
walkdir = "2"
8 changes: 4 additions & 4 deletions crates/cheatcodes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ Foundry cheatcodes definitions and implementations.
## Structure

- [`assets/`](./assets/): JSON interface and specification
- [`src/defs`](./src/defs/mod.rs): Defines traits and structs
- [`src/impls`](./src/impls/mod.rs): Rust implementations of the cheatcodes. This is gated to the `impl` feature, since these are not needed when only using the definitions.
- [`defs/`](./defs/src/lib.rs): Defines common traits and structs
- [`src/`](./src/lib.rs): Rust implementations of the cheatcodes

## Overview

All cheatcodes are defined in a single [`sol!`] macro call in [`src/defs/vm.rs`].
All cheatcodes are defined in a single [`sol!`] macro call in [`defs/src/vm.rs`].

This, combined with the use of an internal [`Cheatcode`](../macros/impl/src/cheatcodes.rs) derive macro,
allows us to generate both the Rust definitions and the JSON specification of the cheatcodes.
Expand Down Expand Up @@ -38,4 +38,4 @@ If you are making use of the JSON interface, please don't hesitate to open a PR
Please see the [cheatcodes dev documentation](../../docs/dev/cheatcodes.md#adding-a-new-cheatcode) on how to add new cheatcodes.

[`sol!`]: https://docs.rs/alloy-sol-macro/latest/alloy_sol_macro/macro.sol.html
[`src/defs/vm.rs`]: ./src/defs/vm.rs
[`defs/src/vm.rs`]: ./defs/src/vm.rs
26 changes: 26 additions & 0 deletions crates/cheatcodes/defs/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "foundry-cheatcodes-defs"
description = "Foundry cheatcodes definitions"

version.workspace = true
edition.workspace = true
rust-version.workspace = true
authors.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true
exclude.workspace = true

[dependencies]
foundry-macros.workspace = true
alloy-sol-types.workspace = true
serde.workspace = true

# schema
schemars = { version = "0.8.15", optional = true }

[dev-dependencies]
serde_json.workspace = true

[features]
schema = ["dep:schemars"]
3 changes: 3 additions & 0 deletions crates/cheatcodes/defs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# foundry-cheatcodes-defs

Minimal crate to provide a common set of cheatcodes definitions.
176 changes: 176 additions & 0 deletions crates/cheatcodes/defs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
//! # foundry-cheatcode-defs
//!
//! Foundry cheatcode definitions.

#![warn(missing_docs, unreachable_pub, unused_crate_dependencies, rust_2018_idioms)]

use serde::{Deserialize, Serialize};
use std::{borrow::Cow, fmt};

mod cheatcode;
pub use cheatcode::{Cheatcode, CheatcodeDef, Group, Safety, Status};

mod function;
pub use function::{Function, Mutability, Visibility};

mod items;
pub use items::{Enum, EnumVariant, Error, Event, Struct, StructField};

mod vm;
pub use vm::Vm;

// The `cheatcodes.json` schema.
/// Foundry cheatcodes. Learn more: <https://book.getfoundry.sh/cheatcodes/>
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct Cheatcodes<'a> {
/// Cheatcode errors.
#[serde(borrow)]
pub errors: Cow<'a, [Error<'a>]>,
/// Cheatcode events.
#[serde(borrow)]
pub events: Cow<'a, [Event<'a>]>,
/// Cheatcode enums.
#[serde(borrow)]
pub enums: Cow<'a, [Enum<'a>]>,
/// Cheatcode structs.
#[serde(borrow)]
pub structs: Cow<'a, [Struct<'a>]>,
/// All the cheatcodes.
#[serde(borrow)]
pub cheatcodes: Cow<'a, [Cheatcode<'a>]>,
}

impl fmt::Display for Cheatcodes<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for error in self.errors.iter() {
writeln!(f, "{error}")?;
}
for event in self.events.iter() {
writeln!(f, "{event}")?;
}
for enumm in self.enums.iter() {
writeln!(f, "{enumm}")?;
}
for strukt in self.structs.iter() {
writeln!(f, "{strukt}")?;
}
for cheatcode in self.cheatcodes.iter() {
writeln!(f, "{}", cheatcode.func)?;
}
Ok(())
}
}

impl Default for Cheatcodes<'static> {
fn default() -> Self {
Self::new()
}
}

impl Cheatcodes<'static> {
/// Returns the default cheatcodes.
pub fn new() -> Self {
Self {
// unfortunately technology has not yet advanced to the point where we can get all
// items of a certain type in a module, so we have to hardcode them here
structs: Cow::Owned(vec![
Vm::Log::STRUCT.clone(),
Vm::Rpc::STRUCT.clone(),
Vm::EthGetLogs::STRUCT.clone(),
Vm::DirEntry::STRUCT.clone(),
Vm::FsMetadata::STRUCT.clone(),
Vm::Wallet::STRUCT.clone(),
Vm::FfiResult::STRUCT.clone(),
]),
enums: Cow::Owned(vec![Vm::CallerMode::ENUM.clone()]),
errors: Vm::VM_ERRORS.iter().map(|&x| x.clone()).collect(),
events: Cow::Borrowed(&[]),
// events: Vm::VM_EVENTS.iter().map(|&x| x.clone()).collect(),
cheatcodes: Vm::CHEATCODES.iter().map(|&x| x.clone()).collect(),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::{fs, path::Path};

const JSON_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../assets/cheatcodes.json");
#[cfg(feature = "schema")]
const SCHEMA_PATH: &str =
concat!(env!("CARGO_MANIFEST_DIR"), "/../assets/cheatcodes.schema.json");
const IFACE_PATH: &str =
concat!(env!("CARGO_MANIFEST_DIR"), "/../../../testdata/cheats/Vm.sol");

/// Generates the `cheatcodes.json` file contents.
fn json_cheatcodes() -> String {
serde_json::to_string_pretty(&Cheatcodes::new()).unwrap()
}

/// Generates the [cheatcodes](json_cheatcodes) JSON schema.
#[cfg(feature = "schema")]
fn json_schema() -> String {
serde_json::to_string_pretty(&schemars::schema_for!(Cheatcodes<'_>)).unwrap()
}

fn sol_iface() -> String {
let cheats = Cheatcodes::new().to_string().trim().replace('\n', "\n ");
format!(
"\
// Automatically generated from `foundry-cheatcodes` Vm definitions. Do not modify manually.
// This interface is just for internal testing purposes. Use `forge-std` instead.

// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.4;

interface Vm {{
{cheats}
}}
"
)
}

#[test]
fn defs_up_to_date() {
ensure_file_contents(Path::new(JSON_PATH), &json_cheatcodes());
}

#[test]
#[cfg(feature = "schema")]
fn schema_up_to_date() {
ensure_file_contents(Path::new(SCHEMA_PATH), &json_schema());
}

#[test]
fn iface_up_to_date() {
ensure_file_contents(Path::new(IFACE_PATH), &sol_iface());
}

/// Checks that the `file` has the specified `contents`. If that is not the
/// case, updates the file and then fails the test.
fn ensure_file_contents(file: &Path, contents: &str) {
if let Ok(old_contents) = fs::read_to_string(file) {
if normalize_newlines(&old_contents) == normalize_newlines(contents) {
// File is already up to date.
return
}
}

eprintln!("\n\x1b[31;1merror\x1b[0m: {} was not up-to-date, updating\n", file.display());
if std::env::var("CI").is_ok() {
eprintln!(" NOTE: run `cargo test` locally and commit the updated files\n");
}
if let Some(parent) = file.parent() {
let _ = fs::create_dir_all(parent);
}
fs::write(file, contents).unwrap();
panic!("some file was not up to date and has been updated, simply re-run the tests");
}

fn normalize_newlines(s: &str) -> String {
s.replace("\r\n", "\n")
}
}
File renamed without changes.
Loading