How to Setup Hardhat and compile, test and deploy contracts using it ?

This tutorial is about how to setup Hardhat and how to compile, test and deploy smart contract using this.

Firstly, Hardhat is basically a development environment to compile, deploy, test and debug Ethereum smart contracts. It serves as an alternative to truffle. However, it is a lot better than the latter. Hardhat had a built-in Hardhat Network (like Ganache, your local blockchain) designed for development. Its main functionality focuses around Solidity, debugging, featuring stack traces, console.log() and explicit error messages when transactions fail.

Hardhat is used through local installation in your project.

To install it, create an npm project by going to an empty folder, running npm init in the terminal.

Then, run npm install — save-dev hardhat to install hardhat as a development dependency.

Create your Hardhat project by running npx hardhat in project folder.

Then you’ll get two options:

1. Create a sample project

2. create an empty hardhat.config.js file

If you select the second option, an empty hardhat.config.js file will be created and you can then configure the dependencies as per your requirements (we’ll discuss about this in next article).

Follow the steps to get an idea how to compile, test and deploy contracts.

Select the option to create a sample project.

Then, you’ll have to install hardhat-waffle and hardhat-ethers.

You can use hardhat-waffle plugin to build tests for smart contract using Waffle in Hardhat and hardhat-ethers brings to you the Ethereum library ethers.js that allows you to interact with the Ethereum blockchain in a easier way.

You can install it by running npm install — save-dev @nomiclabs/hardhat-ethers ethers chai @nomiclabs/hardhat-waffle ethereum-waffle

To get an idea about what’s there in hardhat for you, run npx hardhat in your project folder. This will give you a list of built-in tasks.
To execute any task, say you want to check version( — version), run npx hardhat — version

Or if you want to execute accounts, run npx hardhat accounts

Compiling your contracts: You’ll find a sample contract in our project. However, you can add your own. To compile it, simply run: npx hardhat compile

The sample project comes with tests that use waffle and ethers.js . You would see a sample-test.js in test folder. You can write your own tests in your project.

You can run your tests with npx hardhat test.

Next, to deploy your contracts we’ll use Hardhat script. The sample code is there inside scripts/ in the sample-script.js file

Run it with npx hardhat run scripts/sample-script.js

And whoa! You’re done. You have deployed contract to the local Hardhat Network.

Blockchain Developer at Rapid Innovation