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

6.10 — Web3 Basics: Quick Revision

Compact cheat sheet. Print-friendly.

How to use this material (instructions)

  1. Skim before labs or interviews.
  2. Drill gaps — reopen README.md -> 6.10.a...6.10.e.
  3. Practice6.10-Exercise-Questions.md.
  4. Polish answers6.10-Interview-Questions.md.

Core Vocabulary

TermOne-liner
Web3Decentralized internet — read-write-own, built on blockchains
BlockchainDistributed, immutable, append-only ledger secured by cryptography
Smart contractSelf-executing code deployed on a blockchain (Solidity on EVM chains)
DAppDecentralized application — frontend + smart contracts + blockchain
EVMEthereum Virtual Machine — runtime for executing smart contracts
GasUnit of computational effort on Ethereum — you pay gas fees to write
WalletStores private keys that control blockchain assets (MetaMask, Ledger)
Seed phrase12-24 word backup of master private key — lose it, lose everything
Private keySecret 256-bit number that signs transactions — NEVER share
AddressPublic identifier derived from public key (0x...)
ConsensusHow nodes agree on the state of the blockchain (PoW, PoS)
PoWProof of Work — miners solve puzzles (Bitcoin) — energy-intensive
PoSProof of Stake — validators stake tokens (Ethereum) — energy-efficient
ERC-20Standard interface for fungible tokens (USDC, UNI, LINK)
ERC-721Standard interface for non-fungible tokens (NFTs)
DeFiDecentralized Finance — lending, borrowing, trading without banks
DEXDecentralized exchange — trade tokens via smart contracts (Uniswap)
CEXCentralized exchange — trade via a company (Coinbase, Binance)
IPFSInterPlanetary File System — decentralized, content-addressed storage
DAODecentralized Autonomous Organization — governed by token holders
TVLTotal Value Locked — assets deposited in a DeFi protocol
StablecoinCrypto pegged to fiat (USDC, USDT, DAI) — solves volatility
MempoolWaiting room for unconfirmed transactions
NonceSequential transaction counter per address — prevents replay attacks
ABIApplication Binary Interface — JSON schema for interacting with contracts
Merkle treeHash tree structure for efficient transaction verification

Web1 / Web2 / Web3 Comparison

              Web1              Web2              Web3
Era:          1990-2004         2004-2020         2020+
Mode:         Read              Read-Write        Read-Write-Own
Content:      Static pages      User-generated    User-owned
Identity:     Email             Social login      Wallet (0x...)
Payments:     Credit cards      PayPal/Stripe     Native crypto
Backend:      Own servers       Cloud (AWS)       Blockchain
Data:         Server files      Centralized DB    On-chain + IPFS
Trust:        Trust server      Trust platform    Trust code/math
Governance:   Webmaster         Corporate board   DAO + token vote

Blockchain Basics

BLOCK STRUCTURE:
  ┌─────────────────────────┐
  │ Previous Hash: 0xAABB   │ ← Links to prior block
  │ Timestamp               │
  │ Merkle Root             │ ← Hash tree of all transactions
  │ Nonce                   │ ← Used in PoW mining
  │ Transactions: [TX1...N] │
  │ Block Hash: 0xCCDD      │ ← Computed from everything above
  └─────────────────────────┘

CHAIN SECURITY:
  Change Block N → Hash N changes → Block N+1 previous hash mismatches
  → Must recompute ALL subsequent blocks → Computationally infeasible

HASH PROPERTIES:
  Deterministic:      same input = same hash
  Avalanche effect:   tiny change = completely different hash
  One-way:            cannot reverse from hash to input
  Collision-resistant: near-impossible to find two inputs with same hash

Consensus Mechanisms

PROOF OF WORK (Bitcoin):
  Miners compete → solve puzzle (find nonce) → first wins → earns block reward
  Attack: need >50% hash power
  Energy: enormous (country-level)
  Speed: ~10 min blocks (Bitcoin)

PROOF OF STAKE (Ethereum):
  Validators stake ETH → random selection → propose block → earn fees
  Attack: need >33% staked ETH
  Energy: 99.95% less than PoW
  Speed: ~12 sec blocks (Ethereum)
  Penalty: malicious behavior → stake slashed (destroyed)

Major Chains

Chain       Consensus    TPS      Block Time   Token
────────────────────────────────────────────────────
Bitcoin     PoW          ~7       ~10 min      BTC
Ethereum    PoS          ~15-30   ~12 sec      ETH
Solana      PoS+PoH      ~4,000   ~0.4 sec     SOL
Polygon     PoS (L2)     ~7,000   ~2 sec       MATIC
Arbitrum    Rollup (L2)  ~4,000   ~0.25 sec    ARB
Base        Rollup (L2)  ~2,000   ~2 sec       ETH

DApp Architecture

TRADITIONAL:                     DApp:

  React Frontend                   React Frontend
       │                                │
       ▼                                ▼
  REST API (Express)              ethers.js / Web3.js
       │                                │
       ▼                                ▼
  Database (PostgreSQL)           Smart Contract (Solidity)
       │                                │
       ▼                                ▼
  Server (AWS)                    Blockchain (Ethereum)
                                        │
                                        ▼
                                  IPFS (file storage)

Auth:   JWT / OAuth               Wallet signature
Read:   SELECT (free)             view/call (free)
Write:  INSERT/UPDATE (free*)     Transaction (costs gas!)
Files:  S3                        IPFS
Speed:  Milliseconds              Seconds to minutes

Smart Contract Essentials

Solidity Quick Reference

// Data types
uint256 count;                           // unsigned integer
address owner;                           // 20-byte address
mapping(address => uint256) balances;    // hash map (most used!)
string name;                             // dynamic string
bool active;                             // boolean

// Visibility
public    // anyone can call (internal + external)
external  // only callable from outside (slightly cheaper gas)
internal  // only this contract + derived contracts
private   // only this contract

// State mutability
view      // reads state, no modifications (FREE externally)
pure      // no state read or write (FREE externally)
payable   // can receive ETH

// Key patterns
modifier onlyOwner() { require(msg.sender == owner); _; }
event Transfer(address indexed from, address indexed to, uint256 value);

Contract Lifecycle

Write → Compile → Test → Audit → Deploy → Verify → Interact → Live forever
  │        │        │       │       │        │         │
Solidity  solc   Hardhat  Pros   Gas fee  Etherscan  ethers.js
                 Foundry  $10K+  paid     source     ABI-based

ERC-20 Interface

name()          → token name ("USD Coin")
symbol()        → token symbol ("USDC")
decimals()      → decimal places (6 for USDC, 18 for most)
totalSupply()   → total tokens in existence
balanceOf(addr) → tokens held by address
transfer(to, amount)              → send tokens
approve(spender, amount)          → allow spending
transferFrom(from, to, amount)    → spend on behalf

Security Checklist

1. Reentrancy        → Checks-Effects-Interactions pattern
2. Access control     → onlyOwner / OpenZeppelin AccessControl
3. Integer overflow   → Solidity 0.8+ (built-in checks)
4. Front-running      → Commit-reveal, Flashbots
5. Oracle manipulation → Chainlink oracles, TWAP
6. Unchecked returns  → Always verify external call results

Crypto Types

COINS vs TOKENS:
  Coin  = own blockchain        (BTC, ETH, SOL)
  Token = on another's chain    (USDC, UNI, LINK — all on Ethereum)

STABLECOINS:
  Fiat-backed:    USDC, USDT — trust the issuer holds real dollars
  Crypto-backed:  DAI — overcollateralized, trust the smart contract
  Algorithmic:    Fragile — TerraUST collapsed ($60B wiped)

WALLETS:
  Hot:       Online (MetaMask)    — convenient, less secure
  Cold:      Offline (Ledger)     — inconvenient, very secure
  Custodial: Exchange holds keys  — "not your keys, not your coins"
  Self-cust: You hold keys        — full control, full responsibility

EXCHANGES:
  CEX:  Custodial, KYC, fiat support, order book (Coinbase)
  DEX:  Non-custodial, no KYC, crypto only, AMM (Uniswap)

Gas Fee Cheat Sheet

Operation                Gas Units    At 30 gwei + ETH $3000
─────────────────────────────────────────────────────────────
ETH transfer             21,000       ≈ $1.89
ERC-20 transfer          ~65,000      ≈ $5.85
Uniswap swap             ~150,000     ≈ $13.50
NFT mint                 ~150,000     ≈ $13.50
Contract deployment      ~1,000,000+  ≈ $90+

Layer 2 costs (90-99% cheaper):
  Polygon transfer:      ≈ $0.001
  Arbitrum transfer:     ≈ $0.01-0.10
  Base transfer:         ≈ $0.001-0.01

EIP-1559: Base fee (burned) + Priority fee (to validator)

DeFi Quick Reference

LENDING (Aave, Compound):
  Deposit assets → earn interest (every block)
  Borrow against collateral → overcollateralized (150%+)
  If collateral drops → position liquidated

DEX (Uniswap):
  AMM model: x * y = k (constant product formula)
  Liquidity providers earn 0.3% of each swap
  Risk: impermanent loss if token prices diverge

STAKING:
  Lock tokens → help secure the network → earn rewards
  Ethereum: 32 ETH minimum (~$96K at $3000/ETH)
  Liquid staking (Lido): stake any amount, get stETH receipt

YIELD FARMING:
  Provide liquidity → earn trading fees + token rewards
  Risks: impermanent loss, smart contract bugs, token devaluation

ethers.js Quick Reference

// PROVIDER — read-only blockchain connection
const provider = new ethers.JsonRpcProvider(RPC_URL);
await provider.getBlockNumber();            // current block
await provider.getBalance(address);         // ETH balance

// SIGNER — wallet that can sign transactions
const signer = await browserProvider.getSigner(); // MetaMask
const wallet = new ethers.Wallet(PRIVATE_KEY, provider); // script

// CONTRACT — interact with smart contract
const contract = new ethers.Contract(address, abi, providerOrSigner);
await contract.balanceOf(addr);             // read (free)
await contract.transfer(to, amount);        // write (gas!)

// UTILITIES
ethers.parseEther("1.0");                   // "1.0" → wei
ethers.formatEther(weiValue);               // wei → "1.0"
ethers.parseUnits("100", 6);               // USDC: 100 → 100000000
ethers.formatUnits(rawValue, 6);            // USDC raw → human

// EVENTS
contract.on('Transfer', (from, to, value) => { ... });

Transaction Lifecycle

1. CREATE       → User constructs tx (to, value, data, gas settings)
2. SIGN         → Wallet signs with private key (ECDSA)
3. BROADCAST    → Sent to node → gossipped to network → enters mempool
4. INCLUSION    → Validator selects tx → includes in block
5. EXECUTION    → EVM runs the code → state updates → events emitted
6. ATTESTATION  → Other validators confirm the block
7. FINALITY     → After ~13 min (2 epochs) → economically irreversible

Common Gotchas

GotchaWhy
On-chain storage is expensive~20,000 gas per 32 bytes (SSTORE)
All on-chain data is publicNo secrets — even "private" variables are readable
Failed transactions still cost gasGas is consumed during execution, even if reverted
Smart contracts can't be patchedImmutable — must deploy a new contract
No "forgot password" for walletsLost private key / seed phrase = lost funds forever
Gas prices spike during congestionA $2 transfer can become $50 during high demand
Approve before transferFromDApps need token approval before they can move your tokens
Not all "Web3" is decentralizedMany DApps use Infura/Alchemy, Vercel, centralized APIs
Stablecoins can depegAlgorithm-based stables are especially risky (TerraUST)
MEV/front-running is realValidators/bots can see your pending tx and trade ahead

Decision Framework: Do You Need a Blockchain?

ASK THESE FIVE QUESTIONS:

  1. Multiple distrusting parties share state?     YES → maybe blockchain
  2. Need censorship resistance?                   YES → maybe blockchain
  3. Need tamper-proof audit trail + no auditor?   YES → maybe blockchain
  4. Need programmable money / tokenized assets?   YES → maybe blockchain
  5. Can tolerate: slow, public, expensive, immutable? YES → blockchain fits

  If ALL answers to 1-4 are NO → use a traditional database.
  Most apps don't need a blockchain. The ones that do benefit enormously.

End of 6.10 quick revision.