patternjavascriptTip
Hardhat: deploying and testing contracts with TypeScript and typechain
Viewed 0 times
Hardhat 2.x, ethers.js v6
hardhattypechaindeploy contracttypescript testsgetContractFactorywaitForDeployment
hardhat
Error Messages
Problem
Setting up Hardhat with TypeScript gives you type safety for contract interactions in tests, but requires extra configuration steps.
Solution
Install hardhat, @nomicfoundation/hardhat-toolbox, typechain, and @typechain/hardhat. Run npx hardhat compile to generate typed artifacts. Import generated types in tests.
import { ethers } from 'hardhat';
const Token = await ethers.getContractFactory('MyToken');
const token = await Token.deploy();
await token.waitForDeployment();Why
TypeChain generates TypeScript interfaces from ABI artifacts, providing autocompletion and type checking for contract method calls in tests.
Gotchas
- In Hardhat v2.17+, use deploymentTransaction().wait() instead of deployed()
- Regenerate typechain types after every contract change: npx hardhat compile
- The default Hardhat network resets state between test files unless you use fixtures
Code Snippets
Hardhat deploy and test with TypeScript
import { expect } from 'chai';
import { ethers } from 'hardhat';
import { MyToken } from '../typechain-types';
describe('MyToken', function () {
async function deployFixture() {
const [owner, user] = await ethers.getSigners();
const MyToken = await ethers.getContractFactory('MyToken');
const token: MyToken = await MyToken.deploy(ethers.parseEther('1000000'));
await token.waitForDeployment();
return { token, owner, user };
}
it('should mint initial supply to owner', async function () {
const { token, owner } = await deployFixture();
const balance = await token.balanceOf(owner.address);
expect(balance).to.equal(ethers.parseEther('1000000'));
});
});Context
Setting up a Hardhat project with TypeScript for smart contract development
Revisions (0)
No revisions yet.