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

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.

  • Use crypto.randomBytes when:
  • You are building Node.js applications without blockchain-specific functionality.
  • You want to avoid adding external dependencies.
  • Use ethers.randomBytes when:
  • You are developing Ethereum-related applications and already have ethers.js in your project.
  • You want the flexibility of generating random bytes with minimal configuration, defaulting to 32 bytes for Ethereum addresses or private keys.

Oct 24, 2024
Read More
Tutorial

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

node getTokenTransactions.js

You should see a list of token transactions for the specified address, with details including the sender, recipient, value transferred, and transaction hash.

Oct 24, 2024
Read More
Tutorial

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

  • Data Analytics: Use Etherscan if you need to fetch historical data, such as transaction histories, token balances, or account balances.
  • Blockchain Explorers: Ideal for building tools similar to Etherscan itself, where you query and display blockchain data to users.
  • Read-Only Data: You can’t send transactions, but you can retrieve information about any Ethereum address, smart contract, or token transfer.
  • Decentralized Applications (dApps): If you’re building an application that needs to interact with Ethereum in real-time, such as sending transactions or calling smart contract functions.
  • Wallets: If you are developing a wallet application that needs to sign and broadcast transactions.
  • Smart Contract Deployment: Use Infura to deploy or interact with smart contracts on the Ethereum blockchain.

Oct 24, 2024
Read More
Tutorial

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

Next, let’s interact with a smart contract using Ethers.js and Infura. For this example, we will call a read-only function from an ERC-20 token contract (like querying the balance of a wallet).

const ethers = require('ethers');

// Replace with your Infura Project ID
const infuraProvider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

// Replace with the ERC-20 contract address (e.g., USDT, DAI, or any token)
const contractAddress = '0xTokenContractAddress';

// Replace with the wallet address to query the balance
const walletAddress = '0xYourWalletAddress';

// ABI of the ERC-20 token (we only need the balanceOf function here)
const abi = [
    'function balanceOf(address owner) view returns (uint256)'
];

// Create a contract instance
const contract = new ethers.Contract(contractAddress, abi, infuraProvider);

async function getTokenBalance() {
    try {
        // Call the balanceOf function
        const balance = await contract.balanceOf(walletAddress);

        // Convert the balance from wei (for ERC-20 tokens, it could be small denominations)
        console.log(`Token Balance: ${balance.toString()}`);
    } catch (error) {
        console.error('Error fetching token balance:', error);
    }
}

// Call the function to query the token balance
getTokenBalance();

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

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.

Before you begin, you’ll need the following:

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

Once you've successfully retrieved the balance, you can expand your script to add more features. For example:

  • Check the balance of other Ethereum addresses (not just your wallet).
  • Send ETH to other addresses.
  • Interact with smart contracts using Ethers.js.

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

The Ethereum address "0x000000000000000000000000000000000000dead" is a special placeholder address, often referred to as a burn address. It is not used for transactions or wallet management, but for a specific function in the cryptocurrency ecosystem—burning tokens.

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.

Oct 24, 2024
Read More
Tutorial

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

  • ETH can be wrapped into WETH and vice versa. There is no change in value—1 ETH always equals 1 WETH.

Ethereum predates the ERC-20 token standard, which was introduced to standardize token creation on the blockchain. Since ETH doesn't conform to this standard, it cannot be directly used in many decentralized applications that rely on ERC-20 tokens. WETH solves this problem by allowing ETH holders to wrap their ETH into an ERC-20 compatible token that can be used across a wide range of DeFi protocols and dApps.

Oct 24, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

  • Description: A powerful and feature-rich library for Bitcoin and blockchain-related applications, built by the developers behind BitPay.
  • Use Cases:
  • Create Bitcoin wallets and manage keys.
  • Develop custom Bitcoin transaction scripts.
  • Build and query Bitcoin blockchain services.
  • Key Features:
  • Comprehensive support for Bitcoin development.
  • Provides tools for both full-node and SPV (Simplified Payment Verification) implementations.
  • Includes utilities for working with Bitcoin cash and other forks.
  • Installation:

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • Description: A static analysis tool for Solidity smart contracts, focused on security.
  • Key Features:
  • Detects security vulnerabilities and best practice violations.
  • Integrates with CI/CD pipelines for continuous security testing.
  • Provides detailed analysis and recommendations.
  • Compatible with all Solidity versions.
  • Website: Slither
  • Description: A scalable API and development suite for connecting to the Ethereum blockchain.
  • Key Features:
  • Provides reliable access to Ethereum and IPFS without needing to run your own nodes.
  • Supports various Ethereum networks, including mainnet and testnets.
  • Provides WebSocket and HTTP APIs for interacting with the blockchain.
  • Integrates seamlessly with Truffle, Hardhat, and other frameworks.
  • Website: Infura

Aug 23, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

Modifiers are used to change the behavior of functions.

modifier onlyOwner() {
    require(msg.sender == owner, "Not the owner");
    _;
}

function setMyUint(uint _value) public onlyOwner {
    myUint = _value;
}

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

  • Functions declared with view or pure keywords do not modify the blockchain state and therefore do not consume gas when called externally (only when called by other contracts).
  • Example: Use view functions for read-only operations, such as retrieving data from a contract.

3. Optimize Loops

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

To build a DApp, you first need a smart contract that will serve as the backend logic. Let’s create a simple smart contract that allows users to store and retrieve a message on the blockchain.

Example Contract:

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

Solidity is the programming language used to write smart contracts on Ethereum. Let’s create a simple smart contract that stores a number and allows users to update it.

Example Contract:

Aug 22, 2024
Read More
Tutorial
javascript solidity

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

The rise of blockchain technology has led to the development of decentralized applications (dApps), which operate on a peer-to-peer network rather than relying on centralized servers. dApps provide increased security, transparency, and resistance to censorship. In this tutorial, we'll walk through the process of building a dApp using Solidity, Ethereum, and IPFS. We’ll cover everything from writing smart contracts to deploying them on the Ethereum blockchain, and then integrating them with a front-end built with modern web technologies.

To start, ensure you have Node.js and npm installed on your machine. You can download them from the Node.js website.

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 2: Connect to the Solana Network

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

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

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

const Web3 = require('web3');

// Connect to an Ethereum node using Infura
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

console.log('Connected to Ethereum Mainnet');

Aug 09, 2024
Read More
Tutorial
javascript json

Fetching Address Details from Solana

This function takes a wallet address, converts it to a PublicKey object, and uses the getBalance method to fetch the balance in lamports (the smallest unit of SOL). It then converts lamports to SOL for display.

Step 4: Fetch Transaction History

Aug 09, 2024
Read More
Tutorial
bash rust

Creating a Token on Solana

Check that the SPL Token CLI is installed correctly:

   spl-token --version

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!