top of page

How to Create Your First dApp on Ethereum

What is A decentralized application (dApp)

A decentralized application (dApp) is an application that runs on a decentralized network like Ethereum, which means it operates without a central authority. Unlike traditional apps, dApps leverage smart contracts for backend logic, making them tamper-proof and transparent.


In this guide, we’ll build a simple dApp that interacts with a smart contract on Ethereum. We’ll use Solidity for the smart contract, Web3.js for interacting with Ethereum, and HTML/CSS/JavaScript for the front end.


Step 1: Setting Up Your Development Environment

To start, we’ll need a few tools and libraries:

  1. Node.js: Install Node.js from nodejs.org if you don’t have it already. This will allow you to use npm (Node Package Manager) to install Web3.js and other dependencies.

  2. Metamask: Install the Metamask extension in your browser. This will serve as your wallet and gateway to the Ethereum blockchain.

  3. Remix IDE: We’ll use Remix to write and deploy the smart contract (just like the previous tutorial).


Step 2: Writing and Deploying the Smart Contract

We’ll use a basic smart contract to store and retrieve data (similar to the previous example). This smart contract will be the backend logic of our dApp.


2.1 Writing the Smart Contract

Go to Remix IDE and create a new file, SimpleStorage.sol, with the following code: (this is a sample code, your code may vary depending on your project)


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

contract SimpleStorage {
    uint256 storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }

 }

2.2 Deploying the Smart Contract

  1. Compile the contract using the Solidity Compiler in Remix.

  2. Deploy it on the Ropsten Test Network (via Metamask) as described in the first tutorial.

  3. Once deployed, note the contract address — we’ll need it to interact with the contract from our dApp.


Step 3: Setting Up the Frontend

Now, we’ll build the front end of our dApp using HTML, CSS, and JavaScript. This will include a simple form where users can input a value and store it on the blockchain.


3.1 Install Web3.js

In your project folder, open a terminal and run the following command to install Web3.js, a JavaScript library to interact with the Ethereum blockchain:


npm install web3

3.2 Create the HTML Page

Create a file named index.html and add the following code:(this is a sample code, your code may vary depending on your project)


html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple dApp</title>
    <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.36/dist/web3.min.js"></script>
</head>
<body>
    <h1>Simple Storage dApp</h1>
    <input id="inputValue" type="number" placeholder="Enter a value" />
    <button onclick="storeData()">Store Data</button>
    <br><br>
    <button onclick="retrieveData()">Get Stored Data</button>
    <p id="storedData"></p>

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

Explanation of the HTML:

  • Input field: This allows users to enter a number to store on the blockchain.

  • Buttons: One button will store data (storeData), and the other will retrieve it (retrieveData).

  • Web3.js: The library that will let us interact with the Ethereum network from the front end.


3.3 Create the JavaScript File

Create a file named app.js and add the following code: (this is a sample code, your code may vary depending on your project)

javascript

// Set up Web3 provider (Metamask)
let web3 = new Web3(Web3.givenProvider);

// Contract address and ABI (from Remix)
const contractAddress = "YOUR_DEPLOYED_CONTRACT_ADDRESS";
const contractABI = [
    {
        "constant": false,
        "inputs": [
            {
                "name": "x",
                "type": "uint256"
            }
        ],
        "name": "set",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "get",
        "outputs": [
            {
                "name": "",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    }
];

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

// Function to store data
async function storeData() {
    const accounts = await web3.eth.requestAccounts();
    const value = document.getElementById("inputValue").value;
    contract.methods.set(value).send({ from: accounts[0] });
}

// Function to retrieve data
async function retrieveData() {
    const result = await contract.methods.get().call();
    document.getElementById("storedData").innerText = result;
}

Explanation of the JavaScript:

  • Web3 setup: Connects your dApp to the Ethereum network via Metamask.

  • Contract interaction: Uses the set and get functions from your smart contract to store and retrieve data.

  • storeData(): Sends the value input by the user to the smart contract’s set function.

  • retrieveData(): Calls the smart contract’s get function to retrieve and display the stored data.


Step 4: Running Your dApp

4.1 Connect to Metamask

  • Open your index.html file in a browser.

  • Make sure your Metamask is connected to the Ropsten Test Network.

  • When you click the Store Data button, Metamask will prompt you to confirm the transaction.

  • After the transaction is confirmed, you can click Get Stored Data to retrieve the value.


4.2 Testing

  1. Enter a number, click Store Data, and confirm the transaction in Metamask.

  2. After the transaction is processed, click Get Stored Data to see the stored value on the blockchain.


Learn More from Freecode Camp




 

Join our community for more guides and tips on building dApps and smart contracts, join our Telegram community: https://t.me/aspireworld


留言


bottom of page