Create ERC-20 Token in 5 Steps

·

Creating your own ERC-20 token on the Ethereum blockchain is a powerful way to launch digital assets for decentralized applications, communities, or projects. Whether you're building a new cryptocurrency, reward system, or utility token, this step-by-step guide walks you through the entire process—from environment setup to deployment and usage—with a focus on security, best practices, and real-world functionality.

By following these five clear steps, you’ll create a fully compliant, tested, and deployable ERC-20 token using industry-standard tools like Solidity, Hardhat, and OpenZeppelin.


Step 1: Set Up Your Development Environment

Before writing any code, you need a robust development setup. This ensures smooth compilation, testing, and deployment of your smart contract.

Essential Tools

To get started, install the following:

👉 Jumpstart your blockchain development with secure tools and workflows.

Install Hardhat

Run these commands in your project directory:

npm install --save-dev hardhat
npx hardhat

Choose "Create a JavaScript project" and follow the prompts.

Launch a Local Test Network

Use Hardhat’s built-in network or Ganache for local testing:

npx hardhat node

This starts a local Ethereum node with 20 pre-funded accounts—perfect for testing without spending real ETH.

Configure MetaMask

Connect MetaMask to your local or test network:

  1. Open MetaMask and click "Add Network."
  2. Enter:

    • Network Name: Hardhat Localhost
    • RPC URL: http://127.0.0.1:8545
    • Chain ID: 31337

Now you can send transactions from your development environment directly to your wallet.


Step 2: Write the ERC-20 Token Contract

With your environment ready, it’s time to write the smart contract. We’ll use OpenZeppelin Contracts, a battle-tested library that implements the ERC-20 standard securely.

Create Your Token File

Create a file named MyToken.sol in the contracts folder:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyToken is ERC20, Ownable {
    constructor() ERC20("MyToken", "MTK") {
        _mint(msg.sender, 1_000_000 * 10 ** decimals());
    }

    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }
}

What This Code Does

Using OpenZeppelin eliminates common vulnerabilities and ensures your token meets all six required ERC-20 functions: totalSupply, balanceOf, transfer, transferFrom, approve, and allowance.

Step 3: Test and Verify the Contract

Testing is crucial. A single bug can lead to irreversible loss of funds.

Compile the Contract

In your terminal:

npx hardhat compile

If successful, you’ll see no errors. Warnings should be reviewed but don’t block deployment.

Write a Simple Test

Create test/MyToken.js:

const { expect } = require("chai");

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

  beforeEach(async function () {
    [owner] = await ethers.getSigners();
    const MyToken = await ethers.getContractFactory("MyToken");
    myToken = await MyToken.deploy();
    await myToken.waitForDeployment();
  });

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

Run tests:

npx hardhat test

All tests should pass green—indicating your token works as expected.

👉 Ensure your smart contract is flawless before going live.


Step 4: Deploy Your Token

Now that your contract is tested, deploy it to a testnet like Sepolia.

Update Hardhat Configuration

Edit hardhat.config.js:

module.exports = {
  networks: {
    sepolia: {
      url: "https://sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID",
      accounts: ["YOUR_PRIVATE_KEY"]
    }
  },
  solidity: "0.8.20"
};
🔐 Never commit private keys to version control. Use environment variables instead.

Create Deployment Script

Add scripts/deploy.js:

async function main() {
  const [deployer] = await ethers.getSigners();
  console.log("Deploying contract with account:", deployer.address);

  const MyToken = await ethers.getContractFactory("MyToken");
  const myToken = await MyToken.deploy();
  await myToken.waitForDeployment();

  console.log("MyToken deployed to:", await myToken.getAddress());
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

Deploy:

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

Save the output contract address—you’ll need it next.


Step 5: Use Your New Token

Once deployed, interact with your token in real environments.

Add to MetaMask

  1. Open MetaMask → Assets → Import Tokens.
  2. Paste the contract address.
  3. Confirm symbol and decimals automatically populate.
  4. Click “Add Custom Token.”

Your balance should now appear in your wallet.

Interact With Functions

You can:

Monitor on Block Explorer

Go to Sepolia Etherscan, search your contract address, and:


Frequently Asked Questions (FAQ)

Q: What makes a token ERC-20 compliant?
A: An ERC-20 token must implement six core functions: totalSupply, balanceOf, transfer, transferFrom, approve, and allowance. Using OpenZeppelin’s library ensures compliance.

Q: Can I change my token after deployment?
A: No—smart contracts are immutable by default. For upgrades, consider using proxy patterns (e.g., OpenZeppelin Upgrades), but they add complexity.

Q: How much does it cost to deploy an ERC-20 token?
A: On Ethereum mainnet, gas costs vary ($50–$500+). On testnets like Sepolia, it’s free with test ETH. Use tools like GasNow to estimate fees.

Q: Do I need to pay for OpenZeppelin?
A: No—OpenZeppelin Contracts are open-source and free to use under MIT license.

Q: Can users lose tokens if sent to wrong contracts?
A: Yes—tokens sent to non-receiving contracts may be lost forever. Consider adding receive() or fallback reverts in future designs.

Q: Is auditing necessary before launch?
A: Absolutely. Even small bugs can result in massive losses. Hire professional auditors or use automated tools like Slither or MythX.


Final Thoughts

Creating an ERC-20 token in just five steps—setup, coding, testing, deployment, and usage—empowers developers to enter the world of decentralized finance and Web3 innovation. By leveraging trusted tools like Solidity, Hardhat, and OpenZeppelin, you ensure security, compatibility, and scalability.

Remember: Once deployed, your contract lives forever on-chain. Always test thoroughly, audit when possible, and monitor activity post-launch.

👉 Start building secure, scalable tokens today with professional-grade blockchain tools.