Blockchain - what it is? Ethereum dapp - what it is?

How to Build Your First DApp on Ethereum

Technical introduction

This will be a short technical article on how to build an Ethereum dApp. Let me first mark the tools and frameworks we’ll need today in order to build and run our project. We are going to use  VS Studio Code, NodeJS, Solidity, Angular, Git, Terminal, Etherlime. If you have no idea what any of these is (except Etherlime which I am going to explain further on) I recommend you to follow the links and read their documentation or get them installed. 

What are decentralized applications (dApps)?

Decentralized applications (dApps) are applications that run on the blockchain. Or in other words, they use a peer to peer network of computers, or nodes, that communicate with each other. The biggest plus is that the stored data is put on a so-called public ledger that records everything in a secure and transparent way and guarantees no one can manipulate it.

Just like the traditional, centralized applications, ethereum dApps also consist of backend (the logic) and frontend (the visual) part. The most significant difference is that the core of the backend is the blockchain technology. The instrument which is able to manage and rule the blockchain system are smart contracts. And here comes the point where we’ll start our actual developing part.

Initialize a project

To set the base of our project, we first need to have at least one smart contract. It is going to be very simple, just to illustrate the main principals of the technology.

To make it easier, we are going to use Etherlime (a framework for Ethereum development and deployment). As we don’t want to lose time to write the front end part (because this is not the main point now), Etherlime would provide us complete ready to use ethereum dApp. We’ll go through each piece of code to explain how it works and will add some new functionalities together. In a new Terminal tab run the following commands.

$ npm install -g etherlime

$ mkdir myFirstDApp

$ cd myFirstDApp

$ etherlime shape angular
 

The last command is those who’ll actually create a new project containing everything we need at the moment. Let’s take a look at what we have inside.

This is a common structure of an initial blockchain project. The contracts folder is where our smart contract is located. In this example, it represents a ToDo List and enables interaction with each ToDo’s status. To be able to use this smart contract we need to deploy it on the blockchain. That’s exactly what the code in deployment does. Apparently, the test folder contains tests that check the proper functionality of the smart contract. In web is the frontend part and where transactions to the blockchain are being sent.

Run local blockchain

As we said above, we need to deploy our smart contract on the blockchain if we want to “give him life”. Fortunately, we have the option to build our local blockchain for Ethereum decentralized applications development so we don’t need to use real ETH for the transactions. To get it, just run etherlime ganache in a new Terminal tab and a list with then accounts should appear on the window. Don’t close this tab while you operate with the local blockchain, otherwise, you will lose it and will have to build it again.

Deploy smart contract

Now we’ll dive a little bit deeper into the deployment script provided in the deployment folder and will continue with the actual deployment.

Etherlime gives us the usability to instantiate a deployer that would do the whole “dirty work” instead of us. The deployer has a provider, also called node, that “talks” with Ethereum network and he actually makes the query to the blockchain. It’s deploying method send the transaction. We neither need to compile the contract because this will be done within the deployment command.


 
const etherlime = require('etherlime-lib');

const ToDo = require('../build/ToDoManager.json');

const deploy = async (network, secret) => {

   const deployer = new etherlime.EtherlimeGanacheDeployer()

   const contract = await deployer.deploy(ToDo)

};

module.exports = {

  deploy

};

Having this script inside, all we have to do is to run the command etherlime deploy. You must see now a beautiful colored table with details about the mined transaction. Congratulations! You have deployed your first smart contract successfully!

That what is shown in the table, as a result, is actually the address that our smart contract uses in the local blockchain we’ve built earlier. Copy this address, paste it in config.json file placed in the root of the project and let’s move to the frontend part.

Interaction with the smart contract

Now, through the terminal, navigate to the web folder and run the decentralized application:


 
cd web
ng serve --open

Your ethereum dApp is welcoming you! We have still a little job to do before we add our first ToDo on the list. Now, we need to get  Metamask extension on our browser. If you’ve successfully set it up, the next step is to connect it to the local blockchain. Copy any of the private keys from the lists with accounts.

Open Metamsak icon on the browser, click on the globe of the right side and choose Import Account, then paste the copied private key. Before we’re done, in the middle of the top, you’ll find a list with networks, select “Localhost: 8545” and now you have to have an account full of Ethers.

Go back to the page where “MyToDo dApp” is waiting to be filled. Go on. Add your first to do.

That it is! We have an ethereum decentralized application (ethereum dApp) which reads and record data to the Blockchain! 

Let’s now try to write some code by ourselves. Open ToDoManager.sol in contract folder and we’ll add new functionality that would assign a ToDo to someone, using his address.

First, create new variable mapping (uint => address) public assignedToDo that would keep who is the assignee for each ToDo. Lets now write the new function. You may apply this code to the contract:


 
function assignToDo(uint _index) public {

 assignedToDo[_index] = msg.sender;
}

This simple method will assign the job to those who are claiming it. That’s why we use msg.sender, i.e. those who call/execute the function.

Frontend integration

Lets now continue with the frontend part. Look up in web/src/app/app.component.tsfile and the ngOnInit() method in the beginning — here is the most important part to connect to the blockchain. I’ll walk you through each row and hope you’ll get clear what actually happens. 

If you remember, in the beginning, Metamask asked you for access to view your current account address. This prevents privacy issues and is activated by the command window.ethereum.enable(). At the next row, we instantiate a provider to be able to communicate with Ethereum network. We also need a signer those who will sign the transaction with his public address, or also those who are executing the function(msg.sender). The next one is contractInstance and this, as its name says, is the instance of our ToDoManager smart contract. Through this instance, we could reach all methods and variables of the already deployed smart contract. Etherlime ContractAt functionality helps us to easily access it with only one row of code. As params, we pass the compiled contract, the addresses on which our smart contract “lives” on the blockchain and at least are the signer and provider. The rest of the code is used only for better visualization on the browser.

Ok, now let’s interact with our contractInstance in the frontend and its new function. Add this code in web/src/app/app.component.ts:

public async assignToDo(toDo) {
   try {

       const index = await this.getToDoIndex(toDo);

       await this.contractInstance.assignToDo(index);

       this.addInfoMessage(`You have assigned to do ${toDo}.`);

   } catch (e) {

       this.addInfoMessage(e.message) 

}

The bolded part of the code is how we make a query to the smart contract on the blockchain and how we change the state. (Maybe you noticed that we operate with the ToDos by index, not by their string values because it’s easier to iterate through all of them)

We are going to add another one function to read who is the assignee of a certain ToDo. Again, we access the mapping who keeps the data by the contractInstance. Here it is:


 
public async getAssignee(toDo) {

   try {

       const index = await this.getToDoIndex(toDo);

       let assignee = await

this.contractInstance.assigneedToDo(index)

       this.addInfoMessage(`Assigner is ${assignee}.`);

   } catch (e) {

       this.addInfoMessage(e.message)

}

If you have done this correctly, take a breath. There is just a little work to do. Let’s make the visual part. In web/src/app/app.component.html we are going to add two new buttons for both new function we added.



<button class="btn btn-primary btn-sm btn-warning" (click)="assignToDo(todo, todoText)">Assign ToDo</button>

<button class="btn btn-primary btn-sm btn-warning" (click)="getAssignee(todo)">Show Assignee</button>

That’s how it should look!

Once we are done with the new code, we have to redeploy our smart contract and update its new address in config.json. Then run the ethereum dApp again and the new functionalities we’ve added must be there.

That’s all folks! Congratulations! Was it fun? I hope this was a pleasant journey for you!

If you want to see more examples, you may continue to practice with  Etherlime React Shape.

If you need help in the development of your Ethereum dApp, feel free to contact us at hi@limechain.tech

 

I like it, I share it!

ABOUT THE AUTHOR

Desimira Mitkova
Blockchain Developer
Desi is an inspiration for many. She followed her guts and became a Blockchain developer after being a journalist for 13 years. She enjoys developing smart contracts with Solidity and is eager to find out how the Blockchain technology will transform the world.