Ameer Rosic
4 weeks ago

How To Code A Decentralized Applications or Dapps

4 weeks ago
5
2
Join over 115,115 Members
Angel Investors, Startups & Blockchain developers...
Yes, Get Access!
No Thanks!

In this guide we will cover how to get started with How To Code A Decentralized Applications or Dapps and what are the things that you must cover when making one. Keep in mind that this field is constantly evolving and that it is always a good idea to keep refreshing your knowledge about whatever you learn.

Unless you are living under a rock, you’ve heard about blockchain technologies and how it is the next big thing to shape our lives and our futures. Blockchain lets us for the first time have a shared version of truth that is open, distributed and tamper proof in its nature. Blockchain has these properties because at the heart of it, it has a way to derive consensus (thereby having a shared version of truth) and also has cryptography baked into it by design (thereby letting us have a tamper proof record).

How To Code A Decentralized Applications or Dapps

 

Blockchain has a wide ranging set of applications and almost any field can benefit from having such a technology at its disposal. Blockchain is also heralded as a way by which trust can be ensured in the online world and lets us have greater confidence in the range of products and services that we use online.

However, it isn’t quite enough to know about the properties of blockchain and how it will impact the world around us. To get a thorough understanding of the blockchain it is essential to know how to interact with it programmatically and thinking about solutions from the software development aspect that we are used to. Developing applications on the blockchain is certainly something that is new and cutting edge –in fact, there is a new word to describe the type of applications that are powered by the blockchain. These are called Decentralized Applications or Dapps.

How To Code A Decentralized Applications or Dapps

Dapps are a new way about thinking about how we can go about writing applications for the internet. While previously we would have the backend code residing in a server or a set of servers, Dapps let us run web enabled applications where the back end is instead hosted on a blockchain network which executes the code that is needed for it.

What qualifies as a Dapp?

If you look online, the word Dapp is itself is not precisely defined and can come to mean different sets of things to different people. However, David Johnston has done work in formalizing the process of what a Dapp is and what its characteristics should be. The two main points that we would like to focus on is: Link: https://github.com/DavidJohnstonCEO/DecentralizedApplications/blob/master/README.md

  1. The application’s source code must be open sourced.
  2. The application’s data and records must be stored on a public blockchain.

 

 

How To Code A Decentralized Applications or Dapps

Image credits: https://medium.com/@codeAMT/how-to-launch-swarm-for-dapp-testing-8003e55380e2

Picking what to learn.  Decentralized Applications

As with any programming concept or idea, there are a wide range of platforms available to code on when talking about blockchain. While each platform has its pros and cons, it is important to also see how your application is structured so that you use the appropriate services at each of these stages.

As we are familiar with modern computing, it is important to have all the required components of a tech stack with their counter parts in the decentralized world. However, it is not trivial to find out and do research on each of the components. Thankfully, there is this handy info graphic that we can use to get a sense of the ecosystem:

How To Code A Decentralized Applications or Dapps

Image Source: https://medium.com/@FEhrsam/the-dapp-developer-stack-the-blockchain-industry-barometer-8d55ec1c7d4

As we can see, we have solutions for computing, file storage, API calls (external data), monetization and payments. In this guide we are mainly going to be focused on ethereum and how we can tackle the computing aspect of Dapps. Since computing is one of the most important aspects of building dapps, it makes sense to get familiar with interacting with smart contracts and then proceeding further.

Smart Contracts

Smart contracts are a term that was coined by Nick Szabo in 1994. Smart contracts and blockchain are closely linked – smart contracts are the programs that we write on the blockchain and let us interact with it. It is in a smart contract that we can define business logic and let us code the rules with which we want to interact with the blockchain. The most powerful feature of a smart contract is the fact that once it is deployed on to the blockchain, it is immutable and you cannot go back and edit the programs. This makes us embrace a paradigm where we a piece of code with the logic that we want in it will be immutable and can execute by itself when it is called. It is smart contracts that truly unleash the power of the blockchain and hence it is important to learn to develop smart contracts on the blockchain.

What are smart contract. A beginners guide

Ethereum: Decentralized Applications

Ethereum is probably the most popular blockchain platform that exists right now. They have had a public release for more than 3 years and it has a thriving community that maintains the project. They also have developed their own programming language called Solidity that lets us interact write smart contracts.

Ethereum has a public blockchain that lets people run code on and it one of the simplest way to start programming on the blockchain.

Gas and Gas Costs.

The Ethereum blockchain has a concept of Gas and Gas cost that is a very important to understand before you can start coding on it.

Gas is amount of fuel that you need to pay to get your transaction executed. The transaction could either be deploying your contract on the blockchain or can be running a function that already exists. Every time a function is called, there is some code that is executed. This code is executed on the computer of the person who is mining the transaction and requires computation power – to incentivize people to share their computational power and execute the transaction, each operation is charged some gas depending on the complexity of the transaction. The Gas in an ethereum smart contract can range all the way to 21 million. The gas that your transaction needs is multiplied by the gas cost to get the gas price.

Gas price is paid in ether and hence it is important to make sure that you have the correct balance in your account to deploy the contract on the blockchain. This is why instead of developing on the main network (which costs ether), we will run our code on a local instance of the ethereum virtual machine. Another interesting facet of this is that while coding, you would want to structure your program in a way that reduces your overall gas cost.

Get started with Solidity and Smart contracts.

How To Code A Decentralized Applications or Dapps

Image Credits: https://solidity.readthedocs.io/en/develop/

The ethereum foundation has released a cloud based IDE called Remix that is a simple way to get started. Simply go to http://remix.ethereum.org and you should be greeted with the following screen:

How To Code A Decentralized Applications or Dapps

The Remix default screen.

You see a screen on the left that lets you write code. The right hand side lets you deploy your code on the blockchain and lets you interact with the functions that you have written.

The simplest thing to do in any programming language is declare and write variables so lets see an example of how to do that: (Taken from – https://solidity.readthedocs.io/en/develop/introduction-to-smart-contracts.html)

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
pragma solidity ^0.4.0;

contract SimpleStorage {

   uint storedData;

   function set(uint x) {

       storedData = x;

   }

   function get() constant returns (uint retVal) {

       return storedData;

   }

}

 

Copy paste the following code on the code section in remix and then click on the deploy tab and click on create.

There are two functions – one that lets us set the variable value and one that lets us read it.

The first line of code tells us that we using a particular verison of Solidity. Contract SimpleStorage tells us the name of the contract and it helps us group code and logic into a single unit that can be referenced directly. The next line of the code declares a variable – storeData is of type uint.

The next two functions are simply getter and setter functions of the variable storeData.

Let’s take a minute to see what happens when we click on create. Every time you click on create, you are taking your Solidity based smart contract and deploying it on the blockchain. However, to simplify things and make it faster to develop applications, the blockchain that it deploys to is the ethereum virtual machine and resides in your browser and lets you interact with it. Since code once deployed cannot be changed, each time you have to make a change to your code, you have to redeploy it and test it out again.

How To Code A Decentralized Applications or Dapps

The console output that you see when you create the smart contract.

All you need to do is to deploy to the mainnet blockchain (the actual ethereum blockchain) is change the environment in the run tab and you should be able to write to the blockchain – keep in mind that interacting with the ethereum main-net will actually cost you money and every time you call a function or deploy a new contract, you have pay a gas cost in ethereum to make sure that your contract or function call gets mined and that you get your output.

Once you are up and running with Ethereum, you can read up the Solidity documentation to get yourself familiarized with the platform and its syntax. Solidity is fairly easy to learn and is very similar to javascript in its syntax. Let’s have a look at another Solidity example code to give a better feeling of what programming on it looks like. This one lets us conduct an open auction in a fair manner: (Taken from https://solidity.readthedocs.io/en/develop/solidity-by-example.html)

 

pragma solidity ^0.4.11;



contract SimpleAuction {

// Parameters of the auction. Times are either

// absolute unix timestamps (seconds since 1970-01-01)

// or time periods in seconds.

address public beneficiary;

uint public auctionEnd;



// Current state of the auction.

address public highestBidder;

uint public highestBid;



// Allowed withdrawals of previous bids

mapping(address => uint) pendingReturns;



// Set to true at the end, disallows any change

bool ended;



// Events that will be fired on changes.

event HighestBidIncreased(address bidder, uint amount);

event AuctionEnded(address winner, uint amount);



// The following is a so-called natspec comment,

// recognizable by the three slashes.

// It will be shown when the user is asked to

// confirm a transaction.



/// Create a simple auction with `_biddingTime`

/// seconds bidding time on behalf of the

/// beneficiary address `_beneficiary`.

function SimpleAuction(

uint _biddingTime,

address _beneficiary

) public {

beneficiary = _beneficiary;

auctionEnd = now + _biddingTime;

}



/// Bid on the auction with the value sent

/// together with this transaction.

/// The value will only be refunded if the

/// auction is not won.

function bid() public payable {

// No arguments are necessary, all

// information is already part of

// the transaction. The keyword payable

// is required for the function to

// be able to receive Ether.



// Revert the call if the bidding

// period is over.

require(now <= auctionEnd);



// If the bid is not higher, send the

// money back.

require(msg.value > highestBid);



if (highestBidder != 0) {

// Sending back the money by simply using

// highestBidder.send(highestBid) is a security risk

// because it could execute an untrusted contract.

// It is always safer to let the recipients

// withdraw their money themselves.

pendingReturns[highestBidder] += highestBid;

}

highestBidder = msg.sender;

highestBid = msg.value;

HighestBidIncreased(msg.sender, msg.value);

}



/// Withdraw a bid that was overbid.

function withdraw() public returns (bool) {

uint amount = pendingReturns[msg.sender];

if (amount > 0) {

// It is important to set this to zero because the recipient

// can call this function again as part of the receiving call

// before `send` returns.

pendingReturns[msg.sender] = 0;



if (!msg.sender.send(amount)) {

// No need to call throw here, just reset the amount owing

pendingReturns[msg.sender] = amount;

return false;

}

}

return true;

}



/// End the auction and send the highest bid

/// to the beneficiary.

function auctionEnd() public {

// It is a good guideline to structure functions that interact

// with other contracts (i.e. they call functions or send Ether)

// into three phases:

// 1. checking conditions

// 2. performing actions (potentially changing conditions)

// 3. interacting with other contracts

// If these phases are mixed up, the other contract could call

// back into the current contract and modify the state or cause

// effects (ether payout) to be performed multiple times.

// If functions called internally include interaction with external

// contracts, they also have to be considered interaction with

// external contracts.



// 1. Conditions

require(now >= auctionEnd); // auction did not yet end

require(!ended); // this function has already been called



// 2. Effects

ended = true;

AuctionEnded(highestBidder, highestBid);



// 3. Interaction

beneficiary.transfer(highestBid);

}

}

 

First, let us take this opportunity to also see the various datatypes that solidity gives us:

  1. Uint – unsigned int that can take only positive values.
  2. Address – a type that is created in ethereum that can store wallet addresses.
  3. Mapping – mappings are very useful to keep track of key value pairs. They are declared as mapping(_KeyType => _ValueType). If we make the KeyType as an address, we can keep track of certain information against a particular address.
  4. Bool – a boolean variable that can be ether true or false.

Let us also take time here to talk about Events and what they mean in solidity. Events let other programs (or even your own program) listen to this particular event on the blockchain and then react after it is executed. As soon as the event is fired, all the parameters that are called with the event are passed on the code that is listening to it and can do some additional operations on the code. This is very useful for Javascript callbacks that might be interacting with our Dapp.

Now let’s have a look at the code – we start off by declaring the date for end of the auction in Unix timestamp format. We also store the address and the bid of the highest bidder in address and uint format. We also have a mapping where we map the address of people to the amount that they bid and how much of that bid is left to withdraw. We have a Boolean variable to signal if the auction has ended or not.

Next we have the constructor – constructors in Solidity have the same name as the contract and have to be public in scope.  In this contract, we use to initialize the variables and set the ending date of the auction.

The next function in our code is bid() which is public and has the modifier called payable – payable is a modifier that lets solidity know that this function can send and receive ether.

The function first checks if the auction is still happening. This is done through the require statement that exits the function if the condition is false. The next condition we check if is the bid that we just sent is the highest current bidder – if it is not, then we do not need to do anything further.

If it is, we continue and store the address and value of the highest bid we also raise an event called HighestBidIncreasd so that anyone listening for this event can know and take appropriate action. The way we know the bid amount that was sent to this function (in the form of ether) is by accessing one the default variables that are available to use in Solidity. The one we use in this case is called msg.value and it tells us the value of ether that was sent to the function.

The next function we look at is called withdraw() and that basically checks the pendingReturns of that address by referencing the mapping with the address that is calling this function. Then we set the amount that the person owes as 0 and then send his bid back.

The last function we can look at is the auctionEnd() – this function denotes that the action has ended. We first check if this function has not been called before. Then we raise the event that the auction has ended and then we transfer the amount of the highest bidder to the beneficiary.

If you want, you can copy past this code in Remix and then run it. Make sure that you send different amounts of ether from different addresses and see what happens. You would want to test it out on Javascript VM – that is the easiest and quickest way.

The next step we are going to take now is to integrate our Code that we have written to perform the auction with our web application. The HTML aspect of the page is just normal HTML is nothing special.

 

How To Code A Decentralized Applications or Dapps

The HTML for the Auction app that we are making.

 

Web3

Web3 is the javascript library that we can include in our project to help us talk to the underlying contract and make calls to and from the ethereum blockchain. The web3 library is what interfaces between our web application and our server side code that is written on the blockchain via smart contracts.

How To Code A Decentralized Applications or Dapps

Image Credits: https://twitter.com/feindura/status/895291220657831936

How to integrate with Web3

You can install Web3 either via npm, meteor or just by including the javascript library that can be downloaded.

TestRPC.

A simple way to get started with interacting with the blockchain through our smart contract is to have a local instance of the blockchain running in your system. This way you can develop and checking things quite quickly and don’t need to worry about things like block confirmation timings. This local instance of the blockchain is called TestRPC.

The easiest way to get started with TestRPC is via npm. If you don’t know what npm is or don’t have it installed, you should install node.js for your operating system. Then in the command line type in:

https://www.npmjs.com/package/ethereumjs-testrpc

Once the command finishes, you can start testrpc by running the command:

testrpc

This is what your screen should look like after you have run this command:

How To Code A Decentralized Applications or Dapps

Running TestRPC on your computer

TestRPC not only sets up a private instance of a blockchain, but it also creates 10 default accounts for you and each of those have a balance of 100 ETH in them. As you can see, it quite favourable for testing out and does all the heavy lifting for you.

You can also connect your remix to the TestRPC so that your contracts are deployed on TestRPC instead of the javascript VM that remix provides.

The way to do that is to go to remix and then click on the Run tab on the right hand side. Then in the environment drop down click on Web3 Provider. It will then ask you if you want to connect to a node, after which it will show you localhost:8545 just click okay and you should be connected. If you got an error in this place, make sure that your URL is not https but http.

One that is done, you can click on the create button and your contract should be deployed on testRPC on your local system. Next, go to the complier tab and click on details and in the popup that comes, click on the copy button on the ABI section. Now we have the ABI for the contract with us. We also should copy the contract address and us that in the javascript code that is given below.

What is ABI ?

The best way to understand what an ABI is, is to compare with an API. Just like an API gives us the specifications that are needed to interact with an endpoint on the web, similarly, an ABI tells us the specifications that are needed to interact with the smart contract. It tells us of the various ways in which this contract can be called from an external source (like web3 in our case)

It is a combinations of knowing the ABI and knowing which address the contract is deployed that we can call our solidity powered smart contracts from a web interface.

if(typeof web3 != 'undefined'){
console.log("Using web3 detected from external source like Metamask")
this.web3 = new Web3(web3.currentProvider)
}else{
this.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))
}

const MyContract = web3.eth.contract([here goes the ABI interface])

this.state.ContractInstance = MyContract.at("0x925d81c01d878899adbb7d38f84ce9d5284fa2e7")
}



The above piece of code lets you connect to the contract address and gives you an object through which you can interact with the contract and call a specific function.

yourContractInstance.bet(7, {
gas: 300000,
from: web3.eth.accounts[0],
value: web3.toWei(0.1, 'ether')
}, (err, result) => {
// Result is the transaction address of that function
})

 

Here we are calling our contract function with the value 7 and by setting certain default parameters that are needed.

We can call other methods of the contract as well and it is through this that  we have now connected with the TestRPC and are able to make calls to the contract via the Web3 API.

Now we can tie this up with the usual javascript or jquery events that we are used to. We can trigger to call the function on the click on the button or on some other event. What is important to note is that the only piece of backend code that our app is talking to is the Solidity based smart contracts hosted on our testRPC.

Now that we have replaced the computing part of our Dapp we have taken the first major step to building our own Dapp. Even if you are not particular about the other parts of a Dapp, you can actually host this online itself and it would be your first Dapp that is available to the public. The only major change that you will need to make before deploying this to point the web3 towards either of public test networks (Kovan Or Ropsten) and these you would have the re-deploy the contract on the new network.

Ethereum test nets that are available for testing. Source:

Hope with this you should be on your way to implementing your very first Dapp and get it talk to the blockchain for data and computing. The idea of blockchain and Dapp can be quite overwhelming; however, if one takes the time to understand the new paradigm and get a hang of it, developing and making Dapps should be a piece of cake.

Go ahead and decentralize.

Join over 115,115 Members
Angel Investors, Startups & Blockchain developers...
Yes, Get Access!
No Thanks!

Comments

    Hi,
    I tried to use the sample code on Remix and had some error messages pop up. Not sure if this issue is limiting how I can use the deploy and create tabs, too. Great article, would love to get more experience learning this…
    Hi, I just paste the two samples (SimpleStorage and SimpleAuction) in Remix and see no error messages beside some warnings. I can create the contract in Run tag with results with JavaScript VM.