Hardhat Ethereum Development Environment Complete Guide
Overview
Hardhat is the most popular Ethereum development environment, offering compilation, testing, deployment, and debugging tools. This guide covers every aspect with working examples.
Project Setup
# Create new project
mkdir my-hardhat-project && cd my-hardhat-project
npm init -y
# Install Hardhat
npm install --save-dev hardhat
# Initialize with template
npx hardhat init
# Install toolbox
npm install --save-dev @nomicfoundation/hardhat-toolbox
# Additional useful packages
npm install --save-dev @nomicfoundation/hardhat-chai-matchers
npm install --save-dev @nomicfoundation/hardhat-ethers
npm install --save-dev @nomicfoundation/hardhat-network-helpers
npm install --save-dev @nomicfoundation/hardhat-verify
npm install --save-dev @typechain/hardhat
npm install --save-dev hardhat-gas-reporter
npm install --save-dev solidity-coverage
Complete Configuration
// hardhat.config.ts
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import "@nomicfoundation/hardhat-verify";
import "hardhat-gas-reporter";
import "solidity-coverage";
import dotenv from "dotenv";
dotenv.config();
const config: HardhatUserConfig = {
solidity: {
compilers: [
{
version: "0.8.19",
settings: {
optimizer: {
enabled: true,
runs: 200,
},
viaIR: true,
metadata: {
bytecodeHash: "none",
},
},
},
{
version: "0.8.17",
settings: {
optimizer: {
enabled: true,
runs: 200,
},
},
},
],
overrides: {
"contracts/ComplexContract.sol": {
version: "0.8.19",
settings: {
optimizer: {
enabled: true,
runs: 1000,
},
viaIR: true,
},
},
},
},
networks: {
hardhat: {
forking: {
url: `https://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,
blockNumber: 18000000,
enabled: false,
},
chainId: 31337,
mining: {
auto: true,
interval: 0,
mempool: {
order: "fifo",
},
},
accounts: {
count: 20,
accountsBalance: "10000000000000000000000", // 10,000 ETH
},
},
localhost: {
url: "http://127.0.0.1:8545",
chainId: 31337,
},
sepolia: {
url: `https://eth-sepolia.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,
accounts: [process.env.PRIVATE_KEY!],
chainId: 11155111,
gasPrice: "auto",
gas: "auto",
verify: {
etherscan: {
apiUrl: "https://api-sepolia.etherscan.io",
apiKey: process.env.ETHERSCAN_API_KEY,
},
},
},
mainnet: {
url: `https://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,
accounts: [process.env.PRIVATE_KEY!],
chainId: 1,
gasPrice: "auto",
gas: "auto",
verify: {
etherscan: {
apiUrl: "https://api.etherscan.io",
apiKey: process.env.ETHERSCAN_API_KEY,
},
},
},
polygon: {
url: `https://polygon-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,
accounts: [process.env.PRIVATE_KEY!],
chainId: 137,
},
arbitrum: {
url: `https://arb-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,
accounts: [process.env.PRIVATE_KEY!],
chainId: 42161,
},
optimism: {
url: `https://opt-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`,
accounts: [process.env.PRIVATE_KEY!],
chainId: 10,
},
},
gasReporter: {
enabled: process.env.REPORT_GAS === "true",
currency: "USD",
coinmarketcap: process.env.COINMARKETCAP_API_KEY,
token: "ETH",
gasPriceApi: "https://api.etherscan.io/api?module=gastracker&action=gasoracle",
noColors: false,
excludeContracts: [],
src: "./contracts",
},
etherscan: {
apiKey: {
mainnet: process.env.ETHERSCAN_API_KEY!,
sepolia: process.env.ETHERSCAN_API_KEY!,
polygon: process.env.POLYGONSCAN_API_KEY!,
},
},
paths: {
sources: "./contracts",
tests: "./test",
cache: "./cache",
artifacts: "./artifacts",
},
mocha: {
timeout: 20000,
},
};
export default config;
Compilation
# Compile contracts
npx hardhat compile
# Clean artifacts
npx hardhat clean
# Force recompile
npx hardhat compile --force
// scripts/compile.ts
import { run } from "hardhat";
async function main() {
// Compile all contracts
await run("compile");
// Get contract artifacts
const MyToken = await import("../artifacts/contracts/MyToken.sol/MyToken.json");
console.log("ABI:", MyToken.abi.length, "functions");
console.log("Bytecode length:", MyToken.bytecode.length);
}
main().catch(console.error);
Testing Strategies
// test/MyToken.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { loadFixture, time } from "@nomicfoundation/hardhat-network-helpers";
import { anyValue } from "@nomicfoundation/hardhat-chai-matchers/withArgs";
describe("MyToken", function () {
async function deployFixture() {
const [owner, addr1, addr2, addr3] = await ethers.getSigners();
const Token = await ethers.getContractFactory("MyToken");
const token = await Token.deploy("Test Token", "TT", 1000000);
const MintToken = await ethers.getContractFactory("MintableToken");
const mintToken = await MintToken.deploy("Mint Token", "MT");
return { token, mintToken, owner, addr1, addr2, addr3 };
}
describe("Deployment", function () {
it("Should set correct name and symbol", async function () {
const { token } = await loadFixture(deployFixture);
expect(await token.name()).to.equal("Test Token");
expect(await token.symbol()).to.equal("TT");
});
it("Should deploy with zero total supply", async function () {
const { token } = await loadFixture(deployFixture);
expect(await token.totalSupply()).to.equal(0);
});
it("Should set deployer as owner", async function () {
const { token, owner } = await loadFixture(deployFixture);
expect(await token.owner()).to.equal(owner.address);
});
});
describe("Minting", function () {
it("Should mint tokens to specified address", async function () {
const { mintToken, addr1 } = await loadFixture(deployFixture);
await mintToken.mint(addr1.address, ethers.parseEther("100"));
expect(await mintToken.balanceOf(addr1.address)).to.equal(
ethers.parseEther("100")
);
});
it("Should emit Transfer event", async function () {
const { mintToken, owner, addr1 } = await loadFixture(deployFixture);
await expect(
mintToken.mint(addr1.address, ethers.parseEther("100"))
)
.to.emit(mintToken, "Transfer")
.withArgs(
ethers.ZeroAddress,
addr1.address,
ethers.parseEther("100")
);
});
it("Should only allow owner to mint", async function () {
const { mintToken, addr1 } = await loadFixture(deployFixture);
await expect(
mintToken.connect(addr1).mint(addr1.address, ethers.parseEther("100"))
).to.be.revertedWith("Ownable: caller is not the owner");
});
});
describe("Transfers", function () {
beforeEach(async function () {
const { mintToken, owner, addr1 } = await loadFixture(deployFixture);
await mintToken.mint(owner.address, ethers.parseEther("1000"));
});
it("Should transfer tokens between accounts", async function () {
const { mintToken, owner, addr1 } = await loadFixture(deployFixture);
await mintToken.mint(owner.address, ethers.parseEther("1000"));
await mintToken.transfer(addr1.address, ethers.parseEther("100"));
expect(await mintToken.balanceOf(addr1.address)).to.equal(
ethers.parseEther("100")
);
});
it("Should fail if sender has insufficient balance", async function () {
const { mintToken, addr1, addr2 } = await loadFixture(deployFixture);
await expect(
mintToken.connect(addr1).transfer(addr2.address, ethers.parseEther("1"))
).to.be.revertedWithCustomError(mintToken, "InsufficientBalance");
});
});
describe("Time-dependent tests", function () {
it("Should handle time-locked transfers", async function () {
const { mintToken, owner, addr1 } = await loadFixture(deployFixture);
await mintToken.mint(owner.address, ethers.parseEther("1000"));
const lockTime = await time.latest() + 3600; // 1 hour
await mintToken.lockTokens(addr1.address, ethers.parseEther("100"), lockTime);
// Should fail before unlock
await expect(
mintToken.connect(addr1).unlock()
).to.be.revertedWith("Tokens still locked");
// Fast forward time
await time.increaseTo(lockTime);
// Should succeed after unlock
await mintToken.connect(addr1).unlock();
expect(await mintToken.balanceOf(addr1.address)).to.equal(
ethers.parseEther("100")
);
});
});
describe("Gas reporting", function () {
it("Should report gas usage", async function () {
const { mintToken, owner, addr1 } = await loadFixture(deployFixture);
const tx = await mintToken.transfer(
addr1.address,
ethers.parseEther("100")
);
const receipt = await tx.wait();
console.log(`Gas used: ${receipt.gasUsed.toString()}`);
});
});
});
Mainnet Forking
// test/MainnetFork.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { takeSnapshot, revertToSnapshot } from "@nomicfoundation/hardhat-network-helpers";
describe("Mainnet Fork Tests", function () {
let snapshotId: string;
// Uniswap V2 Router on mainnet
const UNISWAP_ROUTER = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";
const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
const DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F";
before(async function () {
// This test only runs on mainnet fork
if (!process.env.FORKING) {
this.skip();
}
});
beforeEach(async function () {
snapshotId = await takeSnapshot();
});
afterEach(async function () {
await revertToSnapshot(snapshotId);
});
it("Should swap ETH for DAI on Uniswap", async function () {
const [owner] = await ethers.getSigners();
const router = await ethers.getContractAt(
"IUniswapV2Router02",
UNISWAP_ROUTER
);
const amountIn = ethers.parseEther("1");
const amountOutMin = ethers.parseEther("1000");
const balanceBefore = await ethers.provider.getBalance(owner.address);
await router.swapExactETHForTokens(
amountOutMin,
[WETH, DAI],
owner.address,
Math.floor(Date.now() / 1000) + 60 * 20,
{ value: amountIn }
);
const daiBalance = await ethers.getContractAt(
"IERC20",
DAI
).balanceOf(owner.address);
expect(daiBalance).to.be.gt(0);
});
it("Should have correct Uniswap factory state", async function () {
const factory = await ethers.getContractAt(
"IUniswapV2Factory",
"0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"
);
const totalPairs = await factory.allPairsLength();
expect(totalPairs).to.be.gt(0);
});
});
Debugging with console.log
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "hardhat/console.sol";
contract DebugExample {
uint256 public value;
mapping(address => uint256) public balances;
function setValue(uint256 _value) external {
console.log("Setting value from:", msg.sender);
console.log("Old value:", value);
console.log("New value:", _value);
require(_value > 0, "Value must be positive");
value = _value;
console.log("Value updated successfully");
}
function batchTransfer(
address[] calldata recipients,
uint256[] calldata amounts
) external {
require(recipients.length == amounts.length, "Length mismatch");
for (uint256 i = 0; i < recipients.length; i++) {
console.log("Transferring %d to %s", amounts[i], recipients[i]);
balances[recipients[i]] += amounts[i];
}
console.log("Batch transfer completed. Total recipients:", recipients.length);
}
function complexLogic(uint256 input) external returns (uint256) {
console.log("Input received:", input);
if (input > 100) {
console.log("Input is greater than 100");
return input * 2;
} else if (input > 50) {
console.log("Input is between 50 and 100");
return input * 3;
} else {
console.log("Input is 50 or less");
return input * 4;
}
}
}
# Run with console.log output
npx hardhat test --grep "test name"
# Run specific test with verbosity
npx hardhat test test/DebugExample.test.ts --verbose
Deployment Scripts
// scripts/deploy.ts
import { ethers, run, network } from "hardhat";
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying with account:", deployer.address);
console.log("Account balance:", (await deployer.provider.getBalance(deployer.address)).toString());
// Deploy with specific gas settings
const MyToken = await ethers.getContractFactory("MyToken");
const token = await MyToken.deploy("My Token", "MTK", 1000000, {
gasLimit: 3000000,
gasPrice: ethers.parseUnits("20", "gwei"),
});
await token.waitForDeployment();
const address = await token.getAddress();
console.log("MyToken deployed to:", address);
// Wait for confirmations
console.log("Waiting for block confirmations...");
const deployTx = await token.deploymentTransaction();
if (deployTx) {
await deployTx.wait(5);
}
// Verify on Etherscan
if (network.name !== "hardhat" && network.name !== "localhost") {
console.log("Verifying contract on Etherscan...");
try {
await run("verify:verify", {
address: address,
constructorArguments: ["My Token", "MTK", 1000000],
});
console.log("Contract verified successfully!");
} catch (error: any) {
if (error.message.includes("Already Verified")) {
console.log("Contract is already verified");
} else {
console.error("Verification failed:", error);
}
}
}
return { address, deployer: deployer.address };
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
Hardhat Ignition (New Deployment System)
// ignition/modules/MyToken.ts
import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";
const MyTokenModule = buildModule("MyTokenModule", (m) => {
const name = m.getParameter("name", "My Token");
const symbol = m.getParameter("symbol", "MTK");
const initialSupply = m.getParameter("initialSupply", 1000000);
const token = m.contract("MyToken", [name, symbol, initialSupply]);
return { token };
});
export default MyTokenModule;
// Deploy with: npx hardhat ignition deploy ignition/modules/MyToken.ts
Testing Helpers
// helpers/utils.ts
import { ethers } from "hardhat";
import { time, loadFixture } from "@nomicfoundation/hardhat-network-helpers";
export async function increaseTime(seconds: number) {
await time.increase(seconds);
}
export async function takeSnapshot() {
return await time.takeSnapshot();
}
export async function revertToSnapshot(snapshotId: string) {
await time.revertTo(snapshotId);
}
export async function getBlockTimestamp() {
return await time.latest();
}
export async function mineBlocks(blocks: number) {
for (let i = 0; i < blocks; i++) {
await ethers.provider.send("evm_mine", []);
}
}
export async function impersonateAccount(address: string) {
await ethers.provider.send("hardhat_impersonateAccount", [address]);
return await ethers.getSigner(address);
}
export async function setBalance(address: string, balance: bigint) {
await ethers.provider.send("hardhat_setBalance", [
address,
"0x" + balance.toString(16),
]);
}
export async function snapshot() {
return await ethers.provider.send("evm_snapshot", []);
}
export async function revert(snapshotId: string) {
await ethers.provider.send("evm_revert", [snapshotId]);
}
Plugin Ecosystem
| Plugin | Purpose | Installation |
|---|---|---|
| hardhat-toolbox | All-in-one toolkit | npm i -D @nomicfoundation/hardhat-toolbox |
| hardhat-ethers | Ethers.js integration | Included in toolbox |
| hardhat-chai-matchers | Custom Chai matchers | Included in toolbox |
| hardhat-verify | Etherscan verification | Included in toolbox |
| hardhat-gas-reporter | Gas usage reports | npm i -D hardhat-gas-reporter |
| solidity-coverage | Test coverage | npm i -D solidity-coverage |
| hardhat-waffle | Waffle testing | npm i -D @nomiclabs/hardhat-waffle |
| hardhat-upgrades | Proxy upgrades | npm i -D @openzeppelin/hardhat-upgrades |
| hardhat-etherscan | Verification (legacy) | npm i -D @nomiclabs/hardhat-etherscan |
| hardhat-solhint | Solidity linting | npm i -D solhint |
CI/CD Integration
# .github/workflows/test.yml
name: Test
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x, 20.x]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Compile contracts
run: npx hardhat compile
- name: Run tests
run: npx hardhat test
- name: Run coverage
run: npx hardhat coverage
- name: Run gas report
run: REPORT_GAS=true npx hardhat test
env:
COINMARKETCAP_API_KEY: ${{ secrets.COINMARKETCAP_API_KEY }}
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
files: ./coverage.json
flags: solidity
# .github/workflows/deploy.yml
name: Deploy
on:
push:
tags:
- 'v*'
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 20.x
- name: Install dependencies
run: npm ci
- name: Compile contracts
run: npx hardhat compile
- name: Deploy to Sepolia
run: npx hardhat run scripts/deploy.ts --network sepolia
env:
ALCHEMY_API_KEY: ${{ secrets.ALCHEMY_API_KEY }}
PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
ETHERSCAN_API_KEY: ${{ secrets.ETHERSCAN_API_KEY }}
- name: Deploy to Mainnet
run: npx hardhat run scripts/deploy.ts --network mainnet
env:
ALCHEMY_API_KEY: ${{ secrets.ALCHEMY_API_KEY }}
PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
ETHERSCAN_API_KEY: ${{ secrets.ETHERSCAN_API_KEY }}
Gas Optimization
The gas cost formula for contract deployment:
| Optimization | Gas Saved | Implementation |
|---|---|---|
| Enable optimizer | 20-40% | optimizer: true |
| viaIR pipeline | 10-20% | viaIR: true |
| Reduce runs | 5-15% | runs: 200 |
| Remove metadata | 2-5% | metadata: {bytecodeHash: "none"} |
| Use custom errors | 500+ per error | Replace revert strings |
Package.json Scripts
{
"scripts": {
"compile": "hardhat compile",
"clean": "hardhat clean",
"test": "hardhat test",
"test:gas": "REPORT_GAS=true hardhat test",
"test:coverage": "hardhat coverage",
"test:fork": "FORKING=true hardhat test --network hardhat",
"deploy:local": "hardhat run scripts/deploy.ts --network localhost",
"deploy:sepolia": "hardhat run scripts/deploy.ts --network sepolia",
"deploy:mainnet": "hardhat run scripts/deploy.ts --network mainnet",
"verify": "hardhat verify --network mainnet",
"node": "hardhat node",
"console": "hardhat console",
"size": "hardhat size-contracts",
"flatten": "hardhat flatten"
}
}
Interview Questions
-
Explain the difference between
hardhat testandhardhat coverage. When would you use each?- Answer:
hardhat testruns your test suite and reports pass/fail.hardhat coverageinstruments your code to track which lines are executed by tests, generating a coverage report. Usehardhat testduring development for quick feedback, andhardhat coveragebefore audits to ensure all code paths are tested.
- Answer:
-
What is mainnet forking and what are its security implications?
- Answer: Mainnet forking creates a local copy of the Ethereum blockchain state at a specific block. This allows testing against real protocol state (like Uniswap liquidity). Security implications: you're interacting with real contract code, forked state may be stale, and private keys in forked accounts are not compromised (local Hardhat accounts).
-
How would you set up a Hardhat project for a production deployment?
- Answer: Use hardhat-toolbox, configure multiple networks (testnet, mainnet), implement proper secret management (dotenv), set up CI/CD with GitHub Actions, use hardhat-verify for Etherscan verification, implement deployment scripts with error handling, use hardhat-ignition for reproducible deployments, and set up monitoring with tools like Tenderly.
Quiz Questions
-
What is the default chain ID for Hardhat Network?
- A) 1
- B) 5
- C) 31337
- D) 1337
-
Which command generates a test coverage report?
- A)
npx hardhat test - B)
npx hardhat coverage - C)
npx hardhat report - D)
npx hardhat analyze
- A)
-
What is the purpose of
loadFixturein Hardhat testing?- A) Load external data
- B) Reset blockchain state to a snapshot
- C) Connect to mainnet
- D) Deploy contracts