Skip to Content
๐ŸŒ Web3๐Ÿ“– EVM๐Ÿ‘ท Hardhat

๐Ÿ‘ท Hardhat

Hardhat is a development environment for Ethereum and EVM chains: compile Solidity, run tests, and run scripts (deploy, interact) from the command line. Itโ€™s the standard choice for serious EVM development.


๐ŸŽฏ Why Hardhat


๐Ÿš€ Quick Start

mkdir my-project && cd my-project npm init -y npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox npx hardhat init

Choose Create a JavaScript project (or TypeScript). Then:

npx hardhat compile npx hardhat test

๐Ÿ“ Project Layout

contracts/ # Solidity sources scripts/ # Deploy and utility scripts test/ # Tests (e.g. *.js / *.ts) hardhat.config.js

โš™๏ธ Config Example (Multiple Networks)

// hardhat.config.js require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); module.exports = { solidity: "0.8.24", networks: { hardhat: { chainId: 1337, }, sepolia: { url: process.env.SEPOLIA_RPC_URL, accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [], }, mainnet: { url: process.env.MAINNET_RPC_URL, accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [], }, }, etherscan: { apiKey: { sepolia: process.env.ETHERSCAN_API_KEY, mainnet: process.env.ETHERSCAN_API_KEY, }, }, };

Secrets go in .env; see Environment Variables.


๐Ÿ“ Deploy Script Example

// scripts/deploy.js const hre = require("hardhat"); async function main() { const [deployer] = await hre.ethers.getSigners(); console.log("Deploying with", deployer.address); const MyContract = await hre.ethers.getContractFactory("MyContract"); const contract = await MyContract.deploy(/* constructor args */); await contract.waitForDeployment(); const address = await contract.getAddress(); console.log("Deployed to", address); } main() .then(() => process.exit(0)) .catch((err) => { console.error(err); process.exit(1); });

Run:

npx hardhat run scripts/deploy.js --network sepolia

๐Ÿงช Test Example

// test/MyContract.js const { expect } = require("chai"); const hre = require("hardhat"); describe("MyContract", function () { it("should do something", async function () { const [owner] = await hre.ethers.getSigners(); const MyContract = await hre.ethers.getContractFactory("MyContract"); const contract = await MyContract.deploy(); await contract.waitForDeployment(); await expect(contract.someFunction()).to.not.be.reverted; }); });

๐Ÿ”— Resources

Last updated on