Testing smart contracts with Hardhat and Typechain.
init
command that by default installs @nomicfoundation/hardhat-toolbox
. This package already contains Typechain, which is a plugin that generates static types for your smart contracts. This means you can interact with your contracts and get immediate feedback about the parameters received by a particular function and the functions of a smart contract.
The best way to see its true potential is to start writing tests.
After compiling the hardhat project in the previous lesson, a new folder called typechain-types
was created, which Typechain is already installed and running.
Lock.sol
and a sample test inside the test folder named Lock.ts
.
In the following, you reuse this smart contract but rewrite the test using Typechain.
To remove the body of the Lock.ts
file:
typechain-types
, Lock
, and Lock__Factory
.
Typechain always creates two files per contract. The first one Lock
refers to the type and functions of a particular contract. Lock__Factory
is used to deploy the Lock contract or to create instances of a particular contract.
The Lock.sol
contract allows the creator to lock Ether until an unlock time has passed.
Notice the constructor has a payable keyword:
unlockTime
before
function.
The first test case should verify that the unlockTime
variable is correct.
Lock
contract, you simply call ethers.provider.getBalance
.
Create a new test case:
npx hardhat test
and you should get:
owner
npx hardhat test
and you should get:
withdraw
reverts with a particular message:
the block.timestamp
by using the time helper:
npx hardhat test
and you should get: