Foundry is a Rust-based toolkit for Ethereum and other EVM-compatible application development. Its main tools are Forge for project management, compilation, testing, fuzzing, and deployment; Cast for command-line chain interaction; Anvil for a local development node and forked state; and Chisel for interactive Solidity experiments. This guide explains how the tools fit together, how to connect them to an RPC endpoint, and how to verify results without presenting unmeasured performance claims. For endpoint selection, compare the requirements of your project using the [RPC endpoints guide](/en/learn/rpc-endpoints-guide) rather than treating Foundry as an RPC provider.
Foundry’s role in a blockchain development stack
Foundry is a portable toolkit for building, testing, debugging, deploying, and inspecting Ethereum smart contracts. It is not a blockchain network and it does not replace an RPC provider. Foundry commands either operate locally, such as compilation and unit testing, or communicate with an EVM network through a JSON-RPC endpoint.
The practical answer to “what is Foundry blockchain?” is therefore a development workflow rather than a separate chain. You write Solidity, manage dependencies, run deterministic tests, create local or forked environments, and use RPC calls when a test or deployment needs blockchain state. The same project can target Anvil locally, a public test network, or production infrastructure after you change configuration and deployment parameters.
Foundry is a strong fit when you want Solidity-native tests, fast local feedback, fuzz testing, invariant testing, scripted deployments, and command-line control. A hosted RPC service becomes important when tests need remote chain state, deployments must reach a shared network, or a team needs consistent access to an EVM node. See OnFinality API Service for the infrastructure layer and supported networks before choosing a target.
- Forge: compile, test, fuzz, measure coverage, manage dependencies, and run deployment scripts.
- Cast: read contracts, encode data, estimate gas, sign transactions, and inspect blocks or transactions.
- Anvil: run a local EVM node with funded development accounts and optional forked state.
- Chisel: experiment with Solidity expressions interactively.
The Foundry toolchain mental model
Treat the toolchain as four layers. Forge is the project engine: it reads Solidity sources and tests, resolves libraries, compiles artifacts, and executes test functions. Anvil supplies an isolated chain when you need accounts, mining, snapshots, or a fork of an existing network. Cast is the inspection and transaction utility that connects directly to an RPC URL. Chisel is a short feedback loop for testing Solidity syntax and expressions before placing them in a contract.
A useful boundary is local state versus remote state. Compilation and most unit tests can run without an internet connection. A fork test reads selected state from a remote RPC endpoint, while a deployment or live query sends JSON-RPC requests to the configured network. Keeping these boundaries explicit makes failures easier to classify: a compiler error is not an RPC outage, and an RPC timeout is not necessarily a Solidity defect.
Foundry projects conventionally contain a source directory, test directory, script directory, and a configuration file. The exact layout can be customized, but predictable paths help CI systems and other developers reproduce the same commands.
- Use local unit tests for business logic that does not depend on historical chain state.
- Use fork tests for integrations with deployed protocols, token balances, or existing storage.
- Use a separate deployment configuration for each environment; do not reuse production keys in local tests.
- Pin compiler and dependency choices when reproducibility matters.
Installation and project prerequisites
Install Foundry from its official distribution method, then initialize a project and confirm that the binaries are available on your PATH. The installation command may change over time, so use the current instructions in the Foundry documentation. The commands below illustrate the normal project shape; they do not assume a particular operating system package manager.
Before connecting to a remote chain, obtain an RPC URL for the exact network and environment you intend to use. Store it in an environment variable or a secret manager instead of committing it to a repository. A project can compile without an RPC URL, but fork tests, chain reads, gas estimation, and deployments cannot.
A minimal configuration can make compiler behavior and directory discovery explicit. Adjust the Solidity version to match your contracts and dependencies rather than copying a version blindly.
- Keep private keys, API keys, and endpoint credentials outside foundry.toml.
- Use a testnet account with deliberately limited funds for deployment exercises.
- Run forge --version, cast --version, and anvil --version after installation.
[profile.default]
src = "src"
out = "out"
test = "test"
script = "script"
libs = ["lib"]
solc_version = "0.8.24"
[rpc_endpoints]
sepolia = "${SEPOLIA_RPC_URL}"
mainnet = "${MAINNET_RPC_URL}"
[etherscan]
sepolia = { key = "${ETHERSCAN_API_KEY}" }RPC connectivity and forked blockchain state
Foundry communicates with EVM networks through standard JSON-RPC methods. Start with a harmless read such as eth_chainId or eth_blockNumber before attempting a transaction. Confirm that the returned chain ID matches the network you intended to use; an endpoint can be reachable while pointing to the wrong environment.
A forked Anvil instance gives local tests a copy-on-write view of remote state. The fork is useful for reproducing protocol interactions without submitting transactions to the real chain. Forking does not make the remote chain immutable or guarantee that every historical block, archive query, trace, or optional RPC method is available. Check the endpoint’s documented capabilities and use a pinned block when a test must remain stable.
The following example checks an endpoint directly, then starts a local fork. Replace placeholders with environment variables and never place credentials in source control.
- A successful eth_chainId response proves basic JSON-RPC reachability, not that every Foundry workflow will work.
- Use --fork-block-number for deterministic integration tests when the endpoint supports the required historical state.
- Point local tests at http://127.0.0.1:8545 after Anvil starts, rather than sending test transactions to the remote chain.
export RPC_URL="${RPC_URL}"
curl -sS "$RPC_URL" \
-H 'content-type: application/json' \
--data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}'
anvil --fork-url "$RPC_URL" --fork-block-number "${FORK_BLOCK}" --port 8545Contract reads and writes with Cast
Expected verification is a valid block response and, for a correctly encoded contract call, a decoded value. If the call reverts, inspect the function signature, address, chain ID, proxy implementation, and required call parameters before blaming the endpoint.
export RPC_URL="${RPC_URL}"
export CONTRACT="0xYourContractAddress"
cast block latest --rpc-url "$RPC_URL"
cast call "$CONTRACT" "totalSupply()(uint256)" --rpc-url "$RPC_URL"
node <<'NODE'
const rpcUrl = process.env.RPC_URL;
if (!rpcUrl) throw new Error('Set RPC_URL');
const response = await fetch(rpcUrl, {
method: 'POST',
headers: {'content-type': 'application/json'},
body: JSON.stringify({jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: []})
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const body = await response.json();
if (body.error) throw new Error(JSON.stringify(body.error));
console.log(body.result);
NODESolidity tests, fuzzing, and deployment scripts
Forge tests can express setup, assertions, and state transitions in Solidity. Begin with deterministic unit tests for expected cases, then add fuzz tests for input ranges and invariants for properties that must remain true across sequences of actions. This progression produces more useful failures than starting with an unconstrained fuzz campaign.
Deployment scripts should separate configuration from execution. Read the target RPC alias and private key from the environment, broadcast only when explicitly requested, and record the resulting contract address and transaction hash as build artifacts. A simulation or dry run can expose constructor and gas problems before a broadcast, but it is not proof that the eventual transaction will be accepted by a changing network.
A typical command sequence looks like this:
- Use -vvv or higher verbosity when a failing test needs traces.
- Keep fuzz runs and seeds recorded in CI logs when investigating a failure.
- Use a dedicated deployment account and verify the destination chain before --broadcast.
- Treat a transaction hash as submission evidence; use a receipt to confirm inclusion and status.
forge build
forge test -vvv
forge test --match-test testFuzz_ --runs 256
forge script script/Deploy.s.sol:Deploy \
--rpc-url sepolia \
--private-key "$PRIVATE_KEY" \
--broadcast
cast receipt "$TX_HASH" --rpc-url "$SEPOLIA_RPC_URL"Reproducible Foundry workflow measurements
| Test or operation | Environment | Runs | Successful runs | Median time | Error count | Notes |
|---|---|---|---|---|---|---|
| forge build | local CI runner | ___ | ___ | ___ | ___ | compiler and commit |
| forge test | local CI runner | ___ | ___ | ___ | ___ | test count and fuzz runs |
| eth_blockNumber | RPC_URL | ___ | ___ | ___ | ___ | HTTP and JSON-RPC errors |
| fork integration test | pinned block | ___ | ___ | ___ | ___ | archive/state requirements |
Failure diagnosis across the toolchain
Start troubleshooting by locating the failing boundary. Run forge build without an RPC URL to isolate compiler and dependency issues. Run eth_chainId and eth_blockNumber against the endpoint to isolate basic connectivity. Then run the smallest failing cast call before repeating a complete fork test or deployment.
A chain ID mismatch usually means the wrong endpoint or environment variable. An HTTP error may indicate authentication, quotas, a malformed request, or a gateway problem. A JSON-RPC error can instead reflect an unsupported method, missing historical state, an invalid block range, or an execution revert. A transaction that is accepted but never reaches a successful receipt requires inspection of nonce, fee policy, replacement behavior, and the destination network.
When fork tests are flaky, pin the block, reduce unnecessary state reads, and preserve the exact failing calldata. If a test depends on archive state or traces, confirm those requirements with the endpoint documentation. For production workloads that need stronger isolation or predictable capacity, evaluate a dedicated node rather than hiding infrastructure assumptions inside test code.
- Compiler or import failure: inspect solc_version, remappings, dependency commits, and library paths.
- Connection failure: check DNS, TLS, credentials, HTTP status, chain ID, and request limits.
- Fork failure: check block availability, archive requirements, state overrides, and method support.
- Transaction failure: inspect calldata, sender balance, nonce, gas estimation, receipt status, and revert data.
Tradeoffs, security boundaries, and next steps
Foundry’s Solidity-first workflow reduces context switching and makes tests, scripts, and contract code live close together. Its command-line design also works well in CI and reproducible environments. The tradeoff is that teams must design their own deployment conventions, secrets handling, network matrix, and observability. Foundry does not make an unsafe contract safe, and a successful local test does not establish production correctness.
Anvil is excellent for isolated development and fork-based debugging, but it is not a substitute for testing validator behavior, real fee markets, provider limits, reorg handling, or production key custody. Public or shared RPC access is convenient for development, while dedicated infrastructure may be appropriate for sensitive or sustained workloads. Compare service requirements and pricing through RPC pricing, and use the best RPC provider for Web3 projects guide for a methodology-focused provider comparison.
A sensible next step is to commit a small Foundry project with one unit test, one fork test pinned to a documented block, and one deployment script that defaults to simulation. Add CI checks for build, tests, chain ID validation, and secret absence. After that baseline is reproducible, expand fuzz and invariant coverage, measure the workflow using the table above, and choose infrastructure based on observed requirements rather than assumptions.
- Read the official Foundry reference for current commands and configuration.
- Use blockchain node hosting guidance when moving from local development to shared infrastructure.
- Keep RPC selection, contract security review, deployment approval, and key custody as separate decisions.