Dapps 101 – Build and Deploy Your 1st Dapp!

Purnendu Shukla 01 Aug, 2022 • 10 min read

This article was published as a part of the Data Science Blogathon.

Introduction

Dapps are decentralized – applications that allow one to communicate to the blockchain and perform specific actions. These have become an integral part of Web 3.0 due to their security, transparency, and ease of use.

The fact that makes Dapps more interesting is that most of them can be made by anyone and will still inherit the properties of the blockchain it’s deployed on. Further, they are open source and decentralized versions of the current web 2.0 products like Youtube, Twitter,  Medium, and others.

Nowadays, every web3.0 company requires developers to have Dapp’s development skills. So having them in your skill set with some projects will give you an added advantage.

So this article covers how to make a simple one that reads and writes your mood to the blockchain.

Let’s begin!

Overview

The project name is Mood Dairy and has the following components:

index.html – Frontend UI to interact with smart contracts.

main.css – Custom-built CSS file to add style to index.html.

mood_dairy.sol – Smart contract build using solidity for interacting with the blockchain.

This article assumes you are familiar with Web Development (HTML, CSS, JS) and Programing and web three concept three.

Having defined the architecture, let’s set up the working environment.

Working Environment Setup

Before building the project, we need to fix a few things:

1. Metamask 🦊

A software-based crypto wallet is used to sign transactions on blockchain (more on this later!).

1. Head over to the page and download the extension.

2. Open the extension, and it asks for a Create Wallet/ Import Wallet. Click Create Wallet, and then I Agree.

3. On the next page, enter the password you desire, tick✅ the box and then Create.

4. Copy your seed phrase and store it securely (only recovery option!). Finally, paste it at last where which ask for the same.

5. Head to Setting -> Advance -> Show test networks and enable it. This will allow us to test our smart contracts.

An Image Guide For All Steps (till step 5)

metamask | Dapps
metamask | Dapps
metamask | Dapps
Daaps
Daaps | Secret recovery phrase
Daaps

 

2. ETH from Faucet🏧

Faucets are vaults with many funds stored, sending a small amount of them whenever asked. This provides support for the development and has no actual monetary value. Here is how to request funds from the faucet.

We are using the Ropsten network for testing, so let’s request funds for the same.

1. Open metamask, and switch to Rinkiby Test Network.

2. Copy the account address, visit Faucet,  paste the code, and click Give Me Ropsten Eth! 

3. Wait for <1 min, and you will receive your fund.

You only get one chance per account, so make sure you use the correct address required.

Networks | Daaps
testnet faucet | Daaps

3. Installing Node.js and Lite Server⚡

Node.js is an open-source, cross-platform, backend javascript runtime environment that enables the execution of javascript code outside of the web browser, which is ideal for our use case.

We also need a lite-server. This lightweight development node server serves the web app without losing configuration details. Requires node or npm!.

Node.js + Lite server can be installed as:

1. Visit Official Page: Nodejs.org

2. Download & Install the compatible version. Make sure to add to the path.

3. Open cmd and type:

npm install -g lite-server #install lite-server globally

4. Done👍

4. Directory Structure + VS Code

Although not necessary, but proper when one needs to deploy on a real-time server.

Dapps:
├───Resources  #all resources here like png, txt
└───Scripts #all scripts here like HTML+JS, CSS, SOL

Note:  I am going to use VS Code, but one can use whatever editor they want for writing scripts

Having our work environment ready, let’s start coding!.

Frontend – index.html

For simplicity, developers tend to break their code into steps. We are going to follow the same convention:

1. Boiler Plate Code

A sample code is used for reference.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<link rel="stylesheet" href="Scripts/main.css" />

<title>Mood Dairy</title>

</head>

<body>

# your text here

</body>

</html>

Anyone familiar with HTML can quickly guess all this code does is: add structure to our webpage and share metadata to the rendering browser.

Also, the title we used here is Mood Diary, and an external CSS file using the link tag.

2. Add text, label, and input

Inside the body tag, let’s add some text, a label, and an input box to input mood:

<body>

<div>

<h1>Mood Dairy</h1>

<p>Here you can SET or GET mood:</p>

<label for="mood">Input Your Mood:</label> <br />

<input type="text" id="mood" />

</div>

</body>
Here we have set a title using h1, added a label as the mood for referencing later, and created an input field where user can supply their input and everything within a div tag to keep things organized.

3. Add interactive buttons

Within the div tag, adds a few buttons:

Notice the click parameters; it has two functions. These will be part of our smart contract and help in reading and writing to the blockchain, as discussed earlier!.

Here is what the entire code looks like:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<link rel="stylesheet" href="main.css" />

<title>My First dApp</title>

</head>

<body>

<div>

<h1>Mood Dairy</h1>

<p>Here you can SET or GET mood:</p>

<label for="mood">Input Your Mood:</label> <br />

<input type="text" id="mood" />

<button onclick="getMood()">Get Mood</button>

<button onclick="setMood()">Set Mood</button>

</div>

</body>

</html>

Styling – main.css

CSS is used for a site to look user-friendly, which takes a specific element and uses CSS properties to modify it.

Here is a sample snippet of the CSS we are using (main.css); feel free to modify it as per your liking☺

body {

        text-align: center;

        font-family: Arial, Helvetica, sans-serif;

        font-size: x-large;

        background-image: url('Resources/hope.jpg');

}




div {

        width: 20%;

        margin: 0 auto;

        display: flex;

        flex-direction: column; #flex-box

        font-size: 30px;

}




button {

        width: 100%;

        margin: 10px 0px 5px 0px;

        font-size: 30px;

}




input {

        font-size: 30px;

}

Since we have already added it in the head element using the link tag, so no worries

Now let’s develop our smart contract.

Smart Contract – mood_dairy.sol

Smart contracts are codes that can be self-executed when a particular condition is met. Ethereum Project introduced it, making the blockchain accessible to all. To learn more, check out this Twitter thread.

Smart contracts are written in a programming language called Solidity, which resembles C, JS, and python.

To write our code, we will use Remix, an online and offline IDE with support for compiling, deploying, Git, and much more. However, we will stick to the Online version.

Head over to the official site, select default workspace, and under the contracts, make a new file by clicking 📄 . Don’t forget to name it!

 

file explorers | Daaps

Structure of remix files

Let’s start the development!

1. Adding License and Version

Every smart contract requires a license as it demonstrates credibility. We will use MIT (opensource) . Add license as :

// SPDX-License-Identifier: MIT

Btw compiler expects a license as part of code comments, which is strange 🙄.

Also, we need to provide the version of solidity, as the compiler expects. We use the pragma solidity  keyword to define it:

pragma solidity ^0.8.1;

2. Adding Contract Object

In solidity, everything is an object, and one needs to specify every step within our contract object. This can be done as follows:

contract MoodDairy{

}

3. Adding State Variables

State variables are reference values that are declared outside of the function, stored on the blockchain, and share the current state information of the smart contract. Think of it as broadcasting!

We will add a mood that captures the state of the current mood value of the contract:

string mood;

4. Creating read and write functions

Next, we will add our main functions to read and write input values to the blockchain.

As we have already defined the call for the same within our UI part (HTML), it is preferred to use the same:

function setMood(string memory _mood) public {

mood = _mood;

}

function getMood() public view returns(string memory) {

return mood;

}

Notice the difference between setMood and getMood function declaration. The latter is a view-only function, i.e., it doesn’t modify the contract.

Also, we have to use public to ensure the functions can be called from outside the contract.

In a nutshell:

♦ We take the user’s data as input, pass it as a parameter to the function and store it within the mood, i.e., on a smart contract.

♦ In the next part, whenever the call to function getMood(), it takes the value of mood and returns it to the user as output.

With this, our smart contract is finally complete and looks like this:

  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.1;
  3. // Define contract which has to 2 fn – Set mood, get mood
  4. contract MoodDairy{
  5. // declaring a global variables as d_type var;
  6. string mood;
  7. //A public fn that writes into a smart contract (here mood) – setMood (used in the index.htm)
  8. function setMood(string memory _mood) public {
  9. mood = _mood;
  10. }
  11. //A public fn that reads from the smart contract (here mood value) – getMood (used in the index.htm)
  12. function getMood() public view returns(string memory) {
  13. return mood;
  14. }
  15. }
  16. // getMood is a public function that returns a string and stores data in memory.
  17. // Since it doesn’t change the state of the contract, it is called a “view” argument.

However, this backend can’t be merged with the frontend unless deployed. So let’s deploy the same!.

5. Contract Deployment

Follow these steps to deploy our contract:

1. In the remix-ide sidebar, go to compile tab, select solidity version same or greater than the declared, and click compile💫 . 

2. Next, visit the deploy tab and select Injected Web 3 in the Environment section. A new popup will ask to connect to desired wallet account, select as appropriate☑, and click deploy🎯.

3. A new popup will appear asking to pay the gas fees💲 (a small amount of asset to pay validator fees!). Please read it and click Sign📝..

4. Wait for a few minutes contract will be deployed and confirmation of the same will be sent😀

5. Copy and temprorily store the ABI code and Contract address from the compile and deploy tab.

Compile

Deploy

 

deploy and run transactions | Daaps

 

Dapps

Copy

 

Dapps

As our contract is ready,  it is time to merge it with the UI using Javascript and ether.js.

Merging Frontend & Backend

This is the most fun part of our project as we are taking 2 different components and weaving them together to form our final product as a Dapp.

So here is the ideology on how to perform the same.

1. Importing ether.js

Ether.js is a java-script library that provides a complete and compact way to interact with Ethereum Blockchain using javascript code.

We will import it within the index.html file using a script tag:

<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js" type="application/javascript"></script>

</script>

2. Declaring constant variables

Next up, we add some constant  values under a new script tag:

    const provider = new ethers.providers.Web3Provider(window.ethereum, "ropsten");

    const MoodContractAddress = "contract_address";

    const MoodContractABI = []

    let MoodContract;

    let signer;

The names are self-explanatory. Ensure you provide your contact address, and ABI is copied and stored in the temporary file before.

Note: Add contract ABI without [] !

3. Adding Wallet Pop-Up behaviour

Every Dapp works by connecting to a crypto wallet. So let’s add the auto connect functionality for the same:

provider.send("eth_requestAccounts", []).then(() => {

            provider.listAccounts().then(function (accounts) {

                signer = provider.getSigner(accounts[0]);

                MoodContract = new ethers.Contract(

                    MoodContractAddress,

                    MoodContractABI,

                    signer

                );

            });

        });

Here we request permission to connect to the user’s account and instantiate the signer.

Furthermore, we define our contract object (MoodContract) with the contract address and the ABI code declared earlier as constant.

4. Enabling click behaviour

Since there are 2 buttons within our UI, we can connect the button to the contract function calls to simulate clicking behaviour.

In simple terms, once the button is clicked, the function is associated within mood_dairy.sol will be implemented.

We can achieve this functionality using javascript async functions, which enable promise-based behaviour; without configuring promise chains.

    async function getMood() {

      const getMoodPromise = MoodContract.getMood();

      const Mood = await getMoodPromise;

      console.log(Mood);

    }
    async function setMood() {

      const mood = document.getElementById("mood").value;

      const setMoodPromise = MoodContract.setMood(mood);

      await setMoodPromise;

    }

Let’s understand the code in parts:

The first fn is our getMood Function and is used to retrieve the mood state from the smart contract with MoodContract.getMood() and stored the same in a variable, which is then printed.

In the next part, we retrieve the value given as input using the label mood in line 2 and call the setMood() function of the smart contract to write that value to the chain.

Note: await keyword is used to ensure the function waits for a promise(promise-based-behavior)

Technically we have done everything required, and our code looks something like this:

FULL CODE

I have added the Contract Address and ABI too!

The Final Call

Congrats on the hard work, but the work hasn’t finished. Let’s test out the project.

1. Hit up the cmd.

2. Navigate to the project folder – Our case (Dapps/Scripts).

3. Spin up the local deployment server – Our case (Lite Server ).

lite-server

4. A new web browser opens and asks for the account connection permission. Connect to a developer account and make sure to enable Ropsten Network (have funds).

5. Hit Ctrl+Shift+i which enable developer options . Visit the Console tab and see the output as you press the buttons within our UI.

In case you prefer a video guide of the same, here it is:

Source : (Solidity Gyan)

Conclusion

Although we have made a very basic and straightforward Dapp, there was a lot to learn. The following are key takeaways :

1. A Dapp is a web application that allows users to interact with the blockchain using smart contracts written in solidity.

2. However alone Dapp is nothing, so it requires 2 or more components: – UI, Smart Contracts, and Wallets.

3. A UI is called a frontend and can be as simple as ours or as complex as any Dapp out there. But it all boils down to HTML, CSS, JAVA-SCRIPT, REACT, and much more.

4. Smart Contracts are self-executable pieces of instruction that can be programmed by anyone using solidity language in Remix ide.

5. Writing a smart contract is not enough, one needs to compile and deploy it on the blockchain.

6. Performing transactions on the blockchain requires gas fees, so faucets are there to aid developers’ journey. One can request a small number of funds from it.

7. Deployment should always be done on a test server and using a developer / separate account, else there can be a risk of paying real funds.

8. One needs to merge the deployed contract to the frontend using ABI code and contract address, easily copiable within remix.

Extra:-  As a developer, you should tend to break down the project into smaller pieces, work on each separately, and finally merge them all to get a final product.

In the meantime, if you liked the article and got some value from it, share💞 it as much as possible. For any queries, my Dm’s are always open👐 – Twitter, LinkedIn, Github.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Purnendu Shukla 01 Aug 2022

Hey All✋, My name is Purnendu Shukla a.k.a Harsh. I am a passionate individual who likes exploring & learning new technologies, creating real-life projects, and returning to the community as blogs. My Blogs range from various topics, including Data Science, Machine Learning, Deep Learning, Optimization Problems, Excel and Python Guides, MLOps, Cloud Technologies, Crypto Mining, Quantum Computing.

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear