Learning Objectives:

  • Master the ERC-20 fungible token standard and its economic implications

  • Understand ERC-721 and ERC-1155 for NFTs and their use cases

  • Learn advanced token standards and their applications

  • Analyze token economics, security, and real-world implementations


4.5.1: Understanding Token Standards – The Foundation

What Are Token Standards?

Token standards are technical specifications that define how tokens behave on the Ethereum blockchain. They ensure interoperability between different applications, wallets, and exchanges. Without standards, each token would work differently, creating fragmentation and making it impossible for a single wallet or exchange to support multiple tokens.

Why Standards Matter:

text
The Importance of Token Standards:

1. Interoperability:
   - Any wallet can display any standard token
   - Exchanges can list tokens easily
   - dApps can integrate tokens seamlessly

2. Security:
   - Standards are battle-tested
   - Common patterns reduce bugs
   - Auditors know what to check

3. Composability:
   - Tokens work together
   - DeFi protocols can interact
   - Ecosystem effects are powerful

4. User Experience:
   - Consistent interface
   - Predictable behavior
   - Reduced learning curve

Evolution of Token Standards:

 
 
Standard Year Purpose Key Innovation
ERC-20 2015 Fungible tokens Basic token interface
ERC-721 2018 Non-fungible tokens Unique token IDs
ERC-777 2019 Advanced fungible Hooks and operators
ERC-1155 2019 Multi-token Batch transfers
ERC-4626 2021 Yield vaults Standardized vaults
ERC-3643 2022 Security tokens Compliance built-in

4.5.2: ERC-20 – The Fungible Token Standard

What Are Fungible Tokens?

Fungible tokens are interchangeable units where each token is identical to every other token. Think of them like currency: one dollar bill is worth the same as any other dollar bill.

text
Fungible Token Properties:

1. Identical Value:
   - Token A = Token B
   - Each unit worth the same

2. Divisible:
   - Can be split into smaller units
   - Typically 18 decimal places

3. Interchangeable:
   - Any token can replace any other
   - No unique properties

4. Standardized:
   - All tokens follow same rules
   - Can be used anywhere

The ERC-20 Interface – What It Does:

The ERC-20 standard defines six mandatory functions and two events that every token must implement.

text
ERC-20 Core Functions:

1. totalSupply():
   - Returns total number of tokens
   - Immutable (or controlled minting)

2. balanceOf(address):
   - Returns token balance of an address
   - Core accounting function

3. transfer(to, amount):
   - Sends tokens from caller to recipient
   - Most common operation

4. approve(spender, amount):
   - Allows spender to withdraw tokens
   - Creates allowance

5. allowance(owner, spender):
   - Checks remaining allowance
   - Used for delegated spending

6. transferFrom(from, to, amount):
   - Spender moves tokens from owner to recipient
   - Uses allowance system

Events:
- Transfer(from, to, amount): Emitted when tokens move
- Approval(owner, spender, amount): Emitted when allowance changes

How ERC-20 Works – The Flow of Tokens:

text
Token Transfer Flow:

1. User A wants to send 100 tokens to User B
2. User A calls transfer(B, 100)
3. Contract checks: balanceOf(A) >= 100
4. Contract updates: balanceOf(A) = balanceOf(A) - 100
5. Contract updates: balanceOf(B) = balanceOf(B) + 100
6. Contract emits Transfer(A, B, 100)
7. Transaction completes

Token Approval Flow:

1. User A wants to allow DEX to spend 1000 tokens
2. User A calls approve(DEX, 1000)
3. Contract sets: allowance[A][DEX] = 1000
4. Contract emits Approval(A, DEX, 1000)
5. DEX can now call transferFrom(A, DEX, 1000)
6. Contract checks: allowance[A][DEX] >= 1000
7. Contract transfers tokens
8. Contract updates: allowance[A][DEX] = 0

ERC-20 Extensions – Building on the Standard:

 
 
Extension Purpose Key Feature
ERC-20 Burnable Destroy tokens Reduces total supply
ERC-20 Pausable Emergency stop Freeze transfers
ERC-20 Snapshot Vote snapshots Capture balances at block
ERC-20 Permit (EIP-2612) Gasless approvals Off-chain signing
ERC-20 FlashMint Flash loans Borrow and repay same tx
ERC-20 Votes Voting power Weighted voting
ERC-20 Cap Supply cap Max token supply

Tokenomics – The Economics of ERC-20 Tokens:

text
Economic Models for Tokens:

1. Governance Token:
   - Voting rights
   - Proposal creation
   - Parameter setting
   - Examples: UNI, AAVE, COMP

2. Utility Token:
   - Pay for services
   - Access to features
   - Discounts on fees
   - Examples: LINK, BAT, GAS

3. Security Token:
   - Represent real assets
   - Equity/debt ownership
   - Regulatory compliant
   - Examples: Regulated tokens

4. Stablecoin:
   - Pegged to value
   - Collateralized
   - Price stability
   - Examples: USDC, DAI, USDT

5. Meme Token:
   - Community driven
   - Viral marketing
   - Speculative value
   - Examples: DOGE, SHIB

Value Accrual Mechanisms:
- Buyback and burn (deflationary pressure)
- Fee sharing (revenue distribution)
- Staking rewards (yield generation)
- Governance rights (decision power)
- Discounts and benefits (utility value)

ERC-20 Security Considerations:

text
Common ERC-20 Vulnerabilities:

1. Approval Front-Running:
   - Attacker sees approval transaction
   - Submits transferFrom with higher gas
   - Spends tokens before approval updated
   - Mitigation: Use permit or increase/decrease allowance

2. Transfer Hook Reentrancy:
   - Custom tokens have receive hooks
   - Could re-enter before state updated
   - Mitigation: Use checks-effects-interactions

3. Balance Manipulation:
   - Flash loan attacks
   - Rounding errors
   - Mitigation: Use SafeMath (pre-0.8.0)

4. Allowance Inflation:
   - approve(MAX_UINT256) issues
   - Decrease allowance to MAX_UINT256
   - Mitigation: Increase/decrease allowance functions

Real-World ERC-20 Tokens:

 
 
Token Purpose Supply Notable Feature
USDC Stablecoin ~30B Fiat-backed, regulated
UNI Governance ~1B Uniswap governance
AAVE DeFi governance ~16M Lending protocol
LINK Oracle utility ~1B Chainlink oracles
DAI Stablecoin ~5B Decentralized collateral

4.5.3: ERC-721 – The Non-Fungible Token Standard

What Are Non-Fungible Tokens?

Non-fungible tokens (NFTs) are unique digital assets where each token has distinct properties. No two NFTs are identical, and they cannot be exchanged on a one-to-one basis.

text
Non-Fungible Token Properties:

1. Unique Identity:
   - Each token has unique ID
   - No two tokens are identical

2. Indivisible:
   - Cannot be split
   - 1 NFT = 1 whole unit

3. Provenance:
   - Full transaction history
   - Verifiable ownership

4. Metadata:
   - External data linked
   - Properties stored off-chain

5. Scarcity:
   - Limited supply (often)
   - Controlled minting

Fungible vs Non-Fungible:

Fungible (ERC-20):
Token A = Token B = Token C
All tokens are identical

Non-Fungible (ERC-721):
Token A ≠ Token B ≠ Token C
Each token has unique properties

The ERC-721 Interface – What It Does:

text
ERC-721 Core Functions:

View Functions:
1. balanceOf(owner): Returns number of NFTs owned
2. ownerOf(tokenId): Returns owner of specific NFT

Transfer Functions:
3. transferFrom(from, to, tokenId): Basic transfer
4. safeTransferFrom(from, to, tokenId): Safe transfer (checks receiver)

Approval Functions:
5. approve(to, tokenId): Approve single token
6. setApprovalForAll(operator, bool): Approve all tokens
7. getApproved(tokenId): Check single approval
8. isApprovedForAll(owner, operator): Check all approval

Events:
- Transfer(from, to, tokenId): When token moves
- Approval(owner, approved, tokenId): Single approval
- ApprovalForAll(owner, operator, approved): All approval

Extension: ERC-721 Metadata
- tokenURI(tokenId): Returns metadata URI
- name(): Token collection name
- symbol(): Token collection symbol

Extension: ERC-721 Enumerable
- totalSupply(): Total tokens minted
- tokenByIndex(index): Token ID by index
- tokenOfOwnerByIndex(owner, index): Token by owner and index

How ERC-721 Works:

text
NFT Transfer Flow:

1. User A owns NFT with Token ID 123
2. User A calls safeTransferFrom(A, B, 123)
3. Contract checks: ownerOf(123) == A
4. Contract updates: ownerOf(123) = B
5. Contract updates: balanceOf(A) = balanceOf(A) - 1
6. Contract updates: balanceOf(B) = balanceOf(B) + 1
7. Contract checks: B supports ERC-721 (if safe transfer)
8. Contract emits Transfer(A, B, 123)

NFT Approval Flow:

1. User A wants to allow DEX to sell NFT 123
2. User A calls approve(DEX, 123)
3. Contract sets: approved[123] = DEX
4. Contract emits Approval(A, DEX, 123)
5. DEX calls transferFrom(A, B, 123)
6. Contract checks: approved[123] == DEX
7. Contract transfers token
8. Contract clears: approved[123] = 0

NFT Metadata and Storage:

text
Metadata Options:

1. On-Chain Metadata:
   - Stored in contract
   - Immutable and verifiable
   - Expensive (gas costs)
   - Used for: Simple data, security-critical

2. Off-Chain Metadata (IPFS):
   - Stored on IPFS
   - Decentralized and permanent
   - Uses content-addressing
   - Used for: Most NFT projects

3. Off-Chain Metadata (Centralized):
   - Stored on server
   - Easy to update
   - Centralized control
   - Used for: Game items (frequent updates)

4. Hybrid Approach:
   - Base data on-chain
   - Extended data off-chain
   - Balances cost and flexibility

Metadata Structure (OpenSea Standard):
{
  "name": "My NFT",
  "description": "This is a unique NFT",
  "image": "ipfs://Qm...",
  "attributes": [
    {"trait_type": "Rarity", "value": "Legendary"},
    {"trait_type": "Level", "value": 99}
  ],
  "properties": {
    "files": [{"uri": "ipfs://Qm...", "type": "image/png"}]
  }
}

NFT Use Cases:

 
 
Use Case Description Examples
Digital Art Artwork as NFTs Beeple, CryptoPunks
Collectibles Digital collectibles NBA Top Shot, CryptoKitties
Gaming In-game assets Axie Infinity, Gods Unchained
Real Estate Property ownership RealT, Propy
Identity Digital identity ENS domains
Music Royalty rights Audius, Royal
Ticketing Event tickets Ticketmaster, GET Protocol
Membership Access tokens Proof of Attendance

ERC-721 Security Considerations:

text
Common ERC-721 Vulnerabilities:

1. Reentrancy on Safe Transfer:
   - Safe transfer calls receiver hook
   - Hook could call back into contract
   - Mitigation: Checks-effects-interactions

2. Approval Front-Running:
   - Similar to ERC-20 approval
   - Mitigation: Use setApprovalForAll

3. Token ID Reuse:
   - Burning then re-minting
   - History confusion
   - Mitigation: Never reuse token IDs

4. Metadata Manipulation:
   - Centralized metadata can be changed
   - Mitigation: Use IPFS with content addressing

Real-World NFT Projects:

 
 
Project Type Volume Notable Feature
CryptoPunks PFP ~$2B 10,000 unique punks
Bored Ape Yacht Club PFP ~$3B Community membership
Art Blocks Generative Art ~$1B Algorithmic art
Moonbirds PFP ~$500M Utility and staking
ENS Identity ~$100M Domain names
Otherside Gaming ~$300M Virtual land

4.5.4: ERC-1155 – The Multi-Token Standard

What is ERC-1155?

ERC-1155 is a multi-token standard that can represent both fungible and non-fungible tokens in a single contract. It enables batch transfers, reducing gas costs significantly.

text
ERC-1155 - The Best of Both Worlds:

Why ERC-1155 Exists:
1. Single Contract:
   - One contract for multiple token types
   - Reduces deployment costs

2. Batch Transfers:
   - Transfer multiple tokens at once
   - Atomic operations

3. Gas Efficiency:
   - Batch operations save gas
   - Consolidated logic

4. Fungible + Non-Fungible:
   - Support both types
   - Flexible design

5. Hooks:
   - Callback support
   - Advanced functionality

ERC-1155 Token Types:

text
Token ID-Based Types:

Fungible Tokens:
- Token ID represents a class
- amount > 1 for each ID
- Example: Gold (ID 1) = 1000 units

Non-Fungible Tokens:
- Token ID represents specific item
- amount = 1 for each ID
- Example: Sword (ID 101) = 1 unit

Hybrid:
- Some tokens fungible
- Some tokens non-fungible
- Example: Items with quantities

ID Schema Example:
Gold: ID = 1 (fungible, amount 10000)
Silver: ID = 2 (fungible, amount 50000)
Sword: ID = 101 (non-fungible, amount 1)
Shield: ID = 102 (non-fungible, amount 1)

How ERC-1155 Works – Batch Operations:

text
Batch Transfer Flow:

1. User wants to transfer 3 different tokens
2. User calls safeBatchTransferFrom(from, to, ids, amounts)
3. Contract processes:
   - Token 1: ID 1, amount 100
   - Token 2: ID 2, amount 200
   - Token 3: ID 101, amount 1
4. Contract updates all balances atomically
5. Contract calls receiver hooks
6. If any transfer fails, all revert
7. Emits TransferBatch event

Gas Savings:
- Single batch transfer: 10,000 gas
- Three individual transfers: 30,000 gas
- Savings: ~66% gas reduction

Batch Balance Queries:

text
balanceOfBatch Flow:

1. User wants balances of multiple tokens
2. User calls balanceOfBatch(accounts, ids)
3. Contract returns array of balances
4. Example:
   accounts = [A, B, C]
   ids = [1, 2, 3]
   returns [10, 20, 30]

Efficiency:
- One call instead of multiple
- Reduces RPC calls
- Better for dApps

ERC-1155 Extensions:

 
 
Extension Purpose Key Feature
ERC-1155 Burnable Destroy tokens Burn function
ERC-1155 Pausable Emergency stop Pause transfers
ERC-1155 Supply Track supply Supply tracking
ERC-1155 URI Metadata URI per token
ERC-1155 Royalties Royalties EIP-2981 integration

Use Cases for ERC-1155:

text
Ideal Use Cases:

1. Gaming:
   - Multiple item types in one contract
   - Gold, weapons, armor, potions
   - Batch transfers for inventory

2. Trading Card Games:
   - Cards as NFTs (amount=1)
   - Resources as fungible tokens
   - Batch pack opening

3. Marketplace:
   - Sell multiple items at once
   - Batch approvals
   - Efficient trading

4. Subscription Models:
   - Access tokens
   - Tiered membership
   - Batch minting

5. Event Ticketing:
   - Different seat types
   - Batch transfers
   - Scalable

ERC-1155 Security Considerations:

text
Unique Security Concerns:

1. Batch Transfer Reentrancy:
   - Multiple hooks called
   - Reentrancy possible
   - Mitigation: ReentrancyGuard

2. Token ID Conflicts:
   - Same ID used for different purposes
   - Mitigation: Clear ID schema

3. Amount > 1 for NFTs:
   - NFTs should have amount 1
   - Check before transfer

4. URI Resolution:
   - Different URIs per token
   - Gas costs for reading

4.5.5: Advanced Token Standards

ERC-777 – Advanced Fungible Tokens:

ERC-777 extends ERC-20 with hooks, operators, and advanced features.

text
ERC-777 Key Features:

1. Hooks:
   - tokensToSend(): Called before transfer
   - tokensReceived(): Called after transfer
   - Enable advanced logic

2. Operators:
   - Similar to allowance but more powerful
   - Can send/receive on behalf
   - Better than approve/transferFrom

3. Granularity:
   - Minimum transfer amount
   - Prevents dust attacks

4. Backward Compatible:
   - Implements ERC-20 interface
   - Works with existing wallets

5. Events:
   - More detailed logging
   - Better traceability

When to Use ERC-777:
- Need advanced transfer logic
- Want hooks for security
- Need operator functionality
- Want better backward compatibility

ERC-4626 – Tokenized Vaults:

ERC-4626 standardizes yield-bearing vaults, making them interoperable.

text
ERC-4626 Key Concepts:

1. Asset vs Shares:
   - Asset: Underlying token (e.g., USDC)
   - Shares: Vault representation (e.g., yvUSDC)

2. Conversion:
   - convertToShares(assets): Assets → Shares
   - convertToAssets(shares): Shares → Assets

3. Deposit/Mint:
   - deposit(assets, receiver) → shares
   - mint(shares, receiver) → assets used

4. Withdraw/Redeem:
   - withdraw(assets, receiver, owner) → shares burned
   - redeem(shares, receiver, owner) → assets returned

5. Yield Accrual:
   - Shares increase in value
   - Represent proportional ownership

APY Calculation:
APY = (Shares_Price_End - Shares_Price_Start) / Shares_Price_Start × 365 / Days

Use Cases:
- Yield farming strategies
- Lending pools
- Staking rewards
- Automated yield generation

ERC-3643 – Security Tokens:

ERC-3643 is a standard for regulated security tokens with built-in compliance.

text
ERC-3643 Key Features:

1. Identity Module:
   - KYC/AML verification
   - On-chain identity
   - Compliance checks

2. Transfer Restrictions:
   - Only verified addresses can hold
   - Transaction limits
   - Jurisdiction controls

3. Agent Management:
   - Delegated authority
   - Compliance agents
   - Corporate actions

4. Document Management:
   - Attach legal documents
   - Proxy voting
   - Investor reporting

5. Recovery:
   - Lost key recovery
   - Beneficiary designations
   - Corporate actions

Use Cases:
- Security tokens
- Real estate tokenization
- Private equity
- Bonds and debt

4.5.6: Token Security and Best Practices

Security Checklist:

text
Token Security Checklist:

☐ Reentrancy protection
☐ Access control (Ownable/AccessControl)
☐ Overflow protection (SafeMath or 0.8.0+)
☐ Emergency pause (Pausable)
☐ Upgrade path (Transparent proxy)
☐ Multiple audits
☐ Bug bounty program
☐ Test coverage > 95%
☐ Documentation complete
☐ Emergency withdrawal

☐ Checks-effects-interactions
☐ Front-running protection
☐ Rate limiting
☐ Input validation
☐ Event logging
☐ No hardcoded values
☐ Timelocks for sensitive ops
☐ Multi-sig for admin

Common Token Anti-Patterns:

 
 
Anti-Pattern Description Fix
Centralized Mint Single address minting Multi-sig, timelocks
No Pause Cannot stop in emergency Add Pausable
No Audit Unaudited code Multiple audits
Reentrancy External calls before state update Checks-effects-interactions
Approval Race front-running approve Use permit or increase/decrease
Unchecked Math Overflow/underflow SafeMath or 0.8.0+

4.5.7: Real-World Token Economics

Token Distribution Models:

text
Distribution Models:

1. Fair Launch:
   - No pre-mine
   - Equal opportunity
   - Community-driven
   - Example: Uniswap (initial)

2. Private Sale:
   - Early investors
   - Discounts for risk
   - Lock-up periods
   - Example: Most projects

3. Public Sale (ICO/IDO):
   - Crowdfunding
   - Democratic participation
   - Regulatory considerations
   - Example: Many projects

4. Airdrop:
   - Free distribution
   - Community building
   - Marketing tool
   - Example: Uniswap UNI

5. Staking Rewards:
   - Lock tokens
   - Earn yield
   - Long-term alignment
   - Example: Curve CRV

6. Liquidity Mining:
   - Provide liquidity
   - Earn governance tokens
   - Bootstrapping
   - Example: Most DeFi protocols

Token Vesting and Locking:

text
Vesting Schedules:

1. Team Vesting:
   - 1-year cliff
   - 24-48 months linear vesting
   - Aligns long-term interests

2. Investor Vesting:
   - 6-month cliff
   - 12-24 months vesting
   - Reduces sell pressure

3. Community Treasury:
   - Multi-sig controlled
   - Governance approval
   - Operational funding

4. Liquidity Locking:
   - LP tokens locked
   - Prevents rug pulls
   - Builds trust