Introduction
Hardhat Network's forking feature allows developers to interact with Ethereum mainnet (or other networks) in a local development environment. This guide covers everything from basic setup to advanced configurations for effective blockchain simulation.
Core Features
1. Forking from Mainnet
The simplest way to fork Ethereum mainnet is via command line:
npx hardhat node --fork https://eth-mainnet.alchemyapi.io/v2/YOUR_API_KEYOr configure permanently in hardhat.config.js:
networks: {
hardhat: {
forking: {
url: "https://eth-mainnet.alchemyapi.io/v2/YOUR_API_KEY"
}
}
}2. Block Pinning
For consistent testing environments, pin to a specific block:
forking: {
url: "...",
blockNumber: 14390000 // Example block number
}๐ Why block pinning improves performance 20x
3. Custom HTTP Headers
Secure your requests with custom headers:
forking: {
httpHeaders: {
"Authorization": "Bearer YOUR_TOKEN"
}
}4. Account Impersonation
Simulate transactions from any address without private keys:
const signer = await ethers.getImpersonatedSigner("0x...");
await signer.sendTransaction(...);5. Fork Reset
Dynamically reset your fork during runtime:
await network.provider.request({
method: "hardhat_reset",
params: [{
forking: {
url: "...",
blockNumber: 123456
}
}]
});Advanced Configurations
Custom Hardfork History
For non-standard networks, specify hardfork activation blocks:
chains: {
99: { // Chain ID
hardforkHistory: {
berlin: 10000000,
london: 20000000
}
}
}Best Practices
- Always use archive node providers (like Alchemy)
- Pin blocks for reproducible tests
- Clear cache when changing fork parameters
FAQ Section
Q: Why fork Ethereum mainnet?
A: Forking allows testing against real-world state without real transactions or costs.
Q: How long does forked data persist?
A: Hardhat Network caches data locally until manually reset or reconfigured.
Q: Can I fork testnets?
A: Absolutely! Replace the mainnet URL with any Ethereum-compatible network RPC endpoint.
๐ Explore more blockchain development tools
Conclusion
Hardhat's forking capabilities provide unparalleled flexibility for Ethereum development. From mainnet simulation to custom chain configurations, these tools streamline smart contract testing and debugging.