Hardhat Development Environment
Overview
Hardhat is the most popular Ethereum development environment, providing compilation, testing, deployment, and debugging tools for smart contracts.
ā¹ļø
Hardhat's plugin system makes it highly extensible. Most functionality comes from community plugins like hardhat-ethers, hardhat-waffle, and hardhat-gas-reporter.
Architecture
Project Setup
Installation
# Initialize new project
npx hardhat init
# Or with TypeScript
mkdir my-project && cd my-project
npm init -y
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
npx hardhat init
Project Structure
my-project/
āāā contracts/ # Solidity contracts
ā āāā Token.sol
ā āāā interfaces/
āāā test/ # Test files
ā āāā Token.test.js
ā āāā Token.test.ts
āāā scripts/ # Deployment scripts
ā āāā deploy.js
āāā tasks/ # Custom tasks
ā āāā accounts.js
āāā typechain-types/ # Generated TypeScript types
āāā artifacts/ # Compiled contracts
āāā cache/ # Compilation cache
āāā coverage/ # Test coverage reports
āāā hardhat.config.ts # Configuration
āāā package.json
āāā tsconfig.json
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 "hardhat-deploy";
import * as dotenv from "dotenv";
dotenv.config();
const config: HardhatUserConfig = {
solidity: {
version: "0.8.19",
settings: {
optimizer: {
enabled: true,
runs: 200,
},
viaIR: true,
},
},
networks: {
hardhat: {
forking: {
url: process.env.MAINNET_RPC_URL || "",
blockNumber: 18000000, // Pin block for consistency
},
},
goerli: {
url: process.env.GOERLI_RPC_URL || "",
accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [],
chainId: 5,
},
mainnet: {
url: process.env.MAINNET_RPC_URL || "",
accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [],
chainId: 1,
},
},
gasReporter: {
enabled: process.env.REPORT_GAS === "true",
currency: "USD",
coinmarketcap: process.env.COINMARKETCAP_API_KEY,
},
etherscan: {
apiKey: process.env.ETHERSCAN_API_KEY,
},
typechain: {
outDir: "typechain-types",
target: "ethers-v6",
},
};
export default config;
Configuration Options
| Option | Purpose | Default |
|---|---|---|
| solidity.version | Compiler version | 0.8.x |
| optimizer.enabled | Enable optimizer | false |
| optimizer.runs | Optimization runs | 200 |
| networks.*.url | RPC endpoint | - |
| networks.*.accounts | Private keys | [] |
| gasReporter.enabled | Gas reporting | false |
Compilation
Compile Contracts
# Compile all contracts
npx hardhat compile
# Clean and recompile
npx hardhat clean && npx hardhat compile
# Compile with specific version
npx hardhat compile --force
Compiler Configuration
// hardhat.config.ts
solidity: {
compilers: [
{
version: "0.8.19",
settings: {
optimizer: { enabled: true, runs: 200 },
},
},
{
version: "0.7.6",
settings: {
optimizer: { enabled: true, runs: 200 },
},
},
],
overrides: {
"contracts/Complex.sol": {
version: "0.8.19",
settings: {
optimizer: { enabled: true, runs: 1000 },
viaIR: true,
},
},
},
},
Compilation Output
Compiling 2 files with 0.8.19
Compilation finished
- Token.sol: Token.json, Token.d.json
- Vault.sol: Vault.json, Vault.d.json
Artifacts: artifacts/contracts/
TypeChain: typechain-types/
Testing
JavaScript Tests
// test/Token.test.js
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("Token", function () {
let token;
let owner;
let addr1;
let addr2;
beforeEach(async function () {
[owner, addr1, addr2] = await ethers.getSigners();
const Token = await ethers.getContractFactory("Token");
token = await Token.deploy("MyToken", "MTK", 1000000);
await token.deployed();
});
describe("Deployment", function () {
it("Should set the right name and symbol", async function () {
expect(await token.name()).to.equal("MyToken");
expect(await token.symbol()).to.equal("MTK");
});
it("Should assign the total supply to the owner", async function () {
const ownerBalance = await token.balanceOf(owner.address);
expect(await token.totalSupply()).to.equal(ownerBalance);
});
});
describe("Transfers", function () {
it("Should transfer tokens between accounts", async function () {
await token.transfer(addr1.address, 100);
expect(await token.balanceOf(addr1.address)).to.equal(100);
await token.connect(addr1).transfer(addr2.address, 50);
expect(await token.balanceOf(addr2.address)).to.equal(50);
});
it("Should fail if sender doesn't have enough tokens", async function () {
const initialOwnerBalance = await token.balanceOf(owner.address);
await expect(
token.connect(addr1).transfer(owner.address, 1)
).to.be.revertedWith("ERC20: insufficient balance");
expect(await token.balanceOf(owner.address)).to.equal(initialOwnerBalance);
});
});
});
TypeScript Tests
// test/Token.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { Token } from "../typechain-types";
import { SignerWithAddress } from "@nomicfoundation/hardhat-ethers/signers";
describe("Token", function () {
let token: Token;
let owner: SignerWithAddress;
let addr1: SignerWithAddress;
let addr2: SignerWithAddress;
beforeEach(async function () {
[owner, addr1, addr2] = await ethers.getSigners();
const Token = await ethers.getContractFactory("Token");
token = await Token.deploy("MyToken", "MTK", 1000000);
await token.waitForDeployment();
});
describe("Deployment", function () {
it("Should set the right name and symbol", async function () {
expect(await token.name()).to.equal("MyToken");
expect(await token.symbol()).to.equal("MTK");
});
});
describe("Transfers", function () {
it("Should transfer tokens between accounts", async function () {
const transferAmount = ethers.parseEther("100");
await token.transfer(addr1.address, transferAmount);
expect(await token.balanceOf(addr1.address)).to.equal(transferAmount);
});
});
});
Run Tests
# Run all tests
npx hardhat test
# Run specific file
npx hardhat test test/Token.test.ts
# Run with gas reporting
REPORT_GAS=true npx hardhat test
# Run with coverage
npx hardhat coverage
# Run in parallel
npx hardhat test --parallel
Deployment Scripts
Basic Deployment
// scripts/deploy.js
const { ethers } = require("hardhat");
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with:", deployer.address);
console.log("Balance:", ethers.formatEther(await ethers.provider.getBalance(deployer.address)));
const Token = await ethers.getContractFactory("Token");
const token = await Token.deploy("MyToken", "MTK", 1000000);
await token.waitForDeployment();
const tokenAddress = await token.getAddress();
console.log("Token deployed to:", tokenAddress);
// Verify on Etherscan
console.log("Waiting for block confirmations...");
await token.deploymentTransaction()?.wait(6);
await hre.run("verify:verify", {
address: tokenAddress,
constructorArguments: ["MyToken", "MTK", 1000000],
});
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
Hardhat Deploy Plugin
// deploy/001_deploy_token.ts
import { HardhatRuntimeEnvironment } from "hardhat/types";
import { DeployFunction } from "hardhat-deploy/types";
const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
const { deployments, getNamedAccounts } = hre;
const { deploy } = deployments;
const { deployer } = await getNamedAccounts();
const result = await deploy("Token", {
from: deployer,
args: ["MyToken", "MTK", 1000000],
log: true,
});
console.log("Token deployed to:", result.address);
};
export default func;
func.tags = ["Token"];
Deployment Scripts
# Deploy to specific network
npx hardhat run scripts/deploy.js --network goerli
npx hardhat run scripts/deploy.js --network mainnet
# Using hardhat-deploy
npx hardhat deploy
npx hardhat deploy --network goerli
# Verify contract
npx hardhat verify --network mainnet CONTRACT_ADDRESS "Arg1" "Arg2"
Plugins
Essential Plugins
| Plugin | Purpose | Installation |
|---|---|---|
| @nomicfoundation/hardhat-toolbox | All-in-one toolkit | Included by default |
| @nomicfoundation/hardhat-verify | Contract verification | npm i -D @nomicfoundation/hardhat-verify |
| hardhat-gas-reporter | Gas reporting | npm i -D hardhat-gas-reporter |
| solidity-coverage | Test coverage | npm i -D solidity-coverage |
| hardhat-deploy | Deployment management | npm i -D hardhat-deploy |
| @openzeppelin/hardhat-upgrades | Upgradeable contracts | npm i -D @openzeppelin/hardhat-upgrades |
Plugin Configuration
// hardhat.config.ts
import "@nomicfoundation/hardhat-toolbox";
import "@nomicfoundation/hardhat-verify";
import "hardhat-gas-reporter";
import "solidity-coverage";
const config: HardhatUserConfig = {
// ... other config
gasReporter: {
enabled: true,
currency: "USD",
gasPrice: 21,
coinmarketcap: process.env.COINMARKETCAP_API_KEY,
excludeContracts: ["Migrations"],
},
etherscan: {
apiKey: {
mainnet: process.env.ETHERSCAN_API_KEY,
goerli: process.env.ETHERSCAN_API_KEY,
},
},
};
Mainnet Forking
Fork Configuration
// hardhat.config.ts
const config: HardhatUserConfig = {
networks: {
hardhat: {
forking: {
url: process.env.MAINNET_RPC_URL || "",
blockNumber: 18000000, // Pin to specific block
enabled: true,
},
},
},
};
Fork Testing Example
// test/ForkTest.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { impersonateAccount } from "@nomicfoundation/hardhat-network-helpers";
describe("Fork Testing", function () {
it("Should interact with mainnet contracts", async function () {
// Impersonate a whale account
const whaleAddress = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"; // Vitalik
await impersonateAccount(whaleAddress);
const whale = await ethers.getSigner(whaleAddress);
const balance = await ethers.provider.getBalance(whaleAddress);
console.log("Whale balance:", ethers.formatEther(balance));
// Interact with Uniswap, Aave, etc.
const uniswapRouter = await ethers.getContractAt(
"IUniswapV2Router",
"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
);
// Test your contract against real protocol state
});
});
Fork Benefits
| Benefit | Description | Use Case |
|---|---|---|
| Real State | Uses actual mainnet data | Protocol integration |
| Testnet Tokens | Use real token contracts | DeFi testing |
| No Deployment | Skip contract deployment | Quick testing |
| Reproducible | Pin to block number | Consistent results |
Debugging
Hardhat Console
# Start interactive console
npx hardhat console --network localhost
# In console
> const Token = await ethers.getContractFactory("Token")
> const token = await Token.deploy("Test", "TST", 1000000)
> await token.deployed()
> await token.totalSupply()
Debugging Tasks
# Trace transaction
npx hardhat trace --hash 0x...
# Impersonate account
npx hardhat impersonate-account --address 0x...
# Set balance
npx hardhat set-balance --address 0x... --amount 1000000000000000000
# Mine blocks
npx hardhat mine --blocks 10
Logging in Tests
// Using hardhat console.log
import "hardhat/console.sol";
contract Token {
function transfer(address to, uint256 amount) public {
console.log("Transfer from:", msg.sender);
console.log("Transfer to:", to);
console.log("Amount:", amount);
// ... logic
}
}
Gas Reporting
Gas Reporter Output
Token
Deployment
ā Should set the right name and symbol (150ms)
Transfers
ā Should transfer tokens between accounts (120ms)
Gas usage for Token:
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāā¬āāāāāāāāāāāā¬āāāāāāāāāāāā
ā Contract ā Method ā Min Gas ā Max Gas ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¼āāāāāāāāāāāāāāā¼āāāāāāāāāāāā¼āāāāāāāāāāāā¤
ā Token ā transfer ā 52,000 ā 52,000 ā
ā Token ā approve ā 46,000 ā 46,000 ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā“āāāāāāāāāāāāāāā“āāāāāāāāāāāā“āāāāāāāāāāāā
Gas Optimization
| Function | Before | After | Savings |
|---|---|---|---|
| transfer | 52,000 | 48,000 | 7.7% |
| approve | 46,000 | 44,000 | 4.3% |
| mint | 65,000 | 60,000 | 7.7% |
CI/CD Integration
GitHub Actions
# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: "18"
- 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 reporter
run: REPORT_GAS=true npx hardhat test
Real-World Example: Compound Finance
Testing Strategy
| Test Type | Purpose | Coverage |
|---|---|---|
| Unit | Individual functions | 100% |
| Integration | Contract interactions | Critical paths |
| Fork | Protocol integration | DeFi operations |
| Fuzz | Edge cases | Property testing |
Trade-offs
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| Language | JavaScript | TypeScript | TypeScript for type safety |
| Testing | Mocha/Chai | Forge | Use both for coverage |
| Deployment | Scripts | hardhat-deploy | hardhat-deploy for complex |
| Network | Testnet | Fork | Fork for integration tests |
Interview Questions
-
Explain the difference between
hardhat testandhardhat coverage. When would you use each?hardhat testruns tests quickly for development.hardhat coverageinstruments contracts to measure code coverage, showing which lines/branches are tested. Usetestduring development,coveragebefore commits to ensure comprehensive testing. -
How does mainnet forking work and what are its benefits for testing?
Mainnet forking creates a local copy of mainnet state at a specific block. Benefits: test against real protocol state, use actual token contracts, no testnet deployment needed, reproducible results with pinned blocks.
-
Describe the Hardhat plugin ecosystem and how to extend Hardhat's functionality.
Hardhat uses a plugin architecture where plugins extend core functionality via tasks, fixtures, and network helpers. Install plugins via npm, import in config, and they automatically extend Hardhat. Examples: hardhat-ethers adds ethers.js integration, hardhat-gas-reporter adds gas reporting.
Quiz Questions
-
What is the default directory for compiled contract artifacts?
- A) dist/
- B) build/
- C) artifacts/
- D) out/
Answer: C - Hardhat outputs compiled artifacts to the
artifacts/directory. -
How do you enable optimizer in Hardhat configuration?
- A) optimizer: true
- B) optimizer: { enabled: true }
- C) enableOptimizer: true
- D) optimize: true
Answer: B - Set
optimizer: { enabled: true, runs: 200 }in solidity settings. -
What command runs test coverage in Hardhat?
- A) hardhat test --coverage
- B) hardhat coverage
- C) hardhat test:coverage
- D) hardhat run coverage
Answer: B - Run
npx hardhat coverageto generate coverage reports.