Skip to main content
Create your own

Deploy and Interact with ERC-20 Tokens on a Testnet

Welcome back! Over the last few lessons, you have meticulously built and tested your MyToken contract, ensuring its core functions—including transfers and allowances—are secure and behave as expected within a local Hardhat environment. You've mastered the art of unit testing, which is the bedrock of secure smart contract development.

Now, it's time to take the most significant step yet in bridging theory and practice. In this lesson, we will move your token from the isolation of your local machine to a live, public blockchain. You will deploy your ERC-20 token to the Sepolia testnet, a global testing environment that mimics the conditions of the Ethereum mainnet. This process will make your token real, visible, and interactive for anyone with an Ethereum wallet.

Your goal is to deploy the MyToken contract using your Hardhat project and then interact with your newly minted tokens directly from your MetaMask wallet. This experience is fundamental to your goal of building applications for tokenized money, as it mirrors the exact process used to launch stablecoins and security tokens.

1. Preparing for Testnet Deployment

Deploying to a public network, even a testnet, requires a few more pieces than running things locally. While your local Hardhat network provided you with pre-funded accounts, a public network requires you to bring your own.

You will need three key components:

  1. An Account Private Key: To sign the deployment transaction, proving you authorize it and are willing to pay the gas fees.
  2. Testnet ETH: To pay the gas fees for the deployment transaction on the Sepolia network.
  3. A Network Endpoint (RPC URL): To provide your Hardhat project with a connection to the Sepolia blockchain.

From your work in Module 1, you should already have MetaMask installed and an account funded with Sepolia ETH. If your balance is low, you can acquire more from a public faucet.

The most critical new step is configuring your Hardhat project to securely handle your private key and connect to the Sepolia network. The best practice is to store sensitive information like private keys and API keys in a .env file, which is kept out of version control (e.g., via .gitignore).

The article "Deploying ERC20 Token With Hardhat" from Semaphore provides a comprehensive walkthrough of this setup process. We will follow its guidance to configure your project.

Deploying ERC20 Token With Hardhat: A Step-by-Step Guide

This guide details the exact steps needed to configure a Hardhat project for testnet deployment, from handling private keys to setting up the network configuration.

First, read the section "Configuring our Project for Deployment". This will guide you to install the dotenv package and create a .env file. Follow the steps to retrieve your private key from MetaMask and your Sepolia RPC endpoint from a node provider like Infura. Place these values into your .env file as instructed. Finally, update your hardhat.config.js file to include the Sepolia network configuration, which securely loads your credentials from the .env file.

After following the guide, your project directory should contain a .env file with your credentials:

PRIVATE_KEY="YOUR_METAMASK_PRIVATE_KEY"
SEPOLIA_RPC_URL="YOUR_INFURA_OR_QUICKNODE_SEPOLIA_ENDPOINT"

Note: Make sure your .gitignore file includes the line .env to prevent you from ever committing this file to a public repository.

Your hardhat.config.js should be updated to look like this:

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

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.8.20", // Ensure this matches your contract's pragma
  networks: {
    sepolia: {
      url: process.env.SEPOLIA_RPC_URL || "",
      accounts:
        process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [],
    },
  },
};

This configuration tells Hardhat that a network named "sepolia" exists, where to connect to it (url), and which account to use for sending transactions (accounts).

2. Creating the Deployment Script

With your project configured, the next step is to write a script that tells Hardhat how to deploy your contract. Hardhat projects include a scripts directory for this purpose. We will modify the existing deploy.js file (or create a new one).

The script will perform the following actions:

  • Get the contract factory for MyToken.
  • Specify the initialSupply for our token's constructor.
  • Deploy the contract, passing the initialSupply.
  • Wait for the deployment transaction to be confirmed on the blockchain.
  • Print the new contract's address to the console.

The Semaphore article provides a template for this script. We'll adapt it for our MyToken contract, which takes a single initialSupply argument.

Deploying ERC20 Token With Hardhat: A Step-by-Step Guide

This section explains the structure of a Hardhat deployment script.

Read the section "Creating Our Deploy Script". This explains how ethers.getContractFactory and deploy work. We will use a slightly more modern version of this script.

Now, replace the contents of your scripts/deploy.js file with the following code. Note the use of ethers.parseEther to correctly handle the 18 decimals for our token supply.

const hre = require("hardhat");
const { ethers } = require("hardhat");

async function main() {
  // Set the initial supply to 1,000,000 tokens
  const initialSupply = ethers.parseEther("1000000");

  console.log("Deploying MyToken contract with an initial supply of 1,000,000 tokens...");

  // Get the contract factory and deploy the contract
  const myToken = await hre.ethers.deployContract("MyToken", [initialSupply]);

  // Wait for the deployment to be confirmed
  await myToken.waitForDeployment();

  const contractAddress = await myToken.getAddress();
  console.log(`MyToken deployed to: ${contractAddress}`);
}

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

3. Deploying to Sepolia

Everything is now in place. You have your credentials secured, your Hardhat configuration updated, and your deployment script ready.

To start the deployment, run the following command in your terminal. This tells Hardhat to execute your deploy.js script on the sepolia network we defined earlier.

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

When you run this command, two things will happen:

  1. MetaMask Confirmation: Your MetaMask extension will pop up, asking you to confirm the transaction. This is you, as the owner of the private key, signing the contract deployment transaction. It will show the estimated gas fee in Sepolia ETH. Click "Confirm".
  2. Terminal Output: Your terminal will first print the "Deploying..." message. After you confirm in MetaMask and the transaction is mined, it will print the final message with your live contract address.
An example of the MetaMask interface confirming a contract deployment transaction. You will see a similar pop-up to approve the gas fee for deploying your token.

Once successful, you will see output like this in your terminal:

Deploying MyToken contract with an initial supply of 1,000,000 tokens...
MyToken deployed to: 0x... (your new contract address will be here)

Congratulations! Your ERC-20 token is now live on the Sepolia testnet. Copy the contract address from your terminal; you will need it for the next step.

4. Viewing and Interacting with Your Token

Your token exists on the blockchain, but your wallet doesn't know about it yet. We need to tell MetaMask to track your new token. This is where the "aha!" moment happens.

The process involves importing the token using its contract address. The following video from QuickNode provides a clear visual demonstration of this process.

How to create and deploy an ERC20 token

This video shows how to find your deployed contract on a block explorer and import it into MetaMask. While the deployment in the video uses Remix, the MetaMask and Etherscan steps are identical to what you need to do.

First, watch from this segment to see how to take your contract address and find it on the Etherscan block explorer. Then, watch the crucial part from importing the token, where the presenter copies the token address, opens MetaMask, and uses the "Import tokens" feature.

Follow these steps to add MyToken to your wallet:

  1. Open MetaMask and ensure you are on the Sepolia network.
  2. Go to the "Assets" tab and click Import tokens.
  3. On the "Import tokens" page, paste your deployed contract address into the "Token contract address" field.
  4. MetaMask will automatically query the blockchain, find your contract, and fill in the "Token symbol" (MTK) and "Token decimal" (18).
  5. Click Add custom token, then Import tokens.

You will now see 1,000,000 MTK in your MetaMask wallet under the "Assets" tab!

To complete the experience, let's perform a transfer. This proves that your token is fully functional in a live environment.

  1. In MetaMask, create a new account (e.g., "Account 2"). You can do this by clicking the account circle icon in the top-right and selecting "Create account".
  2. Copy the address of Account 2.
  3. Switch back to your main account (the one that deployed the contract).
  4. Click on your MTK token asset, then click Send.
  5. Paste Account 2's address into the recipient field.
  6. Enter an amount to send (e.g., 100 MTK) and click Next.
  7. Confirm the transaction in MetaMask (you will pay a small gas fee in Sepolia ETH).

After the transaction confirms, switch to Account 2. You will need to import the MTK token in Account 2 as well (using the same contract address). Once imported, you will see the 100 MTK balance.

Conclusion

In this lesson, you successfully transitioned from local development to a live blockchain environment. You took a fully tested smart contract, configured your project for a public network, and deployed it using a Hardhat script. Finally, you interacted with your live token using MetaMask, the same way any end-user would. This process of deploying and managing a contract on a testnet is directly analogous to how you would manage a data model or BI report in a UAT environment before pushing it to production—it's the final, crucial validation step in a realistic setting.

Key Takeaways:

  • Testnet Deployment Configuration: Securely managing private keys and network endpoints is done using a .env file and updating hardhat.config.js.
  • Deployment Scripts: Hardhat uses scripts in the /scripts directory to automate the deployment process, making it repeatable and reliable.
  • Gas Fees: Every transaction that changes the state of the blockchain, including contract deployment and token transfers, requires a gas fee paid in the network's native currency (ETH).
  • Importing Tokens: Wallets like MetaMask are not automatically aware of new tokens; you must import them using their unique contract address.
  • Live Interaction: Once deployed, your ERC-20 token is a fully-fledged digital asset on the Sepolia network that can be transferred between any two Ethereum accounts.

You have now completed the entire lifecycle of a basic ERC-20 token. In the next module, we will build on this foundation by exploring how to manage and upgrade smart contracts, starting with implementing role-based access control to grant special permissions—a critical feature for any tokenized asset that requires administration.

Can't find a good explanation? Sign up and we'll make it for you

Sign up