Ethereum Node – How to Configure Custom Ethereum Node in Foundry Project

foundryganachehardhattesting

Hardhat allows users to configure a custom network in the networks configuration object. This allows developers to run their JS/TS test suites against another local node such as Ganache or even a live network such as an Ethereum testnet.

Can this be done in Foundry as well? For example, instead of using Foundry's default node Anvil users can specify a locally running node such as a hardhat or ganache local node that they want to run their Foundry project's test suites(written in solidity) on.

Best Answer

Yes, Foundry allows users to configure custom Ethereum nodes.

RPC-Endpoints settings

Custom RPC endpoints can be defined in the foundry.toml under [rpc_endpoints] as follows:

# foundry.toml

[rpc_endpoints]
  optimism = "https://optimism.alchemyapi.io/v2/1234567" # since the foundry.toml is commited it's not recommened to have the api key explicitly
  mainnet = "${RPC_MAINNET}" # it's recommened to do either this
  goerli = "https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}" # or this

Forge Commands

forge commands typically have a flag that allows you to run various commands with specified network configurations using either an explicit RPC URL or a network alias defined in the foundry.toml

Testing with a Forked Environment:

--rpc-url, --fork-url and -f are valid options for forge test

forge test --fork-url <rpc_url_or_alias>

Deploying contracts to a network

--rpc-url is a valid option for forge create

forge create --rpc-url <rpc_url_or_alias> --private-key <your_private_key> src/MyContract.sol:MyContract

Running solidity scripts against a network

--rpc-url, --fork-url and -f are valid options for forge script

forge script --rpc-url <rpc_url_or_alias> --fork-block-number <block_number> path [args...]