How to Deploy Smart Contracts Using Hardhat: A Step-by-Step Guide

This guide will walk you through deploying a smart contract using Hardhat.

Prerequisites

Before we begin, make sure you have the following:

  1. Node.js installed (version 12.0.0 or later).

  2. NPM or Yarn.

  3. Basic knowledge of Solidity and smart contracts.

Step 1: Install Node.js and NPM (if not already installed)

Download Node.js from the official site and follow the instructions for installation. This will also install NPM (Node Package Manager), which is needed to install Hardhat and other dependencies.

Step 2: Create a New Hardhat Project

Open a terminal and create a new directory for your project, then navigate:

mkdir my-project
cd my-project

Initialize an empty project and install Hardhat:

npm init -y
npm install --save-dev hardhat

Once the installation is complete, run Hardhat to initialize your project:

npx hardhat

Hardhat will present a menu of options. Select Create an empty hardhat.config.js for simplicity.

Step 3: Install Additional Dependencies

You’ll need to install a few additional libraries that will help with writing and deploying contracts:

npm install --save-dev @nomiclabs/hardhat-ethers ethers
npm install dotenv

ethers.js helps interact with the Ethereum blockchain.

dotenv allows you to store environment variables securely (e.g., private keys).

Step 4: Write Your Smart Contract

Create a folder named contracts in the root of your project:

mkdir contracts

Inside the contracts folder, create a new Solidity file, MyContract.sol. Below is a simple example of an ERC20 token contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20 {
    constructor() ERC20("MyToken", "MTK") {
        _mint(msg.sender, 1000 * 10 ** 18);
    }
}

This contract creates an ERC20 token named "MyToken" with the symbol "MTK" and an initial supply of 1000 tokens.

Step 5: Configure Hardhat for Deployment

In the root of your project, locate or create the hardhat.config.js file. Configure it to deploy to a specific network. Add the following configuration:

require('@nomiclabs/hardhat-ethers');
require('dotenv').config();
module.exports = {
  solidity: "0.8.0",
  networks: {
    graphite: {
      url: process.env.RPC_URL,
      accounts: [process.env.PRIVATE_KEY]
    },
  },
};
  • PRIVATE_KEY is your wallet private key. Do not expose it publicly.

To securely store your API keys, create a .env file in the root of your project:

RPC_URL="https://anon-entrypoint-1.devgraphite.com"
PRIVATE_KEY="your-private-key-here"

Step 6: Write a Deployment Script

Create a folder named scripts and inside it, create a deploy.js script:

mkdir scripts

In scripts/deploy.js, add the following code:

async function main() {
    const [deployer] = await ethers.getSigners();
    console.log("Deploying contracts with the account:", deployer.address);
 
    const balance = await deployer.getBalance();
    console.log("Account balance:", balance.toString());
 
    const Token = await ethers.getContractFactory("MyToken");
    const token = await Token.deploy();
 
    console.log("Token deployed to:", token.address);
  }
 
  main()
    .then(() => process.exit(0))
    .catch(error => {
      console.error(error);
      process.exit(1);
    });

Step 7: Compile the Contract

Before deploying, compile your Solidity contract:

npx hardhat compile

If everything is set up correctly, this should compile without errors.

Step 8: Deploy the Contract

Run the deployment script:

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

This command will deploy your contract to the Graphite network using the configuration provided in hardhat.config.js.

Step 9: Verify the Deployment

Once the deployment is successful, Hardhat will print the contract address in the terminal. You can verify the contract on a Graphite Explorer by searching for the deployed contract address.

Step 10: Interact with the Contract

After deployment, you can interact with your contract using ethers.js. Here's an example of how to call a function on your contract:

  1. Create a new script called interact.js in the scripts folder.

async function main() {
    const Token = await ethers.getContractFactory("MyToken");
    const token = await Token.attach("your-deployed-contract-address-here");
 
    const totalSupply = await token.totalSupply();
    console.log("Total Supply:", totalSupply.toString());
 
    const name = await token.name();
    console.log("Token Name:", name);
  }
 
  main()
    .then(() => process.exit(0))
    .catch(error => {
      console.error(error);
      process.exit(1);
    });
  1. Run the script to interact with the contract:

npx hardhat run scripts/interact.js --network graphite

Last updated