Module 6: Building Decentralized Applications (DApps)


    6.1 What is a DApp (Decentralized Application)?

    A DApp is a decentralized application that runs on a blockchain network instead of centralized servers. It interacts with smart contracts to perform operations in a transparent and trustless way.

    Key Features of DApps:

    • Decentralized: No single authority controls the app. Backend logic runs on smart contracts.
    • Transparent: Code is often open-source and verifiable.
    • Trustless: Users don’t need to trust a third party — they trust the code.
    • Incentivized: Many DApps have tokens as incentives for users/participants.

    DApp Architecture:

    1. Frontend: Built using HTML, CSS, JavaScript (React, Vue, etc.).
    2. Smart Contracts: Logic layer written in Solidity (Ethereum) and deployed on a blockchain.
    3. Wallet Integration: MetaMask or WalletConnect used to interact with contracts.
    // Example: Interacting with a contract
    const contract = new web3.eth.Contract(ABI, contractAddress);
    await contract.methods.vote(1).send({ from: userAddress });
      

    Examples of DApps:

    • Uniswap: Decentralized Exchange (DEX)
    • Aave: Lending & Borrowing
    • OpenSea: NFT Marketplace
    • Compound: Interest Earning Protocol
    • Snapshot: DAO Governance Voting

    Tools to Build DApps:

    • Remix IDE: For writing and deploying smart contracts
    • Hardhat / Truffle: Development and testing frameworks
    • MetaMask: User wallet for interacting with the DApp
    • Web3.js / Ethers.js: Libraries to connect frontend to smart contracts

    🚀 DApps are the future of Web3 — they remove middlemen and empower users with full control and transparency.



    6.2 Web3.js vs Ethers.js

    Both Web3.js and Ethers.js are JavaScript libraries that allow your frontend DApp to interact with the Ethereum blockchain. But they differ in design, size, and usability.

    1. Library Size & Performance:

    • Web3.js: ~700 KB (larger)
    • Ethers.js: ~88 KB (lightweight and faster)

    2. Developer Experience:

    • Web3.js: Older, well-established, but slightly more verbose
    • Ethers.js: Modern syntax, intuitive API, better TypeScript support

    3. Wallet and Provider Handling:

    • Web3.js: Requires manual handling for providers (e.g., MetaMask)
    • Ethers.js: Handles providers easily and cleanly (e.g., `ethers.providers.Web3Provider(window.ethereum)`)

    4. Example Comparison

    🔹 Web3.js

    
    const Web3 = require('web3');
    const web3 = new Web3(window.ethereum);
    const accounts = await web3.eth.getAccounts();
    const balance = await web3.eth.getBalance(accounts[0]);
      

    🔸 Ethers.js

    
    import { ethers } from 'ethers';
    const provider = new ethers.BrowserProvider(window.ethereum);
    const signer = await provider.getSigner();
    const address = await signer.getAddress();
    const balance = await provider.getBalance(address);
      

    Summary

    Feature Web3.js Ethers.js
    Size Large Lightweight
    Modern Syntax
    TypeScript Support Basic Excellent
    Provider Management Manual Easy
    Community Support Large Growing

    Recommendation: Use Ethers.js for new projects. It's cleaner, faster, and more future-proof.



    6.3 Connect MetaMask to Frontend

    MetaMask is a browser extension wallet that injects Ethereum’s window.ethereum object into the browser. This allows DApps to interact with the Ethereum blockchain via the user’s wallet.

    Prerequisite

    • MetaMask extension installed in browser
    • Basic HTML + JavaScript knowledge

    HTML + JavaScript Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>MetaMask Connect</title>
    </head>
    <body>
      <h2>🔐 Connect MetaMask Wallet</h2>
      <button id="connectBtn">Connect Wallet</button>
      <p id="account"></p>
    
      <script>
        const connectBtn = document.getElementById('connectBtn');
        const accountDisplay = document.getElementById('account');
    
        async function connectMetaMask() {
          if (window.ethereum) {
            try {
              const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
              accountDisplay.innerText = "Connected: " + accounts[0];
            } catch (error) {
              accountDisplay.innerText = "❌ Connection failed!";
              console.error(error);
            }
          } else {
            accountDisplay.innerText = "🦊 MetaMask not installed!";
          }
        }
    
        connectBtn.addEventListener('click', connectMetaMask);
      </script>
    </body>
    </html>

    Output:

    • Click "Connect Wallet" → MetaMask opens → User approves → Wallet address is shown.

    Behind the Scenes:

    • window.ethereum — injected by MetaMask
    • eth_requestAccounts — method to ask user to connect
    • Returns an array of wallet addresses (usually the first one)

    Next Step

    After connecting MetaMask, you can:

    • Show account balance
    • Send transactions
    • Interact with smart contracts


    6.4 Read/Write Smart Contract from Website

    This example shows how to read from and write to a smart contract using Ethers.js and MetaMask.

    Prerequisites

    • MetaMask installed and connected
    • Deployed contract on testnet
    • ABI and contract address

    Example Smart Contract (Solidity)

    // SimpleStorage.sol
    pragma solidity ^0.8.0;
    
    contract SimpleStorage {
        uint public storedData;
    
        function set(uint x) public {
            storedData = x;
        }
    
        function get() public view returns (uint) {
            return storedData;
        }
    }

    HTML + JS to Interact






    Output:

    Summary

    • Connect MetaMask using Ethers.js
    • contract.set(x) — writes data (transaction)
    • contract.get() — reads data (view call)


    6.5 Build a Simple Voting DApp (Decentralized Application)

    A Voting DApp allows users to cast votes securely on the blockchain. It ensures transparency, immutability, and trustless execution of voting results.

    Tools Required:

    • Solidity: To write the smart contract.
    • Remix IDE: For writing and deploying the smart contract.
    • MetaMask: To interact with the blockchain.
    • Ethereum Testnet: Like Sepolia or Goerli to test the app.
    • Frontend (Optional): HTML + JavaScript to interact with the contract.

    Step-by-Step Guide:

    1. Write the Smart Contract (Solidity):

      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
    
      contract Voting {
          mapping(string => uint) public votesReceived;
          string[] public candidateList;
    
          constructor(string[] memory candidateNames) {
              candidateList = candidateNames;
          }
    
          function voteForCandidate(string memory name) public {
              require(validCandidate(name), "Invalid Candidate");
              votesReceived[name] += 1;
          }
    
          function totalVotesFor(string memory name) public view returns (uint) {
              require(validCandidate(name), "Invalid Candidate");
              return votesReceived[name];
          }
    
          function validCandidate(string memory name) view public returns (bool) {
              for (uint i = 0; i < candidateList.length; i++) {
                  if (keccak256(bytes(candidateList[i])) == keccak256(bytes(name))) {
                      return true;
                  }
              }
              return false;
          }
      }
      

    2. Deploy on Remix IDE:

    • Go to Remix.
    • Paste the code in a new `.sol` file.
    • Compile the contract.
    • Use “Injected Web3” environment to connect MetaMask.
    • Deploy the contract by passing candidate names in an array (e.g., ["Alice", "Bob"]).

    3. Interact with the Contract:

    • Call voteForCandidate("Alice") to vote.
    • Use totalVotesFor("Alice") to check votes.

    Optional: Build a Frontend

    You can connect the smart contract to a simple HTML page using Web3.js or Ethers.js to allow users to vote through a user-friendly UI.

    Benefits:

    • Transparent and secure voting system.
    • No central authority required.
    • Results are stored immutably on blockchain.

    Tip:

    Always test your DApp on testnets before deploying to the Ethereum mainnet.

    Conclusion:

    A voting DApp is a great beginner blockchain project. It helps you learn smart contract development, blockchain deployment, and Web3 integration.



    6.6 Hosting a DApp on IPFS or Fleek

    Once you've built a decentralized application (DApp), the next step is to host it in a decentralized way. This ensures your frontend is censorship-resistant and accessible globally.

    What is IPFS?

    IPFS (InterPlanetary File System) is a decentralized storage network that allows you to host static files like HTML, CSS, JS, and images on a distributed peer-to-peer system.

    What is Fleek?

    Fleek is a platform that makes it easy to deploy websites and DApps on IPFS. It integrates with GitHub and offers automatic deployments, SSL, and IPFS pinning.

    Folder Structure for Hosting

      /my-dapp/
      ├── index.html
      ├── styles.css
      ├── script.js
      └── assets/
      

    Option 1: Hosting Manually on IPFS

    Step 1: Install IPFS CLI

      npm install -g ipfs-cli
      

    Step 2: Initialize IPFS

      ipfs init
      

    Step 3: Add Your Files

      ipfs add -r my-dapp/
      

    Step 4: Get IPFS Hash

    After running the above command, IPFS will return a hash (e.g., QmXYZ123...). You can now access your site via:

      https://ipfs.io/ipfs/QmXYZ123...
      

    Option 2: Hosting with Fleek

    Step 1: Go to https://fleek.co

    Step 2: Sign in with GitHub

    Authorize Fleek to access your repositories.

    Step 3: Create a New Site

    • Choose the GitHub repository with your DApp frontend.
    • Select build settings (for static: set build command as npm run build or leave blank).
    • Set publish directory (e.g., dist or build).

    Step 4: Deploy

    Fleek will deploy your DApp to IPFS and give you a URL like:

      https://your-dapp.on.fleek.co
      

    Optional: Link ENS or .crypto Domain

    You can link your DApp to a decentralized domain name (e.g., mydapp.eth) via ENS or Unstoppable Domains.

    Advantages:

    • Decentralized and censorship-resistant hosting
    • No central server, no downtime
    • Great for Web3 and blockchain-based apps

    Final Note:

    Make sure your DApp is completely frontend (static) and all blockchain interactions happen via smart contracts or public RPCs.

    No comments:

    Post a Comment