Creating an ERC20 Token Using Hardhat

Published: August 09, 2024 | Category: Blockchain Development

Prerequisites

Before starting, ensure you have:

  • An Alchemy account
  • Metamask installed in your browser
  • Some Sepolia test tokens (available from Alchemy's Sepolia Faucet)

Step 1: Create Project Structure

mkdir reddy

Navigate to the folder and initialize your project:

npm init

Step 2: Install Dependencies

npm install --save-dev hardhat

Create a Hardhat project:

npx hardhat init

Step 3: Project Setup

Create the necessary directories:

mkdir contracts mkdir scripts

Step 4: Install OpenZeppelin

npm install @openzeppelin/contracts

Step 5: Create Token Contract

Create MyToken.sol in the contracts folder:

// SPDX-License-Identifier: MIT pragma solidity 0.8.20; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MyToken is ERC20 { uint constant _initial_supply = 10000 * (10 ** 18); constructor() ERC20("MyToken", "MKT") { _mint(msg.sender, _initial_supply); } }

Step 6: Environment Setup

Install required packages:

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

Create .env file:

API_URL="https://eth-sepolia.g.alchemy.com/v2/your-api-key" PRIVATE_KEY="your-metamask-sepolia-private-key"

Step 7: Configure Hardhat

require('dotenv').config(); require("@nomiclabs/hardhat-ethers"); const { API_URL, PRIVATE_KEY } = process.env; module.exports = { solidity: "0.8.20", defaultNetwork: "sepolia", networks: { hardhat: {}, sepolia: { url: API_URL, accounts: [`0x${PRIVATE_KEY}`] } }, }
Important: Note the difference between single quotes ('') and backticks (``). Using the wrong one can cause errors.

Step 8: Deploy Script

Create deploy.js in the scripts folder:

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

Step 9: Deploy to Sepolia

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

After Deployment

  1. Copy the token address from the deployment output
  2. Open Metamask and switch to Sepolia network
  3. Click "Import Token"
  4. Paste the token address
  5. Your new tokens should now be visible in your wallet