Creating Your first DAPP: Beginner’s Guide
--
Decentralized Applications are at boom now 🔥, and everyone want’s to be a Blockchain Developer. Newbies can get overwhelmed by the intriguing concepts of BlockChain furthermore Smart Contracts.
A Smart Contract is the logic behind a Decentralized Application. Smart contracts help you exchange money, property, shares, or anything of value in a transparent, conflict-free way while avoiding the services of a middleman.
In this post, we will be making a simple DAPP and will deploy it on the local network. We will create a front-end which will interact with our smart contract on the BlockChain.
The application we are creating is Mousse on Chain 🍫 . We will provide users to vote for their favorite Mousse Recipe.
Step 1
Firstly you will require Node.js installed on your machine. Node: https://nodejs.org/en/download/
After installing node, open up terminal or cmd and type the following.
npm -g i truffle
This will install the Truffle framework as a node package globally on your pc. Truffle helps us to develop DAPPS by providing various migrating, testing and debugging tools.
mkdir moc
cd moc
truffle init .
This will create a directory named MOC [Mousse on Chain] initialize the basic template for DAPP project
Step 2
Now we will create our Smart Contract, I’ll not dive deep into the code as that is off the scope of this article
- Create MOC.sol in the contracts folder
- Create 2_MOC.js in the migration folder
The first one is where we will add our smart contract code written in Solidity
The second one is the migration file we will talk about it later.
Code for MOC.sol
pragma solidity ^0.5.1;
contract MOC {
uint256[3] items;
constructor() public
{
// setting up the items with their values
for (uint256 i = 0; i < 3; i++)
items[i] = 0;
}
function vote(uint256 x) public returns (uint256)
{
if (x < 3 && x >= 0) {
items[x]++;
return 1;
}
return 0;
}
function getItem(uint256 x) public view returns (uint256)
{
return items[x];
}
}
Code for 2_MOC.js
const MOC = artifacts.require(“MOC”);module.exports = function (deployer) {deployer.deploy(MOC);};
We will design the front-end in HTML, CSS, JS.
Below is the code for index.html and main.css which is placed in the public folder
Step 3
Now we will compile and migrate our smart contract to our local blockchain with truffle
truffle develop
This will open up the truffle development console and will provide you with free 10 accounts.
migrate --reset
If your Smart Contract is correct then this will compile and deploy our smart contract to the local blockchain. the output will be 👇
truffle(develop)> migrate — resetCompiling your contracts…
===========================
> Compiling .\contracts\MOC.sol
> Compiling .\contracts\Migrations.sol
> Artifacts written to E:\Projects\moc\build\contracts
> Compiled successfully using:
— solc: 0.5.16+commit.9c3226ce.Emscripten.clangStarting migrations…
======================
> Network name: ‘develop’
> Network id: 5777
> Block gas limit: 0x6691b71_initial_migration.js
======================Replacing ‘Migrations’
— — — — — — — — — — —
> transaction hash: 0x297e6fadd1c93785059b892ebce78ac683e35359b3888518c29757990b9d889f
> Blocks: 0 Seconds: 0
> contract address: 0x1b02A5B71D53fcc41603E0af415F4B6dB4c7Df4C
> block number: 1
> block timestamp: 1582465106
> account: 0x7EaF571840Bff3bA4236aE952E5A65b90c633394
> balance: 99.9967165
> gas used: 164175
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.0032835 ETH> Saving migration to chain.
> Saving artifacts
— — — — — — — — — — — — — — — — — — -
> Total cost: 0.0032835 ETH2_MOC.js
========Replacing ‘MOC’
— — — — — — — -
> transaction hash: 0xc28ffba6e567d812f314b0e1cdeac92b620308519ae3a4bc8bf944cf80bba371
> Blocks: 0 Seconds: 0
> contract address: 0x37683d1e01Fb3390f50C6Ac590e06be6dC695733
> block number: 3
> block timestamp: 1582465106
> account: 0x7EaF571840Bff3bA4236aE952E5A65b90c633394
> balance: 99.9932666
> gas used: 130154
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.00260308 ETH> Saving migration to chain.
> Saving artifacts
— — — — — — — — — — — — — — — — — — -
> Total cost: 0.00260308 ETHSummary
=======
> Total deployments: 2
> Final cost: 0.00588658 ETHtruffle(develop)>
Keep this terminal open as we will require the development server running 🏃♂️
Now we will connect the front-end with the server using Web3.js
let contractABI = [{
“inputs”: [],
“payable”: false,
“stateMutability”: “nonpayable”,
“type”: “constructor”
},
{
“constant”: false,
“inputs”: [{
“internalType”: “uint256”,
“name”: “x”,
“type”: “uint256”
}],
“name”: “vote”,
“outputs”: [{
“internalType”: “uint256”,
“name”: “”,
“type”: “uint256”
}],
“payable”: false,
“stateMutability”: “nonpayable”,
“type”: “function”
},
{
“constant”: true,
“inputs”: [{
“internalType”: “uint256”,
“name”: “x”,
“type”: “uint256”
}],
“name”: “getItem”,
“outputs”: [{
“internalType”: “uint256”,
“name”: “”,
“type”: “uint256”
}],
“payable”: false,
“stateMutability”: “view”,
“type”: “function”
}
]
document.getElementById(‘landing’).style.display = ‘none’
let contractAddress = “0x0e34Ee66a401A533B0dBDFc896d530b3C780F9Bc”;
let web3 = new Web3(‘http://127.0.0.1:9545/’);
let moc = new web3.eth.Contract(contractABI, contractAddress);document.addEventListener(‘DOMContentLoaded’, () => {
refresh()
if (web3) {
document.getElementById(‘landing’).style.display = ‘flex’
document.getElementById(‘cover’).style.display = ‘none’
}
})const refresh = () => {
for (let i = 0; i < 3; i++)
moc.methods.getItem(i).call()
.then(result => {
document.getElementById(`v${i}`).innerHTML = result;
})
}function vote(e) {
console.log(e.id[4])
moc.methods.vote(e.id[4]).send({
from: `0xa04c681f3aaa61adce9632c9601346c09a26015a`
}).then(result => {
console.log(result)
refresh()
})
}
In the 👆 code
1. replace the contractABI
with the ABI field in MOC.json in the build folder,
2. replace contractAddress
with contractAddress from the output of the migrate command.
3. replace from
in the vote function with any account address provided by truffle like 0xa04c681f3aaa61adce9632c9601346c09a26015a
let web3 = new Web3(‘http://127.0.0.1:9545/');let moc = new web3.eth.Contract(contractABI, contractAddress);
new Web3()
initialize the Web3 API for communicating with the blockchain network, here we are using the local network so http://127.0.0.1:9545/
.web3.eth.Contract()
create a contract variable for calling functions.
moc.methods.getItem(i).call().then(result => {document.getElementById(`v${i}`).innerHTML = result;})
here the moc is the contract variable and we are calling contract functions through the methods and a call()
function, these are async functions so we need .then()
.
Now your First Dapp is ready on the local network
Open index.html
while running the truffle console, you can interact with the Smart Contract through the voting buttons.
The whole project can be clone from GitHub : https://github.com/SuyashSonawane/MOC-DAPP
Follow me on:
Portfolio: https://suyashsonawane.me/
Twitter: Suyash Sonawane (@SuyashYSonawane) / Twitter
LinkedIn: Suyash Sonawane | LinkedIn
Github: SuyashSonawane (Suyash Sonawane)