Back to Blockchain & Web3

Module 2: Ethereum & Smart Contracts

Understanding programmable blockchains and the world computer

🌐 What is Ethereum?

If Bitcoin is like digital gold (a store of value), Ethereum is like a world computer. It's a blockchain that can run programs, not just track money transfers.

Simple Analogy

Bitcoin: Like a calculator - it does one thing really well (transfers value)

Ethereum: Like a smartphone - it can run any app you program for it

Key Differences from Bitcoin

FeatureBitcoinEthereum
PurposeDigital currencyProgrammable platform
Block Time~10 minutes~12 seconds
ConsensusProof of WorkProof of Stake (since 2022)
ProgrammingLimited scriptingTuring-complete (can run any program)
Supply21 million maxNo hard cap

📚 Learn More:

🖥️ Ethereum Virtual Machine (EVM)

The EVM is the heart of Ethereum - it's like a giant, global computer that everyone can use but no one owns. Every computer (node) in the Ethereum network runs a copy of the EVM.

World Computer Analogy

Imagine if every computer in the world was connected and worked together as one massive computer. That's essentially what the EVM is - a decentralized computer that:

  • • Runs 24/7 and never goes down
  • • Can't be shut down by any government or company
  • • Executes code exactly as programmed (no human interference)
  • • Stores data permanently and immutably

How the EVM Works

1. Smart Contract Deployment

You write code (in Solidity), compile it to bytecode, and deploy it to the EVM. The code gets an address and lives on the blockchain forever.

2. Execution

When someone calls your smart contract, every node in the network executes the same code and verifies the results match. This ensures no cheating.

3. State Changes

The EVM updates the blockchain's state (balances, data, etc.) based on the execution results. Everyone's copy stays in sync.

🔑 Key Concept: Deterministic Execution

The EVM is deterministic - given the same input, it always produces the same output. This is crucial because thousands of computers need to agree on the result. No randomness allowed!

📚 Learn More:

⛽ Gas Fees: Paying for Computation

Gas is the fuel that powers the Ethereum network. Every operation on the EVM costs gas, and you pay for it in ETH (Ethereum's cryptocurrency).

Simple Analogy: Driving a Car

Think of Ethereum like a car trip:

  • Gas: The fuel you need (measured in units)
  • Gas Price: How much you pay per gallon (in Gwei, a tiny fraction of ETH)
  • Gas Limit: The size of your gas tank (max you're willing to spend)
  • Total Cost: Gas Used × Gas Price = Your transaction fee

Why Do We Need Gas?

Prevents Spam

Without fees, people could spam the network with infinite loops

Rewards Validators

Gas fees compensate validators for processing transactions

Prioritizes Transactions

Higher gas price = faster processing (like express shipping)

Limits Computation

Each block has a gas limit, preventing overload

Gas Cost Examples

OperationTypical Gas Cost
Simple ETH transfer21,000 gas
ERC-20 token transfer~65,000 gas
Swap on Uniswap~150,000 gas
Deploy simple contract~500,000 gas
Mint an NFT~100,000 gas

💡 Pro Tip: Gas Optimization

Gas prices fluctuate based on network demand. To save money:

  • • Transact during off-peak hours (weekends, late night UTC)
  • • Use gas trackers like Etherscan Gas Tracker
  • • Consider Layer 2 solutions (Arbitrum, Optimism) for cheaper transactions
  • • Write efficient smart contract code to minimize gas usage

📚 Learn More:

👤 Ethereum Accounts: EOA vs Contract Accounts

Ethereum has two types of accounts, and understanding the difference is crucial for working with the blockchain.

👤Externally Owned Account (EOA)

A regular user account controlled by a private key. This is what you get when you create a wallet.

Characteristics:

  • • Controlled by private key (you own it)
  • • Can send transactions
  • • Can hold ETH and tokens
  • • No code associated with it
  • • Free to create

Example Address:

0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb

📜Contract Account

A smart contract deployed on the blockchain. It has code and can execute logic automatically.

Characteristics:

  • • Controlled by code (no private key)
  • • Cannot initiate transactions (must be triggered)
  • • Can hold ETH and tokens
  • • Has associated code
  • • Costs gas to deploy

Example (Uniswap):

0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D

🔑 Key Difference:

EOAs are controlled by humans with private keys. Contract Accounts are controlled by code and execute automatically when triggered. Think of EOAs as people and Contract Accounts as robots that follow programmed instructions.

How They Interact

1. EOA → EOA: Simple ETH transfer

Alice sends 1 ETH to Bob

2. EOA → Contract: Call smart contract function

Alice swaps tokens on Uniswap

3. Contract → Contract: Smart contracts calling each other

Uniswap calls a token contract to transfer tokens

4. Contract → EOA: Send ETH/tokens to user

Staking contract sends rewards to Alice

👛 Wallets: Your Gateway to Ethereum

A wallet is software that manages your private keys and lets you interact with the blockchain. It's like a keychain that holds all your keys to different accounts.

Important: Wallets Don't Store Crypto!

Your crypto isn't "in" your wallet - it's on the blockchain. Your wallet just stores the private keys that prove you own it. Think of it like a key to a safe deposit box - the key isn't the money, but it gives you access to it.

Popular Wallet Types

🦊

Browser Extension Wallets

Install in your browser (Chrome, Firefox, etc.) for easy access to Web3 apps.

Popular Options:

  • MetaMask: Most popular, beginner-friendly
  • Rabby: Advanced features, multi-chain
  • Coinbase Wallet: Integrated with Coinbase exchange
✓ Easy to use✓ Free⚠ Less secure
🔐

Hardware Wallets

Physical devices that store your private keys offline. Most secure option for large amounts.

Popular Options:

  • Ledger: Nano S Plus, Nano X
  • Trezor: Model One, Model T
  • GridPlus: Lattice1
✓ Very secure⚠ Costs $50-200⚠ Less convenient
📱

Mobile Wallets

Apps for your smartphone. Great for on-the-go transactions and QR code scanning.

Popular Options:

  • Trust Wallet: Multi-chain, built-in dApp browser
  • Rainbow: Beautiful UI, Ethereum-focused
  • Argent: Social recovery, no seed phrase
✓ Convenient✓ Free⚠ Medium security

🚨 Security Best Practices:

  • Never share your seed phrase - It's like your master password
  • Write it down offline - Don't store it digitally
  • Use hardware wallets for large amounts - Worth the investment
  • Verify addresses carefully - One wrong character = lost funds
  • Beware of phishing - Always check URLs before connecting wallet
  • Test with small amounts first - Especially on new platforms

📚 Learn More:

📜 Smart Contract Basics

Smart contracts are self-executing programs stored on the blockchain. They automatically enforce agreements without needing a middleman like a lawyer or bank.

Vending Machine Analogy

A smart contract is like a vending machine:

  • • You put money in (send ETH)
  • • Select what you want (call a function)
  • • The machine automatically gives you the product (executes code)
  • • No human needed - it just works based on programmed rules

Simple Smart Contract Example

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

// A simple storage contract
contract SimpleStorage {
    // State variable to store a number
    uint256 public favoriteNumber;
    
    // Function to store a new number
    function store(uint256 _favoriteNumber) public {
        favoriteNumber = _favoriteNumber;
    }
    
    // Function to retrieve the stored number
    function retrieve() public view returns (uint256) {
        return favoriteNumber;
    }
}

Code Explanation:

  • pragma solidity ^0.8.0 - Specifies Solidity version
  • uint256 public favoriteNumber - Stores a number on the blockchain
  • store() - Function to update the number (costs gas)
  • retrieve() - Function to read the number (free, no gas)

Key Characteristics of Smart Contracts

Immutable

Once deployed, code cannot be changed (unless designed with upgradability)

Deterministic

Same input always produces same output

Transparent

Anyone can view the code and verify what it does

Trustless

No need to trust a person - trust the code

💡 Real-World Use Cases:

  • DeFi: Lending, borrowing, trading without banks
  • NFTs: Proving ownership of digital art and collectibles
  • DAOs: Decentralized organizations with voting
  • Gaming: In-game items that players truly own
  • Supply Chain: Tracking products from factory to customer

📡 Events and Logging

Events are a way for smart contracts to communicate that something happened. They're like notifications that get stored on the blockchain and can be listened to by applications.

Simple Analogy: Doorbell

Events are like a doorbell. When someone rings it (triggers an event), everyone inside the house (listening applications) knows something happened. The event tells you "who rang" and "when" without you having to constantly check the door.

Why Use Events?

Cheaper than Storage

Events cost much less gas than storing data in contract variables

Frontend Notifications

Web apps can listen for events and update the UI in real-time

Historical Data

Query past events to build transaction history

Debugging

Track what happened during contract execution

Event Example

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

contract EventExample {
    // Define an event
    event Transfer(
        address indexed from,    // indexed = searchable
        address indexed to,      // indexed = searchable
        uint256 amount          // not indexed
    );
    
    // Function that emits an event
    function transfer(address to, uint256 amount) public {
        // ... transfer logic here ...
        
        // Emit the event
        emit Transfer(msg.sender, to, amount);
    }
}

Code Explanation:

  • event Transfer(...) - Declares an event with parameters
  • indexed - Makes parameters searchable (max 3 indexed params)
  • emit Transfer(...) - Triggers the event, logging it to the blockchain
  • • Events are stored in transaction logs, not in contract storage

Listening to Events (JavaScript)

// Using ethers.js to listen for events
const contract = new ethers.Contract(address, abi, provider);

// Listen for Transfer events
contract.on("Transfer", (from, to, amount, event) => {
    console.log(`${from} sent ${amount} to ${to}`);
    // Update your UI here
});

// Query past events
const filter = contract.filters.Transfer(null, myAddress);
const events = await contract.queryFilter(filter);
console.log("Past transfers to me:", events);

💡 Best Practices:

  • • Emit events for all important state changes
  • • Use indexed parameters for values you'll search by (addresses, IDs)
  • • Keep event names clear and descriptive
  • • Events are permanent - they can't be deleted

📚 Learn More:

🎯 What's Next?

You now understand Ethereum, the EVM, gas fees, accounts, wallets, and smart contracts! In the next module, we'll dive deep into Solidity programming and learn how to write your own smart contracts.