Module 5: Smart Contracts & Solidity


    5.1 What is a Smart Contract?

    A smart contract is a self-executing program stored on a blockchain. It automatically runs when predefined conditions are met — without the need for third parties.

    How It Works

    Smart contracts are written in code (e.g., Solidity for Ethereum) and define rules like traditional contracts. Once deployed, the contract runs exactly as programmed.

    Key Characteristics

    • Trustless: No need to trust any party — the code enforces the rules.
    • Immutable: Once deployed, it cannot be changed.
    • Transparent: Code and actions are visible on the blockchain.

    Example Use Case

    In a crowdfunding DApp, a smart contract could be set to release funds to a project only when a funding goal is reached by a specific date. If not met, the funds are returned automatically to contributors.

    Benefits

    • Removes middlemen
    • Reduces costs and delays
    • Increases security and accuracy

    Popular Smart Contract Platforms

    • Ethereum (Solidity)
    • Solana (Rust)
    • BNB Chain (Solidity)
    • Polygon
    • Avalanche

    In short, smart contracts are the backbone of decentralized applications (dApps), automating processes in finance, gaming, identity, and more.



    5.2 Introduction to Solidity

    Solidity is a high-level, statically typed programming language used to write smart contracts for the Ethereum Virtual Machine (EVM).

    Key Features

    • Contract-Oriented: Solidity is designed specifically for creating and managing smart contracts.
    • Influenced by: Languages like JavaScript, Python, and C++.
    • Compiles to: Bytecode that can be executed on the Ethereum blockchain.

    Basic Syntax Example

    
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    
    contract HelloWorld {
        string public message = "Hello, Blockchain!";
    
        function updateMessage(string memory newMessage) public {
            message = newMessage;
        }
    }
    
      

    Structure of a Solidity Contract

    • Version Declaration: Specifies compiler version (e.g., ^0.8.0).
    • Contract Definition: contract HelloWorld { ... }
    • State Variables: Store data on the blockchain (e.g., string public message).
    • Functions: Define contract behavior (e.g., updateMessage()).

    Common Use Cases

    • Token creation (ERC-20, ERC-721)
    • Decentralized finance (DeFi) protocols
    • Crowdfunding platforms
    • Voting systems

    Development Tools

    • Remix IDE: Online IDE for writing, testing, and deploying smart contracts.
    • Hardhat / Truffle: Frameworks for local development, testing, and deployment.
    • MetaMask: Wallet for interacting with deployed contracts.

    Solidity is essential for Ethereum dApp development, providing the logic and functionality behind decentralized systems.



    5.3 Remix IDE Setup

    Remix IDE is a powerful, web-based Integrated Development Environment (IDE) for writing, testing, debugging, and deploying Solidity smart contracts.

    1. Open Remix IDE

    2. Interface Overview

    • File Explorers: Create, edit, and organize your smart contract files.
    • Solidity Compiler: Compile your Solidity code.
    • Deploy & Run Transactions: Deploy contracts and interact with functions.
    • Terminal: Displays logs, transaction info, and errors.

    3. Creating Your First Smart Contract

    1. Click on File ExplorersNew File
    2. Name the file HelloWorld.sol
    3. Paste the following code:
    
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    
    contract HelloWorld {
        string public message = "Hello Remix!";
    
        function setMessage(string memory newMessage) public {
            message = newMessage;
        }
    }
    
      

    4. Compile the Contract

    1. Go to the Solidity Compiler tab (third icon on left).
    2. Select the correct compiler version (e.g., 0.8.x).
    3. Click Compile HelloWorld.sol.

    5. Deploy the Contract

    1. Go to the Deploy & Run Transactions tab (fourth icon on left).
    2. Make sure the environment is set to JavaScript VM.
    3. Click Deploy.
    4. Scroll down to see the deployed contract and interact with it.

    6. Interact with the Contract

    • Click message to see the current value.
    • Use setMessage to change the message.

    Tips

    • Use Auto Compile for easier development.
    • You can switch environments to Injected Web3 for MetaMask deployment.
    • Use the terminal for debugging transaction issues.

    Remix IDE is the fastest way to learn and test Solidity smart contracts with zero setup. Ideal for beginners and quick prototyping.



    5.4 Your First Smart Contract

    In this tutorial, you will write, compile, and deploy your first Solidity smart contract using Remix IDE.

    1. What is a Smart Contract?

    A smart contract is a self-executing program stored on a blockchain that runs when predefined conditions are met. Think of it as an automated agreement — no third parties needed.

    2. The "HelloWorld" Contract

    Let’s write a simple contract that stores and updates a message.

    Smart Contract Code:

    
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    
    contract HelloWorld {
        string public message = "Hello, Blockchain!";
    
        function setMessage(string memory _newMessage) public {
            message = _newMessage;
        }
    }
    
      

    3. Steps to Deploy on Remix

    Step 1: Open Remix

    Step 2: Create a New File

    • Click the File Explorer icon
    • Create a new file named HelloWorld.sol
    • Paste the above Solidity code

    Step 3: Compile the Code

    • Go to the Solidity Compiler tab
    • Select compiler version 0.8.x
    • Click "Compile HelloWorld.sol"

    Step 4: Deploy the Contract

    • Go to the Deploy & Run Transactions tab
    • Select environment: JavaScript VM
    • Click "Deploy"

    4. Interact with Your Contract

    • Click message to read the current message.
    • Use setMessage input field to change the message (e.g., "Web3 is awesome!").
    • Click message again to see the updated value.

    5. Key Concepts You Learned

    • State Variable: message stores data on the blockchain.
    • Function: setMessage updates the message.
    • Visibility: public allows interaction from outside.
    • Memory: Temporary storage for input strings.

    Next Steps

    • Experiment with new functions
    • Try deploying to testnets using MetaMask
    • Learn events, modifiers, and constructor functions

    Congratulations! You've just deployed your first smart contract 🚀



    5.5 Solidity Basics: Data Types, Functions, and Modifiers

    In this lesson, you will learn the core building blocks of Solidity smart contracts: data types, functions, and modifiers.

    1. Solidity Data Types

    Solidity supports a variety of data types, divided into value and reference types:

    🔹 Value Types

    • uint: Unsigned integer (e.g., uint256)
    • int: Signed integer (e.g., int8)
    • bool: Boolean (true/false)
    • address: Ethereum address
    • bytes1 to bytes32: Fixed-size byte arrays

    🔹 Reference Types

    • string: UTF-8 encoded string
    • bytes: Dynamic byte array
    • array: e.g., uint[]
    • mapping: Key-value pair storage
    • struct: Custom data structures

    🔸 Example:

    uint256 public number = 100;
    bool public isActive = true;
    string public name = "Solidity";
    address public owner = msg.sender;

    2. Functions in Solidity

    Functions define logic and are used to read or update data on the blockchain.

    Function Syntax:

    function functionName(parameterType param) public view returns (returnType) {
      // code
    }

    Types of Functions:

    • pure: Doesn’t read/write blockchain state
    • view: Reads but doesn't write to the state
    • payable: Allows receiving Ether

    🔸 Example:

    function getNumber() public view returns (uint) {
      return number;
    }
    
    function setNumber(uint _num) public {
      number = _num;
    }

    3. Function Modifiers

    Modifiers are used to change the behavior of functions, often for validation like access control.

    Common Example: onlyOwner

    modifier onlyOwner() {
      require(msg.sender == owner, "Not the owner");
      _;
    }
    
    function setMessage(string memory _msg) public onlyOwner {
      message = _msg;
    }
    

    🔍 How It Works:

    • require(): Validates conditions
    • _;: Placeholder to insert the rest of the function

    Quick Recap

    • Learn basic data types: uint, bool, string, address
    • Functions can read or change blockchain state
    • Modifiers add pre-checks (e.g., access control)


    5.6 Deploying Smart Contracts on Ethereum Testnet

    Once your smart contract is ready, the next step is to deploy it on a test network (testnet) before going live on the Ethereum mainnet.

    What is an Ethereum Testnet?

    An Ethereum testnet is a blockchain network used for testing purposes. It behaves like the mainnet but uses test Ether instead of real Ether.

    Popular Testnets:

    • Sepolia (most widely used as of 2024)
    • Holesky
    • Goerli (being deprecated)

    Prerequisites

    • A MetaMask wallet installed and set up
    • Remix IDE with your contract ready
    • Some testnet ETH in your wallet (from a faucet)

    Get Test ETH from Sepolia Faucet:

    Visit: https://sepoliafaucet.com or use Alchemy’s faucet

    Steps to Deploy on Ethereum Testnet

    Step 1: Connect MetaMask to Testnet

    • Open MetaMask → Select Sepolia network from dropdown
    • If it’s not visible, click “Add Network” → Search and add Sepolia

    Step 2: Open Remix IDE

    Go to https://remix.ethereum.org and paste your contract code.

    Step 3: Compile the Contract

    • Click the Solidity Compiler tab (🛠️ icon)
    • Select compiler version (e.g., 0.8.21)
    • Click “Compile [YourContract.sol]”

    Step 4: Deploy Using Injected Provider

    • Go to the Deploy & Run Transactions tab (📝 icon)
    • Under “Environment”, select Injected Provider - MetaMask
    • Confirm the MetaMask connection
    • Click “Deploy” and approve the transaction in MetaMask

    Step 5: Verify Deployment

    • You’ll see the deployed contract under “Deployed Contracts”
    • Use the interface to call functions, check values, and test logic

    Best Practices

    • Test thoroughly on testnet before mainnet deployment
    • Keep MetaMask seed phrase secure
    • Watch gas fees and transaction limits

    🎉 Congratulations! Your contract is now live on the Ethereum testnet.



    5.7 Common Vulnerabilities in Solidity

    Security is a critical part of smart contract development. Let’s explore two major vulnerabilities you must be aware of: Reentrancy and Integer Overflow/Underflow.

    Reentrancy Attack

    Occurs when an external contract makes a recursive call back into the calling contract before the first function is finished executing.

    Example:

    
    // Vulnerable Smart Contract
    function withdraw() public {
        uint amount = balances[msg.sender];
        (bool sent, ) = msg.sender.call{value: amount}(""); // ⚠️ External call before balance update
        require(sent, "Failed");
        balances[msg.sender] = 0; // 🛑 Update happens AFTER
    }
      

    Solution: Checks-Effects-Interactions Pattern

    • Check</> all conditions
    • Effect</>: Update contract state
    • Interaction</>: Do external calls last
    
    // Safe Withdraw Pattern
    function withdraw() public {
        uint amount = balances[msg.sender];
        balances[msg.sender] = 0; // ✅ Update first
        (bool sent, ) = msg.sender.call{value: amount}("");
        require(sent, "Failed");
    }
      

    Integer Overflow / Underflow

    Before Solidity 0.8.0, integers could overflow or underflow silently, causing unexpected behavior.

    Example:

    
    // Before Solidity 0.8.0
    uint8 x = 255;
    x = x + 1; // x becomes 0 (Overflow)
      

    Solution 1: Use Solidity ≥ 0.8.0

    • It has built-in overflow/underflow protection

    Solution 2: Use SafeMath (for older versions)

    Import from OpenZeppelin library:

    
    using SafeMath for uint256;
    uint256 x = x.add(1);
      

    Tips to Avoid Vulnerabilities

    • Follow the Checks-Effects-Interactions pattern
    • Avoid using .call unless necessary
    • Use latest Solidity version for safety checks
    • Use audited libraries like OpenZeppelin
    • Test using tools like Slither, MythX, or Remix Analysis

    Security-first development saves you from major losses on the mainnet.

    No comments:

    Post a Comment