Ethereum DApp Tutorial

Ethereum Kittychain Shop

Build a decentralized pet adoption application using Ethereum, Solidity, Truffle, Ganache, Web3.js and MetaMask.

7 Development steps
5 Core tools
1 Smart contract
DApp Pet adoption project

Project Overview

What is Kittychain Shop?

Kittychain Shop is an adoption tracking system for a pet shop built on the Ethereum blockchain. It demonstrates how a simple business process can be represented using a smart contract, a browser interface and a wallet such as MetaMask.

Decentralized records

Pet adoption records are stored through smart contract interaction.

Smart contract logic

The adoption process is controlled by Solidity code.

Web3 interaction

The browser interface communicates with Ethereum through Web3.js.

MetaMask support

Users confirm transactions with a wallet before changes are written.

Technologies Used

Ganache

Personal blockchain for local development.

Truffle

Development framework for compiling, migrating and testing contracts.

Solidity

Smart contract programming language for Ethereum.

Web3.js

JavaScript library for blockchain interaction.

7-Step Development Journey

1

Development Environment Setup

Install Node.js, Git, Truffle and Ganache.

2

Truffle Project Creation

Initialize the project using the Truffle Pet Shop box.

3

Smart Contract Development

Write the Adoption.sol contract.

4

Compilation and Migration

Compile and deploy the contract to the local blockchain.

5

Smart Contract Testing

Write and execute test cases.

6

User Interface Creation

Build the web interface and connect it to Web3.

7

Browser Integration

Connect the application with MetaMask.

Smart Contract Architecture

Adoption.sol Contract

contracts/Adoption.sol
pragma solidity ^0.4.24;

contract Adoption {
    address[16] public adopters;

    function adopt(uint petId) public returns (uint) {
        require(petId >= 0 && petId <= 15);
        adopters[petId] = msg.sender;
        return petId;
    }

    function getAdopters() public view returns (address[16]) {
        return adopters;
    }
}

Key Contract Features

  • adopters array: Stores 16 Ethereum addresses.
  • adopt() function: Allows users to adopt pets.
  • getAdopters() function: Returns all adoption records.
  • require() validation: Ensures the pet ID is within the valid range.

Development Environment Setup

Required Tools

  • Node.js: JavaScript runtime environment.
  • Git: Version control system.
  • Truffle: Ethereum development framework.
  • Ganache: Personal blockchain simulator.

Project Initialization

Terminal commands
mkdir pet-shop-tutorial
cd pet-shop-tutorial
truffle unbox pet-shop

Project Structure

  • contracts/: Solidity smart contracts.
  • migrations/: Deployment scripts.
  • test/: Test files.
  • truffle.js: Configuration file.

Contract Compilation and Migration

Compilation Process

Compile the smart contract
truffle compile

Compilation converts Solidity code into bytecode for the Ethereum Virtual Machine.

Migration Setup

Create 2_deploy_contracts.js inside the migrations/ directory.

Ganache Configuration

  • Launch the Ganache desktop application.
  • Ganache creates a local blockchain on port 7545.
  • It provides test accounts with development ETH.

Deploy to Blockchain

Deploy contract
truffle migrate

Success Indicators

  • The contract is deployed with a blockchain address.
  • The block number increases in Ganache.
  • The ETH balance decreases because gas is used for deployment.

Smart Contract Testing

Test Structure

Create TestAdoption.sol in the test/ directory.

Required Imports

  • Assert.sol: Testing assertions.
  • DeployedAddresses.sol: Contract deployment addresses.
  • Adoption.sol: The contract being tested.

Test Execution

Run tests
truffle test

Test Benefits

  • Validates contract functionality.
  • Ensures the adoption logic works correctly.
  • Verifies data retrieval functions.
  • Provides confidence before deployment.

Testing Best Practices

  • Test all public functions.
  • Validate edge cases.
  • Check require() conditions.

User Interface Development

Web3 Integration

The app.js file handles blockchain interaction.

Key Components

  • Web3 initialization: Connects to the blockchain.
  • Contract instantiation: Creates a usable contract instance.
  • UI updates: Synchronizes the interface with blockchain state.
  • Transaction handling: Processes adoption requests.

Web3 Provider Detection

Detect MetaMask or local provider
if (typeof web3 !== 'undefined') {
    App.web3Provider = web3.currentProvider;
} else {
    App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}

Contract Interaction

  • Read operations: Use call() for free data retrieval.
  • Write operations: Send transactions that consume gas.
  • Event handling: Update the UI when blockchain state changes.

MetaMask Integration

Wallet Setup Process

  1. Install the MetaMask browser extension.
  2. Import the wallet using the Ganache mnemonic phrase.
  3. Configure the local blockchain network.
  4. Use test accounts for development transactions.

Network Configuration

Local network settings
Custom RPC URL: http://127.0.0.1:7545
Network Name: Private Network

Transaction Flow

  • The user clicks the Adopt button.
  • MetaMask displays a transaction confirmation popup.
  • The user confirms the transaction.
  • The smart contract executes.
  • The user interface updates the adoption status.
Important: Each blockchain transaction consumes ETH as gas fees. Use test ETH on Ganache during development.

Application Architecture

DApp Architecture Flow

User Interface in Browser
MetaMask Wallet
Web3.js Library
Ganache Blockchain
Smart Contract: Adoption.sol

Component Interactions

  • Frontend: HTML, CSS and JavaScript user interface.
  • Web3: Blockchain communication layer.
  • MetaMask: User wallet and transaction signing.
  • Ganache: Local development blockchain.
  • Smart Contract: Business logic and data storage.

Common Issues and Solutions

Issue 1: Transaction Failed in MetaMask

Problem: After restarting Windows, transactions fail.

Solution: Delete JSON files in /build/contracts/, recompile, migrate again and reset MetaMask accounts.

Issue 2: Accounts Show 0 ETH

Problem: MetaMask accounts have no balance.

Solution: Start Ganache, copy the mnemonic from Ganache and import the existing wallet in MetaMask.

Issue 3: Persistent Transaction Failures

Problem: Transactions continue to fail.

Solution: Reset the MetaMask account completely, then reconnect to the local blockchain.

Project Conclusion

What You Have Built

Functional DApp

A pet adoption tracking system with blockchain interaction.

Smart Contract

Immutable adoption records managed by Solidity code.

Web Interface

A browser-based interface for user interaction.

Wallet Integration

MetaMask transaction confirmation and account connection.

Key Learning Outcomes

  • Ethereum blockchain development.
  • Solidity smart contract programming.
  • Truffle framework usage.
  • Web3.js integration.
  • MetaMask wallet connection.
  • DApp testing and deployment.

Next Steps

  • Deploy to an Ethereum testnet.
  • Add more complex business logic.
  • Implement IPFS for pet images.
  • Add payment functionality.
  • Enhance UI and UX design.
Congratulations! You have successfully built a complete Ethereum DApp.