How To Code A Decentralized Applications or Dapps
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).
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
- The application’s source code must be open sourced.
- The application’s data and records must be stored on a public blockchain.
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:
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 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.
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.
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:
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)
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.
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.
First, let us take this opportunity to also see the various datatypes that solidity gives us:
- Uint – unsigned int that can take only positive values.
- Address – a type that is created in ethereum that can store wallet addresses.
- 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.
- Bool – a boolean variable that can be ether true or false.
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.
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.
The HTML for the Auction app that we are making.
Image Credits: https://twitter.com/feindura/status/895291220657831936
How to integrate with Web3
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:
Once the command finishes, you can start testrpc by running the command:
This is what your screen should look like after you have run this command:
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.
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.
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.
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 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.