Unit 5 - Notes

CSC203

Unit 5: Ethereum Basics

1. Ethereum and Smart Contracts

Overview of Ethereum

Ethereum is an open-source, distributed computing platform based on blockchain technology. Unlike Bitcoin, which was designed primarily as a peer-to-peer electronic cash system, Ethereum was designed to be a general-purpose programmable blockchain. It introduces the concept of the Ethereum Virtual Machine (EVM), which serves as a global, decentralized computer.

  • The World Computer: Every node in the Ethereum network runs the EVM and maintains the current state of the ledger.
  • State-Based Architecture: While Bitcoin uses a UTXO (Unspent Transaction Output) model, Ethereum uses an Account-Based Model. This tracks the current state (balances, storage, code) of every account.

Smart Contracts Defined

A Smart Contract is a self-executing contract with the terms of the agreement between buyer and seller being directly written into lines of code. The code and the agreements exist across a distributed, decentralized blockchain network.

  • Origin: The term was coined by computer scientist Nick Szabo in 1994, long before blockchain technology existed.
  • Mechanism: They act like "cryptographic vending machines." If you input the required cryptocurrency (money) and select a product (function), the machine automatically releases the item (executes logic) without a cashier (middleman).
  • Immutability: Once deployed to the Ethereum blockchain, the code cannot be changed (unless specific upgradeability patterns are programmed in advance).

A detailed conceptual architectural diagram showing the execution flow of an Ethereum Smart Contract...
AI-generated image — may contain inaccuracies


2. Turing Completeness and Verification Challenges

Turing Completeness

Ethereum is Turing Complete, meaning its programming language (Solidity, compiling to EVM bytecode) can theoretically solve any computational problem, provided it has enough resources (time and memory).

  • Loops and Logic: Unlike Bitcoin’s scripting language, Ethereum supports complex features like while loops, for loops, and recursive function calls.
  • The Halting Problem: A fundamental problem in computer science is that it is impossible to predict if a program will run forever (infinite loop) or eventually stop.
  • The Solution - Gas: To prevent infinite loops from crashing the network, Ethereum introduces Gas. Every operation costs a specific amount of gas. If a transaction runs out of gas, execution halts, and changes are reverted. This limits the execution time, effectively making it "Quasi-Turing Complete" in practice.

Verification Challenges

Because smart contracts handle significant financial assets, bugs are catastrophic. The flexibility of Turing completeness introduces vulnerabilities.

  1. Re-entrancy Attacks: A vulnerability where a malicious contract calls back into the calling contract before the first invocation is finished (e.g., The DAO Hack).
  2. Integer Overflow/Underflow: Arithmetic operations reaching the maximum capacity of a variable type and wrapping around.
  3. Formal Verification: The mathematical proof that code acts exactly as specified. This is difficult in Ethereum due to the complexity of the EVM and interaction between different contracts.

3. Using Smart Contracts to Enforce Legal Contracts

Smart contracts allow for the automation of contractual performance, but they differ significantly from traditional legal contracts.

Comparison: Code vs. Law

Feature Traditional Legal Contract Smart Contract
Language Natural Language (English, etc.) Programming Language (Solidity)
Ambiguity High (Subject to interpretation) None (Deterministic execution)
Enforcement Courts, Law Enforcement, Arbitrators Cryptographic Code Execution
Cost High (Lawyers, administrative fees) Low (Gas fees, deployment costs)
Scope Broad (Subjective human behavior) Narrow (On-chain data/logic)

Ricardian Contracts

A bridge between legal and smart contracts. A Ricardian contract records the agreement in a format that is both:

  1. Human-readable: A legal text document.
  2. Machine-readable: Parsable code that executes the terms.
    The cryptographic hash of the legal document is often embedded in the smart contract to bind the two.

A split-screen comparison infographic visualizing "Traditional Law vs. Smart Code". The left side fe...
AI-generated image — may contain inaccuracies


4. Comparing Bitcoin Scripting vs. Ethereum Smart Contracts

While both utilize blockchain, their capabilities differ fundamentally based on their design goals.

Bitcoin Scripting

  • Stack-Based Language: Bitcoin uses a language called Script. It functions using a stack data structure (Last-In, First-Out).
  • Not Turing Complete: It intentionally lacks loops (for, while) to avoid infinite execution and Denial of Service (DoS) attacks.
  • Stateless: Scripts usually verify a specific transaction spending condition (UTXO). They do not see the "global state" or balances of other users.
  • Focus: Security and simplicity for monetary transactions.

Ethereum Smart Contracts

  • Turing Complete: capable of complex logic.
  • Stateful: Contracts have persistent memory (storage) that stays on the blockchain between transactions.
  • Account Model: Operates on accounts (User accounts and Contract accounts).
  • Focus: Decentralized Applications (DApps), DAOs, and complex financial instruments (DeFi).

Comparative Architecture

A detailed technical diagram contrasting the Bitcoin UTXO model with the Ethereum Account model. The...
AI-generated image — may contain inaccuracies


5. Writing Smart Contracts: Solidity & JavaScript

Developing on Ethereum typically involves writing the contract in Solidity (backend) and interacting with it using JavaScript (frontend/testing).

Solidity (The Contract Language)

Solidity is an object-oriented, high-level language for implementing smart contracts. It is statically typed and supports inheritance.

Key Components of a Solidity File:

  1. Pragma: Specifies the compiler version.
  2. State Variables: Variables whose values are permanently stored in contract storage.
  3. Functions: Executable units of code.
  4. Events: Way to log activity on the blockchain for the frontend to listen to.

Example: Simple Storage Contract

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

contract SimpleStorage {
    // State variable to store a number
    uint256 private storedData;

    // Event to emit when value changes
    event DataChanged(uint256 newValue);

    // Function to set the value
    function set(uint256 x) public {
        storedData = x;
        emit DataChanged(x);
    }

    // Function to retrieve the value
    // 'view' means it reads state but doesn't modify it (no gas cost for local call)
    function get() public view returns (uint256) {
        return storedData;
    }
}

JavaScript (The Interaction Layer)

JavaScript is used to test contracts, deploy them, and build user interfaces (websites) that talk to the blockchain. Libraries like Web3.js or Ethers.js are used as bridges.

How JS Interacts with Ethereum:

  • JSON-RPC: JavaScript sends requests to an Ethereum node via JSON-RPC.
  • ABI (Application Binary Interface): A JSON file generated by the Solidity compiler that tells JavaScript what functions exist in the contract and what parameters they accept.

Example: Interacting via Ethers.js

JAVASCRIPT
const { ethers } = require("ethers");

// 1. Connect to a Provider (e.g., MetaMask or Infura)
const provider = new ethers.providers.Web3Provider(window.ethereum);

// 2. The Contract Address and ABI
const contractAddress = "0x123..."; 
const contractABI = [ /* ABI array from compilation */ ];

// 3. Create a Contract Instance
const storageContract = new ethers.Contract(contractAddress, contractABI, provider.getSigner());

// 4. Calling the Smart Contract Functions
async function updateValue() {
    // Write operation (requires gas and wallet signature)
    const tx = await storageContract.set(42);
    await tx.wait(); // Wait for block confirmation
    console.log("Value updated!");
}

async function readValue() {
    // Read operation (free, no signature required)
    const value = await storageContract.get();
    console.log("Stored value is: " + value.toString());
}

A flowchart illustrating the development lifecycle of an Ethereum DApp. The flow starts at the top l...
AI-generated image — may contain inaccuracies