Foundry · Ethereum

On this page 7

Foundry is an open-source Ethereum development toolkit, written in Rust, that compiles, tests, debugs and deploys smart contracts from the command line. Its defining idea is that developers write tests in Solidity itself rather than in JavaScript or TypeScript, so the language of the contract and the language of its tests are the same.

In the Ethereum ecosystem of Crypto & blockchain engineering, Foundry sits alongside Hardhat and Remix IDE as one of the main environments for building contracts that run on the EVM. It grew out of the earlier dapptools suite and gained wide adoption among protocol teams and security auditors because of its compilation speed, built-in fuzzing and mainnet forking.

How Foundry is organized

Foundry is a set of four command-line binaries that share one configuration file, foundry.toml, and one project layout. Each binary handles a distinct stage of the contract lifecycle, from writing code to interacting with a live network.

The table below summarizes the four components and their primary roles.

ComponentPrimary roleTypical commands
ForgeBuild, test, fuzz and deploy contractsforge build, forge test, forge script
CastSend transactions and query chain datacast call, cast send, cast abi-decode
AnvilRun a local Ethereum node for developmentanvil, anvil --fork-url
ChiselInteractive Solidity REPLchisel
Core components of the Foundry toolkit

A standard project contains src/ for contracts, test/ for test files, script/ for deployment scripts and lib/ for dependencies. Dependencies are installed with forge install, which by default adds them as Git submodules, and import paths are mapped through remappings. The companion library forge-std supplies assertion helpers, console logging and the Test base contract that most test files inherit.

Testing smart contracts in Solidity

Foundry tests are ordinary Solidity contracts whose public functions prefixed with test are executed by Forge as individual test cases. A setUp() function runs before each test, deploying fresh instances so that tests remain isolated and deterministic.

The decisive feature is the set of cheatcodes, special functions exposed through the vm interface that manipulate the test environment in ways a real chain never allows. They let a test impersonate any address, move time forward or assert that a call must fail.

CheatcodeEffectTypical use
vm.prank(addr)Sets msg.sender for the next callTesting access control
vm.warp(ts)Sets the block timestampTimelocks and vesting schedules
vm.roll(n)Sets the block numberBlock-based logic
vm.deal(addr, amt)Sets an ether balanceFunding test accounts
vm.expectRevert()Requires the next call to revertVerifying failure paths
vm.expectEmit()Checks emitted eventsVerifying logs
Frequently used cheatcodes and their purpose

Beyond unit tests, Forge supports property-based fuzz testing: any test function that takes parameters receives randomly generated inputs, with a default of 256 runs per test that can be raised in configuration. Invariant testing goes further by calling sequences of random functions against a contract and checking that stated properties, such as total supply equaling the sum of balances, hold after every call. These techniques catch edge cases that hand-written examples miss and complement, but do not replace, formal verification.

Foundry compared with other Ethereum frameworks

Foundry differs from its main alternatives chiefly in test language, speed and runtime. Hardhat runs on Node.js and uses JavaScript or TypeScript tests, typically with Ethers.js, while Remix IDE is a browser-based environment aimed at learning and quick experiments.

AspectFoundryHardhatRemix IDE
ImplementationRust binariesNode.js packageBrowser application
Test languageSolidityJavaScript or TypeScriptSolidity or JavaScript
Native fuzzingYes, plus invariantsThrough pluginsLimited
Local nodeAnvilHardhat NetworkIn-browser VM
Plugin ecosystemSmaller, growingLarge and matureBuilt-in plugins
Best fitProtocol and security workFull-stack dApp teamsEducation and prototyping
Foundry, Hardhat and Remix IDE at a glance

Many teams use Foundry and Hardhat together, writing core contract tests in Forge while keeping Hardhat for front-end integration and existing JavaScript tooling. The choice is less about capability than about which language the team wants to think in when expressing test scenarios.

Forking, gas reports and deployment

Mainnet forking lets Forge and Anvil run against a copy of real chain state fetched lazily from an RPC endpoint. A test started with --fork-url can interact with deployed protocols, real token balances and live oracles, which is essential when a contract integrates with existing DeFi systems or a Chainlink price feed.

For cost analysis, forge test --gas-report prints per-function gas usage, and forge snapshot writes gas figures to a file so that a later run can show regressions. These outputs make gas optimization measurable rather than speculative.

Deployment uses Solidity scripts executed with forge script. Without the --broadcast flag the script only simulates; with it, signed transactions are sent to the target network, and forge verify-contract publishes source code to a block explorer. The table below links common tasks to the relevant command.

TaskCommandKey consideration
Run tests against live stateforge test --fork-urlPin a block for reproducibility
Measure gas per functionforge test --gas-reportCompare against a baseline
Track gas regressionsforge snapshotCommit the snapshot file
Check test coverageforge coverageCoverage is not correctness
Deploy contractsforge script --broadcastSimulate first, then broadcast
Read on-chain datacast callNo transaction or gas cost
Choosing the right Foundry command for a task

Limitations and common mistakes

Foundry is powerful but has practical limitations that experienced users account for. The most common problems arise from treating a passing test suite as proof of security.

  • Cheatcodes hide real constraints. A test that uses vm.prank can pass even though no real user could produce that call sequence.
  • Unpinned forks are not reproducible. Forking without --fork-block-number lets results drift as chain state changes.
  • Default fuzz runs are shallow. 256 runs may miss rare inputs, so critical code needs higher run counts and bounded inputs.
  • Coverage numbers mislead. High line coverage says nothing about whether assertions check the right properties.
  • Private keys in scripts are a risk. Deployment keys should come from hardware wallets or encrypted keystores, never from plain text files.
  • Submodule dependencies need care. Version pinning and remapping conflicts can cause subtle build differences between machines.

A Foundry test suite is therefore one layer of assurance, to be combined with a smart contract audit, static analysis and, for high-value systems, formal verification.

In simple terms

Foundry is a workshop for building Ethereum programs. Before a smart contract goes live, where mistakes can cost real money and cannot easily be undone, developers need a safe place to build it, try it and break it on purpose.

Foundry provides that place. It lets programmers write their checks in the same language as the contract, run thousands of random trials in seconds and even practice against a copy of the real blockchain. Think of it as a flight simulator for smart contracts: pilots crash in the simulator so they do not crash in the sky.

A practical example

A small team is building a lending contract that accepts a stablecoin as collateral and reads prices from an on-chain oracle. Using Foundry, the developers write unit tests in Solidity, then add a fuzz test that feeds random deposit and withdrawal amounts into the contract, raising the run count to 10,000 for the critical liquidation function.

They also write an invariant test stating that total borrowed funds can never exceed total collateral value. Running it against a mainnet fork pinned to a specific block, the fuzzer finds a sequence in which rounding during partial repayment leaves a tiny under-collateralized position. The team fixes the rounding direction, adds the failing sequence as a permanent regression test and records a gas snapshot.

Only after the suite passes do they run forge script in simulation, review the planned transactions and broadcast the deployment from a hardware wallet. The outcome is a contract that reaches its external audit with one class of bug already eliminated.