Hardhat
Hardhat is the Node.js development environment for Ethereum: local network, console, testing framework, and deployment tooling in one CLI. The workflow is write contract → write test → run the test against an in-memory Hardhat Network → deploy to a real chain. This example covers the full loop for a tiny token contract.
Test and deploy an ERC-20-lite token
EXAMPLE
// contracts/Token.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Token {
string public name = 'DemoToken';
string public symbol = 'DEMO';
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
constructor(uint256 initialSupply) {
totalSupply = initialSupply;
balanceOf[msg.sender] = initialSupply;
emit Transfer(address(0), msg.sender, initialSupply);
}
function transfer(address to, uint256 amount) external returns (bool) {
require(balanceOf[msg.sender] >= amount, 'insufficient');
unchecked { balanceOf[msg.sender] -= amount; }
balanceOf[to] += amount;
emit Transfer(msg.sender, to, amount);
return true;
}
}
// test/Token.ts
import { expect } from 'chai';
import { ethers } from 'hardhat';
describe('Token', () => {
it('mints supply to deployer and transfers', async () => {
const [deployer, alice] = await ethers.getSigners();
const Token = await ethers.getContractFactory('Token');
const supply = ethers.parseEther('1000');
const token = await Token.deploy(supply);
expect(await token.balanceOf(deployer.address)).to.equal(supply);
await expect(token.transfer(alice.address, ethers.parseEther('10')))
.to.emit(token, 'Transfer')
.withArgs(deployer.address, alice.address, ethers.parseEther('10'));
expect(await token.balanceOf(alice.address))
.to.equal(ethers.parseEther('10'));
});
});
// scripts/deploy.ts
import { ethers } from 'hardhat';
async function main() {
const supply = ethers.parseEther('1000000');
const token = await ethers.deployContract('Token', [supply]);
await token.waitForDeployment();
console.log('Token deployed to', await token.getAddress());
}
main().catch((e) => { console.error(e); process.exit(1); });
// Run: npx hardhat test
// Local deploy: npx hardhat node (separate terminal)
// npx hardhat run scripts/deploy.ts --network localhost
Why it matters
Hardhat Network forks mainnet on demand — `npx hardhat node --fork
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// hardhat.config.ts
import "@nomicfoundation/hardhat-toolbox";
export default {
solidity: "0.8.24",
networks: {
sepolia: {
url: process.env.SEPOLIA_RPC,
accounts: [process.env.PRIVATE_KEY!],
},
},
};
// npx hardhat test
// npx hardhat run scripts/deploy.ts --network sepolia
Try it Yourself »
Discussion
Loading…