Build Complete Ethereum Application

Build Complete Ethereum Application.

Here i simply describes how to build complete Ethereum Application from the scratch. As the initial step i describe Ethereum javascript API. We can use that API to interact with Ethereum Contracts (Robot Account). I will give you a sample example for using Web3 object. Then i will introduce our application architecture and finally i will bring you the complete video coverage for building the application. Okay let's we start with Web3 object.

Ethereum javascript API

We can call Contract functions using this API(Web3). Actually this API is available through Web3.js Library. This will save your day because you don't want to write the boilerplate code that you have to write without this library. There is a java lib for this it is called Web3j. As well as there are several number of Web3 implementations for different languages and i list down them below.
  • Python Web3.py
  • Haskell hs-web
  • Java web3j 
  • Scala web3j-scala 
  • Purescript purescript-qwb3
  • PHP web3.php 
Okay what is the boilerplate code that i have to write if Web3 is not there?
I have to write the code for Remote Procedure Calls (JSON RPC calls) from the client to the Ethereum Network if i haven't integrate Web3. Besides that Web3 provides asynchronous and Synchronous versions. If you do Web3 API call with a callback function then it will recognize as the usage of asynchronous version.

 Also you can interact with Metamask using this API(I introduce Metamask one of my previous tutorial) because Metamask injects a Web3 object into the browser and it starts to behave like a proxy between the Ethereum Network and your application.



How Web3 Library interact with EVM

Let's we talk about what is ABI in solidity?

ABI is stands for Application Binary Interface. Before we learn what is Ethereum ABI, first we discuss what is the difference between API and ABI.


APIABI
Public types, variables, functions that your application exposes (human readable)This is how compiler build the application for computer to  understand instructions and execute functionality. We can say this is the machine language instruction that computer can understand. 

So Ethereum ABI is a kind of instruction set that EVM can understand (JSON Interface). You can generate ABI for each Contract. You can get Contract's ABI from the Remix IDE after compiled the Contract by clicking the Details button on right side top of compile Tab Pane.

Before Move to the project structure

Lets we study how Web3 deal with Ethereum Network. Please study the following diagram

Okay let me explain this. We have to host our HTML + Web3.js in a server first of all. Then users can call the UI using the relevant URL. Once the user loaded the UI using his browser then he can simply do a transaction(Transfer Ether), Deploy a Contract or calling a function of a deployed contract.

If user did a simple Transaction (i mean without calling a Smart Contract) then that particular  transaction should sign with the User Account Private key. If you have accessed your Ethereum account (node) with the Metamask Extension (Ethereum Client Application) then signing part will be handled by the Metamask. Actually what happen is once you call a written function in Web3.js using your UI, Metamask will pop up and ask to accept the transaction (I will show this in a future video).
Once you accept the transaction(signed) that particular transaction is released to the  Ethereum Network using the Client Account. Then all the mining process is happened and transaction details are added to the Blockchain.After all you will get the transaction receipt.

Transaction Receipt contains following information :

blockHash: String, 32 Bytes - hash of the block where this transaction was in.
blockNumber: Number - block number where this transaction was in.
transactionHash: String, 32 Bytes - hash of the transaction.
transactionIndex: Number - integer of the transactions index position in the block.
from: String, 20 Bytes - address of the sender.
to: String, 20 Bytes - address of the receiver. null when its a contract creation transaction.
cumulativeGasUsed: Number - The total amount of gas used when this transaction was executed in the block.
gasUsed: Number - The amount of gas used by this specific transaction alone.
contractAddress: String - 20 Bytes - The contract address created, if the transaction was a contract creation, otherwise null.
logs: Array - Array of log objects, which this transaction generated.
 
But let's imagine you did a transaction that contains some processes related to a Smart Contract. Then the process is happened in this way. Up to adding the mined transaction to a Block of a Node is quiet similar to the above scenario.  But when adding the mined transaction to a block by relevant Node, it will validate the transaction again(but it doesn't generate the Nounce again because this is already mined. this is just validating the transaction status) and same time it will execute the Smart Contract. After that relevant Contract Instance take over the further processing related to the business logic written in the Contract. If you remember contract has a memory, code and Ether. So Contract related data is stored in the Contract Storage. In this way our node also run the Contract and will get the results. Then we can available particular values from the Web3 API.

Let's create the folder structure

To initiate the folder structure just hit : truffle unbox webpack.
If the command worked correctly you will find the following folder structure.


Let's run the newly generated project.

In order to run the project just hit the following command,
 - on new terminal, hit : testrpc // will start the Ethereum Test Server
 - on another new terminal, hit : truffle compile // compile the solution
 - in same terminal hit : truffle migrate
 - finally start the development web server. Actually this command will produce a server for development purposes and will host our application. Command : npm run dev

Ok. Now your demo application can be accessed through the web browser (localhost:8080).   


Okay then i will teach you how to connect METAMASK to our Test application.

Before do that go to the truffle.js file and edit the port as bellow : (8545)
because now Blockchain is running port is 8545. If you go to the testrpc console you will see it. 


 Okay now we are ready to connect to the Metamask. I will explain that process following video.








Application Structure

Git : Smart Car Tracking

This application is designed with a new concept call car tracking. Let's assume X smart car company is going to release this application with their sellers and brand new customers. Sellers are the agents who register brand new customers to this application related to a car. Then with the time one car has many block of records (Tire changes, Oil changes, Max speed and so on). Here the smart car has a account in the block chain and it automatically connected to the network with a account and it release its current details to the network with a periodic manner. Also owners can keep their car related private details as well.

Here i don't have a smart cars 😜. So the duty of the smart car in this application is going to be done by manually for the demonstration. 

So what is the purpose of this application? : We can get the benefits of this application for the second-hand market. If someone really want to buy a car from the second hand market then he can search for specific valid history of cars to decide which car is the best fit for me. By the way new customers who searching for second hand market have to pay some initial cost to buy specified Ether amount for his account balance (use coinbase or other Ether Provider). If that particular second-hand customer wants to get the selected car details (through application filters) then current owner of the car should accept the sharing car details request and the buyer has to transfer some amount of Ether to the current car owner.

 

Recreate project structure

We created the project structure with the command truffle unbox webpack. But the problem is we do not need some files in the generated project structure. So now i am going to remove those unnecessary files.
Follow the video : 



Okay, now we have the correct project structure. Let's develop the project.

1st Phase : 

In this phase i simply develop the Car tracking related Contract only. Here the concept is one car has a one Contract Instance.And one instance contains many trail counts.  And one trail count contains one details set at a time. Finally i set the data set (struct) against the trail count using a map.


Git Sample Code for : SmartCarStorage


2nd Phase : 

Git Sample Code for : app.js
Let's we discuss how to connect your application UI to TestRPC Ethereum Local Server by using Web3.js API. We use app.js file in the project structure to write javascript functions related to the contract. So first of all you have to import the Web3.js library at the top of the file. Then simply initiate web3 as following. Just go to my Git project above and study how i defined this part.


if (typeof web3 !== 'undefined') {
 
 web3 = new Web3(web3.currentProvider);
 
} else {
 
 // Set the provider you want from Web3.providers
 web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
 
}
 

Actually at there you will see this piece of code as well. 


window.App = {
  // All the java script functions  
}
window.App = App // it simply define the Application and now you can add  event listeners
window.addEventListener('load', function() {
 // Web3 initialize code 
 App.start() // after initialized the application is started. start function is defined window.App = {}
}) 


3rd Phase

Then connect your Ethereum wallet and setup the default account. Here default account is considered as the first account that imported to the wallet. One of my previous tutorial i have shown how to do it. Also here i use "eth". Normally it contains Ethereum Blockchain related methods.

window.App = { 
  start: function() {
    web3.eth.getAccounts (function (err, accounts) {
      if(err!==null) {
        alert("Error while retrieving accounts !!!")
        return 
      }
      if(accounts.length == 0) {
       alert("We couldn't get any accounts. Please make sure you have configured Ethereum client correctly")
       return  
      } 
      // set the default account to eth 
      web3.eth.defaultAccount = accounts[0]
    })
  }

} 

4th Phase

This is the most important part. Now you have to get the Smart Contract ABI using the Remix IDE and initialize the ABI for eth. From here we use this ABI to contact our SmartCarStorage functions.
This phase is also write in the start function above. It is better to put this function after initializing your default Account.
Here simply remember to create a global variable for the eth ABI because we can use that variable as the common ABI inside the other functions.

Var smartContract
smartContract = web3.eth.contract([ABI object])

5th Phase

In this step we deploy our contract and create a new instance of the SmartCarStorage Contract. Now we start writing our other functions apart from the "window.App={start: function() { ... }}".

window.App = {
  start: function() {...}
  //new function  
  createNewInstance: function () {
        console.log("Create new Instance")
        smartCarContract.new(
            {
              from: web3.eth.accounts[0], 
              data: '0x60806040526000600160006101000a81548160ff021916908360ff160217905550610f8a8061002f6000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063010c0119146100725780632117f6ca1461015557806335a75805146102fd57806363d1e8931461048557806373f0101c1461059a575b600080fd5b34801561007e57600080fd5b506100a0600480360381019080803560ff1690602001909291905050506105cb565b604051808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001838152602001828103825284818151815260200191508051906020019080838360005b838110156101185780820151818401526020810190506100fd565b50505050905090810190601f1680156101455780820380516001836020036101000a031916815260200191505b5094505050505060405180910390f35b34801561016157600080fd5b506101a3600480360381019080803560ff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506106e4565b60405180806020018060200185815260200180602001848103845288818151815260200191508051906020019080838360005b838110156101f15780820151818401526020810190506101d6565b50505050905090810190601f16801561021e5780820380516001836020036101000a031916815260200191505b50848103835287818151815260200191508051906020019080838360005b8381101561025757808201518184015260208101905061023c565b50505050905090810190601f1680156102845780820380516001836020036101000a031916815260200191505b50848103825285818151815260200191508051906020019080838360005b838110156102bd5780820151818401526020810190506102a2565b50505050905090810190601f1680156102ea5780820380516001836020036101000a031916815260200191505b5097505050505050505060405180910390f35b34801561030957600080fd5b5061032b600480360381019080803560ff1690602001909291905050506109a3565b60405180806020018060200185815260200180602001848103845288818151815260200191508051906020019080838360005b8381101561037957808201518184015260208101905061035e565b50505050905090810190601f1680156103a65780820380516001836020036101000a031916815260200191505b50848103835287818151815260200191508051906020019080838360005b838110156103df5780820151818401526020810190506103c4565b50505050905090810190601f16801561040c5780820380516001836020036101000a031916815260200191505b50848103825285818151815260200191508051906020019080838360005b8381101561044557808201518184015260208101905061042a565b50505050905090810190601f1680156104725780820380516001836020036101000a031916815260200191505b5097505050505050505060405180910390f35b34801561049157600080fd5b50610598600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610bee565b005b3480156105a657600080fd5b506105af610e3f565b604051808260ff1660ff16815260200191505060405180910390f35b6000606060008060008560ff16815260200190815260200160002060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166000808660ff1681526020019081526020016000206003016000808760ff16815260200190815260200160002060040154818054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156106d05780601f106106a5576101008083540402835291602001916106d0565b820191906000526020600020905b8154815290600101906020018083116106b357829003601f168201915b505050505091509250925092509193909250565b606080600060608473ffffffffffffffffffffffffffffffffffffffff166000808860ff16815260200190815260200160002060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151561075d57600080fd5b6000808760ff1681526020019081526020016000206000016000808860ff1681526020019081526020016000206003016000808960ff168152602001908152602001600020600401546000808a60ff168152602001908152602001600020600501838054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108535780601f1061082857610100808354040283529160200191610853565b820191906000526020600020905b81548152906001019060200180831161083657829003601f168201915b50505050509350828054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108ef5780601f106108c4576101008083540402835291602001916108ef565b820191906000526020600020905b8154815290600101906020018083116108d257829003601f168201915b50505050509250808054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561098b5780601f106109605761010080835404028352916020019161098b565b820191906000526020600020905b81548152906001019060200180831161096e57829003601f168201915b50505050509050935093509350935092959194509250565b606080600060606000808660ff1681526020019081526020016000206000016000808760ff1681526020019081526020016000206003016000808860ff168152602001908152602001600020600401546000808960ff168152602001908152602001600020600501838054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610aa05780601f10610a7557610100808354040283529160200191610aa0565b820191906000526020600020905b815481529060010190602001808311610a8357829003601f168201915b50505050509350828054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610b3c5780601f10610b1157610100808354040283529160200191610b3c565b820191906000526020600020905b815481529060010190602001808311610b1f57829003601f168201915b50505050509250808054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610bd85780601f10610bad57610100808354040283529160200191610bd8565b820191906000526020600020905b815481529060010190602001808311610bbb57829003601f168201915b5050505050905093509350935093509193509193565b610bf6610e56565b84816000018190525083816020019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff1681525050828160600181905250818160a00181905250428160800181815250506000600160009054906101000a900460ff1660ff16141515610cef57600080600160009054906101000a900460ff1660ff16815260200190815260200160002060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16816040019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff16815250505b80600080600160009054906101000a900460ff1660ff1681526020019081526020016000206000820151816000019080519060200190610d30929190610eb9565b5060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060408201518160020160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506060820151816003019080519060200190610ddb929190610eb9565b506080820151816004015560a0820151816005019080519060200190610e02929190610eb9565b509050506001600081819054906101000a900460ff168092919060010191906101000a81548160ff021916908360ff160217905550505050505050565b6000600160009054906101000a900460ff16905090565b60c06040519081016040528060608152602001600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff1681526020016060815260200160008152602001606081525090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10610efa57805160ff1916838001178555610f28565b82800160010185558215610f28579182015b82811115610f27578251825591602001919060010190610f0c565b5b509050610f359190610f39565b5090565b610f5b91905b80821115610f57576000816000905550600101610f3f565b5090565b905600a165627a7a7230582033b472547a4e0b5e1e1e0dd18c5a02bc0c5776ce537c91c1233d3792137002ea0029',
              gas: '4700000'
            }, function (e, contract){
             console.log(e, contract);
             if (typeof contract.address !== 'undefined') {
                var contractAddress = contract.address
                console.log('Contract mined! address: ' + contractAddress + ' transactionHash: ' + contract.transactionHash);
                document.getElementById('contractAddress').value = contractAddress
                const status = document.getElementById('status')
                status.style.color = "green";
                status.innerHTML = "successfully deployed !!!"
             }
          })
    }
  }

So here you have to get the byte code of the SmartCarStorage Contract using the Remix IDE and provide it for data.  Here "from" is the account that we send this request and "gas" is the Gas limit. At the end of the function i get the address of the newly deployed contract instance.

Well done and congrats !!!. Now you have done the application setup correctly. From now you have to write the Contract function calling codes using Web.js.
You can get my full source code here : code ⧫

And here is the video for full application description:


So far i believe you have a great journey with my blog on the way to your Solidity Gall. So please keep it on and do not remember to share and comments for the Blog as well as my you tube tutorial channel .

 ⧫⧫⧫ Cheers ⧫⧫⧫

Comments

Most Popular

Introduction to Blockchain