Develop your first Decentralized App (DApp) on Ethereum | Smart Contracts| Web 3.0

Develop your first Decentralized App (DApp) on Ethereum | Smart Contracts| Web 3.0

In this blog, we will learn how to go about creating your first Decentralized App (DApp) on Ethereum.

Pre-requisites:

As this blog will focus more on the technical side of the app, it is recommended that you have some functional knowledge of blockchain, Ethereum smart contracts and the significance of decentralization beforehand.

Architecture:

No alt text provided for this image


Smart Contracts:

The decentralized apps are defined by smart contracts. A smart contract allows us to exchange data in a trusted manner without relying on any third parties like banks, lawyers, etc. These smart contracts are stored as transactions on the Ethereum Blockchain which can be used to build applications (sort of APIs).

As smart contracts are stored on the Ethereum Blockchain, they need to be mined like a normal transaction and therefore the deployment of a smart contract has a small cost associated with it. However, we will be using a test environment to develop our smart contracts which will not cost us any money(or eth).

Creating a Smart Contract:

Solidity is the language that is used to develop a smart contract. The syntax is similar to that of Javascript and it's designed with the Ethereum Virtual Machine in mind. The solidity programs can be executed in local machines or using an online IDE called Remix. In this blog will be using an online editor.

You can access the Remix IDE using the following URL:

https://remix.ethereum.org/

We will be creating a simple smart contract that holds the employee information (Name and Age).

Following are the steps that will help us in creating a smart contract from scratch:

  1. Goto the Remix online IDE, you'll be navigated to the page as shown below.

No alt text provided for this image

2. Click on the contracts folder. Here, there'll be some contract examples for your reference. You can click on the new icon as shown below.

No alt text provided for this image

3. We will create a file with the name EmployeeContract.sol where .sol is the solidity extension.

No alt text provided for this image

4. Below is the solidity code for our use case with the explanation.

//Define the solidity version

pragma solidity >=0.7.0 <0.9.0


//Define the contract

contract Employee {
? ??

? ?string name; //define the name of the employee
? ?uint256? age; // define the age of the employee


//Define the setters and getters for the employee
? ?
function setEmployee( string memory _name, uint256 _age) public {
? ? ? ?name = _name;
? ? ? ?age = _age;
}
? ?

function getEmployee() view public returns (string memory ,uint256) {
? ? ? ?return (name,age);
?}
? ?
};        

The above code is very simple to understand, but if you wish to learn solidity language in-depth, I recommend going through the Solidity Tutorial.

5. Now, let's compile our smart contract.

Select the EmployeeContract.sol file => click on the Solidity Compiler => click on Compile as shown below:

No alt text provided for this image


No alt text provided for this image

6. Now that we have successfully compiled it, it's time to execute our first smart contract.

Click on the deploy icon on the left => Hit the deploy button

No alt text provided for this image


No alt text provided for this image

7. Once you hit the deploy button and if everything is okay, you should see the list of deployed contracts below.

No alt text provided for this image

8. Test the smart contract

Once you clicked on the deployed contract, you'll see the setter and the getter function that we had created for the employee. Let's try to update the employee information using the setter and check if we are getting the same information in the getter method.

No alt text provided for this image

Click on setEmployee and then click on getEmployee to verify if everything worked well.

No alt text provided for this image

This means, our first smart contract works perfectly fine.

Interacting ethereum smart contracts with web3.js:

Now that we have successfully developed a smart contract, it's time to create a UI and integrate the smart contract with it.

1. Setup the test environment:

We will be using Ganache CLI to set up our test environment.

Ganache CLI uses ethereumjs to simulate full client behaviour and make developing Ethereum applications faster, easier, and safer. It also includes all popular RPC functions and features (like events) and can be run deterministically to make development a breeze.

Make sure you have installed the latest version of node and npm. Use the following command to install ganache-cli:

npm install -g ganache-cli        

Use the following command to run the ganache-cli:

ganache-cli        

You should be able to see the following in your terminal:

No alt text provided for this image

Here, if you see, it has started the test environment on port 8545 and also it provides us with 10 dummy accounts to perform all the transactions.

2. Installing Web3.js

Web3.js is an official Ethereum Javascript API. It is used to interact with the Ethereum smart contracts.

Before we install it, we will create a project folder and will run the following command to create the package.json file to store all the project dependencies:

npm init        

Next, run the following command to install web3.js:

npm install web3        

3. Change the environment in Remix IDE

For testing the smart contract we had selected the environment as 'Javascript VM', we need to change it to 'Web3 Provider' and then we can give the URL of our test environment (defaults to https://localhost:8545) that we had created using ganache-cli.

No alt text provided for this image
No alt text provided for this image

This means, instead of using Javascript VM to test and deploy our smart contracts we will now be using the test environment.

4. Creating the UI

Open any preferred editor (I'll go with VSCode) and open the project folder that we had created in step number 2.

We will create a simple UI, which will have a placeholder to display the employee information using getEmployee() method and also will have two form fields to update the information using the setEmployee() method.

Let's start with creating the index.html file.

<!DOCTYPE?html>
<html?lang="en">


<head>
????<meta?charset="UTF-8">
????<meta?name="viewport"?content="width=device-width,?initial-scale=1.0">
????<meta?http-equiv="X-UA-Compatible"?content="ie=edge">
????<title>My?First?DApp</title>
????<link?rel="stylesheet"?>
????<link?rel="stylesheet"?type="text/css"?href="main.css">


????<script?src="./node_modules/web3/dist/web3.min.js"></script>


</head>


<body>
????<div?class="container">
????????<form>


????????????<h1?class="form-title">My?First?Decentralized?App</h1>
????????????<div?class="form-group">
????????????????<label?for="employee">Employee?on?contract</label>
????????????????<h2?type="text"?id="employee"></h2>
????????????</div>
????????????<div?class="form-group">
????????????????<label?for="name">Employee?Name?</label>
????????????????<input?type="text"?class="form-control"?id="name">
????????????</div>
????????????<div?class="form-group">
????????????????<label?for="age">Employee?Age?</label>
????????????????<input?type="number"?class="form-control"?id="age">
????????????</div>
????????</form>
????????<button?id="button"?class="btn?btn-primary">Update?Contract</button>


????</div>


????<script?src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>


????<script>

       //Code will be explained further

????</script>


</body>


</html>        

We don't want our first app to look very raw, so will add some basic CSS to it in the main.css file.

body?
????background-color:#F0F0F0;
????padding:?2em;
}
.container?{
????width:?50%;
????margin:?0?auto;
}
.form-title{
????margin:?2em;
????text-align:?center;
}{        

5. Connecting and Interacting with the Smart Contract using Web3.js

In the index.html, we have an empty script tag at the bottom that we will be using to write all the necessary code.

You can use any framework (Angular, React, etc.) of your choice but just to keep things simple I'll go with jQuery. We are already importing the web3.js library in the head tags. Let's try to use it to connect to our test web3 provider.

<script>
????????if?(typeof?web3?!==?'undefined')?{
????????????web3?=?new?Web3(web3.currentProvider);
????????}?else?{
????????????web3?=?new?Web3(new?Web3.providers.HttpProvider("https://localhost:8545"));
????????}
</script>        

This means, if the web3 is undefined then we will be specifying the provider manually (our ganache-cli test environment) else it will use the current provider (Applicable to the cases when we use chrome extensions like meta-mask or if we are using Ethereum browsers like Mist).

Next, we will have to specify the default Ethereum account. This can be one of the accounts provided by the ganache-cli that we saw earlier in step number 1. We will go with the first account in that list.

<script>

if?(typeof?web3?!==?'undefined')?{
????????????web3?=?new?Web3(web3.currentProvider);
????????}?else?{
????????????web3?=?new?Web3(new?Web3.providers.HttpProvider("https://localhost:8545"));
????????}

//set the defaultAccount

web3.eth.defaultAccount?=?web3.eth.accounts[0];

</script>        

Next, we need to use web3.eth.Contract() to initialise the contract on an address. It accepts two parameters, one is the ABI?(Application Binary Interface) and the second is the contractAddress.

<script

if?(typeof?web3?!==?'undefined')?{
????????????web3?=?new?Web3(web3.currentProvider);
????????}?else?{
????????????web3?=?new?Web3(new?Web3.providers.HttpProvider("https://localhost:8545"));
????????}

//set the defaultAccount

web3.eth.defaultAccount?=?web3.eth.accounts[0];

// initialize the employeeContract

var?employeeContract?=?new?web3.eth.Contract(<ABI>,<contractAddress>);

</script>>        

To get the ABI, go to REMIX IDE => Select the contract file (EmployeeContract.sol) => Click on Compile button => Go to Compilation Details => Copy the ABI

No alt text provided for this image

To get the contractAddress, Go to Deploy section => Hit Deploy => Copy the value from the deployed contract

No alt text provided for this image

Now, we will use the getEmployee() and setEmployee() methods to retrieve and update the information in the smart contracts.

<script>
????????if?(typeof?web3?!==?'undefined')?{
????????????web3?=?new?Web3(web3.currentProvider);
????????}?else?{
????????????web3?=?new?Web3(new?Web3.providers.HttpProvider("https://localhost:8545"));
????????}


????????//set the default account

        web3.eth.defaultAccount?=?web3.eth.accounts[0];

        //initialise the employeeContract

????????var?employeeContract?=?new?web3.eth.Contract(<ABI>,?<contractAddress>);
        
        
        //retrieve the information using getEmployee() function

????????employeeContract.methods.getEmployee().call(function?(error,?result)?{
????????????if?(!error)?{
????????????????$("#employee").html(result[0]?+?'?('?+?result[1]?+?'?years)');
????????????}?else
????????????????console.log(error);
????????});
 
       
        //update the information using the setEmployee() function


????????$("#button").click(function?()?{
????????????employeeContract.methods.setEmployee($("#name").val(),?$("#age").val()).send({?from:?<accountAddress>?},?function?(error,?transactionHash)?{
????????????????if?(!error)?{
????????????????????employeeContract.methods.getEmployee().call(function?(error,?result)?{
????????????????????????if?(!error)?{
????????????????????????????$("#employee").html(result[0]?+?'?('?+?result[1]?+?'?years)');
????????????????????????}?else
????????????????????????????console.log(error);
????????????????????});
????????????????}?else?{
????????????????????console.log(error);
????????????????}


????????????});
????????});


????</script>        

For the setEmployee() function, you need to specify the account address. You can find that in the Remix IDE under the deploy section.

No alt text provided for this image


6. End to End Testing

Open the index.html file in the browser and try updating the contract.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

Also, in the REMIX IDE if you check the getEmployee() function you should see the same information.

No alt text provided for this image

And that's how we have successfully created our first decentralized app on Ethereum.

You can find the complete source code here:

Thanks for the read. Hope it helps.

Sarang Shah

"Strategic Digital Marketing Leader | MSc in Digital Marketing | 10+ Years Driving Business Growth through PPC, SEO, Influencer Marketing | Award-Winning Account Manager"

2 年

Great knowledge sharing Basim Wangde

Tanvi Talwalkar

Project Manager at Percipere

3 年

Whoaaa..!! This is so well put together Basim?? superb

Kunal Moorpana

Sales Director @ Percipere | SAP Cloud ERP, UKI

3 年

Excellent stuff Basim??

Vinay Pardeshi

Chief Technology Officer

3 年

Amazed at your hunger for learning new things...very simple and easy to understand article

要查看或添加评论,请登录

社区洞察

其他会员也浏览了