6. Hardhat
Hardhat Setup
Installed as a node package using npm or yarn
Accessed via
yarn hardhatContracts compiled via
yarn hardhat compile
Deploying SimpleStorage (Method 1)
yarn hardhat run scripts/deploy.js
const { ethers } = require("hardhat");
async function main() {
const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage");
console.log("Deploying contract...");
const simpleStorage = await SimpleStorageFactory.deploy();
await simpleStorage.deployed();
console.log(`Deployed contract to: ${simpleStorage.address}`);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.log(error);
process.exit(1);
});Networks in Hardhat
Hardhat contains default hardhat network, rpc and wallet by default
We can edit
hardhat.config.jsfile to change default settingsWe can also explicitly select network while running hardhat i.e
yarn hardhat run scripts/deploy.js --network goerli
Programatic Verification
In our code script, we can automatically verify our contract code upon deployment
Works on block explorers like etherScan, might not work on other explorers
We can use etherScan API or use hardhat plugins
hardhat-etherscan
hardhat.config.js
deploy.js
Interacting with Contracts in Hardhat
deploy.js
Artifacts Troubleshooting
Delete the cache and artifacts folder if any issue arises (
yarn hardhat clean)Hardhat will re compile and generate the artifacts
Custom Hardhat Tasks
Can be defined in
hardhat.config.jsGenerally created in
tasksfolderCan be accessed via
yarn hardhat block-number
tasks/block-number.js
hardhat.config.js
Hardhat Localhost Node
yarn hardhat nodespins up a local blockchain node as ganache, gives us accounts and rpcThe rpc url must be added to hardhat config like before in order to use that localnode
Hardhat console
let us run interactive commands to interact with blockchain
yarn hardhat console --network <network>
Running Tests
Hardhat works with
mochaframework which is a javascript framework for running testschaiframework is required forassert and expectstatementsWe can run individual tests using grep pattern matching in
itdescription likeyarn hardhat test --grep storeWe can also use
it.onlykeyword which will ignore all other test cases and run only this test case
test/test-deploy.js
Hardhat Gas Reporter
Popular hardhat extension to see how much gas our funciton costs
Automatically gets attached to our tests
Can also specify which tokens to test gas for
hardhat.config.js
Solidity Coverage
A hardhat plugin that checks how many lines of our .sol code is covered in a test
Added in
hardhat.config.json the top asrequire("solidity-coverage")Also generates a folder and file called
coverageandcoverage.json
Hardhat Waffle
Advanced testing framework for solidity by hardhat
Last updated