Стандарт ERC-20
Интерфейс токена
«Стандарт ERC-20» — бесплатный урок Web3 & DApp Development Fundamentals на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web3 & DApp Development Fundamentals, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What Is ERC-20?
ERC-20 is the standard interface for fungible tokens on Ethereum. Fungible means every unit is identical and interchangeable, like currency.
Because all ERC-20 tokens share the same interface, wallets and exchanges can support any of them automatically.
The Required Functions
An ERC-20 token must implement six functions:
totalSupply()balanceOf(account)transfer(to, amount)approve(spender, amount)allowance(owner, spender)transferFrom(from, to, amount)
The Two Events
ERC-20 also requires two events so wallets can track activity:
Transfer- fired on any token movementApproval- fired when an allowance is set
<code>event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);</code>totalSupply and balanceOf
totalSupply() returns the total number of tokens in existence. balanceOf(account) returns how many tokens a given address holds.
<code>function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);</code>The Interface in Code
Solidity lets you declare the standard as an interface. Implementations inherit from it to guarantee compliance.
<code>interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}</code>Optional Metadata
Three optional functions improve display: name(), symbol(), and decimals(). They are not required by the core standard but are expected by wallets.
<code>function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);</code>Understanding Decimals
The EVM has no fractions, so tokens use decimals to represent fractional amounts. Most tokens use 18 decimals, matching Ether.
So 1 token displayed equals 1 * 10**18 in raw units.
<code>uint8 public constant decimals = 18;
// 1 token = 1_000_000_000_000_000_000 base units</code>Why a Standard Matters
Because ERC-20 defines a common shape, a wallet can display any token, a DEX can trade it, and a contract can integrate it without custom code. Interoperability is the whole point.
Return Values
The mutating functions transfer, approve, and transferFrom return a bool indicating success. Most modern implementations revert on failure rather than returning false.
<code>function transfer(address to, uint256 amount) external returns (bool);
// returns true on success; reverts on insufficient balance</code>Using OpenZeppelin
In practice most developers do not write ERC-20 from scratch. They inherit the battle-tested OpenZeppelin implementation and just set the name, symbol, and initial supply.
<code>// import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
// contract MyToken is ERC20 {
// constructor() ERC20('MyToken', 'MTK') {
// _mint(msg.sender, 1000 * 10 ** decimals());
// }
// }</code>The Allowance Mechanism
A defining ERC-20 feature is allowances: an owner can authorize a spender to move tokens on their behalf via approve and transferFrom. This powers DEXs and DeFi protocols.
You will explore this in detail later in the course.
Quick Check
Test your understanding of the ERC-20 standard.
Recap
You learned the ERC-20 standard:
- It defines fungible tokens with a common interface
- Six required functions plus Transfer and Approval events
- Optional name, symbol, and decimals for display (usually 18 decimals)
- Allowances enable delegated transfers
- OpenZeppelin provides a safe ready-made implementation
Часто задаваемые вопросы
Урок «Стандарт ERC-20» бесплатный?
Да — полный текст урока «Стандарт ERC-20» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Web3 & DApp Development Fundamentals, подпишись на CoddyKit PRO. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.
Чему я научусь в уроке «Стандарт ERC-20»?
Интерфейс токена Ты практикуешь Web3 & DApp Development Fundamentals с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Web3 & DApp Development Fundamentals?
Предыдущий опыт не требуется. Web3 & DApp Development Fundamentals на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Стандарт ERC-20»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Web3 & DApp Development Fundamentals?
Да. Каждый урок Web3 & DApp Development Fundamentals включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Стандарт ERC-20
- Реализация токена
- Разрешения
- Выпуск и сжигание