Skip to content

feat(forge): add bypass prevrandao (foundry-rs#12125) & fix(fmt): filter libs when recursing (foundry-rs#12119) #147

Merged
Dargon789 merged 2 commits into
Dargon789:Dargon789/masterfrom
foundry-rs:master
Oct 16, 2025
Merged

feat(forge): add bypass prevrandao (foundry-rs#12125) & fix(fmt): filter libs when recursing (foundry-rs#12119) #147
Dargon789 merged 2 commits into
Dargon789:Dargon789/masterfrom
foundry-rs:master

Conversation

@Dargon789
Copy link
Copy Markdown
Owner

@Dargon789 Dargon789 commented Oct 16, 2025

Motivation

Solution

PR Checklist

  • Added Tests
  • Added Documentation
  • Breaking changes

Summary by Sourcery

Enable bypassing prevrandao on configurable networks and improve the Forge fmt command to skip library directories during recursion

New Features:

  • Add a bypass_prevrandao option to network configs to enable random prevrandao for specific chains
  • Exclude library directories by default when formatting sources via the fmt command

Enhancements:

  • Propagate NetworkConfigs through apply_chain_and_block_specific_env_changes and related setup functions across Forge, Anvil, Cast, and Verify
  • Implement a helper to canonicalize and filter ignored and library paths in fmt recursion

Tests:

  • Add a CLI test to verify fmt excludes libs during recursive runs
  • Add default config check for bypass_prevrandao in Forge config tests

grandizzy and others added 2 commits October 16, 2025 16:34
* feat(forge): add bypass prevrandao

* Update crates/evm/networks/src/lib.rs

Co-authored-by: 0xrusowsky <90208954+0xrusowsky@users.noreply.github.com>

* changes after review: remove duped code

---------

Co-authored-by: 0xrusowsky <90208954+0xrusowsky@users.noreply.github.com>
* fix(fmt): account for ternary operators when estimating size

* fix(fmt): filter libs when recursing

* style: clippy

* test: wipe contracts before formatting

* test: explicitly test ignore
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Oct 16, 2025

Reviewer's Guide

This PR enhances the formatting command to properly exclude libraries during recursive runs, introduces a new bypass_prevrandao configuration option for networks, and refactors environment setup to propagate network settings (including the new flag) across EVM and CLI components. Workspace and test updates ensure defaults and dependencies align with these changes.

Sequence diagram for environment setup with bypass_prevrandao propagation

sequenceDiagram
    participant "CLI/Forge/Cast/Anvil"
    participant "EVM Core"
    participant "NetworkConfigs"
    participant "EnvMut"
    participant "BlockResponse"
    "CLI/Forge/Cast/Anvil"->>"EVM Core": Call environment(..., configs)
    "EVM Core"->>"NetworkConfigs": Pass configs to apply_chain_and_block_specific_env_changes
    "EVM Core"->>"EnvMut": Apply chain and block specific changes
    "EVM Core"->>"NetworkConfigs": Call bypass_prevrandao(chain_id)
    "NetworkConfigs"-->>"EVM Core": Return true/false
    "EVM Core"->>"EnvMut": Set prevrandao if bypass required
    "EVM Core"->>"EnvMut": Finalize environment setup
Loading

Entity relationship diagram for NetworkConfigs and chain types

erDiagram
    NETWORKCONFIGS {
        bool bypass_prevrandao
    }
    NAMEDCHAIN {
        chain_id u64
    }
    NETWORKCONFIGS ||--o| NAMEDCHAIN : "uses chain_id for bypass_prevrandao logic"
Loading

Class diagram for updated NetworkConfigs struct and related methods

classDiagram
    class NetworkConfigs {
        +bool optimism
        +bool celo
        +bool bypass_prevrandao
        +bypass_prevrandao(chain_id: u64) bool
        +is_optimism() bool
        +is_celo() bool
    }
    NetworkConfigs <|-- AnyNetwork
    class AnyNetwork {
        // Inherits network config logic
    }
Loading

Class diagram for FmtArgs filtering logic update

classDiagram
    class FmtArgs {
        +run() Result
        -is_under_ignored_dir(file_path: &Path, include_libs: bool) bool
    }
    FmtArgs --> Input
    class Input {
        +Paths(Vec<PathBuf>)
    }
Loading

File-Level Changes

Change Details Files
Exclude library paths when recursing in the fmt command
  • Expand lib globs separately and canonicalize paths
  • Add is_under_ignored_dir helper to combine ignored and lib checks
  • Update project_paths and directory recursion filters to skip libs
  • Add CLI test verifying lib exclusion in fmt recursion
crates/forge/src/cmd/fmt.rs
crates/forge/tests/cli/fmt.rs
Add bypass_prevrandao flag to network configuration
  • Introduce bypass_prevrandao field with serde and clap attributes
  • Implement bypass_prevrandao() method honoring named chains or user flag
  • Add default bypass_prevrandao entry to CLI config test
crates/evm/networks/src/lib.rs
crates/forge/tests/cli/config.rs
Refactor environment initialization to consume network configs
  • Remove hardcoded Moonbeam-specific randomization in apply_chain_and_block_specific_env_changes
  • Add NetworkConfigs parameter to apply_chain_and_block_specific_env_changes, configure_env_block, and environment()
  • Update call sites in anvil, cast, verify, evm-core/fork/init.rs, evm-core/src/utils.rs, evm-core/src/opts.rs to pass network configs
crates/evm/core/src/utils.rs
crates/anvil/src/config.rs
crates/cast/src/cmd/run.rs
crates/verify/src/bytecode.rs
crates/verify/src/utils.rs
crates/evm/core/src/fork/init.rs
crates/evm/core/src/opts.rs
Update verify workspace dependency
  • Add foundry-evm-networks to the workspace members in verify/Cargo.toml
crates/verify/Cargo.toml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@snyk-io
Copy link
Copy Markdown

snyk-io Bot commented Oct 16, 2025

Snyk checks have passed. No issues have been found so far.

Status Scanner Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello @Dargon789, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces significant improvements to Foundry's forge and anvil tools by enhancing network configuration handling and refining the fmt command's behavior. It provides more granular control over EVM environment settings, particularly for prevrandao values on specific chains, and improves the developer experience by preventing accidental formatting of library code.

Highlights

  • Forge: prevrandao Bypass: Introduced a new configuration option bypass_prevrandao within NetworkConfigs. This allows specific chains (like Moonbeam, Gnosis, etc.) or explicitly configured networks to bypass the default prevrandao behavior, setting it to a random value if it's None. This change centralizes and refactors the logic for handling prevrandao for various networks across anvil, cast, evm/core, and verify crates.
  • Fmt: Library Filtering: The forge fmt command now intelligently filters out files located within configured library directories when performing recursive formatting. This prevents unintended formatting of third-party or dependency code. However, if a file within a library is explicitly specified as an input, it will still be formatted.
  • Dependency Update: The Cargo.lock file has been updated to include the foundry-evm-networks dependency, which is essential for the new network-specific configurations related to prevrandao.
  • New Test Cases: Added a new test case fmt_exclude_libs_in_recursion to ensure the forge fmt command correctly excludes library files during recursive formatting while still allowing explicit formatting of library files.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `crates/forge/src/cmd/fmt.rs:108` </location>
<code_context>
-                            SOLC_EXTENSIONS,
-                        ));
+                        // If the input directory is not a lib directory, make sure to ignore libs.
+                        let exclude_libs = !is_under_ignored_dir(path, true);
+                        inputs.extend(
+                            foundry_compilers::utils::source_files_iter(path, SOLC_EXTENSIONS)
</code_context>

<issue_to_address>
**suggestion:** The exclude_libs logic may not be robust for nested lib directories.

The current approach may not exclude all nested lib directories. Please review whether the logic covers cases where libs are nested but not directly marked, and consider a more comprehensive check for complex directory structures.

Suggested implementation:

```rust
                        // If the input directory is not a lib directory, make sure to ignore libs.
                        let exclude_libs = !is_under_ignored_dir(path, true);
                        inputs.extend(
                            foundry_compilers::utils::source_files_iter(path, SOLC_EXTENSIONS)
                                .filter(|p| {
                                    !(ignored.contains(p)
                                        || ignored.contains(&cwd.join(p))
                                        || (exclude_libs && is_within_lib_dir(p)))
                                }),
                        );

```

```rust
                    } else if path.is_sol() {

```

```rust
fn is_within_lib_dir(path: &std::path::Path) -> bool {
    path.ancestors().any(|ancestor| {
        ancestor.file_name()
            .map(|name| name == "lib")
            .unwrap_or(false)
    })
}

```

- If your project uses a different convention for library directories (e.g., "libs" or "libraries"), adjust the string in `is_within_lib_dir` accordingly.
- Ensure that the helper function is placed in a scope accessible to the code block using it.
- If you have a utility module for path helpers, consider moving `is_within_lib_dir` there and importing it.
</issue_to_address>

### Comment 2
<location> `crates/evm/networks/src/lib.rs:50-57` </location>
<code_context>
         self.optimism
     }

+    pub fn bypass_prevrandao(&self, chain_id: u64) -> bool {
+        if let Ok(
+            Moonbeam | Moonbase | Moonriver | MoonbeamDev | Rsk | RskTestnet | Gnosis | Chiado,
+        ) = NamedChain::try_from(chain_id)
+        {
+            return true;
+        }
+        self.bypass_prevrandao
+    }
+
</code_context>

<issue_to_address>
**suggestion:** The bypass_prevrandao method hardcodes chain IDs, which may be brittle.

Centralizing or making this logic data-driven will help ensure future chain additions or changes are handled consistently and reduce maintenance overhead.

Suggested implementation:

```rust
    pub fn bypass_prevrandao(&self, chain_id: u64) -> bool {
        // Centralized list of chains that require bypassing prevrandao
        use once_cell::sync::Lazy;
        use std::collections::HashSet;

        static BYPASS_PREVRANDAO_CHAINS: Lazy<HashSet<NamedChain>> = Lazy::new(|| {
            [
                NamedChain::Moonbeam,
                NamedChain::Moonbase,
                NamedChain::Moonriver,
                NamedChain::MoonbeamDev,
                NamedChain::Rsk,
                NamedChain::RskTestnet,
                NamedChain::Gnosis,
                NamedChain::Chiado,
            ]
            .iter()
            .cloned()
            .collect()
        });

        if let Ok(chain) = NamedChain::try_from(chain_id) {
            if BYPASS_PREVRANDAO_CHAINS.contains(&chain) {
                return true;
            }
        }
        self.bypass_prevrandao
    }

```

- You may need to add `once_cell` to your dependencies in `Cargo.toml` if it's not already present.
- Ensure that `NamedChain` implements `Clone`, `Eq`, and `Hash` (it likely does if it's used in a HashSet).
- If you prefer not to use `once_cell`, you can use a simple array and `matches!` macro, but the HashSet is more scalable for many chains.
</issue_to_address>

### Comment 3
<location> `crates/evm/core/src/utils.rs:77-61` </location>
<code_context>
         }
     }

+    if configs.bypass_prevrandao(env.cfg.chain_id) && env.block.prevrandao.is_none() {
+        // <https://github.com/foundry-rs/foundry/issues/4232>
+        env.block.prevrandao = Some(B256::random());
+    }
+
</code_context>

<issue_to_address>
**suggestion:** Randomizing prevrandao may affect determinism in some scenarios.

If reproducibility is required, consider allowing this value to be seeded or controlled.

Suggested implementation:

```rust
    if configs.bypass_prevrandao(env.cfg.chain_id) && env.block.prevrandao.is_none() {
        // <https://github.com/foundry-rs/foundry/issues/4232>
        // If a seed is provided in configs, use it for reproducibility, otherwise use true randomness.
        if let Some(seed) = configs.prevrandao_seed() {
            use rand::{RngCore, SeedableRng};
            use rand_chacha::ChaCha20Rng;
            let mut rng = ChaCha20Rng::seed_from_u64(seed);
            let mut bytes = [0u8; 32];
            rng.fill_bytes(&mut bytes);
            env.block.prevrandao = Some(B256::from(bytes));
        } else {
            env.block.prevrandao = Some(B256::random());
        }
    }

```

1. You will need to add a `prevrandao_seed()` method to your `configs` object, which returns an `Option<u64>`.
2. Ensure that the `rand` and `rand_chacha` crates are included in your dependencies.
3. You may want to document the new configuration option for users who require reproducibility.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread crates/forge/src/cmd/fmt.rs
Comment thread crates/evm/networks/src/lib.rs
Comment thread crates/evm/core/src/utils.rs
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces two main changes: a feature to bypass prevrandao for certain networks and a fix for forge fmt to correctly ignore library paths during recursive formatting. The prevrandao bypass is implemented cleanly by adding a configuration option and centralizing the logic. The fmt fix correctly filters out library paths, but the implementation for path checking has a flaw in its use of the current working directory (cwd) instead of the project root, which could lead to incorrect behavior when forge fmt is run from a subdirectory. Additionally, there's a small opportunity for code simplification in the prevrandao logic.

Comment thread crates/forge/src/cmd/fmt.rs
Comment thread crates/evm/networks/src/lib.rs
@Dargon789 Dargon789 merged commit 25c2d64 into Dargon789:Dargon789/master Oct 16, 2025
3 of 17 checks passed
@sourcery-ai sourcery-ai Bot mentioned this pull request Oct 16, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants