Smart Contract Deployment Made Easy with Hardhat

Introduction

Hello reader! Welcome to the world of smart contracts deployment. Smart contracts, an important element of blockchain technology, have completely changed how we conduct transactions and automate agreements. Above all, a smart contract is a self-executing digital contract with predefined rules and conditions. Because of its decentralised structure, it ensures transparency and eliminates the need for middlemen, making it an excellent option for secure and trustless communications.

To simplify the implementation of smart contracts on blockchains, a powerful development environment like Hardhat is needed. Hardhat offers flexibility, reliability, and extensive tooling support, making it an excellent choice for Ethereum and Polygon projects. It doesn't matter whether you are a newbie who is interested in blockchain programming or an experienced developer looking to explore more depths of blockchain and smart contracts, this article will guide you through the steps to deploy your smart contract with ease. Let's begin our journey to unlock the potential of smart contract deployment using Hardhat.

Smart Contract Deployment made easy with Hardat

What is Hardhat?

Hardhat is a powerful development environment and task manager created exclusively for Ethereum-based smart contract development. It simplifies the creation, testing and deployment of smart contracts on various Ethereum Networks, including Polygon. Hardhat provides a user-friendly design and essential tools to make the smart contract deployment journey smoother and more efficient.

What sets Hardhat apart, is its wide feature set. It comes equipped with a solidity compiler which makes it simple to compile the smart contract into bytecode for deployment. Additionally, Hardhat offers built-in support for writing unit tests, allowing us to ensure the reliability of the contracts before deploying them on the live network.

Advantages of Hardhat

Let's discuss the several advantages which Hardhat offers when it comes to contract deployment.

  1. Simple Testing Environment: Hardhat provides a strong testing environment which makes the process of writing tests of our smart contracts easier. Writing comprehensive unit tests become a simple task for all developers, ensuring the contracts perform their function as intended and are free from bugs.
  2. Easy Configuration and Adaptability: Hardhat's adjustable configurations enable developers to tune their development environment to the exact needs of their project. This flexibility allows us to fine-tune settings, integrate plugins, and maintain control over our development workflow.
  3. Built-in TypeScript Support: TypeScript compatibility is an experience changer for developers who are looking for improved code readability, autocompletion, and type-checking.
  4. Rick Plugin Ecosystem: Hardhat's plugin ecosystem provides us with a world of options for increasing the platform's capabilities. We can easily integrate additional tools, libraries, and services to enhance our smart contract development process.
  5. Compatibility with multiple Networks: Hardhat's support for multiple Ethereum networks, including Polygon, makes it a reliable choice for cross-chain development.

Thus, we can easily say that due to all the benefits and features provided by Hardhat. It can be considered the ideal choice for developers when it comes to contract creation and deployment. Now moving forward, let's jump straight into how we can create a basic smart contract and deploy it to the Polygon Testnet Network.

Setting Up the development environment

To code in Hardhat, first, we would require to set up a development environment.

Install VS Code, Node.js and npm

Before we start our journey of deploying smart contracts on the polygon network we need to be prepared with the software that we require. In this tutorial, we will be using Visual Studio Code as IDE and node.js, so need to make sure that we have both of these software installed on our computer. Don't worry, it is not as complicated as it may sound.

Just download Visual Studio Code and Node.js (LTS version) from their official websites.

After your download is successful you need to run the installer for both the software and follow the installation wizard's instructions. If you are worrying about npm, then Node.js comes bundled with npm, so you don't need to worry about separately installing npm.

Create a new project directory and initialize it with npm

After we have installed the software required we'll set up a new project directory where we'll keep all our smart contract files and configurations. Let's create a clean and organized space to work on our Polygon smart contracts.

Step 1. Create a new folder and name it Hardhat_Project. We will be keeping all our code from smart contract creation to deployment in this folder.

Step 2. Open the newly created project in the command prompt(cmd).

Step 3. After we have opened our folder in the command prompt. We need to initialize a node project with npm in that folder. To initialize the project with npm we need to run the command provided below in the terminal.

npm init -y

Running this command will create a package.json file in our blank folder 'Hardhat_Project'. The package.json file will be visible in the folder.

Folder Structure

You can see the package.json file inside the Hardhat_project folder. This file will help us manage our project dependencies and scripts.

Please keep in mind that from now on Visual Studio Code will be referred to as vs code in the article.

Install Hardhat and essential plugins for the project

Hardhat is the backbone of our smart contract development. It comes with a range of useful plugins, including those for Polygon development. Let's install Hardhat and the essential plugins for our project-

Step 1. In the same terminal, where you wrote the code to initialize node.js, install hardhat into that folder by running the below command

npm install --save-dev hardhat

Step 2. After hardhat gets installed, now run the command provided below in the command prompt to see some options to facilitate project creation

npx hardhat

After running the command your command prompt screen should look like this -

Hardhat option wizard

Step 3. You are free to choose any of the three options. If you select the first option Create a JavaScript project then it will automatically set up a sample project with all the pre-required folders. If you select the second option, then the project will be created in TypeScript. But in this tutorial we will be building the project from scratch so here we will be selecting the third option Create an empty hardhat.config.js option. It will create an empty file hardhat.config.js in the folder. After this, the folder structure will appear like this -

Folder Structure

Now after setting up a hardhat project, we need to install an important plugin which will be required later in the project. We will be using the command prompt to install that plugin. Simply in the command prompt, you need to run

npm install @nomicfoundation/hardhat-toolbox

Congratulations, you have completed your hardhat setup, Now create three empty new folders with names contracts, test and scripts. Be sure to use the exact same names as I mentioned here for the folders. After creating the folders, your project's folder structure should look like this -

Folder Structure

Congratulations, now you are all set up to write your first smart contract in solidity.

Write the Smart Contract

After setting up the development environment and installing hardhat and important plugins we can start writing our smart contract. In the contracts folder create a new file with the name MyToken and save the file with the extension (.sol) which is used to save solidity contracts. We will be creating a contract which will create tokens and allow users to transfer tokens among themselves. In the file that you created paste the solidity code written below

// MyToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

contract MyToken {
    string public name;
    string public symbol;
    uint8 public decimals;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;

    event Transfer(address indexed from, address indexed to, uint256 value);

    constructor(
        string memory tokenName,
        string memory tokenSymbol,
        uint8 tokenDecimals,
        uint256 initialSupply
    ) {
        name = tokenName;
        symbol = tokenSymbol;
        decimals = tokenDecimals;
        totalSupply = initialSupply * 10**uint256(tokenDecimals);
        balanceOf[msg.sender] = totalSupply;
    }

    function transfer(address to, uint256 value) external {
        require(balanceOf[msg.sender] >= value, "Insufficient balance");
        balanceOf[msg.sender] -= value;
        balanceOf[to] += value;
        emit Transfer(msg.sender, to, value);
    }
}

Explanation

MyToken.sol is a simple smart contract which creates a fungible token. The code contains the following key elements -

  • name, symbol, decimal and totalSupply, are the state variables that store essential information about our fungible token.
  • balanceOf is a mapping element that keeps track of token balances for each address.
  • The constructor which gets executed during the time of contract deployment, takes for the first time takes in four parameters.
  • The transfer function allows users to transfer tokens to other ethereum addresses while updating their respective token balance.
  • The Transfer event is triggered every time a token transfer takes place, keeping a log of the transfer.

This is a simple smart contract of Token creation and transfer. Now let's compile our smart contract

Compile the Smart Contract

Now that we have written our smart contract, it is time to compile the contract. To compile the contract open up the terminal or command prompt, and make sure you are in the project directory. To compile the contract, execute the command -

npx hardhat compile

compile smart contract

After successfully compiling the smart contract two new folders 'artifacts' and 'cache' will be created automatically. The new folder structure of the project will appear like this -

Folder Structure

We will be discussing these two folders later in the article.

If you are a beginner then there are possibilities of facing a few problems during the compilation process. The most common problems that may occur during the compilation process are as follows -

  1. Compiler Version Mismatch:
    Problem: You may see an error related to the Solidity compiler version being used.
    Solution: Check your contract's Solidity version specified in the pragma statement (e.g., pragma solidity ^0.8.0;) and ensure it matches the version supported by Hardhat. You can update the Solidity version in your contract or Hardhat configuration accordingly.
  2. Missing Dependencies:
    Problem: Hardhat might raise errors due to missing dependencies or plugins required for compiling.
    Solution: Double-check that you've installed Hardhat and the necessary plugins for Polygon development as mentioned in the previous section. Ensure you have also installed Hardhat's dependencies with npm install.
  3. Incorrect File Path:
    Problem: Hardhat cannot find your smart contract file for compilation.
    Solution: Ensure your smart contract file is located in the correct directory (contracts folder, as we specified earlier) and has the correct file extension (.sol). Also, check that your terminal is in the project root directory.
  4. Syntax Errors:
    Problem: You may encounter syntax errors in your smart contract code.
    Solution: Carefully review your contract code for any typos, missing semicolons, or incorrect keywords. Ensure you have followed the correct Solidity syntax.
  5. Compiler Warnings:
    Problem: During compilation, you might receive warnings about potential issues in your contract code.
    Solution: Pay attention to these warnings, as they might indicate code optimizations or potential pitfalls. Review your contract code and make any necessary adjustments to improve efficiency and security.

Keeping these errors and their solutions in mind you can easily troubleshoot these errors if they occur.

Configure Hardhat for Polygon

When we run the hardhat project, it searches the closest hardhat.config.js file starting from the current working directory we are present. This file contains the full Hardhat configuration (config, plugins, and custom tasks) that are required by the project.

To deploy our recently created smart contract on any blockchain network, we need to configure the Hardhat to work with the desired network. It sounds a little confusing and difficult at first, but don't worry all we need to do is update the hardhat.config.js file. In this tutorial, I will be configuring the hardhat project with the Polygon network and deploying the smart contract on Polygon. You can configure your project with any network you want. Let me show you what you need to update in the hardhat.config.js file to connect to the Polygon network.

require("@nomicfoundation/hardhat-toolbox")
module.exports = {
  solidity: "0.8.19",
  networks: {
    hardhat : {},
    polygon_mumbai : {
      url : "https://polygon-mumbai.g.alchemy.com/v2/{api_key}",    // rpc url
      accounts : [
        `0x${"your account's private key"}`    //account's private key containing MATIC
      ]
    }
  }
};

This is how the hardhat.config.js file should look after the update.

Explanation: In the file, we are first importing the plugin @nomicfoundation/hardhat-toolbox, which we additionally installed in the previous section. After that, we are manually adding the network that we need. In our case, we need to add the Polygon network. To add the Polygon network to the Hardhat project, you will need the RPC-URL along with your API. If you already have the RPC URL, you need to paste it into the URL in the file, if you don't have the RPC URL and the API key, you can set it up. You can visit the Alchemy official site and Sign up to get the RPC URL and your API key. You will also be requiring a valid ethereum address with some Mumbai faucet MATIC in it. You can read my previous article How to Connect to Polygon Network Using C#, here you can find a step-by-step guide for obtaining the RPC URL and API key and how to create an Ethereum account connected to Polygon Network with some Matic.

After you have the ethereum account with some Matic, you need to get the private key. Visit your metamask wallet and export the private key. Make sure you do not share the private key with anyone and keep it safe.

Export Private Key

After clicking Show Private Key type in your password to get the private key.

This is all the configuration you will be ending to connect to the Polygon Network. By configuring Hardhat to work with Polygon and understanding the different network options available, you'll have the flexibility to test your contracts in a safe environment and deploy them confidently to the live Polygon network when ready.

Deploy the Smart Contract

After connecting the Hardhat project to the Polygon network we are now ready to deploy the smart contract to the chain. To deploy the smart contract that we compiled earlier on the Polygon Testnet chain we need to write a deployment script in Hardhat. This script will handle the deployment process and interact with the network.

To create the deployment script create a file named deploy.js inside the scripts folder. After creating the deploy.js file, write the following code inside the file.

const hre = require("hardhat");
async function main(){
    
    const MyToken = await hre.ethers.getContractFactory("MyToken");
    const my_token = await MyToken.deploy("My Token","MTK",18,10000);  // deploy with constructor values

    //After successful deployment print the address of the Token
    console.log(`Contract is deployed at address${await my_token.target}`)  

}
main().catch((error)=>{
    console.log(error);
    process.exitCode = 1;
})

Explanation: This script will create an instance of the contract and deploy the contract using the deploy function. During the deployment process, we are providing the token name as My Token, token symbol as MTK, decimal as 18 and initial supply as 10000 which are required by the constructor of the contract during deployment. After the successful deployment, we are printing the address of the currently deployed contract.

Now to deploy the contract you need to open up the terminal and run the command -

npx hardhat node

Running the above command will start a hardhat node locally on your computer.

After that open up a new terminal or command prompt and run the command.

npx hardhat run scripts/deploy.js --network polygon_mumbai

This command will deploy the contract to the polygon testnet network using the RPC URL and the API key that you provided in the hardhat.config.js file.

Deploy Contract

After the successful deployment, you will be getting the address of the deployed contract. You can check your contract's successful deployment on Polygon Scan Mumbai using the address of the contract that you received.

Polygon Scan

The contract address and the ABI of the contract which you can find in the artifacts\contracts\MyToken.sol\MyToken.json file will be used when we want to communicate with the deployed contract using our code i.e., to call the functions of the contract there is a need to have the contract address and ABI of the contract. You can also find the bytecode of the contract in the same file.

Congratulations! Your smart contract is now live and ready to be utilized by users and other decentralized applications on the Polygon blockchain.

Test the Smart Contract

Testing is an important stage in our smart contract development since it ensures that our smart contract functions as it is supposed to. Hardhat provides a powerful testing framework that allows us to write comprehensive tests for our smart contracts. To write some basic tests to check our smart contracts functionality, inside the test folder create a blank MyToken_test.js file inside that file we will be writing our code.

Let's write some basic tests for the contract.

// MyToken_test.js
const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("MyToken", function () {
  let myToken;
  let owner;

  beforeEach(async function () {
    [owner] = await ethers.getSigners();    // getting the signer's details
    const MyToken = await ethers.getContractFactory("MyToken");
    myToken = await MyToken.deploy("MyToken", "MTK", 18, 10000);    // deploying the contract
  });

  it("Should have correct name, symbol, and decimals", async function () {
    expect(await myToken.name()).to.equal("MyToken");
    expect(await myToken.symbol()).to.equal("MTK");
    expect(await myToken.decimals()).to.equal(18);
  });

  it("Should assign the total supply to the deployer", async function () {
    const totalSupply = await myToken.totalSupply();
    const deployerBalance = await myToken.balanceOf(await owner.address);
    expect(deployerBalance).to.equal(totalSupply);
  });

  it("Should transfer tokens correctly", async function () {
    const initialBalance = await myToken.balanceOf(owner.address);
    const recipient = "0x1234567890123456789012345678901234567890";     //some random address
    const amount = BigInt(100);

    await myToken.transfer(recipient, amount);

    const finalBalance = await myToken.balanceOf(owner.address);
    expect(finalBalance).to.equal(initialBalance - amount);

    const recipientBalance = await myToken.balanceOf(recipient);
    expect(recipientBalance).to.equal(amount);
  });
});

Explanation: In the above test file we are running three tests for our smart contract, The first test is to check that the token name, token symbol and decimal values should be the same as we provide during the deployment or we can say during the constructor call. The second test is checking that the total supply of the token should be assigned o the contract creator and the third test is to check whether the token transfer is functioning properly or not.

To run these tests we need to execute a command in the terminal.

Open up your terminal and execute the command -

npx hardhat test --parallel

This command will execute all three tests parallelly. After the successful execution of the test the terminal should look like this -

test smart contract

A successful test run gives you confidence that your smart contract functions as expected, while any test failures indicate potential issues that must be addressed.

Conclusion

Finally, taking advantage of Hardhat for deploying smart contracts on the Polygon network opens up a world of possibilities for blockchain developers. This article has covered the main procedures for configuring the development environment, writing, compiling, deploying, and testing a basic smart contract on the Polygon Testnet. Developers may securely create smart contracts on the live network and contribute to the decentralised application ecosystem by exploiting Hardhat's capabilities and connecting to Polygon.

FAQ's

Q. What is Polygon, and why is it an attractive choice for smart contract deployment?

A. Polygon, formerly known as MATIC, is a blockchain scaling solution and a layer 2 network for Ethereum. It offers several advantages for smart contract deployment, including reduced transaction costs and increased throughput by combining multiple transactions into a single batch. It's high performance and cost-effectiveness make it a preferred platform for various industries and projects seeking secure and efficient communication through smart contracts.

Q. What is Hardhat, and why is it recommended for Ethereum and Polygon projects?

A. Hardhat is a powerful development environment and task manager specifically designed for Ethereum-based smart contract development. It simplifies the creation, testing, and deployment of smart contracts on various Ethereum networks, including Polygon. Hardhat offers a user-friendly design, extensive tooling support, and built-in support for writing unit tests, ensuring reliable and efficient smart contract deployment. Its compatibility with multiple networks and TypeScript support make it an ideal choice for developers exploring the potential of Ethereum and Polygon.

Q. What are the benefits of using Hardhat's testing environment for smart contract deployment on Polygon?

A. Hardhat offers a strong testing environment that simplifies the process of writing tests for smart contracts. The benefits of using Hardhat's testing environment for smart contract deployment on Polygon include -

  1. Writing comprehensive unit tests becomes easier, ensuring that the contracts perform their intended functions and are free from bugs.
  2. Developers can test their contracts locally using the Hardhat node, enabling them to simulate real-world scenarios before deploying to the live network.
  3. Hardhat's built-in support for testing allows for quicker identification and resolution of issues, ensuring the smart contracts are reliable and secure.
  4. By using TypeScript compatibility, developers can enhance code readability, autocompletion, and type-checking during the testing process, leading to more robust contracts.


Similar Articles