Skip to main content

Deconstructing an ERC20 Token

Updated 37 min readMarkdown
Deconstructing an ERC20 Token

1. The Contract at 10,000 Feet

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract ERC20 {

    // Maps each address to its token balance.
    mapping(address => uint256) private _balances;

    // Maps owner → spender → approved amount.
    mapping(address => mapping(address => uint256)) private _allowances;

    // Total number of tokens in existence.
    // Invariant: _totalSupply always equals the sum of all _balances entries.
    uint256 private _totalSupply;

    // Human-readable name of the token (e.g., "USD Coin").
    string private _name;

    // Ticker symbol (e.g., "USDC").
    string private _symbol;

    // Number of decimal places
    uint8 private _decimals;

    // The address with minting privileges.
    address private _owner;

    // Emitted when tokens move between addresses.
    event Transfer(
        address indexed from,
        address indexed to,
        uint256 value
    );

    // Emitted when an allowance is set or changed.
    event Approval(
        address indexed owner,
        address indexed spender,
        uint256 value
    );

    // Emitted when ownership is transferred (or renounced).
    event OwnershipTransferred(
        address indexed previousOwner,
        address indexed newOwner
    );

    // Restricts a function to the current owner.
    modifier onlyOwner() {
        _onlyOwner();
        _;
    }

    function _onlyOwner() internal view {
        require(msg.sender == _owner, "ERC20: caller is not the owner");
    }

    // Runs exactly once during deployment. Sets metadata, records deployer
    constructor(
        string memory tokenName,
        string memory tokenSymbol,
        uint8 tokenDecimals,
        uint256 initialSupply
    ) {
        _name = tokenName;
        _symbol = tokenSymbol;
        _decimals = tokenDecimals;

        _owner = msg.sender;
        emit OwnershipTransferred(address(0), msg.sender);

        if (initialSupply > 0) {
            _mint(msg.sender, initialSupply);
        }
    }

    // Returns the token name.
    function name() public view returns (string memory) {
        return _name;
    }

    // Returns the token symbol.
    function symbol() public view returns (string memory) {
        return _symbol;
    }

    // Returns the number of decimals for display formatting.
    function decimals() public view returns (uint8) {
        return _decimals;
    }

    // Returns the total supply of tokens.
    function totalSupply() public view returns (uint256) {
        return _totalSupply;
    }

    // Returns the balance of a specific account.
    function balanceOf(address account) public view returns (uint256) {
        return _balances[account];
    }

    // Returns the remaining allowance that spender can withdraw from owner.
    function allowance(address tokenOwner, address spender) public view returns (uint256) {
        return _allowances[tokenOwner][spender];
    }

    // Transfers tokens from the caller to `to`.
    function transfer(address to, uint256 amount) public returns (bool) {
        _transfer(msg.sender, to, amount);
        return true;
    }

    // Sets `amount` as the allowance of `spender` over the caller's tokens.
    function approve(address spender, uint256 amount) public returns (bool) {
        _approve(msg.sender, spender, amount);
        return true;
    }

    // Transfers tokens from `from` to `to` using the allowance mechanism.
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public returns (bool) {
        _spendAllowance(from, msg.sender, amount);
        _transfer(from, to, amount);
        return true;
    }

    // Atomically increases the caller's allowance for `spender` by `addedValue`.
    function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
        address tokenOwner = msg.sender;
        _approve(tokenOwner, spender, _allowances[tokenOwner][spender] + addedValue);
        return true;
    }

    // Atomically decreases the caller's allowance for `spender` by `subtractedValue`.
    function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
        address tokenOwner = msg.sender;
        uint256 currentAllowance = _allowances[tokenOwner][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");

        unchecked {
            // Safe: we just verified currentAllowance >= subtractedValue
            _approve(tokenOwner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    // Creates `amount` new tokens and assigns them to `to`.
    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }

    // Destroys `amount` tokens from the caller's account.
    function burn(uint256 amount) public {
        _burn(msg.sender, amount);
    }

    // Destroys `amount` tokens from `account`, deducting from the caller's allowance.
    function burnFrom(address account, uint256 amount) public {
        _spendAllowance(account, msg.sender, amount);
        _burn(account, amount);
    }

    // Returns the current owner.
    function owner() public view returns (address) {
        return _owner;
    }

    // Transfers ownership to `newOwner`. Only callable by the current owner.
    function transferOwnership(address newOwner) public onlyOwner {
        require(newOwner != address(0), "ERC20: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    // Permanently removes the owner. No one can mint after this.
    function renounceOwnership() public onlyOwner {
        _transferOwnership(address(0));
    }

    // Core transfer logic. Shared by transfer() and transferFrom().
    function _transfer(address from, address to, uint256 amount) internal {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");

        unchecked {
            _balances[from] = fromBalance - amount;
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);
    }

    // Creates `amount` tokens and assigns them to `account`.
    function _mint(address account, uint256 amount) internal {
        require(account != address(0), "ERC20: mint to the zero address");

        // Checked arithmetic: reverts if _totalSupply overflows uint256
        _totalSupply += amount;

        // unchecked is safe: _totalSupply didn't overflow, and
        // _balances[account] <= _totalSupply, so this can't overflow either
        unchecked {
            _balances[account] += amount;
        }

        emit Transfer(address(0), account, amount);
    }

    // Destroys `amount` tokens from `account`.
    function _burn(address account, uint256 amount) internal {
        require(account != address(0), "ERC20: burn from the zero address");

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");

        // unchecked is safe:
        unchecked {
            _balances[account] = accountBalance - amount;
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);
    }

    // Sets `amount` as the allowance of `spender` over `owner`'s tokens.
    function _approve(address tokenOwner, address spender, uint256 amount) internal {
        require(tokenOwner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[tokenOwner][spender] = amount;
        emit Approval(tokenOwner, spender, amount);
    }

    // Deducts `amount` from the owner → spender allowance.
    function _spendAllowance(address tokenOwner, address spender, uint256 amount) internal {
        uint256 currentAllowance = _allowances[tokenOwner][spender];

        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");

            // unchecked is safe: currentAllowance >= amount (verified above)
            unchecked {
                _approve(tokenOwner, spender, currentAllowance - amount);
            }
        }
    }

    // Internal ownership transfer helper.
    function _transferOwnership(address newOwner) internal {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

Before we dive into individual lines, let's understand the architecture. This contract is organized into clear sections, and every section has a specific job:

┌──────────────────────────────────────────────────────────┐
│                      ERC20 Contract                      │
├──────────────────────────────────────────────────────────┤
│  STATE VARIABLES        ← The data (the ledger)         │
│  ├── _balances          ← Who owns how many tokens      │
│  ├── _allowances        ← Who can spend on whose behalf │
│  ├── _totalSupply       ← Total tokens in existence     │
│  ├── _name, _symbol     ← Display metadata              │
│  ├── _decimals          ← Display formatting hint       │
│  └── _owner             ← Who can mint                  │
├──────────────────────────────────────────────────────────┤
│  EVENTS                 ← Notifications to the world    │
│  ├── Transfer           ← "Tokens moved"                │
│  ├── Approval           ← "Permission changed"          │
│  └── OwnershipTransferred ← "New admin"                 │
├──────────────────────────────────────────────────────────┤
│  MODIFIER               ← Reusable access gate          │
│  └── onlyOwner          ← "Only the admin can do this"  │
├──────────────────────────────────────────────────────────┤
│  CONSTRUCTOR            ← One-time initialization       │
├──────────────────────────────────────────────────────────┤
│  PUBLIC VIEW FUNCTIONS  ← Free reads (no gas off-chain) │
│  ├── name, symbol, decimals, totalSupply                │
│  ├── balanceOf                                          │
│  └── allowance                                          │
├──────────────────────────────────────────────────────────┤
│  PUBLIC STATE-CHANGING  ← Costs gas, modifies the ledger│
│  ├── transfer           ← Move your tokens              │
│  ├── approve            ← Grant spending permission     │
│  ├── transferFrom       ← Third-party pull transfer     │
│  ├── increaseAllowance  ← Safely raise an allowance     │
│  ├── decreaseAllowance  ← Safely lower an allowance     │
│  ├── mint               ← Create new tokens (owner)     │
│  ├── burn               ← Destroy your tokens           │
│  ├── burnFrom           ← Destroy someone else's (with permission) │
│  ├── transferOwnership  ← Hand over admin rights        │
│  └── renounceOwnership  ← Permanently remove admin      │
├──────────────────────────────────────────────────────────┤
│  INTERNAL FUNCTIONS     ← Shared engine, not public     │
│  ├── _transfer          ← Core balance movement         │
│  ├── _mint              ← Core token creation           │
│  ├── _burn              ← Core token destruction        │
│  ├── _approve           ← Core allowance setting        │
│  ├── _spendAllowance    ← Deduct from allowance         │
│  ├── _transferOwnership ← Core ownership change         │
│  └── _onlyOwner         ← Modifier's validation logic   │
└──────────────────────────────────────────────────────────┘

Every public function is a thin wrapper that validates the caller (msg.sender) and then delegates to an internal function. The internal functions do the actual work. This separation exists because multiple public functions share the same logic — for example, both transfer() and transferFrom() call _transfer() internally. Without this pattern, you'd duplicate code, which is a maintenance and security risk.


2. The Pragma and License

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

These two lines appear at the top of every Solidity file and serve distinct purposes.

// SPDX-License-Identifier: MIT is a machine-readable license identifier. The SPDX (Software Package Data Exchange) standard lets tools like Etherscan automatically detect the license of your source code. MIT is the most permissive common license — it means anyone can use, copy, modify, and distribute this code. When you verify your contract on Etherscan, it reads this line and displays the license. Without it, the Solidity compiler emits a warning.

pragma solidity ^0.8.20; tells the compiler which versions of Solidity can compile this code. The ^ (caret) means "0.8.20 or any newer patch/minor version within 0.8.x, but NOT 0.9.0 or higher." This matters because:

  • Version 0.8.0 introduced automatic overflow/underflow checks (critical for token safety).

  • Version 0.8.20 introduced the push0 opcode support, which slightly reduces deployment gas.

  • Version 0.9.0 (when it eventually exists) could introduce breaking changes, so the caret prevents accidental compilation with an incompatible compiler.

Choosing ^0.8.20 rather than ^0.8.0 ensures you get the latest optimizations while staying within the 0.8.x safety model.


3. State Variables: The Permanent Ledger

State variables are declared inside the contract but outside any function. They live in the contract's storage — the permanent, on-chain database that persists across every transaction. Every variable here costs real gas to read and write, so understanding what each one does and why it exists is essential.

contract ERC20 {

    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;
    uint256 private _totalSupply;
    string private _name;
    string private _symbol;
    uint8 private _decimals;
    address private _owner;

_balances — The Core of Token Ownership

mapping(address => uint256) private _balances;

This single line is the entire foundation of the token. It is a hash table that maps every Ethereum address to a number: how many tokens that address holds. When someone says "I have 500 tokens," they mean _balances[theirAddress] equals 500 (in the token's smallest units).

There is no physical "token" anywhere on the blockchain. There's no file, no object, no data structure called "a token." There is only this mapping — a table of numbers. A transfer is nothing more than subtracting a number from one row and adding it to another.

The mapping uses address as its key. Every possible Ethereum address (2¹⁶⁰ of them) implicitly exists in the mapping with a default value of 0. You never need to "register" an address or "create an account." If an address has never received tokens, _balances[thatAddress] simply returns 0.

Under the hood, the EVM computes the storage location for _balances[someAddress] as keccak256(abi.encode(someAddress, 0)) — where 0 is the storage slot number of the _balances mapping (the first state variable gets slot 0). This hash determines which 32-byte storage slot holds that address's balance. The hash is collision-resistant, so every address effectively gets its own unique storage slot.

The private visibility means no external contract can read _balances directly through Solidity's type system. Instead, we expose balanceOf() as the public getter. Note: private does NOT make the data secret — anyone can read raw storage slots using tools like eth_getStorageAt. It only controls Solidity-level access.

_allowances — The Permission Table

mapping(address => mapping(address => uint256)) private _allowances;

This is a two-dimensional mapping: _allowances[owner][spender] = amount. It answers the question: "How many of owner's tokens is spender authorized to move?"

This structure exists because smart contracts (like Uniswap, Aave, or any DEX) need a way to pull tokens from your wallet. They can't call transfer() on your behalf — transfer() always moves tokens from msg.sender, and the sender would be the contract, not you. The allowance mechanism solves this: you approve() the contract for some amount, and the contract later calls transferFrom() to pull tokens within that limit.

The nesting means every (owner, spender) pair has its own independent allowance. Alice approving Uniswap for 1,000 and Aave for 500 creates two separate entries. Uniswap spending from Alice's allowance does not affect Aave's.

Storage location: keccak256(abi.encode(spender, keccak256(abi.encode(owner, 1)))) — a double hash, where 1 is the slot number of _allowances.

_totalSupply — The Global Counter

uint256 private _totalSupply;

Tracks the total number of tokens in existence. This value is a uint256 — a 256-bit unsigned integer that can hold values from 0 to 2²⁵⁶−1 (approximately 1.16 × 10⁷⁷).

The critical invariant: _totalSupply must always equal the exact sum of every entry in _balances. This invariant is maintained by:

  • _mint: increases both _totalSupply and a balance by the same amount

  • _burn: decreases both _totalSupply and a balance by the same amount

  • _transfer: subtracts from one balance, adds to another — _totalSupply is untouched

If this invariant is ever violated, the token is fundamentally broken.

_name and _symbol — Metadata for Humans

string private _name;
string private _symbol;

These are purely for display. _name holds something like "USD Coin" and _symbol holds "USDC". Wallets (MetaMask), block explorers (Etherscan), and trading interfaces read these to show human-friendly labels. The contract itself never uses these values in any logic or calculation.

Short strings (31 bytes or fewer) are stored compactly in a single 32-byte storage slot. Since token names and symbols are almost always short, they each cost one slot.

_decimals — The Display Hint

uint8 private _decimals;

A uint8 (0 to 255) that tells frontends how to format raw balances for human display. If _decimals is 18, a raw balance of 1500000000000000000 should be shown as 1.5 tokens. The contract never uses this value in any math — it is purely a message to off-chain systems.

uint8 occupies only 1 byte. The Solidity compiler can pack it with the next variable (_owner, 20 bytes) into a single 32-byte storage slot since they are declared consecutively and their combined size (21 bytes) is less than 32.

_owner — Access Control

address private _owner;

The address that has permission to mint new tokens and manage ownership. Set to msg.sender during construction. An address is 20 bytes.

Because _decimals (1 byte) and _owner (20 bytes) are declared adjacent, the compiler packs them into the same storage slot. This saves 20,000 gas the first time both are written (one slot allocation instead of two).

Storage Layout Summary

Slot 0:  _balances       (mapping — slot number used for hash computation)
Slot 1:  _allowances     (nested mapping — slot number used for hash computation)
Slot 2:  _totalSupply    (uint256 — full 32 bytes)
Slot 3:  _name           (string — compact if ≤31 bytes)
Slot 4:  _symbol         (string — compact if ≤31 bytes)
Slot 5:  _decimals (1 byte) + _owner (20 bytes) = 21 bytes, packed into one slot

4. Events: Broadcasting to the Outside World

Events are how your contract communicates with the off-chain world. They are written to the transaction's log — a separate, cheaper data structure that is NOT part of contract storage. Contracts can emit events but can never read past events. Only off-chain systems (wallets, block explorers, indexers, frontends) can query event logs.

Transfer Event

event Transfer(
    address indexed from,
    address indexed to,
    uint256 value
);

This event must be emitted every time tokens change hands. The ERC20 standard mandates three specific uses:

ScenariofromtoMeaning
Regular transfersenderrecipientTokens moved between accounts
Mintingaddress(0)recipientNew tokens created from nothing
Burningholderaddress(0)Tokens permanently destroyed

The indexed keyword on from and to makes them searchable topics in the log. An Ethereum node can efficiently answer: "Give me all Transfer events where to equals my address." Without indexed, the node would have to scan and decode every Transfer event ever emitted. value is NOT indexed — it's stored in the log's cheaper data section because you rarely filter by exact amount.

Approval Event

event Approval(
    address indexed owner,
    address indexed spender,
    uint256 value
);

Emitted whenever an allowance is set or changed — on every approve(), increaseAllowance(), decreaseAllowance(), and on every transferFrom() that deducts a non-infinite allowance (because _spendAllowance calls _approve internally).

OwnershipTransferred Event

event OwnershipTransferred(
    address indexed previousOwner,
    address indexed newOwner
);

Emitted when the contract's owner changes. Fired in three situations:

  1. Deployment: OwnershipTransferred(address(0), deployer) — first owner assigned

  2. Transfer: OwnershipTransferred(oldOwner, newOwner) — admin rights moved

  3. Renouncement: OwnershipTransferred(oldOwner, address(0)) — admin permanently removed


5. The Modifier and Its Helper: Reusable Access Control

modifier onlyOwner() {
    _onlyOwner();
    _;
}

function _onlyOwner() internal view {
    require(msg.sender == _owner, "ERC20: caller is not the owner");
}

A modifier is reusable code that wraps a function with a precondition check. The _; placeholder tells the compiler where to insert the actual function body. When you write function mint(...) public onlyOwner, the compiler generates code equivalent to:

function mint(address to, uint256 amount) public {
    _onlyOwner();              // ← modifier code (before the _;)
    _mint(to, amount);         // ← actual function body (the _;)
}

If _onlyOwner() reverts (because msg.sender != _owner), the function body never executes and the entire transaction is rolled back.

This contract uses an interesting pattern: the modifier delegates to an internal view function _onlyOwner() rather than putting the require directly in the modifier. The reason is practical — when the same check is placed directly in a modifier and that modifier is used on multiple functions, the Solidity compiler may inline the check into every function, increasing bytecode size. Delegating to a function means the check logic exists once in the bytecode and is called from each modified function, keeping the deployed contract smaller.

The internal visibility means _onlyOwner() can only be called from within this contract (or from inheriting contracts). The view modifier indicates it reads state (_owner) but does not modify it.


6. The Constructor: Birth of a Token

constructor(
    string memory tokenName,
    string memory tokenSymbol,
    uint8 tokenDecimals,
    uint256 initialSupply
) {
    _name = tokenName;
    _symbol = tokenSymbol;
    _decimals = tokenDecimals;

    _owner = msg.sender;
    emit OwnershipTransferred(address(0), msg.sender);

    if (initialSupply > 0) {
        _mint(msg.sender, initialSupply);
    }
}

The constructor runs exactly once — during contract deployment. After deployment, the constructor code is discarded and does not exist in the deployed bytecode. It cannot be called again by anyone, ever.

Line-by-line

string memory tokenName — The memory keyword is required here because strings are reference types. Constructor parameters arrive through calldata (the raw input of the deployment transaction), and Solidity loads them into memory for processing. tokenName is a temporary copy that exists only during this constructor call.

_name = tokenName — Copies the string from memory into storage (permanent). This is the moment the token's name becomes part of the blockchain's permanent state. Same for _symbol and _decimals.

_owner = msg.sender — msg.sender in the constructor is the address that deployed the contract. This line records that address as the owner. Since _decimals and _owner share a storage slot (packing), this write and the _decimals write above may be combined by the optimizer into a single storage operation.

emit OwnershipTransferred(address(0), msg.sender) — Signals that ownership went from "nobody" (address(0)) to the deployer. Off-chain systems watching for this event can identify who deployed the contract.

if (initialSupply > 0) { _mint(msg.sender, initialSupply); } — If the deployer specified an initial supply, mint those tokens immediately to the deployer's address. The if check avoids an unnecessary _mint call (and its associated storage writes, event emission, and zero-address validation) when initialSupply is zero. This is a small gas optimization for the deployment transaction.

Data Location Flow in the Constructor

tokenName arrives in → CALLDATA → loaded into → MEMORY → copied to → STORAGE (_name)
tokenDecimals arrives in → CALLDATA → sits on → STACK → written to → STORAGE (_decimals)
msg.sender comes from → GLOBAL CONTEXT → sits on → STACK → written to → STORAGE (_owner)

Every data location in Solidity (calldata, memory, stack, storage) is used during this single function.


7. View Functions: Reading the Ledger for Free

function name() public view returns (string memory) {
    return _name;
}

function symbol() public view returns (string memory) {
    return _symbol;
}

function decimals() public view returns (uint8) {
    return _decimals;
}

function totalSupply() public view returns (uint256) {
    return _totalSupply;
}

function balanceOf(address account) public view returns (uint256) {
    return _balances[account];
}

function allowance(address tokenOwner, address spender) public view returns (uint256) {
    return _allowances[tokenOwner][spender];
}

All six functions share the same characteristics:

public — callable by anyone: users, other contracts, frontends.

view — reads state but does not modify it. This has an important consequence: when called from off-chain (via a frontend or tool like eth_call), view functions are free — they don't create a transaction and cost no gas. The Ethereum node executes the function against its local copy of the blockchain state and returns the result. However, if a state-changing function calls a view function internally during a transaction, normal gas costs apply.

returns (string memory) — For name() and symbol(), the string is copied from storage into memory for the return value. The memory keyword is required because Solidity cannot return a storage reference to an external caller — it must return a self-contained copy.

returns (uint256) / returns (uint8) — Value types are returned directly on the stack. No data location keyword needed.

Why balanceOf() Instead of Making _balances Public?

Solidity can auto-generate a getter if you declare mapping(address => uint256) public _balances. But declaring the mapping as private and writing an explicit balanceOf() function gives you three advantages:

  1. Exact interface match: The ERC20 standard specifies balanceOf(address), not _balances(address).

  2. Control: You could add logic in the getter later (e.g., calculating virtual balances) without changing the interface.

  3. Naming: _balances with the underscore prefix is a Solidity convention for internal state. The public API uses clean names like balanceOf.

The allowance Function — Parameter Naming

function allowance(address tokenOwner, address spender) public view returns (uint256) {
    return _allowances[tokenOwner][spender];
}

Notice this function uses tokenOwner as the parameter name instead of owner. This is intentional — if the parameter were named owner, it would shadow the state variable _owner and also shadow the owner() function. While Solidity allows this (the parameter takes precedence within the function scope), it causes compiler warnings and can lead to confusion. Using tokenOwner avoids the conflict. The same convention is used consistently throughout the internal functions (_approve, _spendAllowance, etc.).


8. transfer(): Moving Your Own Tokens

function transfer(address to, uint256 amount) public returns (bool) {
    _transfer(msg.sender, to, amount);
    return true;
}

This is the simplest way to send tokens. The caller sends amount tokens from their own account to to. The function has three noteworthy aspects:

msg.sender as the source — The from address is hardcoded to msg.sender, which is the address that signed and submitted the transaction. This is the fundamental security model: you can only send your own tokens because msg.sender is cryptographically guaranteed by the Ethereum protocol. No one can forge it.

Delegation to _transfer() — The public function does not contain any logic itself. It delegates entirely to the internal _transfer(), which handles all validation (zero-address checks, balance checks), state changes (balance updates), and event emission. This separation means the same logic is reused by transferFrom() without duplication.

returns (bool) and always returning true — The ERC20 standard requires a boolean return value. In this contract, the function either succeeds and returns true, or it reverts (via require in _transfer). It never returns false. This is modern best practice — early tokens (2016-2017) returned false on failure, but most callers didn't check, causing silent failures and real financial losses. Reverting is unforgeable: a revert rolls back the entire transaction, so it's impossible for a caller to accidentally ignore a failure.


9. approve(): Granting Permission to a Third Party

function approve(address spender, uint256 amount) public returns (bool) {
    _approve(msg.sender, spender, amount);
    return true;
}

This function says: "I, msg.sender, authorize spender to move up to amount of my tokens."

No tokens move. This function only writes to the _allowances mapping. It's a pure permission grant. The actual token movement happens later, when the spender calls transferFrom().

It overwrites, not increments. Calling approve(spender, 500) sets the allowance to 500 regardless of what it was before. If the old allowance was 1,000, the new allowance is 500 — not 1,500. This overwrite behavior is the source of the ERC20 race condition (Section 11).

Why does this exist? Because DeFi protocols need to pull tokens from your wallet atomically. When you swap on Uniswap, the router contract needs to take your input tokens and give you output tokens in a single transaction. It can't do this with transfer() because transfer() always sends from msg.sender, and msg.sender inside Uniswap's contract would be Uniswap — not you. The approve + transferFrom pattern solves this.


10. transferFrom(): How Third Parties Pull Tokens

function transferFrom(
    address from,
    address to,
    uint256 amount
) public returns (bool) {
    _spendAllowance(from, msg.sender, amount);
    _transfer(from, to, amount);
    return true;
}

This is the function that makes DeFi composable. It allows msg.sender (typically a smart contract) to move tokens from from's account to to, provided msg.sender has been pre-approved by from.

The Two-Step Execution

Step 1: _spendAllowance(from, msg.sender, amount)

This checks that msg.sender has at least amount allowance from from, and deducts it. If the allowance is type(uint256).max (infinite), the deduction is skipped entirely (gas optimization). If the allowance is insufficient, the entire transaction reverts.

Step 2: _transfer(from, to, amount)

This performs the actual balance update — subtracts amount from _balances[from], adds it to _balances[to], and emits a Transfer event. All the same zero-address and balance checks apply as in a regular transfer().

Why the Order Matters

Allowance is checked and deducted before the transfer. This follows the Checks-Effects-Interactions pattern. If the transfer were performed first and the allowance check failed afterward, the revert would still roll back everything (Solidity guarantees atomicity), but checking first is the established convention and prevents subtle issues in more complex scenarios.

A Real-World Example: Uniswap Swap

Transaction 1 (sent by Alice):
  Alice → USDC.approve(UniswapRouter, 1000)
  Result: _allowances[Alice][UniswapRouter] = 1000. No tokens moved.

Transaction 2 (sent by Alice):
  Alice → UniswapRouter.swap(USDC, ETH, 1000)
    └── Inside UniswapRouter.swap():
        UniswapRouter → USDC.transferFrom(Alice, LiquidityPool, 1000)
          └── Inside USDC.transferFrom():
              msg.sender = UniswapRouter (NOT Alice!)
              _spendAllowance(Alice, UniswapRouter, 1000)
                → checks: _allowances[Alice][UniswapRouter] >= 1000 ✓
                → deducts: _allowances[Alice][UniswapRouter] = 0
              _transfer(Alice, LiquidityPool, 1000)
                → _balances[Alice] -= 1000
                → _balances[LiquidityPool] += 1000
                → emit Transfer(Alice, LiquidityPool, 1000)
        UniswapRouter → sends ETH to Alice
  Result: Atomic swap. If any step fails, everything reverts.

The crucial detail: inside USDC.transferFrom(), msg.sender is UniswapRouter — not Alice. That's why the allowance lookup checks _allowances[Alice][UniswapRouter]. Alice had to approve UniswapRouter beforehand.


11. increaseAllowance() and decreaseAllowance(): Fixing the Race Condition

The Problem: The ERC20 Race Condition

Imagine Alice has approved Bob for 100 tokens and wants to change it to 50.

Time 0: _allowances[Alice][Bob] = 100
Time 1: Alice sends tx: approve(Bob, 50)     ← pending in mempool
Time 2: Bob sees Alice's pending tx and front-runs:
        transferFrom(Alice, Bob, 100)          ← mined FIRST
        _allowances[Alice][Bob] = 0
Time 3: Alice's approve(Bob, 50) is mined:
        _allowances[Alice][Bob] = 50           ← set, not incremented
Time 4: Bob calls transferFrom(Alice, Bob, 50)
        Total stolen: 100 + 50 = 150 (Alice intended max 100)

This happens because approve() overwrites the allowance blindly. It has no awareness of the old value.

The Solution

function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
    address tokenOwner = msg.sender;
    _approve(tokenOwner, spender, _allowances[tokenOwner][spender] + addedValue);
    return true;
}

Instead of overwriting, increaseAllowance() reads the current allowance and adds to it. If Bob front-runs and spends the current allowance, the current allowance becomes 0. When Alice's increaseAllowance(Bob, 50) is mined, it adds 50 to the current value (0), resulting in 50 — exactly what Alice intended.

The expression _allowances[tokenOwner][spender] + addedValue uses Solidity 0.8's checked arithmetic. If the addition overflows uint256, the transaction reverts automatically. This prevents an attacker from manipulating an allowance to wrap around.

function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
    address tokenOwner = msg.sender;
    uint256 currentAllowance = _allowances[tokenOwner][spender];
    require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");

    unchecked {
        _approve(tokenOwner, spender, currentAllowance - subtractedValue);
    }

    return true;
}

decreaseAllowance() reads the current allowance, verifies it's large enough, and subtracts. The unchecked block is safe because the require above guarantees currentAllowance >= subtractedValue.

Note: increaseAllowance and decreaseAllowance are NOT part of the official ERC20 standard. They are widely adopted extensions (OpenZeppelin includes them) that mitigate the race condition. Any contract that interacts with your token via approve() will still work normally — these functions are additive, not replacements.


12. mint(): Creating New Tokens

function mint(address to, uint256 amount) public onlyOwner {
    _mint(to, amount);
}

Minting creates new tokens that didn't exist before. It increases both _totalSupply and the recipient's _balances entry by amount.

onlyOwner — The modifier ensures only the contract owner (the deployer, unless ownership has been transferred) can call this function. Without this restriction, anyone could create tokens at will, making the token worthless.

The internal _mint() function handles:

  1. Validating that to is not address(0) (minting to the zero address would increase supply with no retrievable balance)

  2. Increasing _totalSupply with checked arithmetic (reverts on overflow)

  3. Increasing _balances[to] inside unchecked (safe because _totalSupply didn't overflow and no individual balance can exceed _totalSupply)

  4. Emitting Transfer(address(0), to, amount) — the "from zero address" convention signals token creation


13. burn() and burnFrom(): Destroying Tokens

function burn(uint256 amount) public {
    _burn(msg.sender, amount);
}

Burning is the reverse of minting. It permanently removes tokens from circulation by:

  1. Subtracting amount from the caller's balance

  2. Subtracting amount from _totalSupply

  3. Emitting Transfer(msg.sender, address(0), amount) — "to zero address" signals destruction

Anyone can burn their own tokens — no access control needed. You're destroying your own property.

function burnFrom(address account, uint256 amount) public {
    _spendAllowance(account, msg.sender, amount);
    _burn(account, amount);
}

burnFrom() lets a third party burn tokens from someone else's account — but only if they've been approved. The flow is identical to transferFrom() except _transfer() is replaced with _burn():

  1. Check and deduct the caller's allowance from account

  2. Burn the tokens from account

Use case: A DeFi protocol that accepts token deposits might burn the deposited tokens as part of its mechanism (e.g., a bridge that burns tokens on Chain A and mints equivalent tokens on Chain B).


14. Ownership: transferOwnership() and renounceOwnership()

function owner() public view returns (address) {
    return _owner;
}

function transferOwnership(address newOwner) public onlyOwner {
    require(newOwner != address(0), "ERC20: new owner is the zero address");
    _transferOwnership(newOwner);
}

function renounceOwnership() public onlyOwner {
    _transferOwnership(address(0));
}

owner()

A simple getter that lets anyone verify who currently has minting privileges. Transparent and essential for trust.

transferOwnership(newOwner)

Moves the minting privilege to a different address. The zero-address check prevents accidental renouncement — if you want to renounce, use the dedicated renounceOwnership() function. This distinction is a safety pattern: two separate functions for two separate intentions, preventing costly mistakes.

renounceOwnership()

Permanently destroys the minting capability by setting the owner to address(0). After this call, onlyOwner will always revert (because no msg.sender can ever equal address(0)), making mint() permanently uncallable.

This is irreversible. There is no unrenounce(). Projects often renounce ownership to prove to token holders that no more tokens will ever be minted — it's a trust signal.

The Internal Helper

function _transferOwnership(address newOwner) internal {
    address oldOwner = _owner;
    _owner = newOwner;
    emit OwnershipTransferred(oldOwner, newOwner);
}

Both transferOwnership() and renounceOwnership() delegate to this. The separation avoids duplicating the state change and event emission. The oldOwner local variable caches the current owner before overwriting it, so the event can report both the old and new owner accurately.


15. Internal Functions: The Engine Room

Internal functions are the workhorses. They contain all the actual logic — validation, state changes, and event emission. They are marked internal, meaning they can only be called from within this contract (or from contracts that inherit from it). External callers cannot invoke them directly, which is a critical security boundary.

_transfer() — The Heart of the Token

function _transfer(address from, address to, uint256 amount) internal {
    require(from != address(0), "ERC20: transfer from the zero address");
    require(to != address(0), "ERC20: transfer to the zero address");

    uint256 fromBalance = _balances[from];
    require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");

    unchecked {
        _balances[from] = fromBalance - amount;
        _balances[to] += amount;
    }

    emit Transfer(from, to, amount);
}

Check 1: from != address(0) — Transferring from the zero address would effectively create tokens (since _balances[address(0)] defaults to 0, this would also fail the balance check, but the explicit zero-address check gives a clear error message and follows convention). When _transfer is called via transfer(), from is msg.sender which can never be address(0). But when called via transferFrom(), from is user-supplied and could be anything.

Check 2: to != address(0) — Tokens sent to address(0) are irrecoverable. No one holds its private key. This check prevents accidental permanent loss. (If you want to deliberately destroy tokens, use burn() instead, which properly decrements _totalSupply.)

Check 3: fromBalance >= amount — The sender must have enough tokens. The balance is read into a local stack variable fromBalance to avoid a second storage read later (gas optimization: one read instead of two).

unchecked {} block — The subtraction and addition are wrapped in unchecked, which disables Solidity 0.8's automatic overflow/underflow checks within this block. This is safe because:

  • Subtraction: fromBalance >= amount was just verified, so fromBalance - amount cannot underflow.

  • Addition: _balances[to] + amount cannot overflow because the sum of all balances equals _totalSupply (a valid uint256), and we're moving amount from one balance to another — the total is unchanged.

Each skipped check saves roughly 100 gas. For a function called millions of times across the token's lifetime, this adds up.

emit Transfer(from, to, amount) — Broadcasts the movement to the off-chain world.

_mint() — Creating Value

function _mint(address account, uint256 amount) internal {
    require(account != address(0), "ERC20: mint to the zero address");

    _totalSupply += amount;

    unchecked {
        _balances[account] += amount;
    }

    emit Transfer(address(0), account, amount);
}

_totalSupply += amount is deliberately OUTSIDE unchecked. This means Solidity's automatic overflow check applies. If _totalSupply + amount would exceed uint256.max, the transaction reverts. This is the safety valve — overflow of total supply would break the fundamental invariant.

_balances[account] += amount IS inside unchecked. This is safe because we just proved _totalSupply + amount didn't overflow, and _balances[account] can never exceed _totalSupply (invariant). Therefore _balances[account] + amount also cannot overflow.

emit Transfer(address(0), account, amount) — The address(0) as from is the convention for minting. Block explorers like Etherscan parse this to display "Tokens minted" instead of "Transfer from 0x000...000."

_burn() — Destroying Value

function _burn(address account, uint256 amount) internal {
    require(account != address(0), "ERC20: burn from the zero address");

    uint256 accountBalance = _balances[account];
    require(accountBalance >= amount, "ERC20: burn amount exceeds balance");

    unchecked {
        _balances[account] = accountBalance - amount;
        _totalSupply -= amount;
    }

    emit Transfer(account, address(0), amount);
}

This mirrors _mint() in reverse. Both operations inside unchecked are safe:

  • accountBalance - amount: verified by require above.

  • _totalSupply -= amount: _totalSupply >= _balances[account] >= amount (invariant), so no underflow.

_approve() — Setting Permissions

function _approve(address tokenOwner, address spender, uint256 amount) internal {
    require(tokenOwner != address(0), "ERC20: approve from the zero address");
    require(spender != address(0), "ERC20: approve to the zero address");

    _allowances[tokenOwner][spender] = amount;
    emit Approval(tokenOwner, spender, amount);
}

This function overwrites the allowance entirely. _allowances[tokenOwner][spender] = amount sets it to exactly amount, regardless of the previous value.

The zero-address checks prevent meaningless operations:

  • Approving FROM address(0) is meaningless (nobody controls it)

  • Approving TO address(0) as a spender is useless (no contract sits at address(0) to call transferFrom)

_spendAllowance() — Deducting Permission

function _spendAllowance(address tokenOwner, address spender, uint256 amount) internal {
    uint256 currentAllowance = _allowances[tokenOwner][spender];

    if (currentAllowance != type(uint256).max) {
        require(currentAllowance >= amount, "ERC20: insufficient allowance");

        unchecked {
            _approve(tokenOwner, spender, currentAllowance - amount);
        }
    }
}

The infinite approval check: type(uint256).max equals 2²⁵⁶ − 1 — a number so large no realistic transfer could exhaust it. When a user approves this exact value, the contract interprets it as "infinite — never decrement."

If the allowance is infinite: skip everything. No require, no subtraction, no _approve call, no storage write. This saves approximately 5,000+ gas per transferFrom call.

If the allowance is finite: check that it's sufficient, then deduct amount via _approve(). The unchecked subtraction is safe because the require above guarantees currentAllowance >= amount.

Note that _approve() is called to deduct the allowance, which means an Approval event is emitted with the updated allowance value. This is correct behavior — off-chain systems can track the remaining allowance.


16. How Everything Connects: The Call Graph

Every public function delegates to internal functions. Here is the complete call graph:

transfer(to, amount)
  └── _transfer(msg.sender, to, amount)

approve(spender, amount)
  └── _approve(msg.sender, spender, amount)

transferFrom(from, to, amount)
  ├── _spendAllowance(from, msg.sender, amount)
  │     └── _approve(owner, spender, newAllowance)     [if not infinite]
  └── _transfer(from, to, amount)

increaseAllowance(spender, addedValue)
  └── _approve(msg.sender, spender, currentAllowance + addedValue)

decreaseAllowance(spender, subtractedValue)
  └── _approve(msg.sender, spender, currentAllowance - subtractedValue)

mint(to, amount)
  └── [onlyOwner modifier → _onlyOwner()]
  └── _mint(to, amount)

burn(amount)
  └── _burn(msg.sender, amount)

burnFrom(account, amount)
  ├── _spendAllowance(account, msg.sender, amount)
  │     └── _approve(owner, spender, newAllowance)     [if not infinite]
  └── _burn(account, amount)

transferOwnership(newOwner)
  └── [onlyOwner modifier → _onlyOwner()]
  └── _transferOwnership(newOwner)

renounceOwnership()
  └── [onlyOwner modifier → _onlyOwner()]
  └── _transferOwnership(address(0))

Key observations:

  • _transfer() is used by two public functions: transfer() and transferFrom().

  • _approve() is used by five code paths: approve(), increaseAllowance(), decreaseAllowance(), and indirectly by transferFrom() and burnFrom() (through _spendAllowance).

  • _spendAllowance() is used by two functions: transferFrom() and burnFrom().

  • _onlyOwner() guards three functions: mint(), transferOwnership(), renounceOwnership().

This is why the internal/public separation exists. Without it, the contract would have duplicate validation logic in multiple places — a maintenance nightmare and a security risk (fix a bug in one copy, forget the other).


17. How Other Smart Contracts Use This Token

The ERC20 standard's greatest power is composability — any contract can interact with any ERC20 token using the same interface.

A DEX Pulling Tokens (approve + transferFrom)

// Another contract (e.g., a DEX) defines the interface it expects:
interface IERC20 {
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
    function allowance(address owner, address spender) external view returns (uint256);
}

contract SimpleDEX {
    function swap(address tokenIn, address tokenOut, uint256 amountIn) external {
        IERC20 input = IERC20(tokenIn);
        IERC20 output = IERC20(tokenOut);

        // Pull input tokens from the user (requires prior approval)
        // msg.sender here is the user who called swap()
        input.transferFrom(msg.sender, address(this), amountIn);

        // Calculate output amount (simplified)
        uint256 amountOut = calculateOutput(amountIn);

        // Send output tokens to the user
        output.transfer(msg.sender, amountOut);
    }
}

The DEX never imports your contract's code. It only needs the interface — the function signatures. The EVM routes the call to your contract using the address, and your contract executes its own logic. This works with ANY ERC20 token, because they all share the same interface.

A Lending Protocol Checking Collateral

contract LendingPool {
    IERC20 public collateralToken;

    function borrow(uint256 borrowAmount) external {
        // Check how much collateral the user has deposited
        uint256 userCollateral = collateralToken.balanceOf(msg.sender);

        // Require sufficient collateral (e.g., 150% ratio)
        require(userCollateral * 100 >= borrowAmount * 150, "Insufficient collateral");

        // ... proceed with loan ...
    }
}

A Vesting Contract Releasing Tokens Over Time

contract TokenVesting {
    IERC20 public token;
    address public beneficiary;
    uint256 public start;
    uint256 public duration;

    function release() external {
        uint256 elapsed = block.timestamp - start;
        uint256 totalAllocation = token.balanceOf(address(this));

        uint256 vested = (totalAllocation * elapsed) / duration;
        token.transfer(beneficiary, vested);
    }
}

A Bridge Burning Tokens on One Chain

contract Bridge {
    IERC20 public token;

    function bridgeToOtherChain(uint256 amount, uint256 destChainId) external {
        // Burn tokens on this chain (requires ERC20 with burnFrom)
        // User must have approved this bridge contract first
        token.transferFrom(msg.sender, address(this), amount);

        // Emit event for the off-chain relayer to pick up
        emit BridgeInitiated(msg.sender, amount, destChainId);
    }
}

The Pattern in All Cases

Every external contract follows the same pattern:

  1. Declare an IERC20 interface (just the function signatures)

  2. Create a reference: IERC20 token = IERC20(tokenAddress)

  3. Call standard functions: balanceOf, transfer, transferFrom, approve, allowance

Your contract doesn't know or care who's calling. It just validates inputs, checks permissions, updates state, and emits events. This is the power of a standard interface.


18. How Frontends Use This Token

Reading Data (Free — No Gas)

// Using ethers.js to read from the token contract

const provider = new ethers.JsonRpcProvider("https://mainnet.infura.io/v3/YOUR_KEY");
const token = new ethers.Contract(tokenAddress, ERC20_ABI, provider);

// These calls are FREE — they don't create transactions
const name     = await token.name();                           // "My Token"
const symbol   = await token.symbol();                         // "MTK"
const decimals = await token.decimals();                       // 18
const supply   = await token.totalSupply();                    // 1000000000000000000000n

// Read a user's balance and format it
const raw     = await token.balanceOf(userAddress);            // 5000000000000000000n
const display = ethers.formatUnits(raw, decimals);             // "5.0"

// Check if user has approved a DEX
const allowed = await token.allowance(userAddress, dexAddress); // 0n or some amount

Writing Data (Costs Gas — Requires Wallet)

// Using a signer (connected wallet like MetaMask)
const signer = await provider.getSigner();
const tokenWithSigner = new ethers.Contract(tokenAddress, ERC20_ABI, signer);

// Approve a DEX to spend tokens — user signs a transaction
const tx1 = await tokenWithSigner.approve(dexAddress, ethers.parseUnits("100", 18));
await tx1.wait(); // Wait for block confirmation

// Transfer tokens to a friend
const tx2 = await tokenWithSigner.transfer(friendAddress, ethers.parseUnits("10", 18));
await tx2.wait();

Listening for Events in Real Time

// Subscribe to Transfer events involving the current user
const filter = token.filters.Transfer(null, userAddress); // to = userAddress
//                                    ^^^^
//             "null" means "any value" — we don't filter on `from`
//             This works because `to` is an `indexed` parameter

token.on(filter, (from, to, value, event) => {
    console.log(`Received ${ethers.formatUnits(value, 18)} tokens from ${from}`);
    refreshUI(); // Update the balance display
});

Querying Past Events

// Get all Transfer events from the last 1000 blocks
const events = await token.queryFilter(
    token.filters.Transfer(),  // all Transfer events
    -1000                      // from 1000 blocks ago
);

for (const e of events) {
    console.log(`Block ${e.blockNumber}: ${e.args.from} → ${e.args.to}: ${e.args.value}`);
}

The ABI: The Bridge Between Frontend and Contract

The ERC20_ABI referenced above is a JSON array describing every function and event. The frontend needs this to encode function calls and decode responses. Here's what the ABI entry for transfer looks like:

{
  "name": "transfer",
  "type": "function",
  "stateMutability": "nonpayable",
  "inputs": [
    { "name": "to", "type": "address" },
    { "name": "amount", "type": "uint256" }
  ],
  "outputs": [
    { "name": "", "type": "bool" }
  ]
}

The Solidity compiler generates this ABI alongside the bytecode when you compile the contract. Frontends use it to know: "to call transfer, I need to encode an address and a uint256 with function selector 0xa9059cbb."


19. Security Analysis: Every Check, Every Guard

Let's trace every possible entry point and verify that all checks are in place.

transfer(to, amount)

→ _transfer(msg.sender, to, amount)
  ✅ from != address(0)    — msg.sender can never be address(0)
  ✅ to != address(0)      — explicit require
  ✅ fromBalance >= amount  — explicit require
  ✅ Underflow safe         — unchecked after require
  ✅ Overflow safe          — sum of balances ≤ totalSupply
  ✅ Event emitted          — Transfer(from, to, amount)

approve(spender, amount)

→ _approve(msg.sender, spender, amount)
  ✅ owner != address(0)   — msg.sender can never be address(0)
  ✅ spender != address(0) — explicit require
  ✅ Event emitted          — Approval(owner, spender, amount)
  ⚠️ Race condition         — mitigated by increaseAllowance/decreaseAllowance

transferFrom(from, to, amount)

→ _spendAllowance(from, msg.sender, amount)
  ✅ Infinite approval handled  — type(uint256).max skips deduction
  ✅ currentAllowance >= amount — explicit require (if not infinite)
  ✅ Underflow safe             — unchecked after require
  ✅ Approval event emitted     — via _approve inside _spendAllowance
→ _transfer(from, to, amount)
  ✅ All transfer checks apply  — (see transfer above)

mint(to, amount)

→ onlyOwner modifier
  ✅ msg.sender == _owner      — require in _onlyOwner()
→ _mint(to, amount)
  ✅ account != address(0)     — explicit require
  ✅ totalSupply overflow check — checked arithmetic (outside unchecked)
  ✅ Balance overflow safe      — unchecked, proven by totalSupply check
  ✅ Event emitted              — Transfer(address(0), account, amount)

burn(amount)

→ _burn(msg.sender, amount)
  ✅ account != address(0)     — msg.sender can never be address(0)
  ✅ accountBalance >= amount  — explicit require
  ✅ Underflow safe (balance)  — unchecked after require
  ✅ Underflow safe (supply)   — totalSupply >= balance >= amount
  ✅ Event emitted              — Transfer(account, address(0), amount)

burnFrom(account, amount)

→ _spendAllowance(account, msg.sender, amount)
  ✅ All allowance checks apply — (see transferFrom above)
→ _burn(account, amount)
  ✅ All burn checks apply      — (see burn above)

increaseAllowance(spender, addedValue)

→ _approve(msg.sender, spender, currentAllowance + addedValue)
  ✅ Overflow check on addition — checked arithmetic (outside unchecked)
  ✅ All _approve checks apply  — zero-address checks on owner and spender

decreaseAllowance(spender, subtractedValue)

→ require(currentAllowance >= subtractedValue)
→ _approve(msg.sender, spender, currentAllowance - subtractedValue)
  ✅ Underflow safe             — unchecked after require
  ✅ All _approve checks apply

transferOwnership(newOwner)

→ onlyOwner modifier           ✅
→ require(newOwner != address(0)) ✅
→ _transferOwnership(newOwner)
  ✅ Event emitted              — OwnershipTransferred

renounceOwnership()

→ onlyOwner modifier           ✅
→ _transferOwnership(address(0))
  ✅ Event emitted              — OwnershipTransferred
  ✅ Intentional address(0)     — bypasses transferOwnership's check

Edge Case: Self-Transfer

What happens when transfer(msg.sender, 100) — sending to yourself?

_balances[from] = fromBalance - 100    → say 1000 - 100 = 900
_balances[to]  += 100                  → 900 + 100 = 1000 (same slot as from!)

Since from == to, the second line reads the already-updated value. Result: balance is unchanged (1000). This is correct and does not break the invariant. ✅


20. The Full Picture: A Token's Lifecycle

Here is the complete lifecycle of a token, from deployment to its use in the real world.

Phase 1: Deployment

Deployer sends deployment transaction with:
  tokenName = "GameCoin"
  tokenSymbol = "GC"
  tokenDecimals = 18
  initialSupply = 1000000 * 10^18  (1 million tokens)

Constructor executes:
  _name = "GameCoin"                          [storage write]
  _symbol = "GC"                              [storage write]
  _decimals = 18                              [storage write]
  _owner = deployer                           [storage write, packed with _decimals]
  emit OwnershipTransferred(0x0, deployer)    [event log]
  _mint(deployer, 1000000 * 10^18):
    _totalSupply = 1000000 * 10^18            [storage write]
    _balances[deployer] = 1000000 * 10^18     [storage write]
    emit Transfer(0x0, deployer, 1000000e18)  [event log]

Result: Contract deployed. Deployer holds all 1M tokens. Supply = 1M.

Phase 2: Distribution

Deployer calls transfer(alice, 100000e18):
  _balances[deployer] = 900000e18
  _balances[alice]    = 100000e18
  emit Transfer(deployer, alice, 100000e18)

Deployer calls transfer(bob, 50000e18):
  _balances[deployer] = 850000e18
  _balances[bob]      = 50000e18
  emit Transfer(deployer, bob, 50000e18)

Phase 3: DeFi Integration

Alice wants to provide liquidity on a DEX:

Alice calls approve(dexRouter, type(uint256).max):
  _allowances[alice][dexRouter] = 2^256 - 1
  emit Approval(alice, dexRouter, 2^256 - 1)

Alice calls dexRouter.addLiquidity(gameCoin, 50000e18, ...):
  DEX internally calls gameCoin.transferFrom(alice, pool, 50000e18):
    _spendAllowance: allowance is max → skip deduction (gas saved!)
    _transfer: _balances[alice] = 50000e18, _balances[pool] = 50000e18
    emit Transfer(alice, pool, 50000e18)

Phase 4: Ongoing Activity

Bob trades on the DEX. The DEX handles it with transferFrom.
New users receive tokens via transfer.
The owner mints 500000e18 more tokens to a treasury address.
Some holders burn tokens they no longer need.
All activity is tracked via Transfer and Approval events.
Frontend dashboards read balanceOf, totalSupply, allowance to display data.

Phase 5: Ownership Renouncement

Deployer calls renounceOwnership():
  _owner = address(0)
  emit OwnershipTransferred(deployer, address(0))

Result: mint() is now permanently disabled.
        No one can ever create new tokens.
        The token supply is fixed forever.
        This is verified on-chain by anyone calling owner() → returns 0x0.

This is the complete picture: a mapping, a set of rules, and events that tell the world what happened. Every wallet, every DEX, every lending protocol, every block explorer interacts with this exact set of functions. The ERC20 standard makes it all interoperable — one interface, infinite composability.

About the author

  • In my free time iwrite and raise my voice in toast.

No comments yet. Be the first to comment.