Blockchain development Quick Starter Guide for Software Developers Using Angular

By April 19, 2021DApps
Click here to view original web page at medium.com

Many companies started to develop application which can run on the blockchain. This article should be enough to get you started if you have basic software development knowledge.

Ethereum is a platform for internal and public projects. Although other blockchain platforms use similar technology behind it, Ethereum is developed to be a great platform for developers and implement smart contracts.

Decentralized Applications(DApps)

In traditional applications, usually, there is a client or user interface which interacts with the user and there is a backend application that handles requests
from this client application. However, the backend application is controlled by a single entity and it can easily be manipulated. Using blockchain, an application can run on multiple computers around the world. This means the application is not controlled by anyone after it is deployed to the network. The entire network behaves like a single computer. In this architecture, these computers are not owned by single organizations. Instead, they are owned by individuals and these individuals can add their computational resource and nobody owns or control the entire network and we can develop applications on top of it.

What are the main advantages of distributed applications?

First of all, the distributed network is reliable. The network cannot be shut down as it is distributed around the globe. In addition to this, it is transparent. Anyone can see the transactions, blocks, and applications in the network. It is also secure as every transaction signed and any fraudulent activity is ignored by the network as the network has to have a consensus on any transaction. This means there is no single point of failure. On top of this, transactions are executed with a small fee, and peers are paid with this fee to execute a transaction. Since peers only execute transactions with public keys of users, the network is anonymous. Therefore there is complete trust in-network and no need to involve third parties.

Even if machines go down, applications will continue to run. They are also secure because nobody can amend them and they are transparent. A single person can’t change it.

What are the main disadvantages of distributed applications?

In addition to advantages, there are disadvantages of distributed applications. Currently, they are still slow compared to traditional applications and speed depends on the entire network's state. If a transaction is being executed by a computer on the other side of the globe, the transaction execution will take longer. Additionally, it is also inefficient at the moment, peers in the network need to solve a puzzle to secure the network and this requires computational power. After executing a transaction and adding a new block to the chain, this block is copied to all peers in the work which requests large Storage on each peer of the network. Also due to the nature of the blockchain, every transaction is read-only and can’t be reverted if any human error happens.

Why Ethereum?

Ethereum is developed from the ground up to be a platform in order to execute applications on the blockchain. The entire network behaves like a computer. In fact, this computer is called the ethereum virtual machine or EVM. This machine’s storage cannot be updated after it is written, it is slow but getting faster every day and it cannot be turned off. It is like Java virtual machine but instead of one computer, applications run on a distributed system and this platform has huge developer community and development skill is in-demand

What can you develop on the blockchain?

Here, Sky is the limit. Any application can be developed on the ethereum platform. Common scenarios are Voting, video platforms, self-executing legal agreements without any lawyer (code is law), supply chains, digital ownerships like NFTs, and much more.

Overall it works like as below

Traditional client or Server applications can easily interact with the ethereum network using web3 API and benefit from the advantages of the network. In this video, we will develop a client which uses ethereum as a backend. So Server will not be required in our example application.

What is blockchain?

As the name suggests, It is like a chain of files linked with previous files and new files can be added by referring latest file on the chain. This is a very simple idea but if you replicate this chain of files across the network, you have a blockchain and a consensus is required to agree on the updates to keep the network secure. If one of the computers fails, it is not important as there are multiple copies in the network. Anyone cannot directly add a new file. In the blockchain, these files are called blocks, each peer in the network has to find a hash that will match the previous file’s hash as in the example. You can read a transaction, write a transaction but you cant update/delete it.

What is a Bitcoin?

It is one of the first implementations of blockchain. Satoshi Nakamoto created the initial version to solve centralized banking-related issues. So Bitcoin doesn’t have any current owner. Finder of the hash codes in the blockchain can earn bitcoin by executing transactions. Bitcoin is just a computer hash value that can be assigned to any other person’s public key. So Bitcoin solved the following problem

The trust : Individuals don’t need to depend on 3rd party such as a bank

Faster transactions: Currency can be sent anywhere in the world in few seconds or minutes

Lower fees: Since entire network acts like one, there is no inter-banking money transfer and this keeps like fees low

How to control changes in the blockchain? Since Nobody owns the network, the source code is open and anybody can change it. However, if you deploy your code to the network, peers or also known as miners may not accept it then your code will work on the peers who accept it. For this reason, sometimes we see forks in blockchain but eventually, the majority of the network decides which network to agree on and globally accepted forks continue to operate.

Ethereum Protocol

Ethereum is quite different than bitcoin. Bitcoin is a fintech solution but Ethereum is a platform. It has a currency called ether as well. So ether is quite similar to bitcoin but some people refer to ether as ethereum but in this course, we will learn the difference in detail. In the ethereum network, everything including transactions is executed by applications called smart contracts. Of course, code execution requires computational power, and the user of the networks need to pay for it. You pay the fee in gas. Gas is a small fraction of ether cryptocurrency.

Smart Contracts

One of the biggest advantages of Ethereum is smart contracts. You can also develop a smart contract on bitcoin but it is not designed for it. A smart contract is software that runs on the network and can be executed. In this article, we will learn how to write a simple smart contract and deploy it to the network. Our sample application will be running on the network all the time, So it can’t be turned off and it will be readonly.

What is a Wallet?

It is just a private and public key combination. The private key is like your password and the public key is like your account number. However, Blockchain network doesn't even know about your private and public key unless any transaction request happens. This means you can create your wallet offline. Later if there is any transaction that involves your public key, blockchain just assigns or increments a value for your public key. Since you are the only person can issue transaction using your private key, Only you can control your public key also known as your wallet address.

DEMO

Let's get started

First, install a wallet. Any wallet would work but I will be using metamask

and switch to Rinkeby networks which will be used for testing.

Since this is a test network, you can get either for free using the link below

Tweet your public address to get free ether.

Now, we can test our code in the test network

We are ready to write our first smart contract. Multiple languages are supported but Solidity is a common choice. It is a javascript-like language and easy to learn.

You can develop applications locally but instead of setting up an environment, we will use an online IDE called Remix.

Delete the files with extension .sol in Remix and create a helloworld.sol and paste the code below. It will just execute hello world application on the network.

pragma solidity >=0.7.0 <0.9.0;contract HelloWorld {

string public message;constructor() public {
message = "Hello World!";
}function speak() public returns(string memory itSays) {
return message;
}function saySomethingElse(string memory newMessage) public returns(bool success) {
message = newMessage;
return true;
}function remove() public {
address payable addr = payable(address(msg.sender));
selfdestruct(addr);
}
}

and make sure it is compiled and then it can be deployed

Now lets develop more complex application. This application will keep track of votes for a referendum.

pragma solidity >=0.7.0 <0.9.0;    uint[] public votes=[0,0];
mapping (address => bool) hasVoted;

function vote(uint option) public {
require(0 <= option && 2 < option, "Invalid option");
require(!hasVoted[msg.sender], "Vote change is not allowed");
hasVoted[msg.sender] = true;
votes[option] = votes[option] + 1;
}
function getVotes() public view returns (uint[] memory) {
return votes;
}
function remove() public {
address payable addr = payable(address(msg.sender));
selfdestruct(addr);
}
}

In this example, instead of defining a solidity version, we define a range. This range will be used for peers in the network and only eligible peers can be able to execute it.

Then we define votes to object to keep “yes” and “no” votes. It is a simple array. Then hasVoted hashmap is defined to keep track of people who already voted. Using this hashmap and require methods, we can prevent people to vote again. Require is like an assert in Java and it helps us with validation. After validating the code, we can increment our votes object with the vote.

We will use getVotes method to get the results from the network. This method won’t change the network state. Therefore it won't require any gas during execution. This is only a readonly operation.

In summary, this application will be running all the time and the only the owner can remove it and nobody can’t change the votes.

Developing the frontend

We will use our Smart Contract as a backend and we will develop a frontend for it. First install nodejs. Later using NPM, install angular-cli using the command below

npm install -g @angular/cli

Now we are ready to create the angular application using the command below

ng new angularClient

We will also need web3 api to interract with Ethereum network. Inside the project directory (angularClient), execute the following command.

npm install web3 --save

In order to make angular work with web3 API, we need ngx-buld-plus. It can be installed with the following command.

ng add ngx-build-plus

We also need to create webpack.config.js in project’s root directory.

Now update angular.json file as below

"architect": {
"build": {
"builder": "ngx-build-plus:browser",
"options": {
...
"styles": [
"src/styles.css"
],
"scripts": [],
"extraWebpackConfig": "webpack.config.js"
},
"configurations": {
...
},
"serve": {
"builder": "ngx-build-plus:dev-server",
"options": {
"browserTarget": "cli1125:build",
"extraWebpackConfig": "webpack.config.js"
},
...
},

We are ready update the sample code and create our UI. My editor of choice is visual studio code. After opening app.component.ts , import Web3

import Web3 from “web3”;

Then create a json file called ContractABI.json under src directory and import it as well. ABI is the definition of the smart contract and our application will use this definition to call the smart contract. ABI value can be copied from the remix IDE as

const  ContractABI = require('./ContractABI.json');

Declare a global variable in app.components.ts as well.

declare let window: any;

Now we are ready to define some variables to use on UI and create the constructor.

constructor() {new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545")this.contract= new this.web3.eth.Contract(

Now lets define getsVotes function as below

Now we are ready to implement vote function

const accounts = await window.ethereum.enable();const account = accounts[0];.send({ from: account, gas });

Lets also improve our html as below

<div class="card highlight-card card-small"><div class="card highlight-card card-small">

Now UI should be similar to below

In summary, we developed a smart contract and deploy to the network. Our Angular based UI uses this smart contract to create a trusted and transparent application. Entire source code can be found at the github repository.

Also, Read

Leave a Reply