DeveloperBreeze

Creating your own ERC-20 token is one of the most common tasks in Ethereum smart contract development. The ERC-20 standard defines a set of rules that all Ethereum tokens must follow, ensuring compatibility with existing applications like wallets, exchanges, and more. OpenZeppelin provides a robust, secure, and widely-used library of smart contract components that simplify the process of creating an ERC-20 token. In this tutorial, we will guide you through the steps to create and deploy your own ERC-20 token using OpenZeppelin.

Prerequisites

Before you begin, make sure you have the following:

  • Node.js and npm: Node.js is required to run the development environment, and npm is used to manage packages.
  • Truffle or Hardhat: These are development frameworks for Ethereum. You can use either one, but for this tutorial, we will use Hardhat.
  • MetaMask: A browser extension wallet to interact with your smart contract.
  • OpenZeppelin Contracts: A library of secure smart contract components.

Step 1: Setting Up the Development Environment

  1. Install Node.js: Download and install Node.js from the official website.
  2. Initialize a Hardhat Project:
  • Open a terminal and create a new directory for your project:
     mkdir my-token
     cd my-token
  • Initialize a new Hardhat project:
     npx hardhat
  • Follow the prompts to create a basic Hardhat sample project.
  1. Install OpenZeppelin Contracts:
  • Install the OpenZeppelin Contracts library:
     npm install @openzeppelin/contracts

Step 2: Writing the ERC-20 Token Contract

Now that your environment is set up, you can create the ERC-20 token contract.

  1. Create the Token Contract:
  • In the contracts directory, create a new file called MyToken.sol:
     touch contracts/MyToken.sol
  • Open MyToken.sol in your code editor and add the following code:
     // SPDX-License-Identifier: MIT
     pragma solidity ^0.8.0;

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

     contract MyToken is ERC20, Ownable {
         constructor(string memory name, string memory symbol, uint256 initialSupply) ERC20(name, symbol) {
             _mint(msg.sender, initialSupply);
         }

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

         function burn(uint256 amount) public {
             _burn(msg.sender, amount);
         }
     }
  1. Explanation of the Code:
  • ERC20: Inherits from the OpenZeppelin ERC20 contract, which implements the standard ERC-20 functions and events.
  • Ownable: Provides basic authorization control, allowing the contract owner to perform restricted actions.
  • Constructor: Initializes the token with a name, symbol, and initial supply, which is minted to the contract creator’s address.
  • Mint Function: Allows the contract owner to mint new tokens to a specified address.
  • Burn Function: Allows token holders to destroy (burn) their tokens, reducing the total supply.

Step 3: Compiling the Contract

Next, you need to compile your contract to ensure there are no errors.

  1. Compile the Contract:
  • Run the following command in your terminal:
     npx hardhat compile
  • Hardhat will compile your contract and generate the necessary artifacts in the artifacts directory.

Step 4: Writing Deployment Script

To deploy the ERC-20 token contract, you need to write a deployment script.

  1. Create the Deployment Script:
  • In the scripts directory, create a new file called deploy.js:
     touch scripts/deploy.js
  • Open deploy.js and add the following code:
     async function main() {
         const [deployer] = await ethers.getSigners();

         console.log("Deploying contracts with the account:", deployer.address);

         const MyToken = await ethers.getContractFactory("MyToken");
         const myToken = await MyToken.deploy("MyToken", "MTK", ethers.utils.parseUnits("1000000", 18));

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

     main()
         .then(() => process.exit(0))
         .catch((error) => {
             console.error(error);
             process.exit(1);
         });
  1. Explanation of the Deployment Script:
  • getSigners: Retrieves the list of accounts provided by the Ethereum node, with the first account used as the deployer.
  • getContractFactory: Gets the contract to deploy.
  • deploy: Deploys the contract with the specified parameters (name, symbol, and initial supply).
  • parseUnits: Converts the initial supply to the correct units, considering the token’s decimals.

Step 5: Deploying the Contract

With the deployment script in place, you can now deploy your contract to a local blockchain or a testnet.

  1. Deploy to Local Network:
  • Start a local Ethereum node using Hardhat:
     npx hardhat node
  • Deploy the contract:
     npx hardhat run scripts/deploy.js --network localhost
  • You should see the deployment address of your token contract.
  1. Deploy to a Test Network:
  • If you want to deploy to a public testnet like Ropsten or Kovan, configure the network in your hardhat.config.js file:
     require("@nomiclabs/hardhat-waffle");

     module.exports = {
         solidity: "0.8.0",
         networks: {
             ropsten: {
                 url: "https://ropsten.infura.io/v3/YOUR_INFURA_PROJECT_ID",
                 accounts: [`0x${YOUR_PRIVATE_KEY}`]
             }
         }
     };
  • Deploy the contract to the testnet:
     npx hardhat run scripts/deploy.js --network ropsten

Step 6: Interacting with the Contract

Once your contract is deployed, you can interact with it using Hardhat or a front-end interface.

  1. Interacting via Hardhat Console:
  • Open the Hardhat console:
     npx hardhat console --network localhost
  • Interact with your contract:
     const MyToken = await ethers.getContractAt("MyToken", "YOUR_DEPLOYED_CONTRACT_ADDRESS");
     await MyToken.mint("0xRecipientAddress", ethers.utils.parseUnits("1000", 18));
  1. Interacting via a Front-End:
  • Use libraries like Web3.js or Ethers.js to build a front-end that interacts with your token contract. Connect the front-end to MetaMask to allow users to interact with the contract.

Step 7: Verifying the Contract (Optional)

If you’ve deployed your contract to a public testnet or the mainnet, you might want to verify the contract on Etherscan.

  1. Install Etherscan Plugin:
   npm install --save-dev @nomiclabs/hardhat-etherscan
  1. Add Etherscan Configuration:
  • Update hardhat.config.js with your Etherscan API key:
     require("@nomiclabs/hardhat-waffle");
     require("@nomiclabs/hardhat-etherscan");

     module.exports = {
         solidity: "0.8.0",
         networks: {
             ropsten: {
                 url: "https://ropsten.infura.io/v3/YOUR_INFURA_PROJECT_ID",
                 accounts: [`0x${YOUR_PRIVATE_KEY}`]
             }
         },
         etherscan: {
             apiKey: "YOUR_ETHERSCAN_API_KEY"
         }
     };
  1. Verify the Contract:
   npx hardhat verify --network ropsten YOUR_DEPLOYED_CONTRACT_ADDRESS "MyToken" "MTK" "1000000000000000000000000"

Conclusion

You’ve now created and deployed your own ERC-20 token using OpenZeppelin. This token adheres to the ERC-20 standard, making it compatible with wallets, exchanges, and other Ethereum-based applications. OpenZeppelin simplifies the process, ensuring that your token is secure and follows best practices. From here, you can further customize your token, add additional features, or integrate it into decentralized applications.

ERC-20 tokens are the foundation of many decentralized finance (DeFi) applications, and by mastering this process, you’re well on your way to becoming a proficient blockchain developer.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

Understanding `crypto.randomBytes` and `ethers.randomBytes`: A Comparison

  • crypto.randomBytes:
  • Takes a single argument specifying the number of bytes.
  • Always requires a size input; no default value is provided.
  • ethers.randomBytes:
  • Optionally takes the number of bytes to generate.
  • If no argument is provided, it defaults to generating 32 bytes.

Both crypto.randomBytes and ethers.randomBytes generate cryptographically secure random bytes, meaning the bytes are suitable for use in cryptographic applications such as key generation, encryption, and other security-sensitive operations.

Oct 24, 2024
Read More
Tutorial

How to Query ERC-20 Token Balances and Transactions Using Ethers.js and Etherscan API

npm install ethers
npm install axios

In this step, we will use Ethers.js to query the balance of an ERC-20 token for a specific Ethereum address.

Oct 24, 2024
Read More
Tutorial

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

You should use Etherscan when you need to read data from the Ethereum blockchain, such as querying transaction details, wallet balances, or token transfers. Etherscan is a powerful tool for building blockchain explorers or applications that focus on data analytics.

const axios = require('axios');

// Replace with your actual Etherscan API key
const apiKey = 'YOUR_ETHERSCAN_API_KEY';

// Replace with the Ethereum address you want to query
const address = '0xYourEthereumAddress';

// Etherscan API URL to fetch wallet balance
const url = `https://api.etherscan.io/api?module=account&action=balance&address=${address}&tag=latest&apikey=${apiKey}`;

async function getWalletBalance() {
  try {
    const response = await axios.get(url);
    const balanceInWei = response.data.result;

    // Convert balance from Wei to Ether
    const balanceInEther = balanceInWei / 1e18;
    console.log(`Wallet Balance: ${balanceInEther} ETH`);
  } catch (error) {
    console.error('Error fetching balance:', error);
  }
}

getWalletBalance();

Oct 24, 2024
Read More
Tutorial

Sending Transactions and Interacting with Smart Contracts Using Infura and Ethers.js

  • Node.js installed on your machine.
  • A basic understanding of JavaScript and blockchain concepts.
  • An Ethereum wallet with some test ETH (using testnets like Goerli or Ropsten is recommended for testing).
  • An Infura Project ID to access the Ethereum network.

If you don't have an Infura account yet, follow these steps:

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

In this tutorial, you'll learn how to use the Etherscan API to query blockchain data such as Ethereum wallet balances, transaction details, token balances, and more. This guide will help you set up your Etherscan API key, make API requests, and interact with the Ethereum blockchain programmatically.

By the end of this tutorial, you will be able to retrieve blockchain information such as transaction history and token balances through simple API calls.

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

Wallet Address: 0xYourEthereumAddress
Wallet Balance: 2.345 ETH
  • Ethers.js: We are using Ethers.js to interact with the Ethereum blockchain. Ethers.js simplifies the process of querying the blockchain and formatting the data for developers.
  • Provider: Whether you use Infura or a public node, the provider allows us to connect to the Ethereum network. Infura is commonly used because of its reliability and scalability, but public nodes can work as well if you're looking for a simple alternative.
  • getBalance(): This function queries the Ethereum network for the balance of the wallet in wei (the smallest unit of ETH). We then use ethers.utils.formatEther() to convert the balance from wei to Ether.

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

Burning tokens refers to the process of sending cryptocurrency tokens to an address from which they cannot be retrieved. Tokens sent to this address are effectively removed from circulation forever. The address ends with "dead," signaling its purpose of making tokens unreachable.

Token burns serve several key purposes in the cryptocurrency world:

Oct 24, 2024
Read More
Tutorial

ETH vs WETH: Understanding the Difference and Their Roles in Ethereum

WETH essentially bridges the gap between ETH and the broader ERC-20 ecosystem, allowing ETH to function seamlessly in DeFi, token swaps, and other smart contract interactions.

Wrapping ETH into WETH is a simple process that can be done through various decentralized exchanges or applications. Here’s a typical process:

Oct 24, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

  npm install ethers

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: An open-source blockchain explorer for Ethereum-based networks.
  • Key Features:
  • Provides a user-friendly interface for exploring blocks, transactions, and tokens.
  • Supports custom networks and sidechains.
  • Allows token holders to track token balances and transaction histories.
  • Easy to deploy and customize.
  • Website: BlockScout

Aug 23, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

  • Always validate inputs with require.

  • Use SafeMath or Solidity's built-in overflow checks for arithmetic.

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

Different operations in a smart contract consume different amounts of gas. Simple operations like adding two numbers are inexpensive, while more complex operations like loops or external contract calls can be costly. It’s important to understand how various Solidity operations consume gas.

Examples of Gas Costs:

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

A decentralized application (DApp) is an application that runs on a peer-to-peer network, like a blockchain, rather than relying on a single centralized server. DApps are open-source, operate autonomously, and the data is stored on the blockchain, making them transparent and resistant to censorship.

Key Characteristics of DApps:

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

Before writing a smart contract, we need to set up a development environment. Here’s what you need:

  • Node.js: Used to install necessary packages and tools.
  • Remix IDE: An online integrated development environment for writing, testing, and deploying smart contracts.
  • MetaMask: A browser extension that acts as a wallet and allows you to interact with the Ethereum blockchain.

Aug 22, 2024
Read More
Tutorial
javascript solidity

Creating a Decentralized Application (dApp) with Solidity, Ethereum, and IPFS: From Smart Contracts to Front-End

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

contract MyDapp {
    string public message;

    event MessageChanged(string newMessage);

    constructor(string memory initialMessage) {
        message = initialMessage;
    }

    function setMessage(string memory newMessage) public {
        message = newMessage;
        emit MessageChanged(newMessage);
    }

    function getMessage() public view returns (string memory) {
        return message;
    }
}

This contract stores a message on the blockchain and allows users to update and retrieve it. It also emits an event whenever the message is changed.

Aug 20, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

async function trackAddress(address) {
  try {
    const publicKey = new solanaWeb3.PublicKey(address);

    console.log(`Tracking address: ${publicKey.toBase58()}`);

    let lastSignature = '';

    // Fetch initial transactions
    const signatures = await connection.getSignaturesForAddress(publicKey, { limit: 1 });
    if (signatures.length > 0) {
      lastSignature = signatures[0].signature;
    }

    // Monitor for new transactions
    setInterval(async () => {
      const signatures = await connection.getSignaturesForAddress(publicKey, {
        limit: 10,
      });

      for (const signatureInfo of signatures) {
        if (signatureInfo.signature !== lastSignature) {
          const transaction = await connection.getConfirmedTransaction(signatureInfo.signature);

          if (transaction) {
            const { meta, transaction: tx } = transaction;

            const instructions = tx.message.instructions;
            const postBalances = meta.postBalances;
            const preBalances = meta.preBalances;

            // Check if the transaction involves token transfers
            instructions.forEach((instruction, index) => {
              const programId = instruction.programId.toBase58();

              // Solana's SPL Token Program ID
              if (programId === solanaWeb3.TOKEN_PROGRAM_ID.toBase58()) {
                const data = Buffer.from(instruction.data);
                const command = data.readUInt8(0);

                // 3 represents the Token Transfer instruction
                if (command === 3) {
                  const amount = data.readUInt64LE(1);
                  const fromAccount = instruction.keys[0].pubkey.toBase58();
                  const toAccount = instruction.keys[1].pubkey.toBase58();

                  const balanceChange = (preBalances[index] - postBalances[index]) / solanaWeb3.LAMPORTS_PER_SOL;

                  console.log(`New Trade Detected!`);
                  console.log(`- Signature: ${signatureInfo.signature}`);
                  console.log(`- From: ${fromAccount}`);
                  console.log(`- To: ${toAccount}`);
                  console.log(`- Amount: ${balanceChange} SOL`);
                }
              }
            });
          }

          lastSignature = signatureInfo.signature;
        }
      }
    }, 10000); // Check every 10 seconds
  } catch (error) {
    console.error('Error tracking address:', error);
  }
}

// Replace with the Solana address you want to track
const addressToTrack = 'YourSolanaAddressHere';
trackAddress(addressToTrack);
  • Fetch Transactions: We fetch the transaction signatures for the specified address and track them using getSignaturesForAddress.
  • Monitor New Transactions: Using setInterval, we periodically fetch new transactions and check for token transfer instructions.
  • Parse Transactions: We parse each transaction's instructions to identify token transfers and log the details to the console.
  • Token Program ID: We check if the program ID matches Solana's SPL Token Program to identify relevant instructions.

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

Step 3: Fetch New Token Creation Transactions

Solana tokens are created using the SPL Token Program, so we'll track transactions involving this program to identify new tokens. Add the following function to your index.js file:

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

Step 2: Connect to the Ethereum Network

Create a new file called index.js and add the following code to connect to the Ethereum blockchain:

Aug 09, 2024
Read More
Tutorial
javascript json

Fetching Address Details from Solana

This code initializes a connection to the Solana Devnet, which is a test network where you can experiment without using real SOL tokens.

Step 3: Fetch Wallet Balance

Aug 09, 2024
Read More
Tutorial
bash rust

Creating a Token on Solana

Ensure you're working on the Solana Devnet to avoid any accidental transactions on the Mainnet.

   solana config set --url https://api.devnet.solana.com

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!