­­FIN451 / MBA651 Blockchain Class Web Page, Fall ' 24

Instructor: Maggie Foley

Jacksonville University

 

The Syllabus           Risk Tolerance Assessment       Term Project: Just complete a smart contract and a DApp

 

Weekly SCHEDULE, LINKS, FILES and Questions

Chapter

Coverage, HW, Supplements

-       Required

References

 

Week 1

 

Week 1 - The basics of Bitcoins and Blockchains by Mr. Lewis

https://www.youtube.com/watch?v=-xEdF8utQNE&t=650s (audiobook)

Cryptography: from 2:38:27 to 3:10:08

Bitcoin:  from 3:10:08 to 5:41:05

Etherum  from 5:41:05 to 8:08:51

 

PPT  on Cryptography

 

Blockchain in general, Bitcoin, Bitcoin Mining, POW   PPT     Quiz1

·       Self-produced video on bitcoin: Understanding Bitcoin

·       Also watch Blockchain Full Course - 4 Hours |Simplilearn (from beginning to 1:20:10)

https://www.youtube.com/watch?v=SyVMma1IkXM&t=4849s

·       Bitcoin Supply Game

 

Blockchain in general, and Bitcoin

1. What is Bitcoin?

  • Definition: Bitcoin is a decentralized digital currency, created in 2009 by an unknown person or group of people using the pseudonym Satoshi Nakamoto. It operates without a central authority or banks.
  • How it works: Bitcoin transactions are recorded on a public ledger called the blockchain, which is maintained by a network of computers (nodes).

2. The Technology Behind Bitcoin

  • Blockchain: The concept of blockchain as a distributed ledger that records all transactions across a network of computers. Each block in the chain contains a list of transactions and is linked to the previous block, forming a chain.
  • Mining: The process of mining, where participants (miners) use computational power to solve complex mathematical problems that validate and secure transactions on the Bitcoin network. In return, miners are rewarded with newly created bitcoins.

3. Why Bitcoin?

  • Decentralization: Unlike traditional currencies, Bitcoin is not controlled by any central government or institution. This decentralization is a key feature that attracts many users.
  • Limited Supply: There will only ever be 21 million bitcoins, which creates scarcity and can drive demand.
  • Transparency and Security: Bitcoin transactions are transparent and secure, thanks to the blockchain. Transactions cannot be altered once they are recorded, which provides a high level of security.

4. How to Use Bitcoin

  • Transactions: Bitcoin can be used to buy goods and services, transferred between individuals, or held as an investment.
  • Wallets: The concept of Bitcoin wallets, which are digital tools that allow users to send, receive, and store their bitcoins. Wallets can be software-based (like apps) or hardware-based (physical devices).

5. The Impact of Bitcoin

  • Financial Innovation: Bitcoin is considered the first successful cryptocurrency and has paved the way for thousands of other digital currencies.
  • Global Economy: The potential impact of Bitcoin on the global financial system, including topics like financial inclusion, remittances, and challenges to traditional banking systems.
  • Challenges and Criticisms: Some challenges Bitcoin faces, such as regulatory issues, price volatility, and environmental concerns related to mining.

6. Future of Bitcoin

  • Adoption: Growing acceptance of Bitcoin by businesses, investors, and even some governments.
  • Technological Advancements: Mention ongoing developments, such as the Lightning Network, which aims to make Bitcoin transactions faster and cheaper.

 

Bitcoin Mining   Blockchain Full Course - 4 Hours by Simplilearn (2:16:48 – 2:34:44)   PPT       Quiz    Bitcoin_Mining_Simulator

 

·       Self-produced video: Bitcoin Mining Explained! | Easy Guide for Beginners

 

1.    What is Bitcoin Mining?

  • Definition: Bitcoin mining is the process by which new bitcoins are created and transactions are added to the blockchain, the public ledger of all Bitcoin transactions.
  • Analogy: Think of Bitcoin mining as a competitive game. In this game, participants (called miners) are trying to solve a really difficult puzzle. The first one to solve the puzzle gets to add a new block of transactions to the blockchain and is rewarded with new bitcoins.

2. The Role of Hashing

  • What is Hashing? Hashing is like taking a piece of information (like a list of transactions) and running it through a special mathematical function that turns it into a unique string of numbers and letters. This string is called a "hash."
  • Analogy: Imagine hashing as a blender. You put in different ingredients (transactions), blend them, and what comes out is a smoothie (the hash). Even if you slightly change the ingredients (like changing a single transaction), you’ll get a completely different smoothie (hash).

3. Proof of Work (PoW)

  • Definition: Proof of Work is the mechanism that makes Bitcoin mining possible. It requires miners to solve a complex mathematical problem before they can add a new block to the blockchain. This problem is solved by finding a special kind of hash.
  • How it Works:
    • The puzzle miners are trying to solve involves finding a hash that starts with a certain number of zeros.
    • Miners do this by trying different inputs (numbers called "nonces") until they find one that, when hashed, produces the required hash with the zeros.
    • The process takes a lot of computational power because miners have to try many different nonces before they find the right one.
  • Analogy: Think of PoW as a guessing game. The game asks miners to guess a number, but the only way to know if the guess is correct is to try it and see if it works. This means miners have to make many, many guesses before they get it right.

4. Why is Mining Important?

  • Security: The difficulty of solving the PoW puzzle ensures that Bitcoin's blockchain is secure. Because it takes so much effort to solve, it’s practically impossible for someone to change or tamper with a block once it’s been added to the blockchain.
  • Decentralization: Mining is decentralized, meaning that anyone with the right equipment can participate, which helps keep the Bitcoin network fair and secure.

5. Mining Rewards

  • Block Reward: When a miner successfully solves the PoW puzzle and adds a new block to the blockchain, they are rewarded with a certain number of bitcoins. This is called the block reward.
  • Transaction Fees: In addition to the block reward, miners also earn transaction fees from the transactions included in the block they added to the blockchain.

6. Environmental Concerns

  • Energy Use: Mining requires a lot of computational power, which in turn requires a lot of electricity. This has raised concerns about the environmental impact of Bitcoin mining.
  • Efforts to Improve: The Bitcoin community is continually looking for ways to make mining more energy-efficient, including exploring alternative consensus mechanisms and renewable energy sources.

Summary

  • Bitcoin mining is the process of adding new transactions to the blockchain and earning new bitcoins as a reward.
  • Hashing is used to turn transaction data into a unique code, and miners must find a specific type of hash to solve the PoW puzzle.
  • PoW is a guessing game that ensures Bitcoin’s security by making it hard to alter the blockchain.

 

 

PPT on Bitcoin Wallet   ppt    Quiz

 Simplilearn 4 hour course (2:35:34 2:57:05)    Crypto Wallet Simulator

 

·       Self-produced video: Stay Safe in Crypto! Tips with MetaMask Fox & Friends

 

1. What is a Bitcoin Wallet?

  • Definition: A Bitcoin wallet is a digital tool that allows you to send, receive, and store your bitcoins. It’s like a bank account for your bitcoins, but instead of holding physical money, it holds digital currency.
  • Analogy: Imagine a Bitcoin wallet as a real wallet you carry in your pocket. Just like you use your physical wallet to store cash, a Bitcoin wallet stores your digital money (bitcoins).

2. How Does a Bitcoin Wallet Work?

  • Private Key and Public Key:
    • Private Key: This is a secret code that allows you to access and control your bitcoins. It’s like the password to your bank account. If someone has your private key, they can spend your bitcoins, so it’s essential to keep it safe.
    • Public Key: This is like your bank account number. It’s a code that people use to send you bitcoins. You can share your public key with others, and they can use it to send bitcoins to your wallet.
  • Analogy: Think of your private key as the key to a safety deposit box. Only you should have access to this key because it gives you control over the money inside. The public key is like the address of the bank where your safety deposit box is located, which others can use to send money to your box.

3. Types of Bitcoin Wallets

  • Software Wallets:
    • These are apps or programs you can install on your computer or smartphone. They allow you to easily access and manage your bitcoins.
    • Example: Mobile wallets like Coinbase or desktop wallets like Electrum.
  • Hardware Wallets:
    • These are physical devices, like a USB stick, that store your private keys offline. They are more secure because they are not connected to the internet, making them less vulnerable to hacking.
    • Example: Ledger Nano S, Trezor.
  • Paper Wallets:
    • This is a piece of paper with your public and private keys printed on it. It’s a very secure way to store bitcoins, as long as you keep the paper safe.
    • Example: You generate a paper wallet using a secure online service, then print it out and store it in a safe place.
  • Analogy: If a software wallet is like an app on your phone, a hardware wallet is like a safe that you keep at home, and a paper wallet is like writing down your bank details on a piece of paper and keeping it in a safe place.

4. Why Use a Bitcoin Wallet?

  • Security: A Bitcoin wallet helps keep your bitcoins safe. By securely storing your private key, you control who can access your funds.
  • Convenience: Bitcoin wallets make it easy to send and receive bitcoins. You can quickly make transactions by scanning a QR code or entering an address.
  • Ownership: When you have a Bitcoin wallet, you have full control over your bitcoins. No one else can access your funds unless they have your private key.

5. How to Use a Bitcoin Wallet

  • Receiving Bitcoins:
    • To receive bitcoins, you give someone your public key (or wallet address). They send the bitcoins to that address, and it shows up in your wallet.
    • Example: You can send your friend a QR code that represents your wallet address, and they can scan it to send you bitcoins.
  • Sending Bitcoins:
    • To send bitcoins, you enter the recipient’s wallet address and the amount you want to send. The wallet uses your private key to authorize the transaction.
    • Example: If you want to pay for something online with Bitcoin, you would enter the seller's wallet address and send the payment through your wallet.

6. Security Tips

  • Backup: Always back up your wallet. If you lose your private key, you lose your bitcoins forever.
  • Secure Storage: Keep your private key safe. Use hardware wallets or paper wallets for long-term storage, especially if you have a significant amount of bitcoins.
  • Beware of Scams: Never share your private key with anyone, and be cautious of phishing attempts that try to steal your private key.

Summary

  • A Bitcoin wallet is a digital tool that stores your private and public keys, allowing you to send, receive, and store bitcoins.
  • There are different types of wallets (software, hardware, paper), each offering varying levels of security and convenience.
  • Security is crucial; keep your private key safe and always back up your wallet.

 

(Disclaimer: Some of the slides posted on this website are screenshots from the Simplilearn 4 Hour Blockchain video at https://www.youtube.com/watch?v=SyVMma1IkXM&t=4849s)

 

 

Quiz to assess knowledge on the first day of class  

 

Bitaddress.org  

Bitaddress.org is an open-source, web-based tool for generating Bitcoin addresses and their corresponding private keys. It's a simple and secure way to create Bitcoin wallets offline, without needing to rely on a centralized service.

How to Use Bitaddress.org:

1.     Access the Site: Go to bitaddress.org. To enhance security, you can download the site’s HTML file and run it offline.

2.     Generate a Bitcoin Address:

·       Move your mouse around or type random characters in the provided box to add randomness. This process helps in generating a unique Bitcoin address.

·       Once enough randomness is collected, a Bitcoin address and its corresponding private key will be displayed.

3.     Save Your Keys:

·       You can print the generated address and private key on paper (often called a paper wallet).

·       Store the printed document securely, as anyone with access to your private key can access your Bitcoin.

4.     Use the Address:

·       The Bitcoin address can be shared with others to receive Bitcoin.

·       The private key is used to send or transfer Bitcoin from that address.

Important: Always ensure you are using Bitaddress.org securely, preferably offline, and keep your private key safe to prevent unauthorized access to your funds.

 

https://etherscan.io/

Etherscan.com is a popular blockchain explorer specifically designed for the Ethereum network. It allows users to explore and search the Ethereum blockchain for transactions, addresses, tokens, prices, and other activities.

Key Features of Etherscan:

1.     Transaction Tracking:

·       You can search for any Ethereum transaction by entering its transaction hash (TXID) into the search bar. This will provide details such as the amount transferred, gas fees, block confirmation, and the status of the transaction (e.g., pending, successful, failed).

2.     Wallet and Address Lookup:

·       Etherscan allows you to view the balance and transaction history of any Ethereum address. Just enter the wallet address in the search bar to see the current Ether balance, list of ERC-20 tokens held, and transaction history.

3.     Smart Contract Interaction:

·       You can view, verify, and interact with smart contracts directly on Etherscan. It shows the contract's source code, ABI (Application Binary Interface), and allows you to execute functions if the contract is verified.

4.     Token Information:

·       Etherscan provides information on all ERC-20 tokens, including their contract address, holders, transactions, and price data.

5.     Gas Tracker:

·       The site features a gas tracker that shows real-time information on Ethereum gas prices, helping users choose optimal times for transactions to minimize fees.

How to Use Etherscan:

1.     Search Transactions or Addresses:

·       Enter a transaction hash, wallet address, or smart contract address into the search bar to retrieve detailed information.

2.     Explore Contracts:

·       If you're dealing with a smart contract, you can search for it on Etherscan to review its code, check its status, or interact with it directly.

3.     Check Gas Fees:

·       Use the gas tracker to monitor current gas prices and plan your transactions accordingly.

4.     Token Lookup:

·       Search for any ERC-20 token to view its distribution, market data, and associated transactions.

Etherscan is an essential tool for anyone working with Ethereum, offering transparency and a wealth of information about the blockchain.

 

 

 

 Useful Websites:

1.     Ethereum.org

    • Ethereum Official Site
    • Great resource for learning about Ethereum, the leading platform for decentralized applications (dApps) and smart contracts.

2.     Solidity Documentation // https://docs.soliditylang.org/en/v0.8.26/

    • Solidity Official Documentation
    • Comprehensive guide for learning Solidity, the programming language for writing smart contracts on Ethereum.

3.     Remix IDE https://remix.ethereum.org/#lang=en&optimize=false&runs=200&evmVersion=null&version=soljson-v0.8.26+commit.8a97fa7a.js

    • Remix IDE
    • Online integrated development environment for Solidity development, providing tools for writing, testing, and debugging smart contracts.

4.     OpenZeppelin

    • OpenZeppelin
    • Framework for building secure smart contracts with libraries, tools, and educational resources.

5.     CryptoZombies

    • CryptoZombies
    • Interactive tutorial that teaches Solidity by guiding students through building their own blockchain-based game.

6.     Truffle Suite

    • Truffle Suite
    • Development environment, testing framework, and asset pipeline for Ethereum, aimed at making development easier.

7.     Hardhat

    • Hardhat
    • Ethereum development environment for professionals, with features for compiling, deploying, testing, and debugging Solidity code.

8.     Dapp University

    • Dapp University
    • Offers tutorials and courses on blockchain development, including Solidity and Ethereum.

9.     Solidity by Example

10.  EthHub  https://docs.ethhub.io/

    • EthHub
    • Comprehensive resources on Ethereum, including guides on smart contracts, Solidity, and blockchain development.

11.  Chainlink Documentation  https://docs.chain.link

    • Chainlink Documentation
    • Resources for integrating Chainlink decentralized oracles with smart contracts to enable off-chain data access.

12.  Ethers.js  https://docs.ethers.org/v6/

    • Ethers.js
    • JavaScript library for interacting with the Ethereum blockchain, useful for front-end developers integrating smart contracts.

13.  DeFi Pulse

    • DeFi Pulse
    • Track the latest stats and trends in decentralized finance (DeFi) projects.

14.  State of the DApps

    • State of the DApps
    • Directory and analytics for decentralized applications, showcasing the latest dApps and their usage statistics.

15.  Github

 

 

Websites for beginners learning about Ethereum and blockchain:

1.     Ethereum Foundation Blog https://blog.ethereum.org/

    • Ethereum Foundation Blog
    • Official blog with updates, news, and educational articles about Ethereum.

2.     Consensys Academy  https://consensys.io/academy

    • Consensys Academy
    • Offers courses and resources on Ethereum development, blockchain basics, and more.

3.     Blockgeeks

    • Blockgeeks
    • Provides educational articles, guides, and courses on blockchain technology and Ethereum.

4.     Coursera - Blockchain Specialization

5.     CryptoCompare

    • CryptoCompare
    • Provides data, news, and educational resources on cryptocurrencies and blockchain technology.

6.     CoinDesk

    • CoinDesk
    • Leading news website that covers blockchain, Ethereum, and cryptocurrency trends and developments.

7.     DappRadar

    • DappRadar
    • A platform for exploring and tracking decentralized applications (dApps) across multiple blockchains.

8.     The Ethereum Reddit Community

    • Ethereum Subreddit
    • A community forum where beginners can ask questions, share information, and learn more about Ethereum.

9.     Binance Academy  https://academy.binance.com/\

    • Binance Academy
    • Provides educational resources on blockchain, cryptocurrency, and decentralized finance (DeFi).

 

 

Week 2

Week 2 – Ethereum

 

Part I – What is Ethereum? A Comparison between Ethereum and Bitcoin    Quiz2

What is Ethereum?    PPT  Simplilearn 4 hour Blockchain Video (from  1:26:00 – 2:19:34 )

 

·       Self-produced video: Ethereum 2.0 & Smart Contracts: Simple Guide to Key Concepts

 

1. Introduction to Ethereum

  • Definition: Ethereum is a decentralized, open-source blockchain platform that enables developers to build and deploy decentralized applications (dApps) and smart contracts. It was proposed by Vitalik Buterin in 2013 and launched in 2015.
  • Purpose: While Bitcoin was created as a digital currency, Ethereum was designed to be a more versatile platform, allowing for the creation of decentralized applications beyond just currency.

2. Key Features of Ethereum

  • Smart Contracts:
    • Definition: Smart contracts are self-executing contracts with the terms of the agreement directly written into code. They automatically enforce and execute the contract when certain conditions are met, without the need for intermediaries.
    • Example: Imagine a vending machine as a smart contract. You insert money, select a product, and the machine automatically delivers it to you. There's no need for a cashier because the contract (machine) handles everything.
  • Ethereum Virtual Machine (EVM):
    • Definition: The EVM is a global decentralized computer that runs the smart contracts on the Ethereum network. It allows anyone to execute code in a decentralized manner, ensuring that the same result is achieved everywhere.
  • Decentralized Applications (dApps):
    • Definition: dApps are applications that run on a blockchain network rather than a central server. They leverage Ethereum’s smart contracts to function without a central authority.
    • Example: A decentralized social media platform where users control their data, and no single entity can censor or remove content.

 

3.     A Comparison between Bitcoin and Ethereum  PPT   Simplilearn 4 hour video (2:57:06 – 3:03:00)

Feature

Bitcoin

Ethereum

Primary Purpose

Digital currency (peer-to-peer transactions)

Platform for decentralized applications and smart contracts

Launch Year

2009

2015

Founder

Satoshi Nakamoto (pseudonymous)

Vitalik Buterin

Native Cryptocurrency

Bitcoin (BTC)

Ether (ETH)

Supply

Maximum supply of 21 million BTC

No fixed supply; continuous issuance of ETH

Blockchain Structure

Simple, secure, focused on transactions

Complex, programmable, supports smart contracts and dApps

Consensus Mechanism

Proof of Work (PoW)

Transitioning from PoW to Proof of Stake (PoS) with Ethereum 2.0

Transaction Speed

~10 minutes per block

~15 seconds per block

Scalability

Handles ~7 transactions per second (TPS)

More scalable; ongoing upgrades like Ethereum 2.0 aim to further improve scalability

Smart Contracts

Not supported

Fully supported; core feature of the platform

Decentralized Applications (dApps)

Not supported

Fully supported; numerous dApps are built on Ethereum

Use Case

Digital money, store of value

Platform for building decentralized applications and smart contracts

Energy Efficiency

Energy-intensive due to PoW mining

Moving towards energy efficiency with PoS in Ethereum 2.0

Nickname

Often referred to as "Digital Gold"

Sometimes called "Programmable Blockchain"

 

Part II – Ethereum Mining  ppt   

 

1. What is Ether Mining?

  • Definition: Ether mining is the process of validating transactions on the Ethereum blockchain and adding them to the public ledger. Miners use computational power to solve complex mathematical puzzles, and in return, they are rewarded with newly created Ether.

2. How Ether Mining Works

  • Proof of Work (PoW): Ethereum currently uses the Proof of Work (PoW) consensus mechanism, similar to Bitcoin. Miners compete to solve cryptographic puzzles, and the first one to solve it gets to add a block of transactions to the blockchain and earns Ether as a reward.
  • Hashing: To solve the puzzle, miners use a hashing function (specifically, Ethash for Ethereum). They repeatedly process the block data through the hashing function with different "nonces" (random numbers) until they find a hash that meets the network’s difficulty target.

3. Equipment Needed

  • Mining Hardware: To mine Ether, you need a powerful computer with a high-performance GPU (Graphics Processing Unit). GPUs are preferred for mining because they are more efficient than CPUs for the type of calculations involved in mining.
  • Mining Software: You’ll need mining software that connects your hardware to the Ethereum network. Popular mining software includes Ethminer, PhoenixMiner, and Claymore.
  • Ethereum Wallet: You’ll need an Ethereum wallet to store the Ether you mine. This can be a software wallet (like MetaMask) or a hardware wallet (like Ledger or Trezor) for added security.

4. Mining Solo vs. Joining a Pool

  • Solo Mining: In solo mining, you mine independently. While the rewards can be significant if you solve a block, it’s highly competitive and may take a long time before you find a block.
  • Mining Pool: Most miners join a mining pool, where multiple miners work together to solve blocks. The rewards are shared among all participants based on the amount of computational power they contribute. This provides more consistent, though smaller, earnings.

5. Steps to Start Mining Ether

  1. Set Up Hardware: Install and configure your mining hardware, ensuring you have a powerful GPU.
  2. Install Mining Software: Download and install your chosen mining software.
  3. Join a Mining Pool: If you prefer, join a mining pool to increase your chances of earning rewards regularly.
  4. Start Mining: Begin mining by running the mining software, which will connect your hardware to the Ethereum network and start solving cryptographic puzzles.
  5. Monitor and Optimize: Regularly monitor your mining performance and optimize your setup to ensure efficient mining.

6. Transition to Proof of Stake (PoS)

  • Ethereum 2.0: Ethereum is transitioning from Proof of Work (PoW) to Proof of Stake (PoS) with Ethereum 2.0. In PoS, validators are chosen to create new blocks based on the amount of Ether they hold and "stake." This transition will eventually make mining obsolete as the network moves towards staking.

 

 

 

Part III – Smart Contract   PPT   Simplilearn 4 hour video (from 1:27:14  to 2:13:44  )   Quiz

1. Definition

  • Smart Contract: A smart contract is a self-executing contract with the terms of the agreement directly written into lines of code. It automatically enforces and executes the contract when certain conditions are met, without the need for intermediaries like lawyers or banks.

2. How Smart Contracts Work

  • Code and Conditions: The smart contract is programmed to perform specific actions when certain predefined conditions are met. For example, a smart contract could be set up to transfer ownership of a digital asset automatically when payment is received.
  • Decentralization: Smart contracts run on a decentralized blockchain network like Ethereum, meaning no single entity controls them. Once deployed, they are immutable (cannot be changed) and transparent, with the code visible to all participants.

3. Example of a Smart Contract

  • Real Estate Transaction: Imagine buying a house through a smart contract. The contract could be programmed to automatically transfer ownership of the property to the buyer when the agreed payment is received. This eliminates the need for a middleman, like a lawyer, to verify and process the transaction.

Software Needed for Smart Contracts

1. Development Environment

  • Solidity: Solidity is the most commonly used programming language for writing smart contracts on the Ethereum blockchain. It’s similar to JavaScript in syntax and is specifically designed for developing smart contracts.
  • Remix IDE: Remix is an online Integrated Development Environment (IDE) that allows developers to write, compile, and deploy smart contracts in Solidity. It’s beginner-friendly and widely used for Ethereum smart contract development.

2. Blockchain Network

  • Ethereum: Ethereum is the most popular blockchain platform for deploying smart contracts. It provides a decentralized environment where smart contracts can be executed securely and transparently.
  • Testnets: Before deploying a smart contract on the Ethereum mainnet (the live blockchain), developers typically use testnets like Ropsten or Rinkeby to test their contracts. This allows them to identify and fix any issues without risking real Ether.

3. Wallet and Blockchain Interface

  • MetaMask: MetaMask is a browser extension wallet that allows users to interact with Ethereum dApps and smart contracts. It also provides a way to manage your Ether and deploy smart contracts.
  • Truffle Suite: Truffle is a development framework for Ethereum that provides tools for compiling, deploying, and managing smart contracts. It’s often used in larger, more complex smart contract projects.

Why Do We Need Smart Contracts?

1. Automation

  • Self-Executing: Smart contracts automate processes that would normally require manual intervention. For example, a smart contract can automatically release funds when a task is completed or a condition is met, reducing the need for middlemen.

2. Trust and Transparency

  • Immutable and Transparent: Once deployed, smart contracts cannot be altered, ensuring that the terms of the agreement are always enforced as written. The contract’s code is also visible to everyone on the blockchain, which increases transparency and trust among participants.

3. Cost Efficiency

  • Reduced Costs: By eliminating intermediaries (like lawyers, notaries, or escrow services), smart contracts reduce transaction costs. This is especially beneficial in industries like finance, real estate, and supply chain management, where traditional processes can be slow and expensive.

4. Security

  • Blockchain Security: Smart contracts benefit from the security of the underlying blockchain. Since they are decentralized and cryptographically secure, they are highly resistant to fraud, tampering, and censorship.

5. Global Reach

  • Borderless: Smart contracts can be used globally without the need for intermediaries or cross-border legal considerations, making them ideal for international transactions and agreements.

Summary

  • Smart contracts are self-executing contracts written in code that automatically enforce and execute agreements without intermediaries.
  • They require specific software tools, including Solidity for programming, Remix for development, and Ethereum as the blockchain platform.
  • Smart contracts offer automation, transparency, cost efficiency, security, and global reach, making them valuable in many industries.

 

Part IV – Solidity Coding    PPT   Simplilearn 6 hour video (from 1:26:00 – 2:41:55  )

1. Introduction to Solidity

  • Definition: Solidity is a high-level programming language designed specifically for writing smart contracts on the Ethereum blockchain. It’s statically typed and contract-oriented, meaning it allows developers to define the data structure and functions that will govern the behavior of the smart contract.
  • Similarities to JavaScript: Solidity syntax is similar to JavaScript, making it easier to learn for those who are already familiar with web development.

2. Purpose of Solidity

  • Smart Contract Development: Solidity is used to create smart contracts that can handle various functions, such as transferring tokens, enforcing agreements, creating decentralized applications (dApps), and more.
  • Blockchain Interaction: Contracts written in Solidity can interact with the Ethereum blockchain, allowing developers to create decentralized and secure applications.

How to Compile and Deploy a Solidity Contract

1. Writing a Smart Contract

  • Using Solidity: Start by writing the smart contract in Solidity. You can use a basic text editor, but it’s better to use a specialized Integrated Development Environment (IDE) like Remix.
  • Example Contract:
pragma solidity ^0.8.0;
 
contract SimpleStorage {
    uint256 storedData;
 
    function set(uint256 x) public {
        storedData = x;
    }
 
    function get() public view returns (uint256) {
        return storedData;
    }
}
  • Explanation: In this simple contract, there is a variable storedData that can be set and retrieved through the set and get functions.

2. Compiling the Smart Contract

  • Using Remix IDE:
    • Open Remix at remix.ethereum.org.
    • Create a new file and paste your Solidity code into the editor.
    • Select the compiler version (e.g., 0.8.0) that matches the pragma statement in your code.
    • Click on the "Compile" button. If there are no errors, your contract will be compiled into bytecode, which is what the Ethereum Virtual Machine (EVM) can execute.
  • Output: The compiler will generate ABI (Application Binary Interface) and bytecode, which are essential for deploying and interacting with the contract.

3. Deploying the Smart Contract

  • Using Remix with MetaMask:
    • Set Up MetaMask: Install the MetaMask browser extension and set up a wallet. Make sure you have some Ether in your wallet for gas fees (you can use test Ether on a test network like Ropsten).
    • Deploy: In Remix, switch to the "Deploy & Run Transactions" tab. Select "Injected Web3" as the environment to connect Remix with MetaMask.
    • Deploy the Contract: Select your contract from the dropdown and click "Deploy." MetaMask will prompt you to confirm the transaction, which includes paying a gas fee.
    • Confirm Deployment: Once confirmed, the contract will be deployed to the Ethereum network (or testnet), and you’ll receive a contract address where it resides on the blockchain.

Procedure Summary

  1. Write your smart contract in Solidity using an IDE like Remix.
  2. Compile the contract using the built-in compiler in Remix, generating ABI and bytecode.
  3. Deploy the contract to the Ethereum network via Remix and MetaMask.
  4. Interact with the deployed contract using the contract’s functions through Remix or any other Ethereum interface.

Main Troubleshooting Issues

1. Compilation Errors

  • Syntax Errors: Most compilation errors come from incorrect syntax. Always ensure that your Solidity code adheres to proper syntax rules. Common issues include missing semicolons, mismatched brackets, or incorrect function declarations.
  • Version Mismatch: Ensure that the Solidity version in your pragma statement (e.g., pragma solidity ^0.8.0;) matches the version selected in the Remix compiler. If there’s a mismatch, the contract might not compile or behave as expected.

2. Deployment Issues

  • Gas Limit Errors: Deployment can fail if the gas limit is too low. The gas limit is the maximum amount of gas you’re willing to spend on the transaction. If it’s set too low, the contract won’t deploy. Adjust the gas limit in MetaMask or the deployment settings in Remix.
  • Network Issues: Make sure you are connected to the correct Ethereum network (mainnet, Ropsten, etc.) via MetaMask. Deployment can fail if you’re on the wrong network or if there’s a network outage.

3. Interaction Issues

  • Contract Not Found: If you try to interact with a contract and get an error saying it’s not found, double-check the contract address. Ensure you’re using the correct address on the correct network.
  • Incorrect Data Types: When interacting with the contract’s functions, ensure you’re passing the correct data types. For example, if a function expects a uint256, sending a string will cause an error.

4. Gas Estimation Errors

  • Incorrect Gas Estimation: Sometimes, the gas estimation might be too low for certain complex operations. In such cases, manually increase the gas limit in MetaMask or your Ethereum client.
  • High Gas Fees: Gas fees can fluctuate based on network congestion. If gas fees are too high, consider waiting for a less congested time or deploying to a test network.

Conclusion

  • Solidity coding allows developers to create and deploy smart contracts on the Ethereum blockchain.
  • Compiling and deploying a contract involves writing the code, compiling it to generate bytecode, and deploying it to the Ethereum network using tools like Remix and MetaMask.
  • Troubleshooting involves addressing common issues like syntax errors, gas limits, and network connectivity problems. Regular practice and careful attention to detail can help avoid many of these issues.

 

 

 

Part V – DApp (Decentralized Application) and DAO     PPT   Quiz

Simplilearn 4 hour video (from  3:02:31  to 3:09:15  )

1. Definition

  • DApp: A decentralized application (DApp) is an application that runs on a decentralized network, typically a blockchain like Ethereum, rather than on a centralized server. Unlike traditional apps, DApps are not controlled by a single entity and operate on a peer-to-peer network.

2. Key Characteristics of DApps

  • Decentralization: DApps are built on a blockchain, which is maintained by a distributed network of computers (nodes) rather than a single central authority. This ensures that no single entity has control over the application.
  • Open Source: Most DApps are open source, meaning their code is available for anyone to inspect, use, and modify. This transparency helps build trust among users.
  • Smart Contracts: DApps use smart contracts, which are self-executing contracts with the terms of the agreement directly written into code. These contracts automate various functions of the DApp without needing intermediaries.
  • Tokenization: Many DApps have their own tokens, which can be used within the application for various purposes, such as payments, voting, or rewarding users. These tokens are often created using Ethereum’s ERC-20 or ERC-721 standards.

3. How DApps Work

  • Frontend: Like traditional apps, DApps have a user interface (frontend) that users interact with. This can be a website, mobile app, or any other user interface.
  • Backend: Unlike traditional apps, the backend of a DApp consists of smart contracts deployed on a blockchain. The logic and data of the DApp are stored on the blockchain, making it immutable and transparent.
  • Interacting with the Blockchain: Users interact with the DApp through a web browser that connects to the blockchain. For example, MetaMask is a popular browser extension that allows users to interact with Ethereum-based DApps.

4. Examples of DApps

  • Decentralized Finance (DeFi): Platforms like Uniswap (a decentralized exchange) and Aave (a lending platform) allow users to trade and lend cryptocurrencies without relying on traditional financial institutions.
  • Gaming: Games like CryptoKitties allow users to buy, breed, and trade virtual cats as non-fungible tokens (NFTs). These assets are owned by the users and exist on the blockchain.
  • Social Media: Platforms like Steemit offer decentralized social networks where users can earn tokens for creating and curating content, with no central authority controlling the platform.

Why Do We Need DApps?

1. Trust and Security

  • Transparency: Because DApps run on a blockchain, all transactions and actions are transparent and verifiable by anyone. This reduces the need to trust a central authority.
  • Security: DApps are more resistant to hacking and censorship because they are decentralized. Even if one part of the network goes down or is compromised, the rest of the network continues to function.

2. User Control and Ownership

  • Data Ownership: In traditional apps, user data is often controlled and monetized by the company that owns the app. In DApps, users have greater control over their data, which is stored on the blockchain and cannot be easily tampered with.
  • Asset Ownership: In DApps that involve digital assets (like tokens or NFTs), users truly own their assets. For example, if you own an NFT in a DApp, it is stored on the blockchain and cannot be taken away by anyone.

3. Innovation and Accessibility

  • Global Access: DApps are accessible to anyone with an internet connection, making them available globally without the restrictions of traditional apps (like geographical restrictions or the need for a bank account).
  • Innovation: DApps enable new types of applications that weren’t possible before, such as decentralized finance (DeFi) platforms, decentralized exchanges, and blockchain-based games.

Challenges and Considerations

1. Scalability

  • Performance Issues: Since DApps run on a decentralized network, they can face scalability issues, such as slower transaction times and higher fees, especially during periods of high network congestion.
  • Ongoing Development: Developers are continuously working on solutions to improve the scalability and performance of DApps, such as layer 2 scaling solutions and more efficient consensus mechanisms.

2. User Experience

  • Complexity: Using DApps can be more complex than traditional apps, especially for users who are not familiar with blockchain technology. For example, users need to manage private keys and interact with smart contracts, which can be confusing for beginners.
  • Improving Accessibility: Efforts are being made to improve the user experience of DApps, making them more accessible to mainstream users without compromising their decentralized nature.

Conclusion

  • DApps are decentralized applications that run on blockchain networks, offering transparency, security, and user control.
  • They leverage smart contracts to automate processes and often use tokens for various functions within the app.
  • DApps are increasingly popular in fields like decentralized finance (DeFi), gaming, and social media, although they face challenges like scalability and user experience.

 

(Disclaimer: Some of the slides posted on this website are screenshots from the Simplilearn 4 Hour Blockchain video at https://www.youtube.com/watch?v=SyVMma1IkXM&t=4849s and Simplilearn 6 HourBlockchain Video at https://www.youtube.com/watch?v=9aXHQ98TMRY&t=6626s)

 

 

 

Part VI – Real World Examples     Quiz

 

1. Walmart Supply Chain Management

·        Overview: Walmart uses blockchain technology to improve the traceability and transparency of its food supply chain. This implementation helps Walmart quickly identify and address issues such as contamination or recalls, ensuring food safety and reducing waste.

·        Blockchain Platform: IBM Food Trust (built on Hyperledger Fabric)  https://www.ibm.com/products/supply-chain-intelligence-suite/food-trust

·        Website:

    • Walmart's Blockchain Initiative: IBM Food Trust for Walmart
    • IBM Food Trust: IBM Food Trust

·        Additional Information: Walmart was one of the first major retailers to adopt blockchain for supply chain management, initially focusing on tracing pork and leafy greens to enhance food safety.

2. Maersk Shipping and Logistics with TradeLens

·        Overview: Maersk, in collaboration with IBM, developed TradeLens, a blockchain-based platform designed to streamline global shipping processes. TradeLens enhances transparency, reduces paperwork, and increases efficiency by providing real-time access to shipping data and documents.

·        Blockchain Platform: TradeLens (built on Hyperledger Fabric)

·        Website: TradeLens   https://www.tradelens.com/

·        Additional Information: TradeLens has partnered with numerous shipping companies, ports, and customs authorities worldwide to create a more connected and efficient global trade ecosystem.

3. De Beers Diamond Provenance Tracking with Tracr

·        Overview: De Beers uses the Tracr platform to track diamonds from the mine to the retail point. This ensures that each diamond is ethically sourced and conflict-free, enhancing consumer trust and maintaining the integrity of their supply chain.

·        Blockchain Platform: Tracr (developed by De Beers)

·        Website: De Beers Tracr   https://www.tracr.com/

·        Additional Information: Tracr allows consumers to verify the origin and journey of their diamonds, promoting transparency and ethical sourcing in the diamond industry.

 

4. Nestlé – Food Supply Chain Transparency

·        Overview: Nestlé leverages blockchain technology to enhance the transparency and traceability of its food products. By tracking ingredients through the supply chain, Nestlé ensures quality, safety, and ethical sourcing.

·        Blockchain Platform: IBM Food Trust (built on Hyperledger Fabric)

·        Website: Nestlé and IBM Food Trust  https://www.ibm.com/blogs/think/2019/04/tracing-your-mashed-potatoes-on-ibm-blockchain/

·        Additional Information: Nestlé's participation in IBM Food Trust helps the company monitor the supply chain in real-time, ensuring that products meet safety standards and are sourced responsibly.

 

5. FedEx Package Tracking and Logistics

·        Overview: FedEx explores blockchain technology to improve its package tracking system, aiming for more secure and transparent tracking information for shipments. Blockchain enhances the reliability and efficiency of tracking packages through the supply chain.

·        Blockchain Platform: Potential Platforms: Hyperledger Fabric, Ethereum, or proprietary solutions

·        Website: FedEx Blockchain Initiatives   https://www.fedex.com/en-us/about/policy/technology-innovation/blockchain.html

·        Additional Information: FedEx has been involved in blockchain pilot projects to explore how distributed ledger technology can optimize logistics and reduce fraud.

 

6. Provenance Supply Chain Transparency for Various Industries

·        Overview: Provenance is a platform that helps businesses track the origins and journey of their products using blockchain. This ensures transparency, ethical sourcing, and allows consumers to verify product claims.

·        Blockchain Platform: Ethereum and other blockchain technologies

·        Website: Provenance  https://www.provenance.org/

·        Additional Information: Provenance works with various industries, including fashion, food, and consumer goods, to provide detailed product histories and build consumer trust through transparency.

 

7. Microsoft Azure Blockchain Services

·        Overview: Microsoft offers Azure Blockchain Services, enabling businesses to build, deploy, and manage blockchain applications easily. Numerous companies use Azure Blockchain to develop solutions across different industries such as finance, supply chain, and healthcare.

·        Blockchain Platform: Azure Blockchain (supports multiple blockchain frameworks including Ethereum, Hyperledger Fabric)

·        Website: Microsoft Azure Blockchain https://azure.microsoft.com/en-us/blog/digitizing-trust-azure-blockchain-service-simplifies-blockchain-development/

·        Additional Information: Azure Blockchain provides tools and templates to help enterprises integrate blockchain into their existing systems, facilitating faster and more secure transactions.

 

8. JPMorgan Chase Financial Services with Quorum

·        Overview: JPMorgan Chase developed Quorum, an enterprise-focused version of Ethereum, to facilitate secure and efficient financial transactions. Quorum is used for various applications, including payment processing, interbank transfers, and blockchain-based financial instruments.

·        Blockchain Platform: Quorum (a fork of Ethereum developed by JPMorgan Chase) https://phemex.com/academy/what-is-quorum-jp-morgan

·        Website: Quorum by ConsenSys  https://consensys.io/blog/what-is-consensys-quorum

·        Additional Information: Quorum enhances Ethereum's capabilities by adding privacy features and improving performance, making it suitable for enterprise use cases in the financial sector.

 

9. IBM Various Enterprise Blockchain Solutions

·        Overview: IBM offers a range of blockchain solutions tailored for different industries, including supply chain, finance, healthcare, and more. IBM Blockchain, built on Hyperledger Fabric, provides the infrastructure for businesses to create secure and scalable blockchain applications.

·        Blockchain Platform: IBM Blockchain (built on Hyperledger Fabric) 

·        Website: IBM Blockchain  https://www.ibm.com/blockchain

·        Additional Information: IBM collaborates with numerous enterprises to implement blockchain solutions that enhance transparency, security, and efficiency in their operations.

 

10. Amazon Web Services (AWS) Managed Blockchain Services

·        Overview: Amazon Web Services offers Amazon Managed Blockchain, a fully managed service that makes it easy to create and manage scalable blockchain networks using popular frameworks like Hyperledger Fabric and Ethereum.

·        Blockchain Platform: Amazon Managed Blockchain (supports Hyperledger Fabric and Ethereum)

·        Website: Amazon Managed Blockchain  Distributed Ledger Software & Technology - Amazon Managed Blockchain - AWS

·        Additional Information: AWS Managed Blockchain allows businesses to quickly set up and manage blockchain networks without the overhead of maintaining the underlying infrastructure, supporting various use cases from supply chain to digital identity.

 

11. Coca-Cola Supply Chain and Product Authentication

·        Overview: Coca-Cola utilizes blockchain technology to enhance its supply chain management and product authentication processes. Blockchain helps Coca-Cola track ingredients, ensure quality, and authenticate products to prevent counterfeiting.

·        Blockchain Platform: IBM Food Trust (built on Hyperledger Fabric)

·        Website: Coca-Cola and IBM Food Trust https://shping.com/shping-and-ibm-food-trust-pioneering-a-new-era-of-product-transparency-for-consumers/

·        Additional Information: By integrating blockchain into its supply chain, Coca-Cola ensures better transparency and efficiency, from sourcing raw materials to delivering finished products.

 

12. Pfizer Pharmaceutical Supply Chain Management

·        Overview: Pfizer uses blockchain to improve the traceability and security of its pharmaceutical supply chain. Blockchain helps Pfizer ensure the authenticity of medicines, prevent counterfeiting, and comply with regulatory requirements.

·        Blockchain Platform: Provenance, IBM Blockchain, or other enterprise blockchains

·        Website: Pfizer and Blockchain Initiatives   https://news.crunchbase.com/health-wellness-biotech/pharmaceuticals-blockchain-crypto-web3-pfizer-pfe/

·        Additional Information: Blockchain technology enables Pfizer to maintain a secure and transparent record of its supply chain, enhancing trust and safety in its pharmaceutical products.

 

13. Starbucks Coffee Supply Chain Tracking

·        Overview: Starbucks has explored using blockchain to track the provenance of its coffee beans, ensuring quality and ethical sourcing. Blockchain helps verify the journey of the coffee from farm to cup, enhancing transparency and consumer trust.

·        Blockchain Platform: IBM Food Trust (similar to Walmart and Nestlé)

·        Website: Starbucks and Blockchain  https://stories.starbucks.com/press/2022/starbucks-brewing-revolutionary-web3-experience-for-its-starbucks-rewards-members/

·        Additional Information: By leveraging blockchain, Starbucks can provide customers with detailed information about the origin and quality of their coffee, supporting sustainable and ethical sourcing practices.

 

14. BP Energy Supply Chain Management

·        Overview: BP utilizes blockchain technology to manage and optimize its energy supply chain. Blockchain helps BP track the movement of energy resources, ensure compliance with regulations, and improve the efficiency of transactions.

·        Blockchain Platform: IBM Blockchain or other enterprise solutions

·        Website: BP and Blockchain  https://www.hartenergy.com/exclusives/bp-tries-out-blockchain-energy-trading-30388

·        Additional Information: BP's adoption of blockchain in the energy sector demonstrates how blockchain can enhance transparency, reduce costs, and improve operational efficiency in complex supply chains.

 

15. Anheuser-Busch InBev Beverage Supply Chain Transparency

·        Overview: Anheuser-Busch InBev uses blockchain to enhance the transparency and efficiency of its beverage supply chain. Blockchain enables the company to track ingredients, monitor production processes, and ensure the authenticity of its products.

·        Blockchain Platform: IBM Food Trust (built on Hyperledger Fabric)

·        Website: AB InBev and IBM Food Trust   https://www.foodnavigator.com/Article/2019/08/06/Anheuser-Busch-InBev-joins-new-IBM-blockchain

·        Additional Information: By integrating blockchain into its supply chain, Anheuser-Busch InBev ensures better quality control, traceability, and consumer trust in its beverage products.

 

Company

Application

Token Use

Walmart, Nestlé, Coca-Cola, BP

Supply Chain Management (IBM Food Trust)

No use of Ether or specific tokens; focus on transparency and traceability.

Maersk

TradeLens (Shipping and Logistics)

No use of Ether or specific tokens; focus on logistics transparency.

De Beers

Tracr (Diamond Provenance Tracking)

No use of Ether or specific tokens; ensures ethical sourcing.

FedEx

Package Tracking and Logistics

No use of Ether or specific tokens; focuses on tracking and logistics.

Provenance

Supply Chain Transparency

May use tokens depending on implementation, not necessarily Ether.

Microsoft Azure Blockchain

Blockchain Services

Token use depends on the specific application; Ether or custom tokens can be used.

JPMorgan Chase

Quorum (Enterprise Blockchain)

Can use Ether or custom tokens depending on the application; often no tokens.

Uniswap

Decentralized Finance (DeFi)

Uses Ether (ETH) for transactions and its own token (UNI) for governance.

Amazon Managed Blockchain

Managed Blockchain Services

Token use depends on the specific application; not inherently tied to Ether.

Pfizer

Pharmaceutical Supply Chain Management

No use of Ether or specific tokens; focuses on supply chain security.

Starbucks

Coffee Supply Chain Tracking

No use of Ether or specific tokens; focuses on transparency.

 

 

Part VII  Understanding Web3                    Quiz

Refer to Chapter 8 of Hands-On Smart Contract Development with Solidity & Ethereum by Solorio, Kanna, and Hoover

              

1.     What is Web3?

Web3 refers to a collection of JavaScript libraries that allow developers to interact with the Ethereum blockchain, either remotely or locally. Think of it as the connection point between the blockchain and your smart contract or decentralized app (DApp). Web3 uses JSON RPC (Remote Procedure Call) to communicate with Ethereum nodes and helps you perform transactions, call smart contract methods, and read/write data from the blockchain.

2.     How Web3 Differs from Web 2.0

In traditional web applications (Web 2.0), a frontend (like React) interacts with a backend (a server and database) to process and store data. In contrast, Web3 allows your frontend to interact directly with the blockchain as if it were the backend. This eliminates the need for centralized databases and servers.

Web3 Application Flow

  • Frontend: Users interact with a frontend (such as a website built with React).
  • Web3: The frontend uses Web3 to make requests to the blockchain instead of a traditional backend.
  • Blockchain: Web3 communicates with Ethereum nodes via RPC to read and write data.

image_1.jpgThis is Web 2.0

image005.jpgThis is Web 3.0

3.     Why Web3 is Important

Web3 is at the core of decentralized applications (DApps). Instead of relying on centralized servers and databases, Web3 allows applications to interact directly with the decentralized blockchain, enhancing security, transparency, and trust.

4.     Setting Up Web3

To use Web3 in your project, you first need to set up a provider that tells Web3 which Ethereum node to connect to. For example, if you are working with Ganache (a local Ethereum blockchain), you would connect as follows:

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));

The provider is like the URL you use in a traditional web app to communicate with an API. It directs RPC calls from Web3 to the correct Ethereum node.

Providers

  • Local (e.g., Ganache): Connect to a local Ethereum node (e.g., Ganache for development).
  • Remote: Connect to public Ethereum nodes (like Infura or Alchemy).

5.     MetaMask for Web3 Injection

MetaMask is a browser extension that makes interacting with Web3 much easier. It:

  • Stores and manages your Ethereum accounts and private keys.
  • Allows you to sign transactions.
  • Pays gas fees for blockchain transactions.

Web3 detects MetaMask as a Web3 provider, enabling you to interact with the blockchain seamlessly.

6.     Application of Web3 in the Blockchain Space

Benefits of Web3:

  • Decentralization: No centralized control, making systems more secure and transparent.
  • Trust: Eliminates the need to trust intermediaries as the blockchain enforces rules.
  • Security: DApps built with Web3 are resistant to attacks and data breaches because of the decentralized nature of the blockchain.
  • Ownership: Users have full control of their assets, unlike traditional apps where data is controlled by centralized entities.

Applications of Web3:

·   Decentralized Finance (DeFi): Web3 is the backbone of DeFi applications, enabling peer-to-peer financial transactions.

·   Voting Systems: As demonstrated by the Voting DApp you built, Web3 allows decentralized and tamper-proof voting mechanisms.

·   Supply Chain: Companies use Web3 to track goods in a transparent and immutable way.

·   Gaming: Web3 powers blockchain-based games that allow players to earn and trade assets.

Platform

Type

Website

Description

How It Uses Web3

OpenSea

NFT Marketplace

OpenSea

A large decentralized marketplace for buying, selling, and discovering NFTs.

Uses Ethereum and Web3 to enable users to trade digital assets like NFTs directly from their Ethereum wallets.

Rarible

NFT Marketplace

Rarible

A community-driven NFT marketplace where users can mint, sell, and trade digital assets.

Connects to Ethereum via Web3 to facilitate transactions and allow users to mint and trade NFTs.

Decentraland

Virtual World (Metaverse)

Decentraland

A decentralized virtual world where users buy and trade virtual real estate and in-game assets.

Uses Web3 to allow players to purchase, sell, and trade virtual LAND and in-game items as NFTs on the Ethereum blockchain.

Foundation

NFT Marketplace for Artists

Foundation

A marketplace focused on empowering artists to create, sell, and auction digital art as NFTs.

Interacts with Ethereum through Web3 to allow artists and collectors to trade artwork in a decentralized manner.

Axie Infinity

Blockchain-Based Game

Axie Infinity

A play-to-earn blockchain-based game where users can battle, breed, and collect NFT-based pets.

Uses Web3 for managing in-game assets (NFTs) and allows players to earn cryptocurrency through in-game activities.

Zora

NFT Marketplace and Protocol

Zora

An open-source protocol for creators to tokenize and sell creative works such as art and media.

Utilizes Ethereum and Web3 to let users mint and trade NFTs in a decentralized fashion.

Uniswap

Decentralized Exchange (DeFi)

Uniswap

A decentralized exchange for trading Ethereum-based tokens, with no central authority or intermediaries.

Uses Web3 to allow users to swap tokens directly from their wallets, using smart contracts to facilitate decentralized trading.

Aave

Decentralized Finance (DeFi)

Aave

A DeFi platform for borrowing and lending cryptocurrency without intermediaries.

Uses Web3 to connect users to liquidity pools for decentralized borrowing and lending via smart contracts on Ethereum.

 

Homework of  Week2 - Guide to Interacting with a Smart Contract Using Truffle

Refer to:  https://github.com/wildmouse/practicing-Hands-On-Smart-Contract-Development-with-Solidity-and-Ethereum/tree/master/greeter

 

1. Setting Up the Environment

  1. Ensure Node.js and npm are Installed:
  2. Install Truffle:
    • Open your terminal and run:

npm install -g truffle

  1. Set Up a Truffle Project:
    • Create a new directory for your project and navigate into it:

mkdir my_truffle_project

cd my_truffle_project

    • Initialize a new Truffle project:

truffle init

 

2. Write and Compile the Smart Contract

  1. Create a Smart Contract:
    • In the contracts directory, create a new file named Greeter.sol:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

 

contract Greeter {

    string public greeting;

 

constructor(string memory _greeting) {

        greeting = _greeting;

    }

 

    function greet() public view returns (string memory) {

        return greeting;

    }

}

  1. Create a Migration Script:
    • In the migrations directory, create a new file named 2_deploy_greeter.js:

const Greeter = artifacts.require("Greeter");

 

module.exports = function(deployer) {

deployer.deploy(Greeter, "Hello, JU!"); // Change greeting here

};

  1. Compile the Contract:
    • Run the following command in your terminal:

truffle compile

3. Deploy the Contract

  1. Start the Development Network:
    • Ensure Ganache or Truffle Develop is running. You can use Truffle Develop:

truffle develop

  1. Deploy the Contract:
    • In a new terminal window (while Truffle Develop is running), deploy the contract:

truffle migrate

4. Interact with the Contract Using a Script

  1. Create a scripts Folder:
    • Ensure there is a folder named scripts in the root directory of your project.
  2. Create a Script File:
    • In the scripts directory, create a file named scripts_test.js:

const Greeter = artifacts.require("Greeter");

 

module.exports = async function(callback) {

    try {

        // Get the deployed instance of the contract

        const instance = await Greeter.deployed();

 

        // Print the address of the deployed contract

console.log("Contract address:", instance.address);

 

        // Call the greet function

        const greeting = await instance.greet();

console.log("Greeting:", greeting);

 

    } catch (error) {

console.error(error);

    }

callback();

};

  1. Run the Script:
    • In your terminal, execute the script with Truffle:

truffle exec scripts/scripts_test.js

 

5. Troubleshooting

  • Ensure Ganache is Running:
    • Verify that Ganache or Truffle Develop is active when deploying and running scripts.
  • Check Truffle Configuration:
    • Ensure truffle-config.js is correctly set up for your network.
  • Reinstall Truffle:
    • If issues persist, try reinstalling Truffle globally:

npm uninstall -g truffle

npm install -g truffle

 

6. Example Output

When running the script, you should see:

Contract address: 0x... (your contract address)

Greeting: Hello, JU!

This guide covers the entire process from setting up the environment to interacting with your smart contract.

 

 

 

Homework of Week 3 - Interacting with a Smart Contract Using MetaMask, Ganache, and Remix

Step by Step Instructional Video Part I (Metamask)  .     Part II (Remix)  

Refer to  https://github.com/arshdeepbahga/blockchain-applications-book/tree/master/Chapter-5

1. Install and Set Up MetaMask

Why: MetaMask is a digital wallet used to manage accounts and interact with Ethereum-based applications. It acts as the bridge between the blockchain (Ganache) and the application (Remix).

  • Step:
    1. Go to the MetaMask website and install the MetaMask browser extension.
    2. After installation, click the MetaMask icon in your browser to open it.
    3. Set up a new wallet by following the on-screen instructions, and make sure to securely store your recovery phrase.
    4. Once the wallet is set up, you'll see your account in MetaMask with a default name like "Account 1."

Expected Outcome: MetaMask is installed and your first Ethereum account is created.

 

2. Set Up Ganache

Why: Ganache simulates a blockchain environment locally, allowing you to deploy and test smart contracts without using real money.

  • Step:
    1. Download and install Ganache from the Truffle Suite website.
    2. Open Ganache and click on “Quickstart Ethereum” to start a new workspace.
    3. Ganache will create 10 accounts with 100 ETH each, and it will run on a local network at http://127.0.0.1:7545.

Expected Outcome: Ganache is running locally, and you have access to 10 accounts with 100 ETH each.

 

3. Connect MetaMask to Ganache

Why: To deploy contracts and send transactions, MetaMask must be connected to the local blockchain (Ganache).

  • Step:
    1. In MetaMask, click on the network selector at the top (it might say "Ethereum Mainnet") and choose “Add Network.”
    2. Click "Add a network manually" and fill in the following details:
      • Network Name: Ganache
      • New RPC URL: http://127.0.0.1:7545
      • Chain ID: 1337 (this is the default for Ganache)
      • Currency Symbol: ETH
    3. Click "Save."
    4. Now, your MetaMask is connected to Ganache.

Expected Outcome: MetaMask is now connected to the local blockchain provided by Ganache.

 

4. Import an Account from Ganache to MetaMask

Why: You need to use one of Ganache’s accounts to deploy contracts and interact with them.

  • Step:
    1. In Ganache, click on the key icon next to the first account (Account 1) to reveal its private key.
    2. Copy the private key.
    3. Open MetaMask, click on the account icon in the top right, and select "Import Account."
    4. Paste the private key and click "Import."

Expected Outcome: The Ganache account with 100 ETH is now added to your MetaMask.

 

5. Open Remix and Write the Smart Contract

Why: Remix is an online tool used to write, compile, and deploy smart contracts.

  • Step:
    1. Go to Remix IDE in your browser.
    2. Create a new file named Voting.sol by clicking on the file icon and then the "+" button.
    3. Paste the following smart contract code into Voting.sol:

 

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

 

contract Voting {

    string[] public candidateList;

    mapping(string => uint256) public votesReceived;

 

    constructor(string[] memory candidateNames) {

        candidateList = candidateNames;

    }

 

    function voteForCandidate(string memory candidate) public {

        require(validCandidate(candidate), "Candidate does not exist");

        votesReceived[candidate] += 1;

    }

 

    function totalVotesFor(string memory candidate) public view returns (uint256) {

        require(validCandidate(candidate), "Candidate does not exist");

        return votesReceived[candidate];

    }

 

    function validCandidate(string memory candidate) public view returns (bool) {

        for (uint i = 0; i < candidateList.length; i++) {

            if (keccak256(abi.encodePacked(candidateList[i])) == keccak256(abi.encodePacked(candidate))) {

                return true;

            }

        }

        return false;

    }

}

 

Expected Outcome: The smart contract code is ready in Remix.

 

6. Compile the Smart Contract

Why: Compilation converts the Solidity code into bytecode that can be deployed to the blockchain.

  • Step:
    1. Click on the "Solidity Compiler" icon on the left sidebar in Remix.
    2. Make sure the compiler version is set to 0.8.0 or higher.
    3. Click "Compile Voting.sol."

Expected Outcome: The contract is compiled successfully, and you should see a green checkmark.

 

7. Deploy the Smart Contract to Ganache

Why: Deploying the contract to the blockchain makes it accessible for interaction.

  • Step:
    1. Click on the "Deploy & Run Transactions" icon on the left sidebar in Remix.
    2. Under "Environment," select "Injected Web3" (this connects Remix to MetaMask).   //Can use Ganache, other other Virtue Machine such as Remix VM (Cancun)
    3. Ensure MetaMask is connected to Ganache.
    4. In the "Deploy" section, you’ll see a field to input the constructor arguments. Enter the candidates as ["Alice", "Bob", "Charlie"].
    5. Click "Deploy" and confirm the transaction in MetaMask.

Expected Outcome: The contract is deployed to Ganache, and you’ll see it listed under "Deployed Contracts" in Remix.

 

8. Cast a Vote for a Candidate

Step:

  1. Locate the voteForCandidate Function:
    • In the "Deployed Contracts" section of Remix, expand the Voting contract.
    • Scroll down to find the voteForCandidate function.
  2. Enter Candidate Name:
    • In the input box next to voteForCandidate, type the name of the candidate you want to vote for, e.g., "Alice".
    • Ensure the name is in quotes and is case-sensitive (it must match exactly as it was input during deployment).
  3. Cast the Vote:
    • Click the voteForCandidate button.
    • MetaMask will ask you to confirm the transaction. Click "Confirm."

Expected Outcome: The vote is cast for "Alice," and a transaction is confirmed in MetaMask.

 

9. Validate a Candidate Name

Step:

  1. Locate the validCandidate Function:
    • In the "Deployed Contracts" section, find the validCandidate function.
  2. Enter Candidate Name:
    • In the input box next to validCandidate, type the candidate's name you want to validate, e.g., "Bob".
    • Again, make sure to match the exact name and format used during deployment.
  3. Check Validity:
    • Click the validCandidate button.
    • The result will appear below the button:
      • true if the candidate exists.
      • false if the candidate does not exist.

Expected Outcome: You can validate whether "Bob" is a valid candidate in the contract.

 

10. Count the Votes for a Candidate

Step:

  1. Locate the totalVotesFor Function:
    • In the "Deployed Contracts" section, find the totalVotesFor function.
  2. Enter Candidate Name:
    • In the input box next to totalVotesFor, type the name of the candidate whose votes you want to count, e.g., "Alice".
  3. Check the Vote Count:
    • Click the totalVotesFor button.
    • The total number of votes for "Alice" will appear below the button.

Expected Outcome: You can see the number of votes "Alice" has received.

 

Summary:

This guide will allow you to:

  • Deploy the Voting contract by entering an array of candidate names.
  • Interact with the contract by casting votes for a specific candidate.
  • Validate whether a name is a valid candidate.
  • Count the total votes for each candidate.

 

Blockchain Concepts

As you go through the steps of deploying and interacting with a smart contract using MetaMask, Ganache, and Remix, you'll be learning essential concepts related to blockchain technology. Below is a comprehensive guide that outlines these key concepts in detail, along with how they relate to the tasks you'll be performing.

1. Blockchain Basics

  • Blockchain: A blockchain is a decentralized digital ledger that records transactions across many computers. It’s secure and immutable, meaning once data is recorded, it cannot be altered without altering all subsequent blocks.
  • Ethereum: Ethereum is a popular blockchain platform that allows developers to create decentralized applications (dApps) using smart contracts.

2. Ethereum Wallets

·        Ethereum Wallet: A digital wallet is a tool that allows you to interact with the Ethereum blockchain. It holds your private keys and enables you to send and receive Ether (ETH) and other tokens.

·        MetaMask: MetaMask is an Ethereum wallet in the form of a browser extension. It acts as a bridge between your browser and the Ethereum blockchain, allowing you to interact with dApps like the one you're creating.

Key Points:

    • Private Key: A private key is a secret number that allows you to access and manage your Ethereum account. It’s crucial to keep it secure because anyone with your private key can control your account.
    • Public Key: A public key is derived from the private key and is used to create a public address. It can be shared with others to receive funds.
    • Account Address: This is the public identifier of your wallet. It's a string of alphanumeric characters and can be shared with others to receive ETH or tokens.

3. Ethereum Networks

  • Mainnet vs. Testnet: The Ethereum Mainnet is the live network where actual ETH is used and where real transactions take place. Testnets like Rinkeby, Goerli, or a local blockchain (Ganache) are used for development and testing without using real money.
  • Gas: Every transaction on Ethereum requires computational work. Gas is the unit used to measure the amount of work needed. It’s paid in Ether and serves as a fee to incentivize miners to include your transaction in a block.

4. Smart Contracts

·        Smart Contract: A smart contract is a self-executing contract with the terms of the agreement directly written into code. It automatically enforces the rules and penalties of an agreement.

·        Solidity: Solidity is the programming language used to write smart contracts on Ethereum. In this exercise, you’re using Solidity to write a simple Voting contract.

Key Points:

    • Deploying a Contract: Deploying a contract means sending the compiled code to the blockchain, where it will live and be accessible to anyone.
    • Interacting with a Contract: Once deployed, you can interact with the contract by calling its functions. In this exercise, you’ll interact with functions like voteForCandidate and totalVotesFor.

5. Ganache: Local Blockchain

·        Ganache: Ganache is a personal blockchain for Ethereum development. It allows you to deploy contracts, develop applications, and run tests in a controlled environment. Ganache simulates a real blockchain network but runs locally on your computer.

Key Points:

    • Accounts with Preloaded ETH: Ganache provides several accounts, each preloaded with 100 ETH, to use for testing without the risk of losing real money.
    • Private Key in Ganache: Each account in Ganache has a corresponding private key, which you can import into MetaMask to manage the account through the MetaMask interface.

6. Connecting MetaMask with Ganache

  • RPC URL: Remote Procedure Call (RPC) URL is used by applications like MetaMask to connect to a blockchain node. Ganache provides an RPC URL that you can use to connect your MetaMask wallet to the local blockchain.
  • Chain ID: The Chain ID is an identifier for the blockchain network. For Ganache, this is typically set to 1337 by default.

7. Deploying and Interacting with Smart Contracts

·        Deployment: Deployment refers to the process of sending your smart contract code to the blockchain so that it becomes an active contract that others can interact with.

·        Constructor Arguments: Some smart contracts require input when they are first deployed. For example, in the Voting contract, you provide an array of candidate names when deploying.

Key Points:

    • Function Calls: After deployment, you can call the functions defined in the smart contract. For example, you might call voteForCandidate("Alice") to cast a vote.
    • Viewing Results: You can retrieve information stored in the contract, such as checking the number of votes a candidate has received using the totalVotesFor function.

8. Transactions and Confirmations

·        Transaction: A transaction is a signed piece of data that represents an action on the blockchain, such as deploying a contract or calling a function within a contract. Each transaction requires a fee (paid in gas).

·        Confirmation: After submitting a transaction, it is broadcast to the network. Miners will pick it up and include it in a block. Once included, the transaction is confirmed and the changes it represents are applied to the blockchain.

Key Points:

    • MetaMask Confirmation: Every time you interact with the smart contract, MetaMask will ask for your approval before sending the transaction to the blockchain.
    • Pending and Confirmed Transactions: While waiting for a transaction to be mined, it may be marked as pending. Once included in a block, it will be confirmed.

Security Considerations in Blockchain and Smart Contracts

1. Importance of Security in Smart Contracts

  • Immutability: Once a smart contract is deployed on the blockchain, its code cannot be changed. This immutability is a double-edged sword; while it provides trust and transparency, it also means any bugs or vulnerabilities in the contract are permanent.
  • Public and Transparent: Smart contracts on public blockchains like Ethereum are visible to everyone. This transparency is beneficial for trust but also means that any vulnerabilities can be exploited by malicious actors.
  • No Central Authority: Unlike traditional applications where issues can be patched by a central authority, smart contracts rely on decentralized consensus. If a security flaw is found, it can only be addressed by deploying a new contract.

Security Best Practices:

  • Audit the Code: Before deploying a smart contract, it’s crucial to audit the code for vulnerabilities. This can involve manual review and using automated tools to detect common issues.
  • Test Thoroughly: Use test networks (like Ganache) to simulate different scenarios and edge cases. Ensure that the contract behaves as expected in all conditions.
  • Limit Access: Use access control mechanisms to restrict who can interact with certain functions. For example, only allow specific addresses to perform administrative tasks.

2. Deploying the Smart Contract on the Ethereum Mainnet

  • Where the Contract Will Be: Once deployed on the Ethereum Mainnet, the smart contract will reside on the blockchain, accessible via its unique address. This address is like a location on the blockchain where the contract’s code and data are stored.
  • Global Accessibility: Since the Ethereum Mainnet is a global network, the deployed contract can be accessed by anyone with an Ethereum account. They can interact with the contract by sending transactions to its address.

How Miners Find and Mine It:

  • Transaction Broadcasting: When you deploy a contract, the deployment transaction is broadcast to the Ethereum network. All nodes on the network receive this transaction.
  • Miners: Miners are special nodes that compete to validate transactions and add them to the blockchain. They do this by solving complex mathematical puzzles (proof-of-work). When a miner successfully solves the puzzle, they get the right to add a block of transactions, including your contract deployment, to the blockchain.
  • Inclusion in a Block: Once your transaction is included in a block, the contract is officially deployed. The block containing your transaction is then propagated to all nodes on the network, making your contract accessible globally.

 

Homework of Week 4 -  Step-by-Step Guide to Setting Up and Running the Voting dApp with Truffle

 

1. Set Up Your Environment

  1. Install Node.js and npm:
    Download and install Node.js from the official website. npm is bundled with Node.js.
  2. Install Truffle and Ganache:
    Open your terminal and run the following commands to install Truffle and Ganache:

npm install -g truffle

npm install -g ganache-cli

Alternatively, you can download the Ganache desktop application from the official website.

 

2. Create a New Truffle Project

  1. Create a New Directory:
    In your terminal, create a new directory for your project and navigate into it:

 

mkdir voting-dapp

cd voting-dapp

 

  1. Initialize a Truffle Project:
    Run the following command to initialize a new Truffle project:

truffle init

  1. Add the Voting Contract:
    Create a file named Voting.sol in the contracts/ directory and paste the following Solidity code:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

 

contract Voting {

    string[] public candidateList;

    mapping(string => uint256) public votesReceived;

 

    constructor(string[] memory candidateNames) {

        candidateList = candidateNames;

    }

 

    function voteForCandidate(string memory candidate) public {

        votesReceived[candidate] += 1;

    }

 

    function totalVotesFor(string memory candidate) public view returns (uint256) {

        return votesReceived[candidate];

    }

}

 

3. Create a Migration Script

  1. Create the Migration Script:
    In the migrations/ folder, create a file named 2_deploy_voting.js and add the following code:

 

const Voting = artifacts.require("Voting");

 

module.exports = function (deployer) {

  const candidates = ["Alice", "Bob", "Charlie"];

  deployer.deploy(Voting, candidates);

};

 

 

4. Truffle Configuration: truffle-config.js

The Truffle configuration file is automatically generated when you initialize a Truffle project, but you should ensure it is properly set up for your local development environment. Here is a basic setup for using Ganache:

 

module.exports = {

  networks: {

    development: {

      host: "127.0.0.1",     // Localhost (default: none)

      port: 7545,            // Standard Ganache port

      network_id: "*",       // Any network (default: none)

    },

  },

  compilers: {

    solc: {

      version: "0.8.0",       // Fetch exact version from solc-bin (default: truffle's version)

    },

  },

};

 

5. Compile and Deploy the Contract

  1. Start Ganache:
    If you're using the Ganache CLI, start it with the following command:

ganache-cli

 

If you're using the Ganache desktop application, simply launch it.

 

  1. Compile the Contract:
    Compile the contract with the following command:

truffle compile

 

  1. Deploy the Contract:
    Deploy the contract to your local Ganache network:

truffle migrate

 

6. Interact with the Deployed Contract

  1. Create the Interaction Script:
    In the scripts/ folder (you may need to create this folder), create a file named interact.js and add the following code:

 

const Voting = artifacts.require("Voting");

 

module.exports = async function (callback) {

    try {

        // Get the deployed instance of the contract

        const votingInstance = await Voting.deployed();

 

        // List of candidates

        const candidates = ["Alice", "Bob", "Charlie"];

 

        // Vote for a candidate

        await votingInstance.voteForCandidate(candidates[0], { from: (await web3.eth.getAccounts())[0] });

        console.log(`Voted for ${candidates[0]}`);

 

        // Get total votes for a candidate

        const votes = await votingInstance.totalVotesFor(candidates[0]);

        console.log(`${candidates[0]} has ${votes} vote(s)`);

 

        callback();

    } catch (error) {

        console.error("Error interacting with the contract:", error);

        callback(error);

    }

};

 

  1. Run the Interaction Script:
    Execute the script to interact with the deployed contract:

truffle exec scripts/interact.js

 

7. Verify the Results

  • After running the script, you should see output in the terminal indicating that the vote for "Alice" was successful, and the total number of votes for "Alice" should be displayed.

 

8. Update the interact.js File to Cast More Votes for the Three Candidates

Update the interact.js file with the following code to cast multiple votes for each candidate:

 

const Voting = artifacts.require("Voting");

 

module.exports = async function (callback) {

    try {

        // Get the deployed instance of the contract

        const votingInstance = await Voting.deployed();

 

        // List of candidates

        const candidates = ["Alice", "Bob", "Charlie"];

        const accounts = await web3.eth.getAccounts();

 

        // Function to vote multiple times for a candidate

        async function voteMultipleTimes(candidate, numVotes) {

            for (let i = 0; i < numVotes; i++) {

                await votingInstance.voteForCandidate(candidate, { from: accounts[0] });

            }

            console.log(`Voted ${numVotes} times for ${candidate}`);

        }

 

        // Cast votes

        await voteMultipleTimes(candidates[0], 10); // 10 votes for Alice

        await voteMultipleTimes(candidates[1], 5);  // 5 votes for Bob

        await voteMultipleTimes(candidates[2], 20); // 20 votes for Charlie

 

        // Get total votes for each candidate

        for (let candidate of candidates) {

            const votes = await votingInstance.totalVotesFor(candidate);

            console.log(`${candidate} has ${votes} vote(s)`);

        }

 

        callback();

    } catch (error) {

        console.error("Error interacting with the contract:", error);

        callback(error);

    }

};

 

 

Run the Interaction Script

Execute the script to interact with the deployed contract by running the following command in your terminal:

 

truffle exec scripts/interact.js

 

Expected Outcome

After running the script, you should see the following output:

 

 

Voted 10 times for Alice

Voted 5 times for Bob

Voted 20 times for Charlie

Alice has 11 vote(s)

Bob has 5 vote(s)

Charlie has 20 vote(s)

 

Notes:

  • Ensure Ganache is Running: Make sure Ganache is running before deploying and interacting with the contract.
  • Use the Correct Account: The from address in the voteForCandidate function should be one of the accounts generated by Ganache.
  • Expand the Script: You can expand the script to vote for other candidates, retrieve votes for all candidates, or even automate voting processes.

 

3. Interacting with the Deployed Contract on the Ethereum Mainnet

  • Finding the Contract: Once deployed, your contract will have a unique address on the Ethereum Mainnet. Anyone with this address can interact with the contract using tools like MetaMask or any Ethereum-compatible wallet.
  • Voting by Outsiders: To vote, an outsider would need to know the contract’s address and have an Ethereum wallet with some ETH to pay for gas fees. They can interact with the contract functions (like voteForCandidate) directly through their wallet or a dApp interface.

Steps for Outsiders to Vote:

  1. Get the Contract Address: The contract address must be shared publicly (e.g., on a website or social media) so that people can find it.
  2. Use MetaMask: They can use MetaMask to connect to the Ethereum Mainnet, where the contract is deployed.
  3. Interact with the Contract: Using tools like Remix or directly through their wallet interface, they can call the contract’s functions (e.g., voteForCandidate).

4. Creating a Decentralized Application (dApp)

  • What is a dApp: A decentralized application (dApp) is an application that runs on a blockchain network. Unlike traditional applications, dApps have no central server and are typically open-source. They rely on smart contracts to function.
  • Frontend Interface: To make your voting contract a dApp, you would typically create a web interface that interacts with the smart contract. Users can connect their Ethereum wallets (like MetaMask) to the dApp and interact with the contract through the user interface.
  • Hosting the dApp: The frontend of the dApp can be hosted on a decentralized file storage network like IPFS (InterPlanetary File System) or a traditional web server. Users access the dApp through their browser.

Steps to Create a dApp:

  1. Develop the Frontend: Use web development technologies like HTML, CSS, and JavaScript to create the user interface.
  2. Connect the Frontend to the Smart Contract: Use web3.js or ethers.js libraries to connect the frontend to the smart contract on the Ethereum blockchain.
  3. Deploy the Frontend: Host the frontend on IPFS or a traditional web server.
  4. Share the dApp URL: Provide users with the URL where they can access the dApp, connect their wallets, and interact with the smart contract.

5. Real-World Example of a Voting dApp

  • Real-World Use Case: Consider an online voting platform where members of a decentralized organization (DAO) can vote on proposals. Each vote is recorded on the blockchain, ensuring transparency and immutability.
  • Value of the dApp: Such a dApp can be valuable in scenarios requiring trustless, transparent voting. Examples include shareholder voting in a company, governance voting in a DAO, or public elections where transparency is critical.

Benefits of a Voting dApp:

  • Transparency: Every vote is recorded on the blockchain and can be publicly verified.
  • Security: The decentralized nature of the blockchain ensures that no single entity can tamper with the voting results.
  • Accessibility: Anyone with an internet connection and an Ethereum wallet can participate in the voting process.

Summary:

·  Learn the Technical Steps:

  • Deploy and interact with a smart contract using MetaMask, Ganache, and Remix.
  • Understand how to write, compile, and deploy smart contracts.
  • Gain practical experience in connecting MetaMask to Ganache and deploying contracts on a local blockchain.

·  Gain a Deep Understanding of Blockchain Concepts:

  • Comprehend how smart contracts work on the Ethereum network.
  • Explore the role of miners, transaction validation, and how contracts are added to the blockchain.
  • Understand the importance of gas fees, transaction confirmations, and blockchain security.

·  Appreciate the Importance of Security:

·  Explore Decentralized Applications (dApps):

·  Understand the Real-World Applications of Blockchain:

 

Homework of Week 5 -  Web3 - A DApp for Voting on a Private Blockchain Using Ganache and Metamask 

Refer to  https://github.com/arshdeepbahga/blockchain-applications-book/tree/master/Chapter-5

          Instructional Video Part I(smart contract)      Part II (NPM, React app, web3)

 

Objective

To build a simple Voting DApp that allows users to vote for candidates and view the vote results.

 

Part 1: Setup and Tools Installation

1. Install MetaMask

MetaMask is a browser extension that allows you to interact with the Ethereum blockchain. Here's how to install and set it up:

  1. Go to the MetaMask website: Visit MetaMask and click Download.
  2. Add the extension: Follow the prompts to add the MetaMask extension to your browser (Chrome, Firefox, etc.).
  3. Set up your wallet:
    • After installing, open MetaMask by clicking the extension icon in your browser.
    • Choose Create a new wallet or Import an existing wallet if you have one.
    • Save your 12-word seed phrase somewhere safe! You’ll need this to recover your wallet if something goes wrong.

2. Install Ganache

Ganache is a personal blockchain that you’ll use to deploy your smart contracts locally. It provides you with a set of test accounts pre-loaded with fake Ether.

  • Download Ganache: Go to Truffle Suite's Ganache page and download either the GUI version or install the CLI.
  • Install Ganache GUI (Recommended for Beginners):
    • Install the downloaded Ganache application.
    • Open the app and click Quickstart to automatically start a local blockchain.
    • By default, Ganache will run on port 7545 with Chain ID 5777.
    • You will see a list of accounts with 100 ETH pre-loaded for each.

3. Install Truffle

Truffle is a development framework for Ethereum, which helps you compile, migrate, and manage smart contracts.

  • Install Node.js: You need Node.js and npm (Node Package Manager) installed. Download it from Node.js.
  • Install Truffle:
    • Open a terminal or command prompt and run:

npm install -g truffle

    • This will install the Truffle framework globally on your system.

 

Part 2: Setup the Voting DApp

1. Create a New Project Directory

Open your terminal or command prompt and create a directory for your project:

mkdir voting-dapp

cd voting-dapp

 

2. Initialize a Truffle Project

Run the following command to initialize your Truffle project:

truffle init

This creates the basic structure of the Truffle project, including folders for your contracts, migrations, and configuration.

 

3. Write the Voting Smart Contract

  • In the contracts folder, create a new file called Voting.sol.
  • Add the following Solidity code to create the smart contract:

 

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

 

contract Voting {

    string[] public candidateList;

    mapping(string => uint256) public votesReceived;

 

    constructor(string[] memory candidateNames) {

        candidateList = candidateNames;

    }

 

    function getCandidateList() public view returns (string[] memory) {

        return candidateList;

    }

 

    function voteForCandidate(string memory candidate) public {

        require(validCandidate(candidate), "Candidate not valid.");

        votesReceived[candidate] += 1;

    }

 

    function totalVotesFor(string memory candidate) public view returns (uint256) {

        require(validCandidate(candidate), "Candidate not valid.");

        return votesReceived[candidate];

    }

 

    function validCandidate(string memory candidate) public view returns (bool) {

        for (uint i = 0; i < candidateList.length; i++) {

            if (keccak256(bytes(candidateList[i])) == keccak256(bytes(candidate))) {

                return true;

            }

        }

        return false;

    }

}

 

4. Compile the Smart Contract

Now, compile the smart contract using Truffle:

truffle compile

This will compile Voting.sol and create the necessary artifacts in the build/contracts folder.

 

Part 3: Deploy the Contract

1. Set Up Migration File

In the migrations folder, create a new file called 2_deploy_contracts.js and add the following code to deploy the contract:

 

const Voting = artifacts.require("Voting");

 

module.exports = function (deployer) {

  const candidates = ["Alice", "Bob", "Charlie"];

  deployer.deploy(Voting, candidates);

};

 

This deploys the Voting contract with three candidates: Alice, Bob, and Charlie.

 

2. Update truffle-config.js

Make sure the truffle-config.js file points to the correct network (Ganache):

 

module.exports = {

  networks: {

    development: {

      host: "127.0.0.1",  // Localhost for Ganache

      port: 7545,         // Port Ganache is using

      network_id: "*", // The Chain ID for Ganache CLI

    },

  },

  compilers: {

    solc: {

      version: "0.8.0",   // Make sure this is your correct Solidity version

    },

  },

};

 

 

3. Deploy the Contract

Now deploy the contract to Ganache:

truffle migrate --network development

You should see a successful deployment message and a contract address.

 

 

 

Part 4: Create the Frontend for Web3

1. Set Up React Frontend

To build the frontend, you can use React:

1. Create React App:

npx create-react-app client

cd client

 

2. Install Web3.js and Dependencies

First, ensure you have Web3.js installed in your React app. Web3.js is a library that allows you to interact with the Ethereum blockchain.

Run the following command in the client folder of your project:

 

npm install web3

 

3. Copy Voting.json file to client/src/contracts

The Voting.json file is automatically generated by Truffle when you compile your smart contracts. It contains important details needed to interact with your smart contract from the frontend (React app) using Web3.js.

Here’s why it’s important:

  • ABI (Application Binary Interface): This tells the frontend how to interact with the functions and data in the contract.
  • Contract Bytecode: This is the compiled version of your smart contract, which gets deployed to the blockchain.
  • Contract Address: After deployment, this is the address where the contract is located on the blockchain.

 

Why do you need to copy the Voting.json file?

To interact with your smart contract from your React app, you need the ABI from the Voting.json file. The ABI allows Web3.js to understand how to communicate with the smart contract. Without it, your frontend won’t know how to call the functions in your smart contract.

 

Steps to Copy Voting.json Manually:

  1. Locate the Voting.json file:
    • After you run truffle compile, the Voting.json file is automatically created in the build/contracts/ folder in your Truffle project.
  2. Create a contracts folder in your React app:
    • In the src folder of your React project, create a new folder called contracts.
  3. Copy the Voting.json file:
    • Manually copy the Voting.json file from build/contracts/ in your Truffle project to the newly created client/src/contracts/ folder in your React app.

 

 

 

4. Create a New File Called app.js in the src Folder

In your React project, you will have a src folder inside the client folder where you place the app’s main JavaScript files.

  • Navigate to client/src.
  • Inside the src folder, create a new file named app.js.

This file will be your main component, and it will handle:

  • Connecting to MetaMask.
  • Fetching the user’s account.
  • Interacting with the Voting contract deployed on the blockchain.
  • Updating the UI with candidates and voting functionality.

 

5. Add Code to app.js. This app.js would work as a voting interface.

Here’s how you can structure your UI to interact with the Voting Smart Contract:

Explanation of Voting Interface

  • Candidates List: The interface will dynamically show the list of candidates fetched from the contract.
  • Vote Button: Users will be able to vote for their favorite candidate by clicking the button next to the candidate's name.
  • Vote Count: The number of votes for each candidate will be displayed next to their name, and it will update automatically after each vote.

 

import React, { useState, useEffect } from 'react';

import Web3 from 'web3';

import VotingContract from './contracts/Voting.json';  // Ensure this path is correct

 

const App = () => {

  const [account, setAccount] = useState('');

  const [contract, setContract] = useState(null);

 

  useEffect(() => {

    const initWeb3 = async () => {

      if (window.ethereum) {

        window.web3 = new Web3(window.ethereum);

        try {

          await window.ethereum.request({ method: 'eth_requestAccounts' });  // Request account access

          const accounts = await window.web3.eth.getAccounts();

          setAccount(accounts[0]);

 

          // Get network and contract instance

          const networkId = await window.web3.eth.net.getId();

          const deployedNetwork = VotingContract.networks[networkId];

          const contractInstance = new window.web3.eth.Contract(

            VotingContract.abi,

            deployedNetwork && deployedNetwork.address,

          );

 

          setContract(contractInstance);

        } catch (error) {

          console.error("MetaMask connection failed", error);

        }

      } else {

        console.error("No Ethereum browser extension detected");

      }

    };

 

    initWeb3();

  }, []);

 

  const voteForCandidate = async (candidate) => {

    if (contract) {

      try {

        await contract.methods.voteForCandidate(candidate).send({ from: account });

        console.log(`Voted for ${candidate}`);

      } catch (error) {

        console.error("Error during voting:", error);

      }

    } else {

      console.error("Contract is not initialized");

    }

  };

 

  return (

    <div>

      <h1>Voting DApp</h1>

      <p>Your account: {account}</p>

      <button onClick={() => voteForCandidate('Alice')}>Vote for Alice</button>

      <button onClick={() => voteForCandidate('Bob')}>Vote for Bob</button>

      <button onClick={() => voteForCandidate('Charlie')}>Vote for Charlie</button>

    </div>

  );

};

 

export default App;

 

 

 

Part 5: Test the DApp

  1. Run the React App: In the client folder, run:

 

npm start

 

The app should open in your browser at http://localhost:3000.

 

  1. Interact with the DApp:
    • You should see the candidates and the voting buttons.
    • Click a Vote button, confirm the transaction in MetaMask, and see the votes update.

 

Expected Outcome

By following this guide:

  • You’ll have a working Voting DApp deployed on a local blockchain (Ganache).
  • You can vote for candidates (Alice, Bob, Charlie) and see the updated vote counts.

 

Part 6:

Invite others to vote on Voting DAPP:

To ask others to vote on your Voting DApp, you can create and host a simple web-based dApp where users can interact with the contract via MetaMask. Here's a step-by-step guide to make your DApp available for others to use through a website.

 

Step 1: Set Up the Voting DApp Frontend – Web3

You’ve already built the frontend using React and Web3.js. Now we need to ensure that everything is set up properly so that other users can interact with it.

  1. Ensure Your Contract is Deployed:
    • Your smart contract should already be deployed on Ganache (or another Ethereum-compatible network).
    • Make sure to note the contract address and network settings (e.g., Ganache, or if you deploy to a testnet like Rinkeby).
  2. Configure the Frontend to Use the Contract:
    • Make sure your frontend is set up to connect to the correct contract using MetaMask. In your React app, make sure the ABI and contract address are correctly referenced.

 

Step 2: How Can Others Vote on Your Local Network (Ganache + React)?

For others to vote on your DApp, they would need to be on the same physical or virtual network as you. This typically means:

·       Same Physical Network (Wi-Fi/LAN):

o   If someone is connected to the same Wi-Fi or local network (LAN) as your computer, they can access your Ganache instance and the DApp frontend if you expose the ports (7545 and 3000) to them.

·       Local Network Setup:

o   Localhost (127.0.0.1) refers to your own computer, so someone on your network will not be able to directly access http://localhost:3000 or http://127.0.0.1:7545 on your machine.

o   However, if you share your local IP address with them, they can access your machine's services.

§  Example: If your machine's local IP address is 192.168.1.10, they would access your DApp at http://192.168.1.10:3000 and Ganache at http://192.168.1.10:7545.

·       Run the DApp:

    • Once they are connected to your local Ganache instance and the DApp frontend, they can vote just like you can.

 

Important: Exposing Localhost to the Web

If you want others who are not on your local network (i.e., people on the internet) to vote, you would need to host your DApp on a public server or use a service like ngrok to expose your localhost temporarily to the internet.

 

Using ngrok to Expose Your Local DApp:

  1. Install ngrok:
  2. Expose Port 3000 (Frontend):
    • In the terminal, run:

ngrok http 3000

    • ngrok will provide a temporary public URL (like https://abc123.ngrok.io) that others can use to access your frontend.
  1. Expose Port 7545 (Ganache):
    • Similarly, expose your Ganache port:

ngrok http 7545

    • Share the public URL provided by ngrok for the blockchain backend (e.g., https://xyz456.ngrok.io).

Limitations:

  • This is a temporary solution (ngrok URLs expire after a while).
  • You would need a more permanent hosting solution (e.g., Heroku, Netlify) for long-term use.

 

What is a Private Blockchain?

A private blockchain is a blockchain that is:

  • Accessible only to specific participants (in this case, just your local machine).
  • Confined to your local environment (Ganache running on your computer).
  • Not connected to public blockchain networks like Ethereum Mainnet or testnets (e.g., Rinkeby, Ropsten).

When you run Ganache, you are running a local instance of an Ethereum blockchain where you:

  • Deploy smart contracts (like your Voting DApp).
  • Interact with the blockchain (sending transactions, mining, etc.).
  • Use MetaMask to simulate how users would interact with contracts on a real blockchain.

 

How Private Blockchains Work

  1. Isolated Environment: A private blockchain like Ganache is isolated to your local machine, meaning only you or people who have access to your local environment can interact with the blockchain.
  2. Test Ethereum (ETH): The ETH provided in Ganache is fake Ether for testing purposes only. It has no value on the public Ethereum blockchain.
  3. No Real-World Impact: Since Ganache is private, transactions and interactions with smart contracts do not affect any public blockchain like Ethereum Mainnet. It is a safe environment to test and develop your applications without incurring gas fees.

 

Why You Use a Private Blockchain (Ganache)

  1. Testing and Development: Ganache is ideal for development and testing because:

·       No real Ether is needed.

·       No gas fees are incurred.

·       You can quickly reset the blockchain if something goes wrong.

·       It’s fast and designed for developers to interact with Ethereum contracts easily.

  1. Simulate Real Blockchain Behavior: Although Ganache is private, it behaves similarly to a public Ethereum blockchain. This allows you to simulate what deploying and interacting with smart contracts would be like on a live network, but with no cost.
  2. Safe Environment: You can try out experimental code, test deployments, and transactions without worrying about impacting real-world assets or contracts.

 

Invite others to vote on Voting DAPP:

To ask others to vote on your Voting DApp, you can create and host a simple web-based dApp where users can interact with the contract via MetaMask. Here's a step-by-step guide to make your DApp available for others to use through a website.

 

 

Deploying a Voting DApp to the Sepolia Testnet: A Step-by-Step Guide (optional)

Step 1: Set Up Infura for Sepolia

  1. Create an Infura Project:

·       Go to Infura and create a free account if you don’t have one.

·       Once logged in, create a new project and select Sepolia as the network.

·       Copy the Project ID from your Infura project dashboard.

Step 2: Modify truffle-config.js for Sepolia

You will need to modify the truffle-config.js file to include the Sepolia network configuration.

1.     Install HDWalletProvider (if not already installed):

npm install @truffle/hdwallet-provider

2.     Update truffle-config.js: Open the truffle-config.js file and add the Sepolia network settings. You’ll use HDWalletProvider to connect your MetaMask wallet via Infura.

At the top of the truffle-config.js file, add the following line:

const HDWalletProvider = require('@truffle/hdwallet-provider');

Then, add the Sepolia configuration inside the networks section:

const mnemonic = 'your twelve word MetaMask seed phrase here'; // Your MetaMask seed phrase
 
module.exports = {
  networks: {
    sepolia: {
      provider: () => new HDWalletProvider(mnemonic, `https://sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID`),
      network_id: 11155111, // Sepolia's network ID
      gas: 4500000,         // Gas limit
      gasPrice: 10000000000 // 10 Gwei
    },
  },
  compilers: {
    solc: {
      version: "0.8.0" // Use your correct Solidity version
    }
  }
};
  • Replace YOUR_INFURA_PROJECT_ID with your actual Infura Project ID.
  • Replace the mnemonic with your MetaMask seed phrase (use caution and keep it safe!).

Step 3: Deploy the Smart Contract to Sepolia

With the configuration updated, you’re ready to deploy your smart contract to Sepolia.

1.     Connect MetaMask to Sepolia:

    • In your MetaMask extension, switch to the Sepolia test network. You can do this by clicking on the network selector dropdown and choosing "Sepolia."

2.     Get Sepolia Testnet Ether:

    • You need Sepolia testnet ETH to pay for gas fees. Go to a Sepolia faucet and request some test Ether to your MetaMask wallet address.

3.     Deploy to Sepolia: In your terminal, navigate to your project folder and run the following command:

truffle migrate --network sepolia

If everything is set up correctly, Truffle will compile and deploy the contract to Sepolia. You should see a confirmation message with the contract address on Sepolia.

Step 4: Update the Frontend for Sepolia

Now that the contract is deployed to Sepolia, update your React frontend (app.js) to interact with the deployed contract on the testnet.

1.     Update the Contract Address and Network ID:

    • In your app.js, find where you load the contract instance and update it to use the Sepolia network and the newly deployed contract address.
const networkId = 11155111; // Sepolia's network ID
const contractAddress = 'YOUR_DEPLOYED_CONTRACT_ADDRESS'; // Replace with the actual Sepolia contract address

2.     MetaMask Connection: Ensure MetaMask is connected to Sepolia in the frontend. MetaMask will automatically detect the contract on Sepolia if the correct network ID and contract address are used.

Step 5: Test Your Voting DApp

1.     Start the React App:

    • In the client folder of your project, start the React app:
npm start

2.     Interact with the DApp:

    • Open the app in your browser (typically at http://localhost:3000).
    • Ensure MetaMask is connected to Sepolia and try interacting with the DApp by casting votes.
    • Confirm transactions in MetaMask and ensure they are successfully sent to the Sepolia network.

Step 6: Deploy and Share the Voting DApp

If you want to allow others to interact with your DApp, you need to host it publicly.

1.     Build the React App:

    • Build the React app for production:
npm run build

2.     Host the App:

    • You can use hosting services like Netlify, GitHub Pages, or Heroku to host your DApp.
    • Once hosted, you can share the link with others who can interact with the DApp using MetaMask connected to the Sepolia testnet.

By following these steps, your Voting DApp should now be live on the Sepolia testnet, ready for others to interact with!

 

 

Step-by-Step Guide for Deploying with Truffle

1. Set Up Your Truffle Environment

If you haven’t already, you’ll need to install Truffle and Ganache:

·        Install Truffle:

 
npm install -g truffle

·        Install Ganache: Download Ganache from Truffle Suite and run it.

2. Initialize a New Truffle Project

Create a new project directory and initialize a Truffle project:

 
mkdir VotingTokenDapp
cd VotingTokenDapp
truffle init

This will create a basic folder structure for your Truffle project, including contracts, migrations, and test folders.

3. Write Your VotingToken Contract

In the contracts folder, create a new file called VotingToken.sol:

 
cd contracts
touch VotingToken.sol

Now, copy the VotingToken.sol contract code into this file:

 
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
 
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
 
contract VotingToken is ERC20 {
    address public owner;
    mapping(address => bool) public voters;  // To keep track of registered voters
 
    // Event to log when a voter is registered
    event VoterRegistered(address voter);
 
    // Event to log when votes are cast
    event VotesCasted(address voter, address to, uint256 amount);
 
    constructor(uint256 initialSupply) ERC20("VotingToken", "VOTE") {
        owner = msg.sender;  // The deployer of the contract becomes the owner
        _mint(owner, initialSupply);  // Mint the initial supply of tokens to the owner
    }
 
    // Function for the owner to register voters
    function registerVoter(address voter) public onlyOwner {
        require(!voters[voter], "Voter is already registered");  // Prevent duplicate registration
        voters[voter] = true;  // Mark voter as registered
        emit VoterRegistered(voter);  // Emit event to signal voter registration
    }
 
    // Function for registered voters to vote (transfer tokens)
    function vote(address to, uint256 amount) public {
        require(voters[msg.sender], "You are not registered to vote");  // Ensure voter is registered
        require(balanceOf(msg.sender) >= amount, "Insufficient balance to vote");  // Ensure voter has enough tokens
        transfer(to, amount);  // Transfer tokens (cast votes)
        emit VotesCasted(msg.sender, to, amount);  // Emit event to log the vote
    }
 
    // Modifier to restrict certain functions to only the owner of the contract
    modifier onlyOwner() {
        require(msg.sender == owner, "Only the owner can perform this action");
        _;
    }
}

4. Install OpenZeppelin ERC20 Dependency

You need to install the OpenZeppelin contracts in your project (in the project root directory):

npm install @openzeppelin/contracts

This will allow you to use OpenZeppelin’s ERC20 implementation.

5. Create a Migration File

In the migrations folder, create a new migration file to deploy the VotingToken contract:

 
touch 2_deploy_voting_token.js

Add the following content to the 2_deploy_voting_token.js file:

 
const VotingToken = artifacts.require("VotingToken");
 
module.exports = function(deployer) {
  // Initial token supply of 1000
  deployer.deploy(VotingToken, 1000);
};

This migration file tells Truffle to deploy the VotingToken contract with an initial supply of 1000 tokens.

6. Configure Truffle for Ganache

In the truffle-config.js file, configure the network settings for Ganache:

  1. Open the truffle-config.js file.
  2. Add the following configuration for the development network:
module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",     // Localhost (default: none)
      port: 7545,            // Standard Ganache port (default: none)
      network_id: "*",       // Any network (default: none)
    }
  },
  compilers: {
    solc: {
      version: "0.8.20",     // Fetch exact version from solc-bin (default: truffle's version)
    }
  }
};

This configuration connects Truffle to the local Ganache instance running on localhost:7545.

7. Compile the Contract

Now, compile the contract using Truffle:

 
truffle compile

This will compile the VotingToken.sol contract and generate the necessary build files.

8. Deploy the Contract

Now deploy the contract to the local Ganache blockchain:

 
truffle migrate --network development

This will deploy the VotingToken contract and output the contract address.

9. Interact with the Contract Using Truffle Console

Once the contract is deployed, you can interact with it using the Truffle console:

 
truffle console --network development

In the Truffle console, you can interact with the deployed contract:

·        Get the deployed instance:

 
const token = await VotingToken.deployed();

·        Check the token supply:

 (await token.totalSupply()).toString();

·        Register a voter:

await token.registerVoter("0x1234...");  // Replace with a valid Ganache address

·        Cast a vote:

await token.vote("0x5678...", 10);  // Replace with the recipient address and vote amount

10. Monitor Transactions in Ganache

In Ganache, you will see all the transactions made by Truffle, including contract deployment and function calls.

Summary

  1. Set up the Truffle project.
  2. Write the VotingToken contract and include the OpenZeppelin ERC20 dependency.
  3. Create a migration script to deploy the contract.
  4. Configure Truffle to connect to Ganache.
  5. Compile and deploy the contract.
  6. Use Truffle Console to interact with the deployed contract.

You can now deploy your VotingToken contract using Truffle on Ganache!

 

 

Homework of Week 6 – Building an ERC20-Based Token on Ethereum

Instructional Video                                 Quiz

·     Part 1 (Ganache Window Platform, ?)

·     Part II  (Ganache on Truffle, works)

·     PartIII   (Metamask, works)      

 

What is ERC20?

ERC20 is a widely-used standard for creating tokens on the Ethereum blockchain. It defines a set of rules that all Ethereum-based tokens must follow to ensure interoperability between different tokens and decentralized applications (dApps). These rules define functions that allow tokens to be easily transferred, approved for use by other accounts, and checked for balance.

Technically, Bitcoin and ERC20 tokens operate on two different blockchain.

·       Bitcoin operates on its own Bitcoin blockchain, while ERC20 tokens are designed for the Ethereum blockchain.

What is this Standard for Tokens?

The ERC20 standard provides a blueprint for how tokens behave and interact with other smart contracts or wallets. The standard functions include:

  • totalSupply(): Returns the total supply of tokens in circulation.
  • balanceOf(address account): Returns the balance of tokens held by a specific account.
  • transfer(address recipient, uint256 amount): Transfers tokens from the sender to the recipient.
  • approve(address spender, uint256 amount): Allows an address to spend a specified number of tokens on behalf of the token holder.
  • transferFrom(address sender, address recipient, uint256 amount): Enables a third party (approved spender) to transfer tokens on behalf of the owner.
  • allowance(address owner, address spender): Checks the remaining amount of tokens that a spender is allowed to transfer from an owner.

These functions allow ERC20 tokens to behave consistently and be used across different dApps without requiring special modifications.

What is a Token For?

A token is a digital asset that can represent various forms of value. On Ethereum, tokens can be used to represent things like:

  • Currency (e.g., stablecoins like USDC).
  • Voting Rights: Tokens can be used as voting mechanisms in decentralized governance.
  • Ownership: Tokens can represent ownership in a digital or physical asset.
  • Access Control: Some platforms use tokens to give users access to certain functionalities or content.

What Can Tokens Be Used For in a dApp?

In decentralized applications (dApps), tokens can serve different roles. For example:

  • Voting: Tokens can be used in a decentralized governance system where users vote on proposals based on the number of tokens they hold. More tokens can give users more voting power.
  • Payment: Tokens can be used as a form of currency for transactions between users and dApps.
  • Staking: Tokens can be locked up in a smart contract to secure a network or dApp, with rewards paid to users.

ERC20 Token Solidity Code Example

Here's a basic example of an ERC20 token that could be used for voting in a dApp:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import "@openzeppelin/contracts/utils/Context.sol";

import "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";

contract VotingToken is ERC20 {

    address public owner;

 

    // Constructor to initialize the contract with a given supply

    constructor(uint256 initialSupply) ERC20("VotingToken", "VOTE") {

        owner = msg.sender; // Set the owner to the contract deployer

        _mint(owner, initialSupply); // Mint the initial supply of tokens

    }

 

    // Other functions can be added here as needed

}

 

This VotingToken contract:

  • Sets the token name to "VotingToken" and symbol to "VOTE".
  • Mints the initial supply of tokens to the deployer’s address.
  • Follows the ERC20 standard, so it includes functions like transfer, approve, and balanceOf.

How to Deploy Using Remix, Ganache, and MetaMask

Here’s how you can deploy the VotingToken smart contract using Remix, Ganache, and MetaMask.

Step 1: Setup Ganache and Metamask

1. Set Up a New Workspace in Ganache

1.     Open Ganache:

    • Start Ganache on your computer.

2.     Create a New Workspace:

    • On the Ganache homepage, click New Workspace.
    • Give your workspace a name (e.g., "Voting Token Station").

3.     Configure Workspace Settings:

    • In the workspace settings, you'll see several options like server settings, accounts, and gas limits.

2. Change the Default ETH Balance to 10000

1.     Go to Accounts & Keys:

    • In the workspace configuration window, find the Accounts & Keys section.

2.     Set the Default Balance:

    • Change the default balance from the default value (usually 100 ETH) to 10000 ETH. This means that each account in your Ganache workspace will start with 10000 ETH.

3. Set the Gas Limit to 8,000,000

1.     Go to Server Settings:

    • In the workspace settings, click on Server.

2.     Update Gas Limit:

    • You will see an option to set the Gas Limit. Change this to 8000000.

3.     Save and Start:

    • After making these changes, save the workspace and click Start. Ganache will now launch with the specified settings (10000 ETH per account and a gas limit of 8,000,000).

4. Connect MetaMask to the New Workspace

1.     Open MetaMask:

    • Open MetaMask in your browser.

2.     Connect to the New Ganache Workspace:

    • In MetaMask, go to the network dropdown and click Custom RPC.
    • Enter the RPC URL from Ganache (typically http://127.0.0.1:7545), and set the Chain ID (either 5777 or the ID configured in Ganache).
    • MetaMask will now connect to the new Ganache workspace, and you will have 10000 ETH available for each account.

Step 2: Deploy the Contract with Remix

1.     Open Remix:

    • Go to the Remix IDE.

2.     Create a New File:

    • Create a new Solidity file (e.g., VotingToken.sol), and paste the smart contract code.

3.     Compile the Contract:

    • Click on the "Solidity Compiler" tab and compile the contract.

4.     Deploy the Contract:

    • Go to the "Deploy & Run Transactions" tab.
    • Change the environment to “Ganache" to connect Remix to Ganache and MetaMask.
    • Select the correct account in MetaMask (the one connected to Ganache).
    • Enter the initial supply of tokens (e.g., 1000000), and deploy the contract.

5.     Confirm in MetaMask:

    • MetaMask will pop up asking for confirmation. Approve the transaction to deploy the contract.

Step 3: Interact with the Contract

  • After deploying, you can interact with the contract using Remix’s UI or MetaMask:
    • Use the balanceOf function to check token balances.
    • Use transfer to send tokens to another account.

Step 4: Testing Voting with Tokens

If you want to build a voting system, you can write a function in Solidity to count votes based on token balances. Tokens can represent voting power, and participants can cast votes by transferring tokens or through a more complex function that records votes without transferring tokens.

 

 

If the above code does not work: Step-by-Step Guide: Setting Up Ganache, MetaMask, and Remix

 

1. Stop Any Existing Process on Port 8545:

If Ganache or another application is already using port 8545, we need to stop it.

Find and Kill the Process:

  1. Open Command Prompt as Administrator.
  2. Run the following command to find the process using port 8545:
netstat -ano | findstr :8545
  1. Youll see an output like this:
TCP    127.0.0.1:8545    0.0.0.0:0    LISTENING    <PID>

Note the PID (Process ID) for the process.

  1. Run the following command to stop that process:
taskkill /PID <PID> /F

Replace <PID> with the actual Process ID from the previous step.

 

2. Start Ganache (Local Blockchain):

Once port 8545 is free, you can start Ganache on the correct settings.

Run Ganache on Port 8545:

  1. Open Command Prompt.
  2. Run the following command to start Ganache on port 8545 with network ID 1337:
ganache-cli --port 8545 --networkId 1337 --chain.chainId 1337
  1. You should see output like this:
ganache v7.9.2 (@ganache/cli: 0.10.2, @ganache/core: 0.10.2)
Starting RPC server at http://127.0.0.1:8545
  1. Ganache will generate several accounts, each with 1000 ETH, ready to be used.

 

3. Connect MetaMask to Ganache:

To interact with Ganache using MetaMask, you need to configure MetaMask to connect to the local blockchain.

Set Up MetaMask:

  1. Open MetaMask.
  2. Click the network dropdown at the top and select Add Network.
  3. Enter the following details:
    • Network Name: Ganache
    • RPC URL: http://127.0.0.1:8545
    • Chain ID: 1337
    • Currency Symbol: ETH (optional)
  4. Save the network and switch to it in MetaMask.

 

4. Use Remix to Deploy Smart Contracts:

Now, we’ll use Remix to write and deploy smart contracts on the local Ganache network.

Configure Remix to Use MetaMask:

  1. Open Remix (https://remix.ethereum.org).
  2. In the Deploy & Run Transactions tab on the left, select Injected Web3 from the environment dropdown.
    • This will connect Remix to MetaMask, which is already connected to Ganache.
  3. Make sure MetaMask is connected to the Ganache network you set up in step 3.

5. Deploy a Smart Contract:

Now that everything is connected, you can deploy a contract.

Deploy a Contract in Remix:

  1. Write or open a smart contract in Remix.
  2. Click Compile to ensure the contract compiles without errors.
  3. In the Deploy & Run Transactions tab, select your contract and click Deploy.
    • MetaMask will prompt you to sign the transaction.
  4. Once the contract is deployed, you can interact with it using the available functions in Remix.

6. Verify the Deployment:

If everything is set up correctly, the contract will be deployed to Ganache, and you can interact with it using the Remix interface or MetaMask.

 

Optional: Use a Different Port:

If port 8545 is already in use and you don't want to stop the process, you can start Ganache on a different port (e.g., port 8546):

Run Ganache on Port 8546:

 
ganache-cli --port 8546 --networkId 1337 --chain.chainId 1337

Make sure to update the RPC URL in MetaMask to http://127.0.0.1:8546 and follow the same steps as before.

Summary

  1. Free port 8545 if it's being used.
  2. Run Ganache on port 8545 (or another port).
  3. Connect MetaMask to the Ganache network.
  4. Use Remix to write, compile, and deploy smart contracts.

By following these steps, you will be able to successfully set up a local blockchain, connect it to MetaMask, and deploy contracts using Remix.

 

 

Voting Token Assignment (Optional. Simply replace the Solidity code with the following and repeat the process you have done earlier:)

Solidity code:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

 import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

 contract VotingToken is ERC20 {

    address public owner;

    mapping(address => bool) public voters;  // To keep track of registered voters

     // Event to log when a voter is registered

    event VoterRegistered(address voter);

     // Event to log when votes are cast

    event VotesCasted(address voter, address to, uint256 amount);

 

    constructor(uint256 initialSupply) ERC20("VotingToken", "VOTE") {

        owner = msg.sender;  // The deployer of the contract becomes the owner

        _mint(owner, initialSupply);  // Mint the initial supply of tokens to the owner

    }

     // Function for the owner to register voters

    function registerVoter(address voter) public onlyOwner {

        require(!voters[voter], "Voter is already registered");  // Prevent duplicate registration

        voters[voter] = true;  // Mark voter as registered

        emit VoterRegistered(voter);  // Emit event to signal voter registration

    }

     // Function for registered voters to vote (transfer tokens)

    function vote(address to, uint256 amount) public {

        require(voters[msg.sender], "You are not registered to vote");  // Ensure voter is registered

        require(balanceOf(msg.sender) >= amount, "Insufficient balance to vote");  // Ensure voter has enough tokens

        transfer(to, amount);  // Transfer tokens (cast votes)

        emit VotesCasted(msg.sender, to, amount);  // Emit event to log the vote

    }

     // Modifier to restrict certain functions to only the owner of the contract

    modifier onlyOwner() {

        require(msg.sender == owner, "Only the owner can perform this action");

        _;

    }

}

Explanation:

In this contract, the token serves as the unit of voting. Here's how it works and why the token is important:

1.     Voting Power: The token represents voting power. Each token gives its holder the ability to cast a certain number of votes. The more tokens a voter holds, the more voting power they have. When a registered voter transfers tokens to another address, it is considered casting votes for that address.

2.     Transfer of Votes: The vote function allows a voter to transfer their tokens to another address. This transfer is equivalent to casting a vote for that address. The tokens themselves are the means through which votes are allocated and counted.

3.     Ownership and Control: The initial supply of tokens is minted to the contract owner when the contract is deployed. The owner can distribute these tokens among registered voters, giving them voting power. The number of tokens a voter has determines how many votes they can cast.

Use Cases for the Token:

  • Weighted Voting: If different voters are assigned different amounts of tokens, it creates a weighted voting system, where some voters have more influence than others based on the number of tokens they hold.
  • Voting Representation: The token represents voting rights in the system. Each transfer of tokens signifies casting votes for a particular candidate or option.
  • Incentivized Participation: Tokens can also serve as an incentive for participation in governance. Voters who hold more tokens might be given greater decision-making power or other benefits tied to their token holdings.

In short, the token in this contract acts as a voting token, allowing registered users to vote by transferring tokens to other addresses, where the number of tokens transferred represents the number of votes cast.

 

 

Term Project  1 (option 1)- Deploy and Interact with a Smart Contract KYC (Know your customer, a DApp used by banks))

 

 

·        Instructional Video1 (smart contract)

·        Video2  (truffle console, optional)

·        Video3 (web3 part1)   

·        Video4 (web3, part2)

 

Refer to  https://github.com/Simplilearn-Edu/Blockchain-Capstone-Projects/blob/main/Project%201%20Decentralized%20KYC%20Verification.zip

1. Set Up Your Development Environment

1.1 Install Node.js and npm:

  • Download and install Node.js from nodejs.org. This will include npm (Node Package Manager).

1.2 Install Truffle and Ganache:

  • Install Truffle globally using npm:

npm install -g truffle

  • Download and install Ganache from trufflesuite.com/ganache (or use the CLI version with npm install -g ganache-cli).

2. Initialize a Truffle Project

2.1 Create a New Directory for Your Project:

 

mkdir my-project

cd my-project

 

2.2 Initialize Truffle:

truffle init

This command creates a basic Truffle project structure.

 

3. Write Your KYC Smart Contract

3.1 Create a New Solidity File:Create a new file KYC.sol in the contracts directory:

 

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

 

contract KYC {

    // Define Bank and Customer structs

    struct Bank {

        string name;

        address bankAddress;

    }

 

    struct Customer {

        string name;

        address customerAddress;

        bool isVerified;

    }

 

    // Mappings to store bank and customer data

mapping(address => Bank) public banks;

mapping(address => Customer) public customers;

 

    // Arrays to store the list of bank and customer addresses

address[] public bankList;

address[] public customerList;

 

    // Event to emit when a new bank is added

    event BankAdded(string name, address bankAddress);

 

    // Event to emit when a new customer is added

    event CustomerAdded(string name, address customerAddress);

 

    // Event to emit when a customer is verified

    event CustomerVerified(address customerAddress);

 

    // Function to add a new bank

    function addNewBank(string memory name, address bankAddress) public {

require(bankAddress != address(0), "Invalid address");

        require(bytes(name).length> 0, "Bank name cannot be empty");

 

        banks[bankAddress] = Bank(name, bankAddress);

bankList.push(bankAddress);

 

        emit BankAdded(name, bankAddress);

    }

 

    // Function to add a new customer

    function addNewCustomer(string memory name, address customerAddress) public {

require(customerAddress != address(0), "Invalid address");

        require(bytes(name).length> 0, "Customer name cannot be empty");

 

        customers[customerAddress] = Customer(name, customerAddress, false);

customerList.push(customerAddress);

 

        emit CustomerAdded(name, customerAddress);

    }

 

    // Function to verify a customer

    function verifyCustomer(address customerAddress) public {

require(customerAddress != address(0), "Invalid address");

        require(customers[customerAddress].customerAddress != address(0), "Customer does not exist");

 

        customers[customerAddress].isVerified = true;

 

        emit CustomerVerified(customerAddress);

    }

 

    // Function to retrieve all banks

    function getBanks() public view returns (Bank[] memory) {

Bank[] memory allBanks = new Bank[](bankList.length);

        for (uint i = 0; i<bankList.length; i++) {

allBanks[i] = banks[bankList[i]];

        }

        return allBanks;

    }

 

    // Function to retrieve all customers

    function getCustomers() public view returns (Customer[] memory) {

Customer[] memory allCustomers = new Customer[](customerList.length);

        for (uint i = 0; i<customerList.length; i++) {

allCustomers[i] = customers[customerList[i]];

        }

        return allCustomers;

    }

}

 

 

 

3.2 Compile Your Contract:

truffle compile

 

4. Migrate Your Smart Contract

4.1 Create a Migration Script: Create a new file 2_deploy_contracts.js in the migrations directory:

 

// migrations/2_deploy_contracts.js

const KYC = artifacts.require("KYC");

 

module.exports = function(deployer) {

  deployer.deploy(KYC);

};

 

4.2 Run Migrations:

truffle migrate --network development

 

5. Interact with Your Smart Contract Using Truffle Console

5.1 Start Ganache:

  • Open Ganache and start a new workspace.
  • Ensure it's running on the default port 7545.

5.2 Open Truffle Console:

truffle console --network development

 

5.3 Interact with Your Contract: In the Truffle Console: 

 

const KYC = artifacts.require("KYC");

const kyc = await KYC.deployed();

const accounts = await web3.eth.getAccounts();

 

// Add new banks

await kyc.addNewBank("Bank1", accounts[1]);

await kyc.addNewBank("Bank2", accounts[2]);

 

// Add new customers

await kyc.addNewCustomer("Customer1", accounts[3]);

await kyc.addNewCustomer("Customer2", accounts[4]);

 

// Verify a customer

await kyc.verifyCustomer(accounts[3]);

 

// Retrieve and log banks and customers

const banks = await kyc.getBanks();

console.log("Banks:", banks);

 

const customers = await kyc.getCustomers();

console.log("Customers:", customers);

 

5.4 DApp and Web3

 

Step 1: Writing the Frontend

1.     Install Dependencies for Web3 Interaction: Install Web3.js and other dependencies that will allow your frontend to interact with the smart contract (you need to create a folder called kyc-dapp first and install web3 in the kyc-dapp folder)

npm install web3

2.     Set Up a Basic Frontend: You can create a simple webpage using React to interact with the blockchain, or just HTML and JavaScript if you prefer. Here’s a minimal setup using plain HTML and JavaScript.

3.     Install Lite Server (for serving the webpage locally):

npm install lite-server --save-dev

4.     Set Up index.html for Your Webpage: Create an index.html file inside the /public folder for your project. This will be the frontend where users can interact with the KYC dApp.

/your-react-app (such as kyc-dapp folder)

├── /node_modules

├── /public

   ├── index.html          // Main HTML file

   ├── favicon.ico         // Favicon

   └── manifest.json       // Web app manifest

├── /src

   ├── App.js              // Main app component

   ├── index.js            // Entry point for React

   ├── kyc.js              // Your KYC contract file

   └── web3.js             // Web3 initialization file (if any)

├── package.json             // Project metadata and dependencies

└── README.md                // Project documentation

 

 

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>KYC DApp</title>

 

  <!-- Web3.js CDN -->

  <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.6.1/dist/web3.min.js"></script>

 

  <!-- CSS Styling for a better appearance -->

  <style>

    body {

      font-family: Arial, sans-serif;

      margin: 0;

      padding: 20px;

      background-color: #f0f0f0;

    }

 

    h1, h2 {

      color: #333;

    }

 

    input {

      padding: 10px;

      margin: 5px;

      border: 1px solid #ccc;

      border-radius: 5px;

      width: 300px;

    }

 

    button {

      padding: 10px 20px;

      margin: 5px;

      background-color: #28a745;

      color: white;

      border: none;

      border-radius: 5px;

      cursor: pointer;

    }

 

    button:hover {

      background-color: #218838;

    }

 

    .container {

      max-width: 600px;

      margin: 0 auto;

      background-color: white;

      padding: 20px;

      border-radius: 10px;

      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

    }

 

    .form-group {

      margin-bottom: 20px;

    }

  </style>

</head>

<body>

  <div id="root"></div>

 

  <script>

    // Setup Web3

    let web3 = new Web3(Web3.givenProvider || "http://localhost:7545");

 

    // ABI and contract address will come from Truffle deployment

    const contractAddress = "PASTE_YOUR_CONTRACT_ADDRESS_HERE";

    const abi = /* PASTE_YOUR_CONTRACT_ABI_HERE */;

 

    const kycContract = new web3.eth.Contract(abi, contractAddress);

 

    // React component for the KYC DApp

    class App extends React.Component {

      constructor(props) {

        super(props);

        this.state = {

          bankName: '',

          bankAddress: '',

          customerName: '',

          customerAddress: '',

          verifyAddress: ''

        };

      }

 

      handleChange = (e) => {

        this.setState({ [e.target.name]: e.target.value });

      };

 

      addNewBank = async () => {

        const { bankName, bankAddress } = this.state;

        const accounts = await web3.eth.getAccounts();

        try {

          await kycContract.methods.addNewBank(bankName, bankAddress).send({ from: accounts[0] });

          alert("Bank Added");

          this.setState({ bankName: '', bankAddress: '' }); // Clear input fields

        } catch (error) {

          console.error("Error adding bank: ", error);

          alert("Error adding bank.");

        }

      };

 

      addNewCustomer = async () => {

        const { customerName, customerAddress } = this.state;

        const accounts = await web3.eth.getAccounts();

        try {

          await kycContract.methods.addNewCustomer(customerName, customerAddress).send({ from: accounts[0] });

          alert("Customer Added");

          this.setState({ customerName: '', customerAddress: '' }); // Clear input fields

        } catch (error) {

          console.error("Error adding customer: ", error);

          alert("Error adding customer.");

        }

      };

 

      verifyCustomer = async () => {

        const { verifyAddress } = this.state;

        const accounts = await web3.eth.getAccounts();

        try {

          await kycContract.methods.verifyCustomer(verifyAddress).send({ from: accounts[0] });

          alert("Customer Verified");

          this.setState({ verifyAddress: '' }); // Clear input field

        } catch (error) {

          console.error("Error verifying customer: ", error);

          alert("Error verifying customer.");

        }

      };

 

      render() {

        return (

          <div className="container">

            <h1>KYC DApp</h1>

 

            <div className="form-group">

              <h2>Add New Bank</h2>

              <input

                type="text"

                name="bankName"

                value={this.state.bankName}

                onChange={this.handleChange}

                placeholder="Bank Name"

              />

              <input

                type="text"

                name="bankAddress"

                value={this.state.bankAddress}

                onChange={this.handleChange}

                placeholder="Bank Address"

              />

              <button onClick={this.addNewBank}>Add Bank</button>

            </div>

 

            <div className="form-group">

              <h2>Add New Customer</h2>

              <input

                type="text"

                name="customerName"

                value={this.state.customerName}

                onChange={this.handleChange}

                placeholder="Customer Name"

              />

              <input

                type="text"

                name="customerAddress"

                value={this.state.customerAddress}

                onChange={this.handleChange}

                placeholder="Customer Address"

              />

              <button onClick={this.addNewCustomer}>Add Customer</button>

            </div>

 

            <div className="form-group">

              <h2>Verify Customer</h2>

              <input

                type="text"

                name="verifyAddress"

                value={this.state.verifyAddress}

                onChange={this.handleChange}

                placeholder="Customer Address"

              />

              <button onClick={this.verifyCustomer}>Verify</button>

            </div>

          </div>

        );

      }

    }

 

    const rootElement = document.getElementById("root");

    if (rootElement) {

      const root = ReactDOM.createRoot(rootElement);

      root.render(<App />);

    } else {

      console.error("Target container is not a DOM element.");

    }

  </script>

</body>

</html>

Step 2: Get Contract ABI and Address:

After deploying your smart contract using Truffle (or any other deployment tool), you'll typically find the ABI and contract address in the build/contracts/KYC.json file.

·        Open build/contracts/KYC.json:

  • Locate the ABI under the abi field and the contract address under the network field (for the desired network, e.g., development).
  • Update Your Contract File (kyc.js): You can store the ABI and address in your kyc.js file, which initializes your contract instance.

The kyc.js file: (under /src folder)

import web3 from './web3'; // Import the initialized Web3 instance

 

// Replace this with your actual deployed contract address

const contractAddress = '0xB8554bbFe82bF0125B6dfd78Dc2Cc6D4180f08eB';

 

// This is the ABI from your KYC contract

const abi = [

  {

    "anonymous": false,

    "inputs": [

      {

        "indexed": false,

        "internalType": "string",

        "name": "name",

        "type": "string"

      },

      {

        "indexed": false,

        "internalType": "address",

        "name": "bankAddress",

        "type": "address"

      }

    ],

    "name": "BankAdded",

    "type": "event"

  },

  {

    "anonymous": false,

    "inputs": [

      {

        "indexed": false,

        "internalType": "string",

        "name": "name",

        "type": "string"

      },

      {

        "indexed": false,

        "internalType": "address",

        "name": "customerAddress",

        "type": "address"

      }

    ],

    "name": "CustomerAdded",

    "type": "event"

  },

  {

    "anonymous": false,

    "inputs": [

      {

        "indexed": false,

        "internalType": "address",

        "name": "customerAddress",

        "type": "address"

      }

    ],

    "name": "CustomerVerified",

    "type": "event"

  },

  {

    "inputs": [

      {

        "internalType": "uint256",

        "name": "",

        "type": "uint256"

      }

    ],

    "name": "bankList",

    "outputs": [

      {

        "internalType": "address",

        "name": "",

        "type": "address"

      }

    ],

    "stateMutability": "view",

    "type": "function"

  },

  {

    "inputs": [

      {

        "internalType": "address",

        "name": "",

        "type": "address"

      }

    ],

    "name": "banks",

    "outputs": [

      {

        "internalType": "string",

        "name": "name",

        "type": "string"

      },

      {

        "internalType": "address",

        "name": "bankAddress",

        "type": "address"

      }

    ],

    "stateMutability": "view",

    "type": "function"

  },

  {

    "inputs": [

      {

        "internalType": "uint256",

        "name": "",

        "type": "uint256"

      }

    ],

    "name": "customerList",

    "outputs": [

      {

        "internalType": "address",

        "name": "",

        "type": "address"

      }

    ],

    "stateMutability": "view",

    "type": "function"

  },

  {

    "inputs": [

      {

        "internalType": "address",

        "name": "",

        "type": "address"

      }

    ],

    "name": "customers",

    "outputs": [

      {

        "internalType": "string",

        "name": "name",

        "type": "string"

      },

      {

        "internalType": "address",

        "name": "customerAddress",

        "type": "address"

      },

      {

        "internalType": "bool",

        "name": "isVerified",

        "type": "bool"

      }

    ],

    "stateMutability": "view",

    "type": "function"

  },

  {

    "inputs": [

      {

        "internalType": "string",

        "name": "name",

        "type": "string"

      },

      {

        "internalType": "address",

        "name": "bankAddress",

        "type": "address"

      }

    ],

    "name": "addNewBank",

    "outputs": [],

    "stateMutability": "nonpayable",

    "type": "function"

  },

  {

    "inputs": [

      {

        "internalType": "string",

        "name": "name",

        "type": "string"

      },

      {

        "internalType": "address",

        "name": "customerAddress",

        "type": "address"

      }

    ],

    "name": "addNewCustomer",

    "outputs": [],

    "stateMutability": "nonpayable",

    "type": "function"

  },

  {

    "inputs": [

      {

        "internalType": "address",

        "name": "customerAddress",

        "type": "address"

      }

    ],

    "name": "verifyCustomer",

    "outputs": [],

    "stateMutability": "nonpayable",

    "type": "function"

  },

  {

    "inputs": [],

    "name": "getBanks",

    "outputs": [

      {

        "components": [

          {

            "internalType": "string",

            "name": "name",

            "type": "string"

          },

          {

            "internalType": "address",

            "name": "bankAddress",

            "type": "address"

          }

        ],

        "internalType": "struct KYC.Bank[]",

        "name": "",

        "type": "tuple[]"

      }

    ],

    "stateMutability": "view",

    "type": "function"

  },

  {

    "inputs": [],

    "name": "getCustomers",

    "outputs": [

      {

        "components": [

          {

            "internalType": "string",

            "name": "name",

            "type": "string"

          },

          {

            "internalType": "address",

            "name": "customerAddress",

            "type": "address"

          },

          {

            "internalType": "bool",

            "name": "isVerified",

            "type": "bool"

          }

        ],

        "internalType": "struct KYC.Customer[]",

        "name": "",

        "type": "tuple[]"

      }

    ],

    "stateMutability": "view",

    "type": "function"

  }

];

 

const kycContract = new web3.eth.Contract(abi, contractAddress);

export default kycContract;

 

Add Babel Plugin to Fix Warnings (if needed): We encountered a warning about an outdated plugin. To fix this, run:

npm install --save-dev @babel/plugin-proposal-private-property-in-object

Step 3: Fix the App.js (under /src folder)

import React, { useState, useEffect } from 'react';

import Web3 from 'web3'; // Import Web3

 

import kycContract from './KYC'; // Use the correct casing

 

 

const App = () => {

    const [account, setAccount] = useState('');

    const [banks, setBanks] = useState([]);

    const [bankName, setBankName] = useState('');

    const [bankAddress, setBankAddress] = useState('');

    const [customerName, setCustomerName] = useState('');

    const [customerAddress, setCustomerAddress] = useState('');

    const [verifyAddress, setVerifyAddress] = useState('');

 

    // Initialize Web3 and check for MetaMask

    useEffect(() => {

        const initWeb3 = async () => {

            if (window.ethereum) {

                const web3 = new Web3(window.ethereum);

                try {

                    const accounts = await web3.eth.requestAccounts();

                    setAccount(accounts[0]);

                } catch (error) {

                    console.error("Error fetching accounts: ", error);

                }

            } else {

                alert('Please install MetaMask!');

            }

        };

 

        initWeb3();

    }, []);

 

    // Function to add a new bank

    const addNewBank = async () => {

        if (!bankName || !bankAddress) {

            alert("Please provide both bank name and address.");

            return;

        }

        try {

            const accounts = await window.ethereum.request({ method: 'eth_accounts' });

            await kycContract.methods.addNewBank(bankName, bankAddress).send({ from: accounts[0] });

            alert("Bank Added");

            setBanks([...banks, { name: bankName, address: bankAddress }]);

            setBankName('');

            setBankAddress('');

        } catch (error) {

            console.error("Error adding bank: ", error);

            alert("Error adding bank.");

        }

    };

 

    // Function to add a new customer

    const addNewCustomer = async () => {

        if (!customerName || !customerAddress) {

            alert("Please provide both customer name and address.");

            return;

        }

        try {

            const accounts = await window.ethereum.request({ method: 'eth_accounts' });

            await kycContract.methods.addNewCustomer(customerName, customerAddress).send({ from: accounts[0] });

            alert("Customer Added");

            setCustomerName('');

            setCustomerAddress('');

        } catch (error) {

            console.error("Error adding customer: ", error);

            alert("Error adding customer.");

        }

    };

 

    // Function to verify a customer

    const verifyCustomer = async () => {

        if (!verifyAddress) {

            alert("Please provide a customer address to verify.");

            return;

        }

        try {

            const accounts = await window.ethereum.request({ method: 'eth_accounts' });

            await kycContract.methods.verifyCustomer(verifyAddress).send({ from: accounts[0] });

            alert("Customer Verified");

            setVerifyAddress('');

        } catch (error) {

            console.error("Error verifying customer: ", error);

            alert("Error verifying customer.");

        }

    };

 

    return (

        <div style={{ padding: '20px', fontFamily: 'Arial, sans-serif', backgroundColor: '#f0f0f0' }}>

            <h1>KYC DApp</h1>

            {account ? <p>Connected account: {account}</p> : <p>Please connect your MetaMask account.</p>}

 

            <div>

                <h2>Add New Bank</h2>

                <input

                    type="text"

                    value={bankName}

                    onChange={(e) => setBankName(e.target.value)}

                    placeholder="Bank Name"

                />

                <input

                    type="text"

                    value={bankAddress}

                    onChange={(e) => setBankAddress(e.target.value)}

                    placeholder="Bank Address"

                />

                <button onClick={addNewBank}>Add Bank</button>

            </div>

 

            <div>

                <h2>Add New Customer</h2>

                <input

                    type="text"

                    value={customerName}

                    onChange={(e) => setCustomerName(e.target.value)}

                    placeholder="Customer Name"

                />

                <input

                    type="text"

                    value={customerAddress}

                    onChange={(e) => setCustomerAddress(e.target.value)}

                    placeholder="Customer Address"

                />

                <button onClick={addNewCustomer}>Add Customer</button>

            </div>

 

            <div>

                <h2>Verify Customer</h2>

                <input

                    type="text"

                    value={verifyAddress}

                    onChange={(e) => setVerifyAddress(e.target.value)}

                    placeholder="Customer Address"

                />

                <button onClick={verifyCustomer}>Verify</button>

            </div>

 

            <h2>List of Banks:</h2>

            <ul>

                {banks.map((bank, index) => (

                    <li key={index}>{bank.name} - {bank.address}</li>

                ))}

            </ul>

        </div>

    );

};

 

// Exporting the App component as default

export default App;

 

Step 4: Running the DApp Locally

1       Run the Local Server:

npm start

2.     Interact with the Contract: Open your browser and navigate to http://localhost:3000. You should see the webpage where you can add banks, add customers, and verify customers using the buttons provided. All interactions will happen on your local Ganache blockchain.

Step 5: Testing the DApp

1.     Open MetaMask: Ensure you have MetaMask set up with the network pointing to localhost:7545 (where Ganache is running).

2.     Add a Bank or Customer: Use the frontend to add banks or customers. Interactions will be signed using your MetaMask account and submitted to the local blockchain.

3.     Verify Data: Use console.log to check the data being returned by the contract or inspect the events emitted on the blockchain.

 

 

Appendix 1 – Contract Explanation

This KYC (Know Your Customer) smart contract is designed to manage KYC processes on the Ethereum blockchain. Here's a detailed breakdown of the code:

Contract Overview:

  • Admin Role: The contract is managed by an admin (kycadmin), who has special privileges, including adding or blocking banks from participating in KYC processes.
  • Bank Management: Admins can add banks to the system. Each bank has specific permissions to add customers and submit KYC requests.
  • Customer Management: Banks can add customers and submit KYC requests on their behalf.

Key Components:

1.     Structs:

    • Bank: Represents a bank with fields for:
      • name: The name of the bank.
      • kycCount: The number of KYC requests processed by the bank.
      • bankAddress: The Ethereum address of the bank.
      • canAddCustomers: A boolean indicating if the bank can add new customers.
      • canPerformKYC: A boolean indicating if the bank can perform KYC processes.
    • Customer: Represents a customer with fields for:
      • name: The name of the customer.
      • data: The hashed data associated with the customer.
      • validatedBy: The Ethereum address of the bank that validated the customer.
      • isVerified: A boolean indicating the KYC status of the customer.

2.     Mappings:

    • banks: Maps an Ethereum address to a Bank struct, allowing easy retrieval of bank information.
    • customersInfo: Maps a customer's username to a Customer struct, facilitating access to customer data.

Functions:

1.     Admin Functions:

    • addNewBank: Allows the admin to add a new bank to the system.
    • blockBankFromKYC: Revokes a bank's permission to perform KYC processes.
    • allowBankFromKYC: Restores a bank's permission to perform KYC.
    • blockBankFromAddingNewCustomers: Prevents a bank from adding new customers.
    • allowBankFromAddingNewCustomers: Grants a bank permission to add new customers.

2.     Bank Functions:

    • addNewCustomerToBank: Allows a bank to add a new customer if it has permission.
    • viewCustomerData: Enables a bank to view the details of its customers.
    • addNewCustomerRequestForKYC: Submits a KYC request for a customer. If successful, it increments the bank's KYC count.

3.     Utility Functions:

    • getCustomerKycStatus: Returns the KYC status of a specified customer.
    • areBothStringsSame: A private function that checks if two strings are identical, used internally for string comparisons.

Key Points:

  • Security: The admin maintains control over managing banks, ensuring that only authorized entities can participate in the KYC process.
  • Permissions: Banks have distinct permissions for adding customers and performing KYC, allowing for granular control over their actions and responsibilities.
  • Customer Validation: Each customer is linked to a validating bank, and any bank can check a customer's KYC status, ensuring transparency in the validation process.

Example Usage Scenarios:

  1. Admin adds a new bank:
addNewBank("BankName", "0xBankAddress");
  1. Bank adds a new customer:
addNewCustomerToBank("CustomerName", "CustomerDataHash");
  1. Bank submits a KYC request:
addNewCustomerRequestForKYC("CustomerName");

This contract can be utilized in a decentralized environment where multiple banks collaborate to efficiently manage KYC processes, with the admin maintaining control over permissions.

 

 

 

Term Proejct 2 - Simple Fraternity Dapp (Option 2)

 

Fraternity DApp Project Folder Structure

 

fraternity-dapp/             # Root project folder

├── contracts/               # Folder where Solidity contracts are stored

   └── FraternityRegistration.sol  # Your smart contract code

├── migrations/              # Migration files for deploying contracts

   └── 2_deploy_contracts.js  # Deployment script for Truffle

├── build/                   # Truffle's build folder (generated after compilation)

   └── contracts/           # Contains the compiled contracts and ABI

         └── FraternityRegistration.json  # ABI JSON file of your contract

├── frontend/                # Folder for your front-end code (web3 and lite-server)

   ├── index.html           # HTML file for the front-end

   └── app.js               # JavaScript to interact with the smart contract

   ├── package.json             # Node.js package manager file for managing dependencies

├── truffle-config.js        # Truffle configuration file (to configure network, compiler, etc.)

└── README.md                # Optional: Instructions or project description

1.     Create a new project directory:

mkdir fraternity-dapp
cd fraternity-dapp

2.     Initialize Truffle: Inside the fraternity-dapp directory, initialize a Truffle project:

truffle init

This will create a project structure with the following folders:

    • contracts/: Where you will put your smart contract.
    • migrations/: For deployment scripts.
    • test/: For testing your smart contracts.

 

3. Write the Smart Contract

 

Create a new file in the contracts/ folder called FraternityRegistration.sol and write the following code:

 

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

 

contract FraternityRegistration {

    address public owner;

    uint256 public totalMembers;

 

    struct Member {

        string name;

        bool isRegistered;

    }

 

    mapping(address => Member) public members;

 

    event MemberRegistered(address indexed memberAddress, string name);

    event MemberRemoved(address indexed memberAddress);

 

    modifier onlyOwner() {

        require(msg.sender == owner, "Only the contract owner can execute this action");

        _;

    }

 

    constructor() {

        owner = msg.sender;

    }

 

    function registerMember(address _memberAddress, string memory _name) public onlyOwner {

        require(!members[_memberAddress].isRegistered, "Member is already registered");

        members[_memberAddress] = Member({name: _name, isRegistered: true});

        totalMembers++;

        emit MemberRegistered(_memberAddress, _name);

    }

 

    function isMember(address _memberAddress) public view returns (bool) {

        return members[_memberAddress].isRegistered;

    }

 

    function getMemberDetails(address _memberAddress) public view returns (string memory) {

        require(members[_memberAddress].isRegistered, "Member is not registered");

        return members[_memberAddress].name;

    }

 

    function removeMember(address _memberAddress) public onlyOwner {

        require(members[_memberAddress].isRegistered, "Member is not registered");

        delete members[_memberAddress];

        totalMembers--;

        emit MemberRemoved(_memberAddress);

    }

 

    function transferOwnership(address _newOwner) public onlyOwner {

        require(_newOwner != address(0), "Invalid new owner address");

        owner = _newOwner;

    }

}

4. Compile the Contract

Run the following command to compile the smart contract:

truffle compile

This will compile the contract and create JSON files in the build/contracts/ directory.

5     Deploy the Deployment Script

Create a new migration file in the migrations/ folder called 2_deploy_contracts.js and add the following code:

const FraternityRegistration = artifacts.require("FraternityRegistration");
 
module.exports = function (deployer) {
  deployer.deploy(FraternityRegistration);
};

Run Ganache

  1. Open Ganache and start a local blockchain on port 7545 (default).

Deploy the Contract

1.     Deploy the contract to the local blockchain:

truffle migrate --network development

If everything works correctly, you will see the contract deployed on Ganache, and the contract address will be displayed.

 

6. Front-End Setup

Initialize a Front-End Project

6.1  Inside your project folder (fraternity-dapp), create a frontend/ directory:

mkdir frontend
cd frontend

6.2  Initialize a Node.js project:

npm init -y

6.3  Install necessary dependencies:

npm install web3 lite-server --save-dev

6.4  Create your front-end files: Create the following files:

·   index.html

·   app.js

 

index.html

Create a basic HTML page in the frontend/index.html:

 

 <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Jacksonville University Baseball and Cross Team Decentralized Registration Form</title>

</head>

<body style="font-family: Arial, sans-serif; background-color: #f4f4f4; color: #333;">

    <h1 style="text-align: center; color: navy;">Jacksonville University Baseball and Cross Team Decentralized Registration Form</h1>

    <div style="width: 60%; margin: auto; padding: 20px; background-color: white; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">

        <h2 style="color: darkblue;">Register a New Member</h2>

        <label>Member Address: </label>

        <input type="text" id="memberAddress" placeholder="Enter member's Ethereum address" style="width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 5px;">

       

        <label>Member Name: </label>

        <input type="text" id="memberName" placeholder="Enter member's name" style="width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 5px;">

       

        <button onclick="registerMember()" style="width: 100%; padding: 10px; background-color: darkblue; color: white; border: none; border-radius: 5px; cursor: pointer;">Register Member</button>

 

        <h2 style="color: darkblue; margin-top: 20px;">Check Membership</h2>

        <button onclick="checkMembership()" style="width: 100%; padding: 10px; background-color: navy; color: white; border: none; border-radius: 5px; cursor: pointer;">Check Membership</button>

 

        <div id="result" style="margin-top: 20px; color: darkred;"></div>

        <div id="owner" style="margin-top: 20px; color: green;"></div>

    </div>

 

    <script src="https://cdn.jsdelivr.net/npm/web3/dist/web3.min.js"></script>

    <script src="app.js"></script>

</body>

</html>

 

 

app.js

Create a JavaScript file (frontend/app.js) for interacting with the smart contract:

 

// Check if Web3 is injected by the browser (MetaMask)

if (typeof window.ethereum !== 'undefined') {

    console.log('MetaMask is installed!');

    window.web3 = new Web3(window.ethereum);

    ethereum.request({ method: 'eth_requestAccounts' }).then(() => {

        // After MetaMask connects, initialize the contract

        initializeContract();

    });

} else {

    console.log('Please install MetaMask!');

}

 

// ABI from your uploaded JSON file under build folder

const contractABI = [

    {

        "inputs": [],

        "stateMutability": "nonpayable",

        "type": "constructor"

    },

    {

        "anonymous": false,

        "inputs": [

            {

                "indexed": true,

                "internalType": "address",

                "name": "memberAddress",

                "type": "address"

            },

            {

                "indexed": false,

                "internalType": "string",

                "name": "name",

                "type": "string"

            }

        ],

        "name": "MemberRegistered",

        "type": "event"

    },

    {

        "anonymous": false,

        "inputs": [

            {

                "indexed": true,

                "internalType": "address",

                "name": "memberAddress",

                "type": "address"

            }

        ],

        "name": "MemberRemoved",

        "type": "event"

    },

    {

        "inputs": [

            {

                "internalType": "address",

                "name": "_memberAddress",

                "type": "address"

            }

        ],

        "name": "members",

        "outputs": [

            {

                "internalType": "string",

                "name": "name",

                "type": "string"

            },

            {

                "internalType": "bool",

                "name": "isRegistered",

                "type": "bool"

            }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

    },

    {

        "inputs": [],

        "name": "owner",

        "outputs": [

            {

                "internalType": "address",

                "name": "",

                "type": "address"

            }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

    },

    {

        "inputs": [],

        "name": "totalMembers",

        "outputs": [

            {

                "internalType": "uint256",

                "name": "",

                "type": "uint256"

            }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

    },

    {

        "inputs": [

            {

                "internalType": "address",

                "name": "_memberAddress",

                "type": "address"

            },

            {

                "internalType": "string",

                "name": "_name",

                "type": "string"

            }

        ],

        "name": "registerMember",

        "outputs": [],

        "stateMutability": "nonpayable",

        "type": "function"

    },

    {

        "inputs": [

            {

                "internalType": "address",

                "name": "_newOwner",

                "type": "address"

            }

        ],

        "name": "transferOwnership",

        "outputs": [],

        "stateMutability": "nonpayable",

        "type": "function"

    }

];

 

// Replace this with your deployed contract address

const contractAddress = '0xff25815599aB4cb56B83CB2B9d0D26626f8b7E05';

 

// Initialize the contract after MetaMask is connected

function initializeContract() {

    try {

        const contract = new web3.eth.Contract(contractABI, contractAddress);

        console.log('Contract initialized successfully.');

 

        // Set the contract globally to be used later

        window.contract = contract;

 

        // Log the contract owner

        checkContractOwner();

    } catch (error) {

        console.error('Error initializing contract:', error);

    }

}

 

// Function to register a member with gas estimation

function registerMember() {

    const memberAddress = document.getElementById('memberAddress').value;

    const memberName = document.getElementById('memberName').value;

 

    // Disable the button to prevent multiple clicks

    document.querySelector('button').disabled = true;

 

    if (!web3.utils.isAddress(memberAddress)) {

        document.getElementById('result').innerHTML = 'Invalid member address.';

        document.querySelector('button').disabled = false; // Re-enable the button

        return;

    }

 

    web3.eth.getAccounts().then(accounts => {

        const account = accounts[0];

 

        // Estimate gas for the transaction

        window.contract.methods.registerMember(memberAddress, memberName)

            .estimateGas({ from: account })

            .then(gasAmount => {

                console.log('Estimated Gas:', gasAmount);

 

                // Send the transaction with estimated gas

                return window.contract.methods.registerMember(memberAddress, memberName)

                    .send({ from: account, gas: gasAmount });

            })

            .then(() => {

                document.getElementById('result').innerHTML = 'Member registered successfully!';

                document.querySelector('button').disabled = false; // Re-enable the button

            })

            .catch(err => {

                console.error('Error registering member:', err);

                document.getElementById('result').innerHTML = 'Error registering member: ' + err.message;

                document.querySelector('button').disabled = false; // Re-enable the button

            });

    });

}

 

// Function to check if someone is a member

function checkMembership() {

    const memberAddress = document.getElementById('memberAddress').value;

 

    if (!web3.utils.isAddress(memberAddress)) {

        document.getElementById('result').innerHTML = 'Invalid member address.';

        return;

    }

 

    window.contract.methods.isMember(memberAddress).call()

        .then(isMember => {

            const resultText = isMember ? 'This address is a member.' : 'This address is not a member.';

            document.getElementById('result').innerHTML = resultText;

        })

        .catch(err => {

            console.error('Error checking membership:', err);

            document.getElementById('result').innerHTML = 'Error checking membership: ' + err.message;

        });

}

 

// Function to check the contract owner

function checkContractOwner() {

    window.contract.methods.owner().call()

    .then(ownerAddress => {

        console.log('Contract Owner:', ownerAddress);

        document.getElementById('owner').innerHTML = `Contract Owner: ${ownerAddress}`;

    })

    .catch(err => {

        console.error('Error fetching owner address:', err);

    });

}

 

7. Run the Front-End

Start Lite Server

7.1  Add the following script into frontend/package.json to run the front-end:

"scripts": {
  "start": "lite-server"
}
 
Or just copy the following into frontend/package.json
{
  "name": "fraternity-dapp",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "lite-server",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "web3": "^4.13.0"
  },
  "devDependencies": {
    "lite-server": "^2.6.1"
  }
}

7.2  Run the front-end:

npm start

8       Access the DApp at http://localhost:3000 in your browser.

 

9. Testing the DApp

  • Open the DApp in the browser and connect MetaMask to the local blockchain (Ganache).
  • Register a member by filling in the address and name, then click "Register Member."
  • Check if the member is registered using the "Check Membership" button.

 

10. Troubleshooting Common Issues

  • Pending transactions: Check Ganache for pending transactions, and reset the network in MetaMask if necessary.
  • Contract not deploying: Ensure that Ganache is running and the contract migration script is properly set up.
  • Gas issues: Increase the gas limit

image009.jpg

 

 

Term Project  3 (option 3) - An Escrow Smart Contract 

Refer to  https://github.com/arshdeepbahga/blockchain-applications-book/tree/master/Chapter-1

 

Part 1: Setting Up the Development Environment

Step 1: Install Node.js

1.               Download and Install Node.js:

o        Go to the Node.js website.

o        Download the LTS (Long Term Support) version suitable for your operating system (Windows, macOS, or Linux).

o        Follow the installation instructions provided on the website.

2.               Verify the Installation:

o        Open Command Prompt (Windows) or Terminal (macOS/Linux).

o        Type the following commands to check if Node.js and npm (Node Package Manager) are installed correctly:

node -v

npm -v

o        You should see the version numbers of Node.js and npm displayed.

Step 2: Install Truffle

1.               Install Truffle Globally:

o        In your Command Prompt or Terminal, type the following command to install Truffle:

npm install -g truffle

o        To verify that Truffle is installed, type:

truffle version

o        This will show you the version of Truffle installed on your system.

Step 3: Install Ganache

1.               Download and Install Ganache:

o        Go to the Ganache website.

o        Download the version for your operating system.

o        Follow the instructions to install Ganache.

2.               Start Ganache:

o        Open Ganache after installation.

o        Click on "Quickstart Ethereum" to set up a new local blockchain network. This network will simulate how a real blockchain works.

Step 4: Set Up a New Truffle Project

1.               Create a Project Directory:

o        In Command Prompt or Terminal, navigate to the location where you want to create your project and type:

mkdir Escrow

cd Escrow

2.               Initialize a Truffle Project:

o        In the project directory, type:

truffle init

o        This will create the basic structure of your Truffle project.

3.               Configure Truffle to Connect to Ganache:

o        Open the truffle-config.js file in the project directory.

o        Update the configuration to look like this:

module.exports = {

  networks: {

    development: {

      host: "127.0.0.1", // Localhost

      port: 7545,        // Ganache port

network_id: "*",   // Match any network id

    },

  },

  compilers: {

solc: {

      version: "0.8.0", // Specify the Solidity compiler version

    },

  },

};

Part 2: Creating the Escrow Smart Contract

Step 1: Create the Smart Contract

1.               Create a New Contract File:

o        In the contracts directory, create a new file named Escrow.sol.

2.               Write the Smart Contract:

o        Open Escrow.sol and add the following code:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

 

contract Escrow {

    address public buyer;

    address public seller;

uint public deposit;

uint public timeToExpiry;

uint public startTime;

 

    // Buyer sets up the escrow contract and pays the deposit

constructor(address _seller, uint _timeToExpiry) payable {

require(msg.value> 0, "Deposit must be greater than zero");

        buyer = msg.sender;

        seller = _seller;

        deposit = msg.value;

timeToExpiry = _timeToExpiry;

startTime = block.timestamp;

    }

 

    // Buyer releases deposit to seller

    function releaseToSeller() public {

require(msg.sender == buyer, "Only buyer can release funds");

        require(!isExpired(), "Escrow is expired");

        payable(seller).transfer(deposit);

        deposit = 0; // Set deposit to zero to prevent re-entry

    }

 

    // Buyer can withdraw deposit if escrow is expired

    function withdraw() public {

        require(isExpired(), "Escrow is not expired yet");

require(msg.sender == buyer, "Only buyer can withdraw funds");

uint amount = deposit;

        deposit = 0; // Set deposit to zero to prevent re-entry

        payable(buyer).transfer(amount);

    }

 

    // Seller can cancel escrow and return all funds to buyer

    function cancel() public {

require(msg.sender == seller, "Only seller can cancel the escrow");

uint amount = deposit;

        deposit = 0; // Set deposit to zero to prevent re-entry

        payable(buyer).transfer(amount);

    }

 

    // Check if the escrow is expired

    function isExpired() public view returns (bool) {

        return block.timestamp>startTime + timeToExpiry;

    }

}

Step 2: Write a Migration Script

1.               Create a New Migration File:

o        In the migrations directory, create a new file named 2_deploy_contracts.js.

2.               Write the Deployment Script:

o        Add the following code to 2_deploy_contracts.js:

const Escrow = artifacts.require("Escrow");

 

module.exports = function (deployer, network, accounts) {

  const sellerAddress = accounts[1]; // Example seller address

  const timeToExpiry = 3600; // 1 hour in seconds

deployer.deploy(Escrow, sellerAddress, timeToExpiry, {

    value: web3.utils.toWei("1", "ether"), // 1 ETH deposit

    from: accounts[0], // Example buyer address

  });

};

3.               Deploy the Contract:

o        Save this script as 2_deploy_contracts.js in the migrations folder.

o        Run the migration using the following command:

truffle migrate --reset

o        This will deploy the Escrow contract on your local blockchain (Ganache).

Part 3: Interacting with the Escrow Contract

Step 1: Start the Truffle Console

·                  In your project directory, type:

truffle console

·                  This command opens the Truffle console connected to your local blockchain.

Step 2: Interact with the Contract

1.               Get the Deployed Contract Instance:

o        In the Truffle console, type:

const escrowInstance = await Escrow.deployed();

2.               Check the Contract's Initial State:

o        You can check the initial values of the contract's public variables:

const buyer = await escrowInstance.buyer();

const seller = await escrowInstance.seller();

const deposit = await escrowInstance.deposit();

const timeToExpiry = await escrowInstance.timeToExpiry();

const startTime = await escrowInstance.startTime();

 

console.log("Buyer:", buyer);

console.log("Seller:", seller);

console.log("Deposit (in wei):", deposit.toString());

console.log("Time to Expiry (seconds):", timeToExpiry.toString());

console.log("Start Time (timestamp):", startTime.toString());

3.               Interact with the Contract's Functions:

o        Release Funds to Seller:

await escrowInstance.releaseToSeller({ from: buyer });

§     This releases the deposited funds to the seller.

o        Withdraw Funds (if expired):

await escrowInstance.withdraw({ from: buyer });

§     This withdraws the funds if the contract has expired.

o        Cancel Escrow:

await escrowInstance.cancel({ from: seller });

§     This cancels the escrow and returns the deposit to the buyer.

4.               Check if the Contract is Expired:

const expired = await escrowInstance.isExpired();

console.log("Is the escrow expired?", expired);

Step 3: Monitoring Transactions in Ganache

·                  While interacting with the contract, you can monitor the transactions in the Ganache UI. This will show details like transaction hashes, gas used, and affected accounts.

Step 4: Testing with Different Accounts

·                  If you want to simulate different roles (buyer and seller), you can use different accounts provided by Ganache:

const accounts = await web3.eth.getAccounts();

 

// As the buyer (account[0])

await escrowInstance.releaseToSeller({ from: accounts[0] });

 

// As the seller (account[1])

await escrowInstance.cancel({ from: accounts[1] });

 

Summary

·                  Step 1: Set up your development environment with Node.js, Truffle, and Ganache.

·                  Step 2: Create and deploy the Escrow smart contract.

Step 3: Interact with the contract using the Truffle console and monitor transactions in Ganache.

Final Exam – 100 Multiple Choice Questions
(September 26, 2024, on Blackboard due to weather)

 

Final Exam Answer Key (100 multiple-choice questions, 9/28/2024)

 

~Study Guide~

 

1. Blockchain Fundamentals

  • Definition of Blockchain: Understand the concept of a distributed ledger that is immutable and decentralized.
  • Data Structure: Know what a blockchain consists of - blocks linked by hashes.
  • Consensus Mechanisms: Proof of Work (PoW), Proof of Stake (PoS), and their differences. Know how Bitcoin and Ethereum achieve consensus.
  • Public vs Private Blockchains: Understand the difference between open blockchains (e.g., Bitcoin) and permissioned blockchains.
  • Double Spending: What it is and how blockchain prevents it.

2. Cryptocurrency Basics

  • Bitcoin: Purpose as a decentralized payment system and its finite supply of 21 million coins.
  • Ethereum: Understand Ethereum's purpose as a platform for smart contracts and decentralized applications (dApps), as well as its lack of a maximum supply.
  • Mining: Know what mining is and its role in validating transactions and securing the blockchain.
  • Nonce and Hashing: Understand the role of the nonce and SHA-256 in Bitcoin mining.

3. Smart Contracts

  • Definition: Self-executing contracts with terms directly written into code.
  • Ethereum and Solidity: Know that smart contracts are primarily built on Ethereum using Solidity.
  • dApps: What decentralized applications are and how they operate without a central authority.

4. Ethereum Specifics

  • Gas and Gas Fees: Gas is the unit of computation used in Ethereum transactions. Know the role of gas in executing smart contracts and transactions, and understand gas limits and gas prices.
  • Ethereum Virtual Machine (EVM): Understand that the EVM is responsible for executing smart contracts on Ethereum.
  • Tools: Familiarize with key tools like MetaMask (used to interact with Ethereum), Truffle (used for writing and testing smart contracts), and Ganache (a local Ethereum blockchain for testing).

5. Advanced Concepts

  • Forks: Differences between soft forks and hard forks, and their implications for the blockchain.
  • Immutability: Understand why blockchain transactions cannot be changed once recorded.
  • 51% Attack: Know what it means and its implications for blockchain security.

Refer to Simplilearn Video from 1:02:00 1:11:26 (Soft fork,  hard fork, 51% Attack, Byzantine Fault Tolerence)

  • DAO: What a Decentralized Autonomous Organization (DAO) is, and how it functions using smart contracts.

6. Ethereum Tokens

  • ERC-20 Tokens: Understand the ERC-20 standard for creating fungible tokens on the Ethereum network.
  • Fungible vs Non-Fungible Tokens (NFTs): Differences between assets like Ether (fungible) and NFTs (non-fungible), and their use cases.

7. Wallets and Keys

  • Private vs Public Keys: Know the difference between these cryptographic keyshow public keys are used to receive cryptocurrency and private keys are used to sign transactions.
  • Hot vs Cold Wallets: Differences in security between hot wallets (connected to the internet) and cold wallets (offline storage).
  • MetaMask: Its function as a browser extension wallet used to interact with dApps and manage Ethereum private keys.

8. Consensus Mechanisms

  • Proof of Work (PoW): How it works, with Bitcoin as an example.
  • Proof of Stake (PoS): Post-Ethereum Merge, understand PoS and its validator system based on staked cryptocurrency.

9. Initial Coin Offerings (ICO)

  • ICOs: Understand their role as a fundraising method for blockchain projects and the difference between hard and soft caps in ICOs.

10. Other Important Blockchain Concepts

  • Merkle Trees: Their role in ensuring the integrity of transactions.
  • Sharding: Understand sharding as a method for improving blockchain scalability.
  • Trustless Systems: What it means for a system to be trustless, where participants don't need to trust each other.

Key Terms to Know:

  • Blockchain
  • Consensus Mechanism
  • Decentralization
  • dApp
  • Gas and Gas Price
  • Hashing (SHA-256)
  • ICO
  • Immutability
  • Merkle Tree
  • Mining
  • Nonce
  • Private/Public Key
  • Proof of Stake / Proof of Work

·        Smart Contract

image007.jpg