Deploy a contract with Hardhat

This section is a guide on how to deploy a smart contract on the TAOVM using Hardhat.

Hardhat is a popular smart contract development frameworks. It is used in the TAOVM rollup as a default for deploying and automatically verifying smart contracts.

Prerequisites

Before you begin, you will need to prepare the following:

Initialize Hardhat project

  • mkdir <project-name>;cd <project-name>

  • Initialize a project with Hardhat: npx hardhat.

  • Next, (… To avoid failure … please go slow with this cli dialogue…)

  • Press <ENTER> to set the project root.

  • Press <ENTER> again to accept addition of .gitignore.

  • Type n to reject installing sample project's dependencies.

    The idea here is to postpone installing dependencies to later steps due to a possible version-related bug.

Configure Hardhat project

Open the hardhat.config.js file and paste the below code:

require("dotenv").config();
require("@nomicfoundation/hardhat-toolbox");

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
solidity: "0.8.9",
paths: {
    artifacts: "./src",
},
networks: {
    taovmTestnet: {
    url: `https://testnet-rpc.taovm.io`,
    accounts: [process.env.ACCOUNT_PRIVATE_KEY],
    },
},
};

Add smart contract

  • Create a new file, in the contracts folder, named Counter.sol: touch contracts/Counter.sol.

  • Copy the below code and paste it in the Counter contract code:

    //SPDX-License-Identifier: MIT
    pragma solidity ^0.8.9;
    
    contract Counter {
    uint256 currentCount = 0;
    
        function increment() public {
            currentCount = currentCount + 1;
        }
    
        function retrieve() public view returns (uint256){
            return currentCount;
        }
    }

Add deploy script

  • Create a new file in the scripts folder deploy-counter.js: touch scripts/deploy-counter.js.

  • Add the code below to the deploy-counter.js file:

    const hre = require("hardhat");
    
    async function main() {
        const deployedContract = await hre.ethers.deployContract("Counter");
        await deployedContract.waitForDeployment();
        console.log(
            `Counter contract deployed to https://testnet-scan.taovm.io/address/${deployedContract.target}`
        );
    }
    
    main().catch((error) => {
        console.error(error);
        process.exitCode = 1;
    });

Compile and deploy

  • Before compiling the contract, you need to install the toolbox. You may need to change directory to install outside the project. Use this command:

    npm install --save-dev @nomicfoundation/hardhat-toolbox
  • Compile your contract code (i.e., go back to the project root in the CLI):

    npx hardhat compile
  • Now run the scripts:

    npx hardhat run scripts/deploy-counter.js --network taovmTestnet

Last updated