Introduction
Foundry, an Ethereum smart contract development framework, offers the capability to run tests across multiple chains. This is extremely useful for testing smart contracts that interact with different blockchain networks. In this tutorial, we'll explore how to set up and run tests on multiple chains using Foundry's vm.createFork
and vm.selectFork
functions.
Setting Up Test Files
Scenario
We have two test files:
VaultL1.t.sol
: Tests a vault strategy against Uniswap V3 on Ethereum mainnet.VaultL2.t.sol
: Tests the same strategy on a lending protocol on Polygon zkEVM.
Creating Forks and Selecting Networks
For Ethereum Mainnet (VaultL1.t.sol
)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {Test} from "forge-std/Test.sol";
contract VaultL1Test is Test {
string ETH_RPC_URL = vm.envString("ETH_RPC_URL");
function setUp() public {
uint256 mainnetFork = vm.createFork(ETH_RPC_URL);
vm.selectFork(mainnetFork);
// Your setup code here
}
// Your tests here
}
For Polygon zkEVM (VaultL2.t.sol
)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import {Test} from "forge-std/Test.sol";
contract VaultL2Test is Test {
string ZKEVM_RPC_URL = vm.envString("ZKEVM_RPC_URL");
function setUp() public {
uint256 zkEvmFork = vm.createFork(ZKEVM_RPC_URL);
vm.selectFork(zkEvmFork);
// Your setup code here
}
// Your tests here
}
Setting Up .env
Create a .env
file in the root directory:
ETH_RPC_URL="your_ethereum_rpc_url_here"
ZKEVM_RPC_URL="your_polygon_zkevm_rpc_url_here"
Running the Tests
With the setup complete, executing forge test
will automatically select the appropriate network as specified in the test files. This allows for convenient validation across different chains without needing separate projects.
Benefits
Cross-chain Testing: Validates contract interaction across various chains.
Organized Development: Maintains a single project for multi-chain testing.
Efficiency: Simplifies the testing process with automated network selection.
Real-World Examples
Check out how this setup is used in real-world projects:
Conclusion
Foundry's ability to handle tests across multiple chains is a powerful feature for smart contract developers. It enhances the testing process, ensuring that contracts work correctly in various blockchain environments.