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/, Solidity
fixtures and integration test projects live under testdata/, and the
developer documentation defines documentation ownership
and indexes maintained cross-crate guides.
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.
For custom network work, follow the ownership, state-lifecycle, tool-dispatch,
and CI checklist in docs/dev/networks.md.
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:
- Follow
docs/dev/lintrules.md#lint-writing-styleandcrates/lint/docs/README.mdfor lint names, diagnostic wording, and reference-page structure. - Update
crates/lint/docs/<id>.mdin the same Foundry PR as the lint. The Book'simport:lintsworkflow generates the published reference pages and navigation. - 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.
Follow docs/dev/output-channels.md, the canonical
stdout/stderr contract. Use the foundry_common::io sh_* and prompt! macros;
workspace Clippy configuration forbids direct std::print* and std::eprint*.
When adding or changing a foundry.toml setting:
- Define the field and its documentation in
crates/config, including an explicit default and any required serde behavior. Keep related settings in a dedicated nested config type when they form a coherent section. - Wire the setting through every command that consumes it. If a CLI flag can override the setting, resolve precedence in one shared place and test config, CLI, and combined behavior.
- Add focused config parsing and serialization tests. Update the
forge configand default-config snapshots when the serialized surface changes. - For renamed or moved settings, preserve compatibility when practical and add a targeted deprecation warning that points to the canonical key. Test aliases, profiles, inheritance, environment variables, collisions, and malformed values where those providers are affected.
- Document the setting in
foundry-rs/bookundersrc/pages/config/reference/, including its section, type, default, environment variable when supported, behavior, and a valid TOML example. Update the config reference navigation anddefault-config.mdxin the same documentation PR. - Keep CLI option text in the Rust clap definition; the book's CLI reference is generated from command help and should not be edited by hand.
Use the implementation, defaults, and tests as the source of truth. Do not merge new user-facing configuration without the corresponding book update.
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.
- The fragment-based changelog workflow has been removed. Do not create or
restore
.changelog/or add changelog fragment files; release notes are generated from pull requests. - Use
RUST_LOG=<filter>for debugging CLI internals, for exampleRUST_LOG=forgeorRUST_LOG=cast. - 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
- Generally add new Rust functions, methods,
implblocks, modules, imports, Cargo dependencies, and other items at the bottom of the relevant scope, section, or group. Constructors usually go at the top of animplblock. First check where similar items sit in the file and match the existing order, grouping, and style, including alphabetical order where used. - 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::*;. - Put imports used only by tests inside the relevant
#[cfg(test)]module, merging them into its ordinary imports instead of adding#[cfg(test)] useitems to the parent. Keep any additional feature or platform conditions on those imports. Retain parent-level test-gated imports or re-exports only when test-only helpers or multiple test modules need them there. - Keep crate-level dependency anchors such as
#[cfg(test)] use cc as _;at crate scope. - Put conditional imports after unconditional imports, separated by a blank line. Group imports with the same
#[cfg(...)]condition together, with a blank line between different conditions. Apply this to every feature, platform, and test gate, including imports in nested modules. Within each group, merge imports from the same crate when their conditions and other attributes match. Keep the full condition on eachuse; do not introduce import-only modules or macros to avoid repeated attributes. Apply the same ordering within the separatepub usegroup, keeping local re-exports after their module declarations. - In test modules, always import the parent module with
use super::*. - 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. - Prefer map entry APIs such as
entry,or_insert, andor_insert_withwhen multiple consecutive operations would otherwise look up and then insert or update the same key. - 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()). - In tests, avoid
.containsassertions for error/output strings when the project has snapshot testing support such assnapbox. Prefer exact snapshot assertions (stderr_eq,stdout_eq,assert_data_eq!, etc.) and use redactions only for genuinely variable parts. - Always leave a blank line in between module doc-comments, items or item categories, unless in rare exceptions: it's a one-shot struct with one single impl block, or it's a list of impls that are all very similar. But in general blank line in between items is the norm but it's just unenforced. Items includes imports (together) too. The previous rules apply first.