Introduction
In our previous tutorial, we explored the Anatomy of Solidity-based ERC-20 Tokens. This guide demonstrates how to interact with tokens using smart contracts written in Solidity.
We'll create a virtual decentralized exchange (DEX) where users can trade Ethereum for a newly deployed ERC-20 Token.
Key Components
- Smart Contract: Core logic for token exchange
- ERC-20 Standard: Token implementation blueprint
- DEX Functions: Buy/sell mechanisms
Base Contract Structure
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract DEX {
IERC20 public token;
event Bought(uint256 amount);
event Sold(uint256 amount);
constructor() {
token = new ERC20Basic();
}
function buy() payable public {
// Implementation
}
function sell(uint256 amount) public {
// Implementation
}
}Buy Function Implementation
The buy function allows users to exchange ETH for tokens:
- Validates ETH sent
- Checks contract token reserve
- Executes token transfer
function buy() payable public {
uint256 amountTobuy = msg.value;
uint256 dexBalance = token.balanceOf(address(this));
require(amountTobuy > 0, "You need to send some ether");
require(amountTobuy <= dexBalance, "Not enough tokens in the reserve");
token.transfer(msg.sender, amountTobuy);
emit Bought(amountTobuy);
}Sell Function Implementation
The sell function requires prior approval:
- Validates token amount
- Checks allowance
- Transfers tokens and ETH
function sell(uint256 amount) public {
require(amount > 0, "You need to sell at least some tokens");
uint256 allowance = token.allowance(msg.sender, address(this));
require(allowance >= amount, "Check the token allowance");
token.transferFrom(msg.sender, address(this), amount);
payable(msg.sender).transfer(amount);
emit Sold(amount);
}Best Practices
👉 Secure Your Transactions with Proper Allowance Checks
- Always validate balances before transfers
- Implement event logging for transparency
- Test contract functionality thoroughly
FAQ Section
What is the ERC-20 standard?
ERC-20 is a technical standard for fungible tokens on Ethereum, defining common rules for token interactions.
Why approve before selling?
Approval ensures the DEX contract has permission to transfer tokens from your account, enhancing security.
How do I check my token balance?
Call balanceOf(yourAddress) on the token contract.
Can I customize exchange rates?
Yes, the basic 1:1 ratio can be modified to implement dynamic pricing.
What happens if a transfer fails?
The transaction reverts, and no state changes occur.
Complete Implementation
// Full contract code as shown earlierConclusion
This tutorial covered essential ERC-20 token operations:
- Checking balances and allowances
- Transferring tokens
- Handling approvals
For next steps, consider:
👉 Building Advanced DEX Features
- Adding liquidity pools
- Implementing price oracles
- Creating governance mechanisms
Remember to test all contracts thoroughly before deployment.
Key optimizations:
- Structured hierarchy with clear headings
- Integrated 6 core keywords naturally
- Added FAQ section addressing common queries
- Included engaging anchor texts as specified
- Removed promotional content while preserving technical details
- Ensured professional yet accessible tone