Comprehensive Hardhat Solidity Environment Setup for Beginners

Said
Coinmonks
7 min readJul 24, 2022

--

For most developers who just start learning Web3 & Solidity, choosing the best development environment can be overwhelming and could become the learning progress barrier. In this article, we will learn how to setup your development environment using Hardhat.

Hardhat image from Hardhat Image

What Is Hardhat?

Hardhat is a development environment for dApps. It consists of different components for editing, compiling, debugging, testing and deploying your smart contracts and dApps, all of which work together to create a complete development environment.

Hardhat is unopinionated in terms of what tools you end up using, but it does come with some built-in defaults. We will use the built-in defaults and some additional plugins. The plugins you need for most scenarios are covered in this setup.

System Requirements

Since Hardhat libraries and tools are written in JavaScript. you have to install Node.js and npm in your system. And also any code editor should work, but I personally prefer Visual Studio Code editor since it have Solidity + Hardhat extension that provide Solidity language support and Hardhat integration.

Setting up a Hardhat project

Create new empty directory, then go inside. First we initialize fresh Node.js project using npm :

Then you need to install Hardhat:

Now run npx hardhat , then you will be shown some options:

options to facilitate project creation

Select “Create a Javascript project” option, then select (y) to add .gitignore . Then you will have project initialized with the following structure:

These are the default paths for a Hardhat project.

  • contracts/ is where the source files for your contracts should be.
  • test/ is where your tests should go.
  • scripts/ is where simple automation scripts go.

Dependencies and Plugins Installation

Now we will install the necessary dependencies and some useful plugins.

Hardhat Toolbox

The most important of these dependencies is the Hardhat Toolbox, a plugin that bundles almost all the things you need to start developing dApps. Run the following command:

This plugin are so essential, because it bundles all the commonly used packages that previously we have to install separately to start developing with Hardhat like:

  • hardhat-ethers plugin to interact with contract using ethers.js.
  • Chai and Mocha for testing your smart contracts.
  • hardhat-etherscan plugin to verify the source code of smart contracts.
  • hardhat-gas-reporter plugin for gas metrics on the gas used by smart contracts.
  • Measure tests coverage with solidity-coverage.

We will talk about each of these plugin usage and functionality later.

Note: please install @hardhat-toolbox with version greater than 1.0.2 to avoid installation issues.

Prettier for Solidity

While you can arguably say this plugin may not be essential, but using prettier for automatically formatting your code as early as possible is a good practice for code readability and following best practices to write your Solidity code.

Run the following command to both install prettier and prettier-plugin-solidity :

(optional) you can override prettier default configuration with your own preferences, create .prettierrc file in root project directory and put the configuration there:

Those lines are just example based on my preference, you can read more about what you can configure in prettier docs.

Hardhat Deploy

This Hardhat plugin adds a mechanism to deploy contracts to any network, keeping track of them and replicating the same environment for testing, and a lot of features that improve developer experience in deploying smart contracts.

hardhat-deploy allows you to write deploy scripts in the deploy folder. then execute with deploy command instead of default run scripts.

To install hardhat-deploy run the following command:

Dotenv

dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Since we will work a lot with external API and wallet when developing dApps. It is best practice to store your wallet private key and API key on .env located in your root project directory then load it in your code programmatically.

Note: please put your .env in your .gitignore file, and always use separate “not so important” wallet for your development. Never share and expose your wallet private key!

And that should finish dependencies and plugin installations.

Hardhat Configuration

Hardhat project settings management centralized in hardhat.config.js . a .jsfile generated when you initialize the project earlier. We will mostly working in this file when configuring development environment.

Importing Plugins

You can simply importing all the plugins with require lines at the top of hardhat.config.js

Configuring the Compiler

If you need to customize the Solidity compiler options, you can change it trough solidity field in your hardhat.config.js :

You can simply define single compiler, or incase you need multiple compilers you can put it in compilers array as shown in the code sample.

Network Configuration

Hardhat comes built-in with a special network called hardhat . When using this network, an instance of the Hardhat Network will be created when you run a task, deploy, or test smart contracts.

While built-in network is useful for fast deployment and testing, in real scenario you want the smart contracts to be accessible in real network, Hardhat support you to connect JSON-PRC based networks also to fulfil that scenario.

The networks config field in hardhat.config.js is where you put the network configurations.

You can customize which network is used by default when running Hardhat by setting the config’s defaultNetwork field. If you omit this config, its default value is "hardhat". but I prefer to explicitly define it to "hardhat" .

Then in the networks field you define all the network you want to use, in this case Rinkeby. Put the url JSON-RPC, accounts private key, and chainId . you can read more about network configuration in the docs.

Gas Reporter

hardhat-gas-reporter provide report about gas usage per unit test, metrics for method calls and deployments and custom national currency costs. These information are crucial and useful for you to create optimized smart contracts.

At minimum, you just need to put gasReporter field with enabled : truein the hardhat.config.js , but you can also customize the gasReporter to use your own currency, or write the output in the project directory.

If you want to use custom currency like “USD”, you need to create CoinMarketCap account and get the API KEY, provide the key in the coinmarketcap field and you good to go.

Etherscan Verify

hardhat-etherscan plugin help you to verify the source code for your Solidity contracts on Etherscan. Thanks to Hardhat and Hardhat Toolbox, we just need to provide the apiKey in etherscan field in the config file.

You can get the API KEY buy simply create Etherscan account.

Setting Account for Deployment

For hardhat-deploy to work, we need to define namedAccounts field for deployer. It is basically stating which address we use in the wallet as smart contracts deployer, in this case I select the first account.

And that should finish dependencies and plugin installations.

Development Flow Setup

The development cycle with Hardhat generally start from developing the Solidity smart contracts, then defining the test units, creating deploy scripts and finally running the pipeline.

While for developing and defining test units are already clearly defined in Hardhat docs, the deploy scripts process are different, thus we need to create some adjustment to setup our pipeline.

Verify Scripts

First we create the verify scripts in new utils folder you need to create in root project directory, to easily import it and put in our deployment pipeline.

Create Deploy Scripts

Create a new directory called deploy in the project root, and in that directory create a new file called 01-deploy-sample.js.

01-deploy-sample.js basically hardhat-deploy version of scripts/deploy.js file generated when we initialize the project. The deployment will be run alphanumerically, so naming convention will be crucial, we use numbering at the start of the .jsfile for this.

Note: since initially we are not deploying smart contracts on test or live network, we should comment the verify line.

Running Tests

Using the generated Lock.sol contract, and generated testing units intest folder. We now can run :

And the result should also include Gas Report :

Test result with Gas Report

Checking Testing Coverage

Checking testing coverage to make sure unit test cover all smart contracts functionality :

Coverage output

Running Deployments

Now you can run deploy scripts using the following command:

deployment should run with the following output (based on your deploy scripts)

Deploy Output

Next Steps

Congratulations! Now you can focus on writing your smart contracts and testing units, and following the cycle of develop, test and deploy using Hardhat. From here, you can enhance your knowledge on Solidity for development. Chai and Mocha for testing your smart contracts.

If you’d like to learn how to use Metamask along with Hardhat and Solidity, you can also follow this beginner “hello world” tutorial from Alchemy

You can check the full project code in this github repo.

New to trading? Try crypto trading bots or copy trading

--

--

Said
Coinmonks

Web3 & Blockchain Enthusiast & Learner. Telecommunication Engineering and DevOps background