Web3.js

How do I use Web3js with a decentralized application DApp


Using Web3.js with a Decentralized Application (DApp)

Web3.js is a powerful JavaScript library that allows you to interact with the Ethereum blockchain. In this guide, we'll walk through how to create a simple decentralized application (DApp) using Web3.js.

1. Prerequisites

Before you start, ensure you have the following:

  • Node.js and npm installed on your machine
  • A local Ethereum node or access to a test network (e.g., Ganache)
  • Basic understanding of HTML, CSS, and JavaScript

2. Set Up Your Project

Create a new project directory and initialize it:

mkdir my-dapp
cd my-dapp
npm init -y

3. Install Web3.js

Install the Web3.js library using npm:

npm install web3

4. Create a Simple Smart Contract

For this example, we will create a simple smart contract that allows users to store and retrieve a message. Below is the Solidity code for the contract:

pragma solidity ^0.8.0;
contract SimpleStorage {
    string public message;
    function setMessage(string memory _message) public {
        message = _message;
    }
    function getMessage() public view returns (string memory) {
        return message;
    }
}

Use Remix IDE to compile and deploy this contract to your local Ethereum node or a test network.

5. Create the Frontend

Create an index.html file in your project directory:

<!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/npm/web3/dist/web3.min.js`></script>
    <script src=`app.js`></script>
</head>
<body>
    <h1>Simple Storage DApp</h1>
    <input type=`text` id=`messageInput` placeholder=`Enter a message`>
    <button id=`setMessageButton`>Set Message</button>
    <button id=`getMessageButton`>Get Message</button>
    <p id=`messageDisplay`></p>
</body>
</html>

6. Create the JavaScript File

Create an app.js file in your project directory:

const Web3 = require('web3');
// Connect to your local Ethereum node or test network
const web3 = new Web3('http://localhost:8545'); // Change to your node URL
// Replace with your deployed contract address
const contractAddress = '0xYourContractAddress'; 
// ABI of the SimpleStorage contract
const contractABI = [ 
    {
        `inputs`: [{`internalType`: `string`,`name`: `_message`,`type`: `string`}],
        `name`: `setMessage`,
        `outputs`: [],
        `stateMutability`: `nonpayable`,
        `type`: `function`
    },
    {
        `inputs`: [],
        `name`: `getMessage`,
        `outputs`: [{`internalType`: `string`,`name`: ``,`type`: `string`}],
        `stateMutability`: `view`,
        `type`: `function`
    }
];
// Create contract instance
const simpleStorage = new web3.eth.Contract(contractABI, contractAddress);
// Function to set a message
async function setMessage() {
    const accounts = await web3.eth.getAccounts();
    const message = document.getElementById('messageInput').value;
    await simpleStorage.methods.setMessage(message).send({ from: accounts[0] });
    alert('Message set!');
}
// Function to get a message
async function getMessage() {
    const message = await simpleStorage.methods.getMessage().call();
    document.getElementById('messageDisplay').innerText = 'Stored Message: ' + message;
}
// Add event listeners
document.getElementById('setMessageButton').addEventListener('click', setMessage);
document.getElementById('getMessageButton').addEventListener('click', getMessage);

7. Run Your DApp

To run your DApp, you can use a simple HTTP server. If you have Python installed, you can run:

python -m http.server 8000

Then, open your browser and navigate to http://localhost:8000 to interact with your DApp.

8. Conclusion

By following these steps, you can create a simple decentralized application using Web3.js. This DApp allows users to store and retrieve messages on the Ethereum blockchain, demonstrating the power of decentralized technology.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.