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:
  • Library: crypto.randomBytes is part of Node.js’s built-in crypto module. It requires no additional dependencies and is readily available in any Node.js environment.
  • Usage: The function takes a single argument specifying the number of bytes to generate and returns a Buffer object containing the random bytes.
  • Example:
    const crypto = require('crypto');
    const randomBytes = crypto.randomBytes(32);
    console.log(randomBytes.toString('hex')); // Prints a 32-byte random hex string

Oct 24, 2024
Read More
Tutorial

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

We will use Ethers.js to interact with the Ethereum blockchain and Axios to make HTTP requests to the Etherscan API.

npm install ethers
npm install axios

Oct 24, 2024
Read More
Tutorial

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

  • Etherscan:
  • Primarily a block explorer and data provider. It offers read-only access to Ethereum blockchain data such as transaction histories, balances, token transfers, and more.
  • Does not allow real-time interaction with the blockchain (e.g., sending transactions).
  • Ideal for querying historical data and performing analytics on blockchain data.
  • Infura:
  • Provides full node access to the Ethereum network, allowing developers to interact with the blockchain in real-time.
  • Supports read and write operations, such as sending transactions, deploying smart contracts, and interacting with dApps.
  • Best for applications that require real-time interaction with Ethereum, such as decentralized apps (dApps).

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.

Oct 24, 2024
Read More
Tutorial

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

  • Infura Provider: You connect to the Ethereum network using the Infura provider (infuraProvider), which allows you to interact with Ethereum nodes.
  • Private Key: Replace 'YOUR_PRIVATE_KEY' with your Ethereum wallet’s private key (keep it secure).
  • Recipient Address: Replace '0xRecipientEthereumAddress' with the Ethereum address you want to send Ether to.
  • Gas and Fees: The gasLimit and gasPrice fields are required for sending transactions. The getGasPrice function retrieves the current gas price from the Infura node.

Once the script is ready, run it using Node.js:

Oct 24, 2024
Read More
Tutorial

Understanding and Using the Etherscan API to Query Blockchain Data

To use Etherscan’s API, you first need an API key. Follow these steps to get your API key:

We will use Axios to make HTTP requests to the Etherscan API. To install Axios, run the following command in your project folder:

Oct 24, 2024
Read More
Tutorial

Getting Wallet Balance Using Ethers.js in Node.js

Run the following command in your project folder to install it:

npm install ethers

Oct 24, 2024
Read More
Tutorial

Understanding 0x000000000000000000000000000000000000dead Address and Token Burns in Ethereum

Token burns are typically done to increase scarcity, and scarcity can lead to a higher token value if demand remains the same or increases. The basic principle of supply and demand comes into play: when the supply of an asset is reduced, it becomes more valuable (assuming demand holds steady).

Many projects use token burns strategically, announcing burn events in advance to generate interest in the project and potentially boost the value of the remaining tokens.

Oct 24, 2024
Read More
Tutorial

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

  • Transaction Fees: ETH is required to pay gas fees, which are used to process transactions and execute smart contracts on the Ethereum network.
  • Store of Value: ETH, like Bitcoin, is often used as a store of value or an investment asset.
  • Participating in dApps: ETH is essential for interacting with decentralized applications (dApps) that run on the Ethereum network.

WETH (Wrapped Ether) is a token that represents an ERC-20 standard version of ETH. While ETH is the core currency of the Ethereum blockchain, it is not compatible with the ERC-20 standard, which governs the majority of tokens on the Ethereum network. This is where WETH comes into play.

Oct 24, 2024
Read More
Cheatsheet
solidity

Blockchain Libraries Cheatsheet

  • Description: A comprehensive Bitcoin library for .NET, designed for developing Bitcoin applications with C#.
  • Use Cases:
  • Develop Bitcoin wallets and applications in C#.
  • Handle Bitcoin transactions and blocks programmatically.
  • Build and deploy full-featured Bitcoin services on .NET.
  • Key Features:
  • Full support for Bitcoin protocol and SegWit.
  • Compatible with various .NET environments.
  • Detailed examples and documentation for easy integration.
  • Installation:

Aug 23, 2024
Read More
Cheatsheet
solidity

Blockchain Development Tools, Libraries, and Frameworks Cheatsheet

  • 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
  • Description: A blockchain developer platform offering APIs for building on Ethereum.
  • Key Features:
  • Provides enhanced APIs for Ethereum and Layer 2 solutions.
  • Includes tools for debugging, monitoring, and analytics.
  • Supports subscription-based WebSocket and HTTP APIs.
  • High scalability and reliability for production DApps.
  • Website: Alchemy

Aug 23, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

  • private: Accessible only within the contract

  • external: Accessible only externally (cannot be called internally without this)

Aug 22, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

  • Optimization: Gnosis Safe optimized their contract by minimizing storage writes and using efficient data structures like mappings and structs.
  • Impact: These optimizations reduced the gas cost for executing multi-signature transactions, making the platform more accessible.

Understanding gas and optimizing its consumption in smart contracts is crucial for developing cost-effective and efficient decentralized applications. By implementing strategies such as minimizing storage writes, using view and pure functions, optimizing loops, and leveraging efficient data structures, you can significantly reduce the gas costs associated with your smart contracts.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

Key Characteristics of DApps:

  • Decentralized: Operates on a blockchain network.
  • Open-source: The code is public and available for anyone to view and audit.
  • Autonomous: Once deployed, it runs independently without human intervention.
  • Smart Contract Integration: Relies on smart contracts to execute transactions and operations.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

Steps to Deploy:

  • Switch to the "Deploy & Run Transactions" tab.
  • Select "Injected Web3" as the environment to connect to MetaMask.
  • Choose a test network like Ropsten or Kovan in MetaMask.
  • Click "Deploy" and confirm the transaction in MetaMask.

Aug 22, 2024
Read More
Tutorial
javascript solidity

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

Compile the contract using Truffle:

truffle compile

Aug 20, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

   mkdir solana-address-tracker
   cd solana-address-tracker
   npm init -y

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

Step 4: Monitor for New Tokens

You can run this script periodically to monitor for new token creation events. Consider setting up a cron job or a scheduled task to execute the script at regular intervals.

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Ethereum

Step 3: Fetch Newly Created Tokens

We will use Etherscan's API to fetch information about newly created tokens. Add the following function to your index.js file:

Aug 09, 2024
Read More
Tutorial
javascript json

Fetching Address Details from Solana

async function getTransactionHistory(walletAddress) {
  try {
    const publicKey = new solanaWeb3.PublicKey(walletAddress);
    const confirmedSignatures = await connection.getSignaturesForAddress(publicKey);

    console.log('Transaction History:');
    for (const signatureInfo of confirmedSignatures) {
      const transactionDetails = await connection.getTransaction(signatureInfo.signature);
      console.log(`- Transaction Signature: ${signatureInfo.signature}`);
      console.log(`  Slot: ${transactionDetails.slot}`);
      console.log(`  Result: ${transactionDetails.meta.err ? 'Error' : 'Success'}`);
    }
  } catch (error) {
    console.error('Error fetching transaction history:', error);
  }
}

getTransactionHistory(walletAddress);

This function retrieves the transaction signatures associated with the wallet address and fetches the details of each transaction. It logs the transaction signature, slot number, and result status (success or error).

Aug 09, 2024
Read More
Tutorial
bash rust

Creating a Token on Solana

Replace <RECIPIENT_TOKEN_ACCOUNT> with the token account address of the recipient.

Congratulations! You have successfully created, minted, and transferred a custom token on the Solana blockchain. This tutorial introduced you to the SPL Token Program and demonstrated how to manage tokens using the Solana and SPL Token CLIs. With this knowledge, you can start building more complex decentralized applications on Solana and explore its capabilities further.

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!