DEV Community

ORJI CECILIA O.
ORJI CECILIA O.

Posted on

MY ERC20 WALKTHROUGH

**

What is an ERC20?

**
Ethereum Request for Comment 20 (ERC20) is a standard for the Ethereum blockchain that defines a set of required functions and events for creating fungible tokens within a smart contract. ERC20 can be thought of as a set of predefined function signatures that any token contract must implement to be compatible with Ethereum's ecosystem.

By the end of this article, you will gain a clear understanding of function signatures, particularly those found in ERC20, and how to create custom functions using established patterns. We will also explore events, their practical applications, and examine real-world use cases of ERC20, along with examples of decentralized applications (dApps) that utilize ERC20.
**
Use Cases of ERC20**

  1. Decentralized Finance (DeFi) ERC-20 tokens play a critical role in decentralized finance (DeFi) by enabling various financial applications:

Stablecoins: ERC-20 tokens represent fiat-pegged digital assets to provide stability for users.
Lending and Borrowing: Users can earn interest on ERC-20 assets or use them as collateral to access liquidity.
Decentralized Exchanges (DEXs): ERC-20 tokens allow peer-to-peer trading without intermediaries.
Yield Farming: Users earn rewards by providing liquidity to DeFi protocols.
ERC-20 tokens have transformed traditional finance by providing decentralized alternatives to banking, lending, and trading.

2. Non-Fungible Tokens (NFTs)
Although NFTs are primarily based on ERC-721 and ERC-1155, ERC-20 tokens still play a key role in the NFT ecosystem:

Wrapped NFTs: ERC-20 tokens can represent ownership of NFTs, allowing them to be traded on decentralized exchanges.
NFT Marketplaces: ERC-20 tokens act as the primary currency for buying and selling NFTs.
Platform Governance: Some NFT projects use ERC-20 tokens for voting and decision-making within their ecosystems.
By integrating ERC-20 tokens, the NFT market has expanded its liquidity, accessibility, and interoperability.

3. Gaming
The gaming industry is leveraging ERC-20 tokens in multiple ways:

In-Game Currency: Players use ERC-20 tokens to purchase virtual assets and access premium content.
Asset Ownership: Blockchain gaming platforms use ERC-20 tokens to allow true ownership of digital assets.
Decentralized Economies: Play-to-earn games use ERC-20 tokens as rewards for gameplay achievements.
Community Governance: Some gaming platforms let players vote on game updates using ERC-20 tokens.
ERC-20 tokens have revolutionized gaming by creating decentralized economies where players have true ownership and financial incentives.

4. Supply Chain Management
ERC-20 tokens are increasingly integrated into supply chain management to improve transparency and efficiency:

Product Tracking: Companies tokenize physical goods with ERC-20 tokens for real-time tracking on the blockchain.
Inventory Management: Automated token-based inventory systems reduce errors and fraud.
Supply Chain Financing: Companies tokenize invoices and purchase orders for faster payments and financing.
Sustainability Tracking: Consumers can verify the environmental and ethical impact of a product.
By leveraging ERC-20 tokens, supply chain networks become more secure, transparent, and efficient.

5. Tokenized Assets
ERC-20 tokens facilitate fractional ownership of assets, making high-value investments more accessible:

Real Estate: Investors can own fractions of real estate through ERC-20 tokens.
Stocks & Bonds: Traditional securities can be tokenized, allowing global, 24/7 trading.
Intellectual Property: Artists and creators can sell tokenized shares of their work.
Art & Collectibles: Rare assets can be fractionalized and traded on digital marketplaces.
Tokenization using ERC-20 removes barriers to investment and increases asset liquidity.

6. Stablecoins
ERC-20 tokens are at the core of stablecoin development, enabling price-stable cryptocurrencies:

Fiat-Pegged Stablecoins: Tokens like USDT, USDC, and DAI are backed by real-world assets.
Algorithmic Stablecoins: Some ERC-20 stablecoins maintain stability without collateral by using smart

EXAMPLE OF DECENTRALIZED APPLICATIONS THAT USES ERC20

Some prominent examples of decentralized applications (dApps) that utilize ERC-20 tokens include Uniswap (a decentralized exchange for trading ERC-20 tokens), Aave (a DeFi platform for lending and borrowing crypto assets), and Compound (another DeFi platform for lending and borrowing), all of which operate on the Ethereum blockchain and rely on the ERC-20 standard for token functionality.

In order to Properly understand what the function in ERC20, here are some basics you should take note of:

*What is a function signature?
*

A function Signature is a unique identifier for a function in a program. It is the hash of a function’s component which are:

Function name: The function name is the name given to the function as a unique entity

Function parameters: These are the inputs that a function receives. They can be one or many. They can vary in number and type.

Function visibility: This refers to where can a function be visible from(i.e within or from outside your code) when a user wants to interact with it . Its visibility can include public, internal, external and private.

Function return types: This refers to the kind of value that the function returns. It could be a single value, an array of values, an object or any data type.

Function modifiers: Modifiers are keywords that are added to the definitions of functions to alert the functionality of a function. They can be used to control access to the function, to modify the return type of the function, or to impose other restrictions or allowances on the function.

WHAT ARE EVENTS IN SOLIDITY?

In Solidity, events are a way to log and notify external entities (such as user interfaces or other smart contracts) about specific occurrences within a smart contract. They serve as a mechanism for emitting and recording data onto the blockchain, making it transparent and easily accessible. Emits, on the other hand, are used to trigger or emit events within the smart contract code.

Defining and Emitting Events:

a. Event Declaration:

To define an event, you need to declare it within the contract. An event declaration consists of the event’s name, a list of parameters (if any), and their data types. Here’s an example:

Image description
Image description

In this example, we define an event named “NewTransaction” that takes three parameters: transactionId (an unsigned integer), sender (an Ethereum address), and amount (an unsigned integer).

b. Emitting Events:

To emit an event within the contract, you use the “emit“ keyword followed by the event name and any necessary parameters. Here's an example of emitting the Successfultxn event:In this example, we define an event named “Successfultxn” that takes three parameters: transactionId (an unsigned integer), sender (an Ethereum address), and amount (an unsigned integer).

b. Emitting Events:

To emit an event within the contract, you use the “emit“ keyword followed by the event name and any necessary parameters. Here's an example of emitting the succussfultxn event:

Image description

So lets get into the code

Image description

Here the code started with me declaring the license Identifier as unlicensed meaning that the code base is not under any open source license and does not grant permission for others to use, modify or distribute.

Followed immediately is version of solidity compiler that solidity uses (0.8.28). Then the name of the contract was named as “erc20”.

State variables named name, symbol, _decimals and total supply was declared with the data type string, string, uint8 and uint256 respectively.

Also an address data type name owner was declared. Then both a mapping and a 2D mapping data type was declared name balances and allowances where both were given the visibility as public meaning, that under the hood, a getter function has also been declared to us.

Custom errors was also written that would be used in the contract. These custom errors are name InvalidAddress, InsufficientFunds, InsufficientAllowance, OnlyOwnerAllowed and InvalidAmount.

Then comes the 2 events need when interacting with an ERC20 standard. The Transfer and the Approval. The minted event was added by me. The Transfer event carries three parameters, the from with an address data type, to also with an address data type and value with a unsigned Integer data type. As for Approval, its parameters includes owner with address data type, spender also with an address data type and an unsigned Integer named value.

Then a modifier is defined. Remember one of the details that can be found in a function signature is a function modifier and this function modifier was written like how the modifier called onlyOwner is written. It carries a condition that if msg.sender(a users interacting with a particular function in our contract) isnt equals to the owner that was declared earlier the, code should be reverted with OnlyOwnerAllowed custom error that was defined above.

Now lets go to our functions declarations.

Image description

The first function declared in the contract is name(). It has public visibility, a view function modifier, and returns a string stored in memory. This function serves as a getter function, retrieving the value of the _name state variable declared earlier in the contract.

Since Ethereum operates as a state machine, this function simply reads the value stored in the _name variable. The public visibility means the function can be called both internally (within the contract) and externally (by other contracts or users). The view modifier ensures that the function does not modify the blockchain state but only retrieves data. The returns keyword specifies the expected return data type, which in this case is a string—matching the _name state variable.

This same principle applies to other getter functions like symbol(), decimals(), and totalSupply(), each of which retrieves the corresponding state variable value without modifying the blockchain state.

The balanceOf function is responsible for retrieving the token balance of a specific address. It takes an address parameter (owner) and has a function visibility of public with a view modifier. This means it does not alter blockchain data but only reads and returns an unsigned integer (uint256) representing the balance.

Before returning the balance, the function first performs a sanity check to ensure the provided address is not the zero address (0x0). If the check fails, it triggers a custom error InvalidAddress, preventing invalid balance lookups.

In Solidity, mappings are used to store key-value pairs. The balanceOf function retrieves a balance using the balances mapping, where the key is an address, and the value is the associated token balance. This mapping ensures efficient storage and retrieval of token balances without the need for looping through data.

By following this structure, balanceOf efficiently tracks token ownership, ensuring security and accuracy in ERC20 token implementations.

Image description

The balances mapping is publicly accessible and is used to store the token balance of each address. It is defined with the address data type as the key and uint256 as the value. This means that each Ethereum address is associated with a specific numeric balance representing the amount of tokens it holds.

To retrieve the balance of a particular address using this mapping, the key (the address) is passed in as follows:

Image description

The _owner inside the square bracket act as the key pointing to a value with the data type uint256 and this uint256 is what is been returned from the function.

It is worthy to recognize that the function balanceOf returns a uint256 with an implicit return name balance. So the balance which has a data type of uint256 is set to the balances mapping .

The transfer function takes two arguments, the address data type named to and a uint256 named value, and returns a boolean implicitly name success. The function checks if address argument to is an address zero and if true return the InvalidAddress custom error. Also the function check if argument value is greater than the balance of the msg.sender(a user interacting with the function), if true return InsufficientFunds custom error. Then the balances mapping of the msg.sender is decremented by the value passed as an argument, while the balances mapping of the to address passed in the argument is incremented with the value passed into the argument since we are trying to transfer from the caller of the function to the receiver , in this case the to address. Also remember that an event was set earlier in our contract called Transfer. That event is emitted whenever this function is called. Recall that the event received three parameters and because of this the emit also would have to hold three parameter relative to the parameter in the event. The parameters to be emit are the address of the msg.sender, the address of the to and the value. Since the function returns a boolean implicitly named success, success is set to true.

Top comments (0)