Developing Decentralized Applications on Blockchain

Kacharlabhargav
Nov 20 · 7 min read

Decentralized applications (Dapps) are the applications that run on decentralized network as opposed to centralized applications that run on a single computer. Dapps run on a P2P network of computers with no central point of failure. Blockchain is one such kind of P2P network. Traditional web applications use HTML, CSS and Javascript to render the webpage. This page interacts with a centralized database where all the data is stored. Decentralized applications are similar to traditional web applications. The front end uses the exact same technology to render the page. The back end is business logic represented by one or more smart contracts. So lets look at different ways to start building Dapps on blockchain.

1. Developing Dapp with Truffle

Truffle is basically a development environment where you could easily develop smart contracts with its built-in testing framework, smart contract compilation, deployment, interactive console, and many other features.

Install Node js by following commands,

sudo apt-get install curl
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash –
sudo apt-get install nodejs

Now install truffle using node package manager,

npm install -g truffle

Initialize truffle project :

Create a new directory for your project and move to that directory

mkdir myproject
cd myproject

Below command initializes your truffle project,

truffle init

This creates a bare project template, but you can use Truffle Boxes which provide you project templates to get started.

Once this is done, you will have a project structure with the following items,

By default you will have Migrations.sol in contracts folder and 1_initial_migration.js in migrations folders.

  1. Truffle requires you to have a Migrations contract in Migrations.sol in order to use the Migrations (deploying smart contracts) feature.
  2. 1_initial_migration.js is for deploying this Migrations contract. You must deploy this contract inside your first migration in order to take advantage of the Migrations feature.

Develop a Smart Contract:

Lets create a simple smart contract SimpleContract.sol and add it to our contracts folder.

pragma solidity ^0.5.10;
contract Simple {
string private message = “My Contract”;
function getMessage() public view returns(string memory) {
return message;
}
function setMessage(string memory newMessage) public {
message = newMessage;
}
}

Next add a migration file for the Simple contract and name it 2_deply_contracts.js.

Note that the filename is prefixed with a number and is suffixed by a description. The numbered prefix is required in order to record whether the migration ran successfully. Add the below code to the file.

const Simple = artifacts.require("Simple");
module.exports = function(deployer) {
deployer.deploy(Simple);
};

This code deploys Simple contract on to the blockchain. But where ? How does truffle know to which blockchain contract has to be deployed ? Hmm… That’s where truffle-config.js file comes to use.

Deploy smart contract:

You created a smart contract and created a migrations file to deploy the smart contract. Now lets tell truffle where to deploy our smart contract by configuring truffle-config.js. Before configuring truffle-config.js lets start our personal blockchain by opening Ganache. Note the RPC server details and let Ganache be running in the background.

Now come back to truffle-config.js and provide below details,

module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*"
}
}
}

Host and port numbers are obtained from the RPS server details inside your Ganache. Now the sample Dapp is ready to be deployed on to blockchain. Wait… Is that all ? Where is my front end ? Well, you can add your HTML, JS files and initialize package.json and write your own front end for the Dapp using various front end technologies like Vue, React etc. But Wait ? Doesn’t truffle provide all these files by default ? As I said truffle init provides bare project template for your smart contract development and deployment. But if you want truffle to add a default front end template to your project you can make use of various truffle boxes like React or Vue which provide default project templates for your Dapp. Don’t worry we will build a Dapp using React box from truffle after this. Huge sigh!!!

Now lets compile our project before deploying on to blockchain. You can do so by,

truffle compile

When the project is compiled, you can see json files created in your build/contracts folders.

The json file contains a lot of information about the compiled contract. It includes the whole compiled bytecode, along with function signatures, events, and compiler information.

The two most important parts are the “abi” and “bytecode”/ “deployedBytecode”.

  • Ethereum has specified a common way of interacting with contracts using the Application Binary Interface (ABI). This is what tells clients how to create transactions that will run on the contract, and what events you should expect
  • The bytecode is what gets run on the Ethereum Virtual Machine (EVM). In order for you to “deploy” a contract onto the Ethereum blockchain, you must submit the deployedBytecode as a transaction. Technically, the bytecode is what is stored as the contract, and when you call a function, it can only interact with that bytecode in the EVM.

Note: If you get any errors other than syntax errors then it could probably be due to solc compiler version. Check the solc compiler version of truffle and your solidity file.

Now if the project compiled successfully then its time to deploy your contracts on to blockchain. You can do so by,

truffle migrate

Make sure Ganache is running in the background. If all goes well then your contracts will be deployed on to blockchain and you can interact with your contracts from your Dapp using Web3 Js from your javascript code.

Do you really need to run Ganache GUI in the background ? Not really. You can run your personal blockchain from console using Ganache CLI.

You can start Ganache CLI from console by,

ganache-cli start

By default it runs on port 8545 so make sure your truffle-config.js is specified with port 8545.

Still thinking about your front end for your Dapp ? I don’t want to disappoint you. So lets create another simple Dapp using truffle React box.

2. Developing Dapp using Truffle React box

Type below commands to create a new directory for your project and move to that directory

mkdir myproject
cd myproject

To use truffle react box you need to run the unbox command.

truffle unbox react

This will create a project template with the folder structure of react application. Open the project in visual studio code, you can check the additional src folder with App.js, App.css and other files being added for your front end with some default template.

  1. Compile your project to generate json file for your contracts in src/contracts directory because your Dapp is dependent on those files.
truffle compile

2. Check truffle-config.js and provide the network configuration to deploy the contracts on to your blockchain. I have given the configuration below for Ganache-CLI.

networks: {
development: {
host: "127.0.0.1",
port: 8545,
network_id: "*"
}
}

3. Setup metamask

Make sure to run metamask with network localhost 8545 because your react application is dependent on metamask which you can check in App.js under componentDidMount. Make sure your metamask have sufficient funds or you can import the account from your Ganache-CLI using the private key of any account.

4. Deploy your contracts

truffle migrate

5. Once the contracts are deployed then you can start the development server to run your web application using,

npm run start

The application runs on port 3000 and metamask confirmation prompts up.

BAMMM… Your Dapp is up and running with React front end.

But do you really need to know truffle to develop a Dapp ? No, not really. Lets say you are a Front end developer and you want build a Dapp using React/Vue but don’t want to use Truffle. You can do so. Lets create a Dapp using react without using Truffle. Huge sigh again !!!

3. Developing Dapp using React without Truffle

i) Create reactjs project using,

create-react-app myreact-app

This will create react js project. Open the project in visual studio code and run,

npm start

This starts your development server and opens the web application in your browser.

Now you don’t want to use truffle but how are you going to deploy your contracts and interact with them ? Well as we discussed earlier about ABI, which lets you interact with the smart contract. Just revisit to that section about ABI and come back. Welcome! So we need ABI of our deployed contract, lets get the ABI of our Simple contract we have developed. Deploy the contract and get the contract address and ABI of the contract. But whatever further changes you do to your contract, then the corresponding ABI has to be updated.

ii) Install web3

npm install –save web3@1.0.0-beta.46

iii) Create a javascript file with name of your choice, lets say config.js and assign contract address and ABI to the variables.

export const CONTRACT_ADDRESS=”< deployed contract address>”
export const CONTRACT_ABI=[<contract ABI>]

iv) Add below code to App.js,

import React, {Component} from 'react';
import Web3 from 'web3'
import './App.css'
import { CONTRACT_ABI, CONTRACT_ADDRESS } from './config'
class App extends Component {
componentWillMount() {
this.loadContract()
}
async loadContract(){
const web3 = new Web3(Web3.givenProvider)
const accounts = await web3.eth.getAccounts()
console.log(accounts[0])
const simpleContract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS)
console.log("simplecontract",simpleContract)
}
render() {
return (
<div>
Hello
</div>
);
}
}
export default App;

The above simple code will use web3 provider from browser which is metamask and get the account address on which metamask is running. web3.eth.contract loads the contract with the ABI and contract address we are passing. Go to the browser, press f12 from keyboard and go to the console, you should see account address and simple contract details logged.

Great !!! Now you can use web3 to interact with your contract from React application.

Uff… That’s a lot to digest. We have discussed various ways to get started with Dapp development. So its time for you to build the fully fledged decentralized applications on blockchain.

Happy Learning!!!

Kacharlabhargav

Written by

Blockchain Enthusiast | Software Developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade