实施 ERC-20 代币
开发并部署您自己的符合 ERC-20 标准的代币,包括转账、授权和额度函数。
实施 ERC-20 代币 是 CoddyKit 上的免费 Blockchain Smart Contracts with Solidity 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Blockchain Smart Contracts with Solidity 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Build Your Own ERC-20 Token
Welcome! In this lesson, you'll learn to implement your very own ERC-20 compliant token. We'll cover the essential functions and variables that make up this widely used standard.
By the end, you'll have a working understanding of how these tokens operate at a fundamental level on the Ethereum blockchain.
Token Identity: Name, Symbol, Decimals
Every ERC-20 token needs basic identifying information: a name, a symbol, and decimals. These are often public state variables.
- name: The full name of your token (e.g., "MyCoddyToken").
- symbol: A short ticker symbol (e.g., "MCT").
- decimals: How many decimal places the token can be divided into (commonly 18, like Ether).
Let's start our contract with these properties:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyToken {
string public name = "MyCoddyToken";
string public symbol = "MCT";
uint8 public decimals = 18; // Common for ERC-20
}Total Supply & Initial Minting
The totalSupply variable keeps track of all existing tokens. We also need a way to store each user's balance, typically using a mapping.
The constructor is a special function that runs only once when the contract is deployed. We use it to set the initial totalSupply and assign all initial tokens to the deployer's address.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyToken {
string public name = "MyCoddyToken";
string public symbol = "MCT";
uint8 public decimals = 18;
uint256 public totalSupply; // Total tokens in existence
mapping(address => uint256) private _balances; // User balances
constructor(uint256 initialSupply) {
totalSupply = initialSupply;
_balances[msg.sender] = initialSupply; // Mints to deployer
}
}Checking Balances: `balanceOf`
The balanceOf function allows anyone to query the token balance of a specific address. It's a view function, meaning it doesn't change the contract's state and costs no gas to call off-chain.
We retrieve the balance from our _balances mapping.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyToken {
string public name = "MyCoddyToken";
string public symbol = "MCT";
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) private _balances;
constructor(uint256 initialSupply) {
totalSupply = initialSupply;
_balances[msg.sender] = initialSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
}Direct Transfers: `transfer`
The transfer function enables a token holder to send tokens directly to another address. It's a core function of the ERC-20 standard.
Before transferring, we must ensure the sender has sufficient balance. After the transfer, we emit a Transfer event, which is vital for blockchain explorers and dApps to track token movements.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyToken {
string public name = "MyCoddyToken";
string public symbol = "MCT";
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) private _balances;
// ERC-20 events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(uint256 initialSupply) {
totalSupply = initialSupply;
_balances[msg.sender] = initialSupply;
emit Transfer(address(0), msg.sender, initialSupply); // Minting event
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(_balances[msg.sender] >= amount, "Insufficient balance");
_balances[msg.sender] -= amount;
_balances[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
}Delegated Spending: `approve`
The approve function allows a token holder (the owner) to grant another address (the spender) permission to spend a certain amount of their tokens on their behalf.
This is crucial for interacting with decentralized applications (dApps) where you might want a smart contract to manage your tokens (e.g., for staking or trading). We track these approvals in an _allowances mapping.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyToken {
string public name = "MyCoddyToken";
string public symbol = "MCT";
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances; // New: owner => (spender => amount)
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(uint256 initialSupply) {
totalSupply = initialSupply;
_balances[msg.sender] = initialSupply;
emit Transfer(address(0), msg.sender, initialSupply);
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(_balances[msg.sender] >= amount, "Insufficient balance");
_balances[msg.sender] -= amount;
_balances[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) public returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
}Checking Allowance: `allowance`
The allowance function lets you check how many tokens a specific spender is currently permitted to transfer from an owner's balance.
This is a view function, similar to balanceOf, and helps external applications understand the spending limits set by users.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyToken {
string public name = "MyCoddyToken";
string public symbol = "MCT";
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(uint256 initialSupply) {
totalSupply = initialSupply;
_balances[msg.sender] = initialSupply;
emit Transfer(address(0), msg.sender, initialSupply);
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(_balances[msg.sender] >= amount, "Insufficient balance");
_balances[msg.sender] -= amount;
_balances[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) public returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
}Spending on Behalf: `transferFrom`
The transferFrom function is used by a spender (who has been approved) to move tokens from an owner's balance to a recipient.
It requires checks for both the sender's balance and the allowance granted. After a successful transfer, the allowance is reduced by the transferred amount.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyToken {
string public name = "MyCoddyToken";
string public symbol = "MCT";
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(uint256 initialSupply) {
totalSupply = initialSupply;
_balances[msg.sender] = initialSupply;
emit Transfer(address(0), msg.sender, initialSupply);
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(_balances[msg.sender] >= amount, "Insufficient balance");
_balances[msg.sender] -= amount;
_balances[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) public returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public returns (bool) {
require(_balances[sender] >= amount, "Insufficient balance from sender");
require(_allowances[sender][msg.sender] >= amount, "Insufficient allowance");
_allowances[sender][msg.sender] -= amount;
_balances[sender] -= amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
return true;
}
}Full Minimal ERC-20 Implementation
Here's a complete, minimal ERC-20 token contract. While more advanced implementations (like OpenZeppelin's) include additional features and safety checks, this code covers all the core functions required by the standard.
You can deploy this contract to a testnet to create your own functional token!
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyToken {
string public name = "MyCoddyToken";
string public symbol = "MCT";
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(uint256 initialSupply) {
totalSupply = initialSupply;
_balances[msg.sender] = initialSupply;
emit Transfer(address(0), msg.sender, initialSupply);
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(_balances[msg.sender] >= amount, "Insufficient balance");
_balances[msg.sender] -= amount;
_balances[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) public returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public returns (bool) {
require(_balances[sender] >= amount, "Insufficient balance from sender");
require(_allowances[sender][msg.sender] >= amount, "Insufficient allowance");
_allowances[sender][msg.sender] -= amount;
_balances[sender] -= amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
return true;
}
}ERC-20 Core Functions Check
You've learned about the essential functions for an ERC-20 token. Now, let's test your knowledge!
Recap: Your Own Token
Congratulations! You've now implemented the core logic for an ERC-20 token. You learned how to define its properties, manage total supply and individual balances, and enable both direct and delegated token transfers.
Understanding these fundamental building blocks is key to working with any token on the Ethereum blockchain. Next, you might explore how to integrate with existing ERC-20 libraries or add more advanced features!
常见问题解答
「实施 ERC-20 代币」课时是免费的吗?
是的 — 「实施 ERC-20 代币」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Blockchain Smart Contracts with Solidity 课程的其余内容,请升级到 CoddyKit PRO。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。
「实施 ERC-20 代币」这节课中我会学到什么?
开发并部署您自己的符合 ERC-20 标准的代币,包括转账、授权和额度函数。 你通过在浏览器中直接运行的动手代码来练习 Blockchain Smart Contracts with Solidity,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Blockchain Smart Contracts with Solidity 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Blockchain Smart Contracts with Solidity 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「实施 ERC-20 代币」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Blockchain Smart Contracts with Solidity 课中编写并运行代码吗?
能。每节 Blockchain Smart Contracts with Solidity 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- ERC-20 同质化代币标准
- 实施 ERC-20 代币
- ERC-721 非同质化代币(NFT)
- ERC-1155 多代币标准