Guidance for AI coding agents working in this repository.
Foundry is a fast, portable, modular toolkit for Ethereum application development, written in Rust.
forge: build, test, fuzz, debug, lint, and deploy Solidity contractscast: command-line utilities for EVM contracts, transactions, and chain dataanvil: local Ethereum development nodechisel: Solidity REPL
The repository is a Cargo workspace. Core crates live under crates/, docs for
contributors live under docs/dev/, and Solidity fixtures and integration test
projects live under testdata/.
cargo build --workspace # Build the workspace
cargo nextest run --workspace # Run tests
cargo +nightly fmt --all # Format Rust code
cargo +nightly fmt --all -- --check # Check Rust formatting
cargo +nightly clippy --workspace --all-targets --all-features # Lint Rust code
cargo deny check # Check dependencies
cargo shear # Check unused dependenciesRust formatting uses nightly.
crates/forge: Forge CLI and test/build workflowscrates/cast: Cast CLI commandscrates/anvil: local Ethereum nodecrates/chisel: Solidity REPLcrates/cheatcodes: Forge cheatcode definitions and implementationscrates/common: shared CLI, shell, compile, and terminal utilitiescrates/config: Foundry configurationcrates/debugger: debugger supportcrates/lint: Solidity lintercrates/script: script execution supportcrates/verify: contract verification support
Foundry's EVM execution tooling is built around revm. Cheatcodes are calls to
the fixed cheatcode address and are dispatched through the cheatcode inspector.
Custom network behavior for anvil, forge, and cast is implemented through
the EVM networks crate.
For symbolic execution work under crates/evm/symbolic, read
crates/evm/symbolic/AGENTS.md before editing.
- Add tests for code changes that fix behavior or add functionality.
- Use focused unit tests for small pure logic.
- Use integration tests for CLI behavior and larger workflows.
- Tests that use forking must contain
forkin their name. - Forge integration fixtures live under
testdata/. - Lint rule tests live under
crates/lint/testdata/with blessed.stderroutput.
For CLI and integration tests:
- Put Forge CLI coverage under
crates/forge/tests/cli/and Cast CLI coverage undercrates/cast/tests/cli/. - Use the existing
forgetest!,forgetest_init!, andcasttest!macros to create isolated test projects and command handles. - Assert command output with snapbox helpers such as
assert_success(),assert_failure(),stdout_eq(str![...]),stderr_eq(str![...]), andassert_empty_stdout(). - For JSON output, use
assert_json_stdout(...)orassert_json_stderr(...)so comparisons are parsed as JSON and unordered where appropriate. - Prefer full output snapshots with redactions over ad hoc
String::containschecks or manualserde_json::Valueinspection.
For lint rules:
- Add a Solidity test file under
crates/lint/testdata/. - Use
//~WARN:and//~NOTE:annotations for expected diagnostics. - Regenerate blessed output with
cargo bless-lints. - Run lint UI tests with
cargo nextest run -p forge --test ui.
For script work, keep the two execution phases separate: ScriptArgs::execute
runs the script, while on-chain simulation only executes the collected
broadcastable transactions. --resume resumes publishing transactions; it does
not recreate the original --broadcast state.
For fuzz or invariant corpus coverage work, forge test --showmap-out <DIR>
replays persisted corpus entries and writes AFL showmap-style coverage files.
Foundry CLIs follow a stdout/stderr contract:
- stdout is the command's machine-readable primary result
- stderr is for warnings, errors, progress, status text, prompts, and banners
--jsonchanges stdout format, not channel cleanliness--quietsuppresses diagnostics and progress, not the command result- verbosity flags such as
-vvvmust not change stdout content
Use the sh_* macros from foundry_common::io:
sh_println!/sh_print!: primary stdout result onlysh_status!: status prose on stderrsh_progress!: progress on stderrsh_warn!: recoverable warnings on stderrsh_err!: errors on stderrprompt!: prompt on stderr and read from stdin
Do not use println!, print!, eprintln!, or eprint!; workspace clippy
configuration forbids them.
When adding a cheatcode:
- Add the Solidity definition in
crates/cheatcodes/spec/src/vm.rs. - Implement the generated call type in
crates/cheatcodes/. - Update
spec::Cheatcodes::newifVmgained a struct, enum, error, or event. - Run
cargo cheatstwice to update generated JSON assets. - Add an integration test under
testdata/default/cheats/.
Cheatcode functions and structs must be documented and function parameters must be named.
Default format is conventional commits:
type: description
type(scope): description
type(scope)!: breaking description
Use feat, fix, perf, chore, docs, test, or refactor. Check recent
git log output before committing to match the repository's current style.
- Use imperative mood.
- Keep the description under 50 characters when practical.
- Do not end the description with a period.
- Include a body for performance changes, bug fixes, and complex changes.
- For performance changes, include measurements.
- PR titles should follow the same format as commit messages.
PR descriptions should explain what changed and why in flowing prose. Link
related issues and PRs when they exist. Include only real measurements, and do
not include validation/testing boilerplate such as "Validated with", "Tested
with", or command lists unless explicitly requested. Do not use templates,
bullet lists, or long essays. When writing PR bodies from scripts, use a file or
heredoc with real newlines; never pass escaped \n sequences.
When drafting or updating a PR body for a performance-related change, benchmark
the feature branch against master or the user-specified base before writing the
performance claims.
- Use the local benchmark runners under
benches/unless the user explicitly asks for GitHub Actions or the Derek/decofe automation. - Use
foundry-benchwhen the claim is about elapsed time for a Foundry command on an existing Solidity project:forge build, cached rebuilds,forge test, fuzz-test replay, isolated tests, coverage, or focused symbolic tests. - For invariant or campaign-style benchmarking, use
foundry-scfuzzbench; this is the local equivalent of thederek bench invariant/decofe bench invariantPR flow, which publishes ascfuzzbenchevent. - The local runners do not compare two local refs in one invocation. Run the baseline and candidate separately, with identical benchmark inputs, timeout, worker count, environment, target repository, and output schema.
- For branch-vs-base PR comparisons, use the profiling profile
(
FOUNDRY_BENCH_LOCAL_BUILD_PROFILE=profiling) rather than an ad hoc debug or release build. Keep ordinaryfoundry-bench --versions localcomparisons on the default release distribution profile. - Include only benchmarks that exercise the changed path. Do not pad the PR body with unrelated benchmark suites.
- Report both wall-time results and domain counters when available, for example solver queries, reported solver time, throughput, coverage relscore/relcov, or invariant findings.
- If results are neutral, noisy, or regress a secondary metric, state that directly. Do not convert noise into a performance claim.
- Keep the PR body short: one paragraph explaining the optimization and why it
is correct, followed by a
### Resultstable. - Exact benchmark commands and result-table mechanics in
benches/README.md.
- Use
RUST_LOG=<filter>for debugging CLI internals, for exampleRUST_LOG=forgeorRUST_LOG=cast. - Disclose AI assistance in PRs when used, per
CONTRIBUTING.md. - Do not send spelling-only or grammar-only documentation PRs.
- Keep release feature lists aligned between the root
Makefileand release workflows when changing published CLI feature surfaces.
- Comments end with periods (except URLs)
- Files end with LF and trailing newline
- Follow existing patterns
- Never expose secrets
- Put doc comments before attributes, always:
/// ...comes before#[derive],#[inline],#[cfg], and every other attribute. - Put module documentation at the top of the module file with inner doc comments (
//! ...), not on themoditem in the parent module. - NEVER put imports inside functions unless required for
#[cfg(...)]gating. All imports go at the top of the file. - Group all
useimports together. Keeppub useimports in a separate group. For local module re-exports, writemod x;beforepub use x;; for re-exporting another module or external crate, useuse x;, then a blank line, thenpub use y;, then a blank line before localmod my_mod; pub use my_mod::*;. - In
Cargo.toml, generally group optional dependencies for a feature together. Put a comment immediately above the group containing only the feature name, for example# jit. - Prefer
let Some(x) = x else { return };/let Ok(x) = x else { return };overmatch x { Some(x) => x, _ => return }. - Use
let ... elseonly for a single early-exit guard. When multiple conditions or patterns gate the same block, prefer a combinedif let/letchain instead of several sequentiallet ... elsestatements. - Use combined
if letchains (if let Some(x) = x && let Some(y) = y { ... }) instead of nesting (if let Some(x) = x { if let Some(y) = y { ... } }). - In loops, prefer an
if letchain around the loop body over multiplelet ... else { continue };statements when the body only runs if all patterns match. - NEVER use
ref/ref mutin patterns as the first resort. Always prefer borrowing the expression with&/&mutinstead. - Avoid specifying type hints in variables unless absolutely necessary (e.g.
HashMap<_, Vec<_>>forx.entry(y).or_default().push(z)where type inference won't work). Rely on the compiler. - When type hints are needed, prefer turbofish (
let x = Type::<X, Y>::new()) over annotation (let x: Type<X, Y> = Type::new()).