Getting Started with Building Your Own Decentralized Application (DApp) on Ethereum Blockchain using HTML
Introduction
In this guide, we will walk through the process of creating a simple Decentralized Application (DApp) on the Ethereum blockchain using HTML, Web3.js, and Truffle. This DApp will not include any CSS styling to keep the focus on the core functionality.
Prerequisites
Before diving into the development process, ensure you have the following prerequisites in place:
1. A basic understanding of HTML, JavaScript, and Solidity (Ethereum’s programming language for smart contracts)
2. Install Node.js (>= v10.x) and npm (>= 6.x)
3. A Metamask extension installed in your browser for interacting with the Ethereum network
4. A small amount of Ether (ETH) in a wallet compatible with the Ethereum Mainnet
Setting Up the Development Environment
1. Install Truffle by running the following command in your terminal:
“`
npm install -g truffle
“`
2. Create a new Truffle project by running:
“`
truffle init
“`
3. Navigate to the newly created `MyDApp` directory in your terminal.
Writing the Smart Contract
Create a new Solidity file named `SimpleStorage.sol` in the `contracts` folder:
“`solidity
pragma solidity ^0.5.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
“`
This contract will store a single integer value and provide methods for setting and retrieving it.
Compiling and Deploying the Contract
1. Compile the contract by running:
“`
truffle compile
“`
2. Deploy the contract using the following command, ensuring you have connected to the Ethereum Mainnet:
“`
truffle migrate –network mainnet
“`
Creating the DApp Interface
Now, let’s create the HTML interface for interacting with our contract. Create an `index.html` file in the `www` folder and add the following content:
“`html
My Decentralized Application (DApp)
Set a number:
Retrieved Number:
“`
Writing the JavaScript Logic
Create a new file named `App.js` in the `www` folder and add the following content:
“`javascript
const ethers = require(‘ethers’);
const contractAddress = “0x…”; // Replace with your contract address obtained from Truffle migration
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(contractAddress, [
“function set(uint256 _value) public”,
“function get() public view returns (uint256)”,
], signer);
document.getElementById(‘setNumber’).addEventListener(‘click