Episode 6 — Scaling Reliability Microservices Web3 / 6.10 — Web3 Basics

6.10.e — Cryptocurrencies

In one sentence: Cryptocurrencies are digital assets secured by cryptography that live on blockchains — ranging from Bitcoin (digital gold) to Ethereum (programmable money) to stablecoins (digital dollars) — and they serve as the native payment, governance, and incentive layer of Web3.

Navigation: <- 6.10.d — Smart Contracts | 6.10 Overview


1. What Are Cryptocurrencies?

A cryptocurrency is a digital or virtual currency that uses cryptography for security and operates on a blockchain — a decentralized, distributed ledger. Unlike traditional currencies (USD, EUR), cryptocurrencies are not issued or controlled by any central authority (government or central bank).

TRADITIONAL MONEY:                    CRYPTOCURRENCY:

  Issued by: Central bank              Issued by: Protocol rules (code)
  Controlled by: Government             Controlled by: Network consensus
  Stored in: Bank accounts              Stored in: Blockchain wallets
  Transferred via: Banks, SWIFT         Transferred via: Blockchain transactions
  Supply: Central bank decides          Supply: Fixed or algorithmic
  Censorship: Bank can freeze account   Censorship: No one can freeze on-chain
  Privacy: Bank sees everything         Privacy: Pseudonymous (address-based)
  Settlement: Days (ACH, wire)          Settlement: Seconds to minutes
  Access: Requires bank account         Access: Anyone with internet

2. Bitcoin as Digital Gold

Bitcoin (BTC) was the first cryptocurrency, created by the pseudonymous Satoshi Nakamoto in 2009. Its primary value proposition is as a store of value — "digital gold."

BITCOIN KEY PROPERTIES:

  Total supply:       21,000,000 BTC (fixed forever — deflationary)
  Current supply:     ~19.6 million mined (as of 2025)
  Block time:         ~10 minutes
  Consensus:          Proof of Work
  Smart contracts:    Very limited (Script language)
  Primary use:        Store of value, censorship-resistant money
  
  WHY "DIGITAL GOLD":
    - Fixed supply (like gold — scarce)
    - No central authority can inflate it
    - Halvings reduce new supply every ~4 years
    - Widely recognized and liquid
    - Decentralized security (no single point of failure)
    
  HALVING SCHEDULE:
    2009: 50 BTC per block
    2012: 25 BTC per block (1st halving)
    2016: 12.5 BTC per block
    2020: 6.25 BTC per block
    2024: 3.125 BTC per block
    2028: 1.5625 BTC per block
    ~2140: Last BTC mined

3. Ethereum as Programmable Money

Ethereum (ETH) is the second-largest cryptocurrency and the foundation of Web3. Unlike Bitcoin, Ethereum is designed to be programmable — it runs smart contracts.

ETHEREUM KEY PROPERTIES:

  Total supply:       No fixed cap (but net issuance can be deflationary post-merge)
  Block time:         ~12 seconds
  Consensus:          Proof of Stake (since September 2022)
  Smart contracts:    Full Turing-complete (Solidity)
  Primary use:        Platform for DApps, DeFi, NFTs
  Gas token:          ETH (required to pay for transactions)
  
  WHY ETHEREUM MATTERS:
    - Hosts ~60% of all DeFi activity
    - ERC-20 standard (thousands of tokens built on Ethereum)
    - ERC-721 standard (NFTs)
    - Largest developer ecosystem in Web3
    - Layer 2 scaling (Arbitrum, Optimism, Base)

Bitcoin vs Ethereum

FeatureBitcoinEthereum
Created20092015
CreatorSatoshi NakamotoVitalik Buterin
PurposeDigital gold, store of valueSmart contract platform
ConsensusProof of WorkProof of Stake
SupplyFixed (21M)No fixed cap
Block time~10 minutes~12 seconds
Smart contractsVery limitedFull Turing-complete
ProgrammingScript (simple)Solidity (complex)
Transaction speed~7 TPS~15-30 TPS
Layer 2 scalingLightning NetworkArbitrum, Optimism, Base
EnergyHigh (PoW)Low (PoS)

4. Tokens vs Coins

This distinction is important and often confused.

COIN:
  - Has its own blockchain
  - Used to pay for transactions on that blockchain
  - Examples: BTC (Bitcoin), ETH (Ethereum), SOL (Solana)
  
TOKEN:
  - Lives on SOMEONE ELSE'S blockchain
  - Created via smart contracts
  - Examples: USDC (on Ethereum), UNI (on Ethereum), SHIB (on Ethereum)
  
ANALOGY:
  Coin = A country's currency (USD in the US)
  Token = A gift card or arcade token (operates within a system built on that country)
CoinsTokens
BlockchainOwn blockchainBuilt on existing blockchain
ExamplesBTC, ETH, SOL, AVAXUSDC, UNI, LINK, SHIB
CreationRequires building a blockchainDeploy a smart contract
Gas feesPaid in the native coinPaid in the host chain's coin
StandardN/AERC-20, ERC-721, SPL (Solana)

5. ERC-20 Token Standard

ERC-20 is the technical standard for fungible tokens on Ethereum. It defines a common interface that all tokens must implement, enabling interoperability.

EVERY ERC-20 TOKEN MUST IMPLEMENT:

  // Read functions (free)
  name()          → "USD Coin"
  symbol()        → "USDC"
  decimals()      → 6
  totalSupply()   → Total tokens in existence
  balanceOf(addr) → How many tokens an address holds
  allowance(owner, spender) → How many tokens a spender can use on behalf of owner

  // Write functions (cost gas)
  transfer(to, amount)               → Send tokens
  approve(spender, amount)           → Allow someone to spend your tokens
  transferFrom(from, to, amount)     → Spend tokens on behalf of someone (after approval)

  // Events
  Transfer(from, to, value)          → Emitted on every transfer
  Approval(owner, spender, value)    → Emitted on every approval

Why the Approve/TransferFrom Pattern Exists

DIRECT TRANSFER:
  Alice calls token.transfer(Bob, 100)
  Simple. Alice sends Bob 100 tokens.

APPROVE + TRANSFER_FROM (used by DApps):
  1. Alice calls token.approve(Uniswap, 100)
     "I allow Uniswap to spend up to 100 of my tokens"
  
  2. Alice calls uniswap.swap(tokenA, tokenB, 100)
     Inside the swap function, Uniswap calls:
     tokenA.transferFrom(Alice, Uniswap, 100)
  
  WHY: Smart contracts cannot "pull" tokens from your wallet without permission.
  The approve step is the permission. This is why DApps ask you to "approve"
  before your first trade.

Reading ERC-20 Data with ethers.js

import { ethers } from 'ethers';

const provider = new ethers.JsonRpcProvider('https://eth-mainnet.g.alchemy.com/v2/KEY');

// Human-readable ABI (ethers.js feature)
const erc20Abi = [
  'function name() view returns (string)',
  'function symbol() view returns (string)',
  'function decimals() view returns (uint8)',
  'function totalSupply() view returns (uint256)',
  'function balanceOf(address) view returns (uint256)'
];

// Check multiple tokens
const tokens = {
  USDC: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
  USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
  DAI:  '0x6B175474E89094C44Da98b954EedeAC495271d0F',
  UNI:  '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984'
};

for (const [name, address] of Object.entries(tokens)) {
  const contract = new ethers.Contract(address, erc20Abi, provider);
  const [symbol, decimals, totalSupply] = await Promise.all([
    contract.symbol(),
    contract.decimals(),
    contract.totalSupply()
  ]);
  console.log(`${symbol}: Total supply = ${ethers.formatUnits(totalSupply, decimals)}`);
}

6. Stablecoins

Stablecoins are cryptocurrencies designed to maintain a stable value, typically pegged 1:1 to the US dollar. They solve the volatility problem of crypto for everyday transactions.

StablecoinPegMechanismIssuerMarket Cap
USDT (Tether)$1 USDFiat-backed (reserves)Tether Ltd~$100B+
USDC (USD Coin)$1 USDFiat-backed (audited reserves)Circle~$30B+
DAI$1 USDCrypto-collateralized (overcollateralized)MakerDAO (decentralized)~$5B+
FRAX$1 USDHybrid (partially algorithmic)Frax Finance~$1B

How Each Type Works

FIAT-BACKED (USDC, USDT):
  1. You send $100 to Circle (the company)
  2. Circle mints 100 USDC tokens on Ethereum
  3. Circle holds $100 in a bank account (reserves)
  4. When you redeem: burn 100 USDC, Circle sends you $100
  
  Trust: You trust Circle to actually hold the reserves
  Pros: Simple, stable, widely accepted
  Cons: Centralized — Circle can freeze USDC addresses

CRYPTO-COLLATERALIZED (DAI):
  1. You lock $150 worth of ETH in a MakerDAO smart contract
  2. The contract lets you mint 100 DAI (overcollateralized)
  3. If ETH price drops and your collateral ratio falls below 150%:
     Your position gets liquidated (collateral sold to maintain peg)
  4. To get your ETH back: repay the 100 DAI + stability fee
  
  Trust: You trust the smart contract code (audited, decentralized)
  Pros: Decentralized, censorship-resistant
  Cons: Capital-inefficient (need $150 to borrow $100)

7. Wallets

A crypto wallet stores the private keys that control your blockchain assets. The wallet does NOT store your cryptocurrency — the assets live on the blockchain. The wallet stores the keys that prove ownership.

WALLET = PRIVATE KEY + PUBLIC KEY + ADDRESS

  Private key:  A 256-bit random number (NEVER share this)
                0x4c0883a69102937d6231471b5dbb6204fe51296170827936ea5cce5f...
  
  Public key:   Derived from private key (math — elliptic curve)
                0x04bfcab...  (can be shared)
  
  Address:      Derived from public key (hash)
                0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045
  
  ANALOGY:
    Private key = PIN number (never share)
    Public key  = Bank account number (safe to share)
    Address     = Your public identifier (like an email for money)

Hot Wallets vs Cold Wallets

FeatureHot WalletCold Wallet
ConnectionConnected to internetOffline
ExamplesMetaMask, Coinbase WalletLedger, Trezor (hardware)
ConvenienceEasy to use, instant accessRequires physical device
SecurityVulnerable to hacks, phishingVery secure (keys never online)
Best forDaily transactions, DApp useLong-term storage, large amounts
RecoverySeed phraseSeed phrase + hardware

Custodial vs Non-Custodial

FeatureCustodialNon-Custodial
Who holds keysThird party (exchange)You
ExamplesCoinbase, BinanceMetaMask, Ledger
Recovery"Forgot password" flowSeed phrase (lose it = lose funds)
ControlCompany can freeze/limitFull control, no restrictions
RiskExchange hack, bankruptcyUser error, phishing
Web3 saying"Not your keys, not your coins""Your keys, your coins"

Seed Phrases

A seed phrase (mnemonic) is a human-readable backup of your private key:

  witch collapse practice feed shame open despair creek road again ice least

  - 12 or 24 words from a standard word list (BIP-39)
  - Encodes your master private key
  - Can recover ALL wallets and accounts derived from it
  - NEVER share your seed phrase with anyone
  - NEVER store it digitally (screenshot, email, cloud)
  - Write it on paper/metal and store securely

  If you lose your seed phrase AND your device:
    Your funds are GONE. Forever. No customer support can help.

8. Transaction Fees

Every blockchain transaction requires a fee, paid to validators/miners who process the transaction.

FEE COMPARISON:

  Blockchain       Avg. Transfer Fee    Speed
  ─────────────────────────────────────────────
  Bitcoin          $1-10                ~10 min
  Ethereum (L1)    $1-50               ~12 sec
  Polygon          $0.001-0.01         ~2 sec
  Solana           $0.00025            ~0.4 sec
  Arbitrum         $0.01-0.10          ~0.25 sec
  Base             $0.001-0.01         ~2 sec
  
  Traditional:
  Wire transfer    $25-50              1-5 days
  Stripe           2.9% + $0.30       Instant (settled in days)
  PayPal           2.9% + $0.30       Instant (settled in days)

Ethereum Gas Fees Explained

// Ethereum uses EIP-1559 fee model (since August 2021)
// Fee = (Base Fee + Priority Fee) * Gas Used

// Base Fee: set by the protocol, adjusts based on network congestion
//           This portion is BURNED (destroyed) — makes ETH deflationary
// Priority Fee (tip): goes to the validator, incentivizes faster inclusion

// Example transaction:
const tx = await signer.sendTransaction({
  to: '0xRecipient...',
  value: ethers.parseEther('1.0'),
  // Gas settings (optional — wallet usually estimates these)
  maxFeePerGas: ethers.parseUnits('30', 'gwei'),       // Maximum total fee
  maxPriorityFeePerGas: ethers.parseUnits('2', 'gwei') // Tip for validator
});

// Check current gas prices
const feeData = await provider.getFeeData();
console.log('Gas price:', ethers.formatUnits(feeData.gasPrice, 'gwei'), 'gwei');
console.log('Max priority fee:', ethers.formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'gwei');

9. DEXs vs CEXs

CEX (Centralized Exchange)

Examples: Coinbase, Binance, Kraken

  How it works:
    1. You create an account (KYC: name, ID, address)
    2. You deposit money (bank transfer, credit card)
    3. The exchange holds your crypto (custodial)
    4. You trade on the exchange's order book
    5. You withdraw to your own wallet (optional)
  
  Pros: Easy to use, fiat on-ramp, customer support, insurance
  Cons: Custodial (they hold your keys), KYC required, can be hacked
  
  Notable hacks:
    Mt. Gox (2014):  850,000 BTC lost (~$450M at the time)
    FTX (2022):      $8 billion in customer funds missing (fraud)

DEX (Decentralized Exchange)

Examples: Uniswap, SushiSwap, Curve, Jupiter (Solana)

  How it works:
    1. Connect your wallet (no account needed)
    2. Trade directly from your wallet (non-custodial)
    3. Trades execute via smart contracts (AMM — Automated Market Maker)
    4. Liquidity provided by other users (liquidity pools)
  
  Pros: Non-custodial, permissionless, no KYC, 24/7, transparent
  Cons: Higher fees (gas), slippage, impermanent loss for LPs, harder UX

CEX vs DEX Comparison

FeatureCEXDEX
CustodyExchange holds fundsYou hold funds
KYCRequiredNot required
Fiat supportYes (bank, credit card)No (crypto only)
Trading modelOrder bookAMM (liquidity pools)
SpeedInstantBlockchain confirmation time
FeesTrading fee (0.1-0.5%)Gas fee + swap fee (0.3%)
Token listingExchange decidesPermissionless (any token)
Hack riskExchange can be hackedSmart contract risk
AvailabilityBusiness hours + maintenance24/7/365

10. DeFi Basics

DeFi (Decentralized Finance) rebuilds traditional financial services using smart contracts instead of banks.

Lending and Borrowing

TRADITIONAL BANK:
  Lender → Bank → Borrower
  Bank sets rates. Bank keeps the spread. Bank approves/denies.

DeFi (Aave, Compound):
  Lender → Smart Contract (Pool) → Borrower
  Algorithm sets rates. Rates adjust by supply/demand. Permissionless.

  How it works:
    LENDER:
      1. Deposit 1000 USDC into Aave lending pool
      2. Receive aUSDC tokens (receipt — represents your deposit + interest)
      3. Interest accrues every block (seconds, not monthly)
      4. Withdraw anytime — no lock-up period
    
    BORROWER:
      1. Deposit $1500 ETH as collateral (overcollateralized)
      2. Borrow up to $1000 USDC
      3. Pay interest (variable rate, set by utilization algorithm)
      4. If collateral value drops below threshold → liquidated

Yield Farming

Yield farming = providing liquidity to DeFi protocols in exchange for rewards

  Example (simplified):
    1. Deposit ETH + USDC into a Uniswap liquidity pool
    2. Traders use your liquidity to swap (you earn 0.3% of each swap)
    3. Additionally earn UNI governance tokens (liquidity mining incentive)
    4. Stake UNI tokens in governance for additional rewards
    
  RISKS:
    - Impermanent loss: if token prices change, you may be worse off than holding
    - Smart contract risk: the protocol could have a bug
    - Token devaluation: reward tokens can lose value

DeFi Categories

CategoryWhat It DoesExamples
LendingEarn interest / borrow against collateralAave, Compound
DEXsTrade tokens without intermediaryUniswap, Curve
Liquid stakingStake ETH and get a liquid receipt tokenLido (stETH)
BridgesMove assets between blockchainsWormhole, LayerZero
DerivativesSynthetic assets, perpetual futuresdYdX, GMX
InsuranceCover against smart contract failuresNexus Mutual
PaymentsStreaming payments, invoicingSuperfluid, Request

11. Tokenomics Overview

Tokenomics = the economic design of a cryptocurrency or token. It determines supply, distribution, and incentive mechanisms.

KEY TOKENOMICS FACTORS:

  SUPPLY:
    Fixed supply:    Bitcoin (21M), limited = potentially deflationary
    Inflationary:    Dogecoin (no cap), continuous new supply
    Deflationary:    Ethereum (burn mechanism can outpace issuance)
    
  DISTRIBUTION:
    Team/founders:   10-20% (often with vesting schedule)
    Investors:       10-25% (VCs, early backers)
    Community:       30-60% (airdrop, mining, staking rewards)
    Treasury:        10-20% (protocol development fund)
    
  UTILITY (why hold the token?):
    Gas fees:        ETH, SOL (needed to use the network)
    Governance:      UNI, AAVE (vote on protocol changes)
    Staking:         ETH (earn rewards for securing the network)
    Access:          Some tokens gate features or services
    Revenue share:   Some protocols distribute fees to token holders
    
  VESTING:
    Tokens allocated to team/investors are usually locked:
    "4-year vesting with 1-year cliff"
    = No tokens for year 1, then 25% per year for years 2-4
    Prevents founders from dumping tokens immediately

12. Crypto in Web3 Applications

Cryptocurrencies serve three main roles in Web3 applications:

Payments

// Accept crypto payment in a DApp
async function acceptPayment(signer, amount) {
  const tx = await signer.sendTransaction({
    to: '0xMerchantAddress...',
    value: ethers.parseEther(amount.toString())
  });
  
  const receipt = await tx.wait();
  console.log(`Payment of ${amount} ETH confirmed in block ${receipt.blockNumber}`);
  return receipt;
}

// Accept stablecoin payment (USDC — more practical for commerce)
async function acceptUSDCPayment(signer, amount) {
  const usdc = new ethers.Contract(USDC_ADDRESS, [
    'function transfer(address, uint256) returns (bool)'
  ], signer);
  
  const tx = await usdc.transfer(
    '0xMerchantAddress...',
    ethers.parseUnits(amount.toString(), 6) // USDC has 6 decimals
  );
  
  await tx.wait();
  console.log(`Payment of ${amount} USDC confirmed`);
}

Governance

DAO governance with tokens:

  1. Protocol issues governance tokens (e.g., UNI for Uniswap)
  2. Token holders can create proposals:
     "Change the swap fee from 0.3% to 0.25%"
  3. Token holders vote (1 token = 1 vote, typically)
  4. If proposal passes threshold:
     Smart contract executes the change automatically
  5. Entire process is transparent, on-chain, auditable

Incentives

Token incentives align user behavior with protocol goals:

  LIQUIDITY MINING:
    "Provide liquidity → Earn protocol tokens"
    Bootstraps initial liquidity for new protocols
  
  STAKING REWARDS:
    "Lock tokens → Earn yield"
    Secures the network and reduces sell pressure
  
  AIRDROPS:
    "Use the protocol early → Receive free tokens later"
    Rewards early adopters and builds community
    Example: Uniswap airdropped 400 UNI to every early user (~$5,000+ at peak)

13. Regulatory Landscape Overview

THE REGULATORY SITUATION (as of 2025):

  UNITED STATES:
    - SEC (Securities and Exchange Commission) regulates securities
    - CFTC (Commodity Futures Trading Commission) regulates commodities
    - Ongoing debate: are tokens securities or commodities?
    - SEC has taken enforcement actions against multiple crypto projects
    - Stablecoins gaining regulatory clarity
    - Bitcoin ETFs approved (January 2024)
  
  EUROPEAN UNION:
    - MiCA (Markets in Crypto-Assets) regulation — comprehensive framework
    - Requires licensing for crypto service providers
    - Stablecoin issuers must hold reserves
    - Most structured regulatory approach globally
  
  OTHER REGIONS:
    - Singapore: Progressive, licensed framework
    - UAE/Dubai: Crypto-friendly special zones
    - China: Banned crypto trading and mining
    - El Salvador: Bitcoin as legal tender (first country)
    - India: Heavy taxation (30% on crypto gains)
  
  FOR DEVELOPERS:
    - KYC/AML requirements may apply to your DApp
    - Token launches may be regulated (consult legal counsel)
    - Tax reporting obligations for users
    - Data privacy laws still apply (GDPR)
    - Regulatory landscape is evolving rapidly

14. Key Takeaways

  1. Bitcoin is digital gold, Ethereum is programmable money — they serve fundamentally different purposes in the Web3 ecosystem.
  2. Coins have their own blockchain; tokens live on someone else's — USDC is a token on Ethereum, not a coin with its own chain.
  3. ERC-20 is the universal token standard — it defines the interface that makes all Ethereum tokens interoperable with wallets, exchanges, and DApps.
  4. Stablecoins bridge crypto and fiat — they are the most practically useful cryptocurrencies for commerce and payments. USDC and USDT dominate.
  5. Not your keys, not your coins — non-custodial wallets give you full control but full responsibility. Seed phrases are sacred.
  6. DeFi rebuilds finance on smart contracts — lending, borrowing, trading, and yield generation without banks. Real value, real risks.
  7. Tokenomics determines a token's economic behavior — supply, distribution, utility, and vesting schedules matter as much as the technology.
  8. Regulation is coming — the MiCA framework in the EU and ongoing SEC actions in the US are shaping how crypto projects operate.

Explain-It Challenge

  1. A friend asks "should I keep my crypto on Coinbase or move it to a MetaMask wallet?" Explain the trade-offs of custodial vs non-custodial storage.
  2. Your startup wants to accept cryptocurrency payments. Walk through the technical implementation and the pros/cons vs Stripe.
  3. Explain why stablecoins might be the most important innovation in crypto for real-world adoption, even though they are "boring" compared to volatile tokens.

Navigation: <- 6.10.d — Smart Contracts | 6.10 Overview