Ethereum Dapp Development on Windows for Dummies

Build Your Ethereum DApp On Windows With Truffle, Ganache And Metamask
 
In this tutorial, I am going to show you how simply you can develop an Ethereum DApp from scratch using Truffle, Metamask, and Ganache. To set up your system with necessary dependencies, refer to my previous article and set up your system to begin developing your first DApp.
 
Before we dive into the development, let me give you an overview of the architecture of Ethereum DApp we are going to develop and how different puzzles are going to fit into the picture. So, let’s start the journey to build your Ethereum DApp.
 

What are Ethereum DApps?

 
DApps are the decentralized applications that run on a peer-to-peer network, unlike traditional web apps that run on centralized servers. When these DApp are built over the Ethereum network, these are known as “Ethereum DApps”. In decentralized apps, all the user data is stored on immutable distributed ledger and every participating node has a copy of that ledger. These DApps' logic that runs on the blockchain nodes is written in solidity language and traditionally called as “smart contracts”.
 

The architecture of our Ethereum DApp

 
Build Your Ethereum DApp On Windows With Truffle, Ganache And Metamask
 
Client’s Browser
 
It is just like a normal browser of any web application written in HTML, CSS, and JavaScript.
 
Web3.js
 
Web3.js is a collection of libraries that enables your browser to interact with the blockchain. It enables you to read and write data from smart contracts, transfer ethers between accounts and much more.
 
Web3 Provider
 
Ethereum network contains nodes and all nodes share the same copy of data. Setting a “web3 provider” in web3.js tells our code which node we are going to read and write data from. We are using Metamask in our implementation that injects its web3 provider in the browser. Metamask is a browser extension for Chrome and Firefox that lets users securely manage their Ethereum accounts and private keys, and use these accounts to interact with websites that are using Web3.js.
 
Ethereum Virtual Machine
 
Every Ethereum node in Ethereum network runs their own EVM implementation and is responsible for running the same instructions of smart contracts over the Ethereum network.
 
Ok, that’s all about the theory to wake you up. Let’s start with the development.
 

What we are going to develop?

 
We are going to develop a simple decentralized newsfeed system. News publisher can post news on blockchain with their account addresses. This news will be immutable and displayed in the same order as they are posted.
 
Our Final DApp will look something like this,
 
Build Your Ethereum DApp On Windows With Truffle, Ganache And Metamask
 
You can refer to the code at GitHub anytime you face issues. But I urge you to code each step yourself along with me.
 
Step 1 - Setting up the Structure
 
I presume that you have set the development environment already. In command prompt create a new directory and unbox “truffle-box” in that respective directory to get the structure of the project.
 
 mkdir postnews
cd postnews
truffle unbox pet-shop
 
This will set up the following basic structure in your folder,
 
Build Your Ethereum DApp On Windows With Truffle, Ganache And Metamask
 
Let’s examine the project structure Truffle Box gave us.
 
Contracts - As obvious with the name, all our smart contracts will reside here.
 
Migrations - Includes Migration files to migrate smart contracts to blockchain.
 
Node_modules - Contains all node dependencies
 
Src - Home for all client-side application code
 
Test - Where we write tests for our smart contract either in solidity or JavaScript. We are not going to write any tests in our implementation because we are building a basic implementation of Dapp. But tests are important to write when you are working on commercial projects because each migration of smart contract on blockchain causes gas cost. Thus, you want to make sure that your smart contracts are bug-free and perform the intended functionality.
 
Step 2 - Writing Smart Contract
 
Create a new file news.sol in contract folder and write the following code in it.
  1. pragma solidity >=0.4.0 <=0.6.0;  
  2.   
  3. contract news{  
  4.     struct newsfeed{  
  5.         address publisher;  
  6.         string newsdesc;  
  7.     }  
  8.     mapping(uint => newsfeed) public newsfeeds;  
  9.     uint public newsCount;  
  10.   
  11.     function addnews(string memory newsdesc) public {  
  12.         newsCount++;  
  13.         newsfeeds[newsCount].publisher = msg.sender;  
  14.         newsfeeds[newsCount].newsdesc = newsdesc;  
  15.   
  16.     }  
  17. }  
Let me explain this code. First, we specify that the current code is runnable on the solidity compiler version greater than 0.4.0 and smaller than 0.6.0 with “pragma solidity”. Then we initialized the contract and initialized the structure of our newsfeed containing the address of publisher (initialized with address data type) and the news itself (initialized with string data type).
 
To store this created structure we have created a mapping that is just like a key-value pair. The key to mapping is an unsigned integer and the value is the “newsfeed struct”.
“newscount” keeps track of the number of posted news and initially 0. The Addnews function will store publisher address and news in the struct referenced by the key value. “msg.sender” gets the address of account which has called the contract.
 
Simple. Isn’t it? Now let’s compile this smart contract to see if it runs properly. To do this, navigate to your project folder in the console and write.
 
truffle compile
 
Build Your Ethereum DApp On Windows With Truffle, Ganache And Metamask
 
Now let's migrate our current smart contract on Ganache. To do this, create a new file in Migration folder named “2_deploy_contracts.js”. Paste the following code in that file to migrate your contract,
  1. var news = artifacts.require("./news.sol");  
  2. module.exports = function(deployer) {  
  3.     deployer.deploy(news);  
  4. };  
Save it and in console type,
 
truffle migrate
 
Make sure that Ganache is open and running while you migrate your contract. And hurrah! Your contract is successfully migrated to Ganache.
 
Build Your Ethereum DApp On Windows With Truffle, Ganache And Metamask
 
Step 3 - Developing a client-side application to interact with the contract
 
Go to your index.html file and paste the following code.
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3.   <head>  
  4.     <meta charset="utf-8">  
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.     <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->  
  8.     <title>Decentralized Newsfeed</title>  
  9.   
  10.     <!-- Bootstrap -->  
  11.     <link href="css/bootstrap.min.css" rel="stylesheet">  
  12.   
  13.     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->  
  14.     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->  
  15.     <!--[if lt IE 9]>  
  16.       <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>  
  17.       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>  
  18.     <![endif]-->  
  19.   </head>  
  20.   <body>  
  21.     <div class="container">  
  22.       <div class="row">  
  23.         <div class="col-xs-12 col-sm-8 col-sm-push-2">  
  24.           <h1 class="text-center">Decentralized Newsfeed</h1>  
  25.           <hr/>  
  26.           <br/>  
  27.         </div>  
  28.       </div>  
  29.   
  30.       <div id="newsRow" class="row">  
  31.         <!-- PETS LOAD HERE -->  
  32.       </div>  
  33.       <!-- <button class="btn btn-default" type="button" class="aaaaaddProd">Add Product</button> -->  
  34.      <!-- Button trigger modal -->  
  35.   <button type="button" style="align:center;" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">  
  36.     Add News  
  37.   </button>  
  38.     </div>  
  39.   
  40.      
  41.     
  42.   <!-- Modal -->  
  43.   <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">  
  44.     <div class="modal-dialog modal-dialog-centered" role="document">  
  45.         
  46.       <!-- Modal Content-->  
  47.       <div class="modal-content">  
  48.   
  49.         <!--Modal Header-->  
  50.         <div class="modal-header">  
  51.           <h5 class="modal-title" id="exampleModalCenterTitle">Add News</h5>  
  52.           <button type="button" class="close" data-dismiss="modal" aria-label="Close">  
  53.             <span aria-hidden="true">×</span>  
  54.           </button>  
  55.         </div>  
  56.         <!--Modal Body-->  
  57.         <div class="modal-body">  
  58.             <form>  
  59.                 <div class="form-group">  
  60.                   <textarea class="form-control postbox" id="post" placeholder="Add you story Here..." rows="5"></textarea>  
  61.                 </div>  
  62.                                   
  63.                 <button type="submit" data-dismiss="modal" class="btn btn-primary addNews">Post News</button>  
  64.               </form>  
  65.         </div>  
  66.   
  67.         <div class="modal-footer">  
  68.           <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>  
  69.         </div>  
  70.       </div>  
  71.     </div>  
  72.   </div>  
  73.   
  74.     <div id="postTemplate" style="display: none;">  
  75.   
  76.       <div class="col-md-12">  
  77.         <div class="panel panel-default panel-pet">  
  78.   
  79.           <div class="panel-heading">  
  80.             <strong>Publisher Address</strong> <h3 class="panel-title"> Account Address </h3>  
  81.           </div>  
  82.   
  83.           <div class="panel-body">  
  84.   
  85.             <strong>Descrition</strong>: <span class="desc"> </span><br/>  
  86.   
  87.           </div>  
  88.         </div>  
  89.       </div>  
  90.     </div>  
  91.   
  92.     <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->  
  93.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>  
  94.     <!-- Include all compiled plugins (below), or include individual files as needed -->  
  95.     <script src="js/bootstrap.min.js"></script>  
  96.     <script src="js/web3.min.js"></script>  
  97.     <script src="js/truffle-contract.js"></script>  
  98.     <script src="js/app.js"></script>  
  99.   </body>  
  100. </html>  
Ok! Don’t scare yourself; it’s just some simple HTML. Let me go through it. The Add News button is navigating to the model that opens a dialogue for adding news. “Posttemplate” contains the layout of how your posts will be displayed on the screen.
 
To make this code in action let's write some code in app.js and see how it is going to link up with our smart contract.
 
In your “app.js” file, first, add the following code to set up the web3 provider for web3.js in the browser.
  1. App = {  
  2.   web3Provider: null,  
  3.   contracts: {},  
  4.   
  5.   initWeb3: async function() {  
  6.     // Modern dapp browsers...  
  7.     if (window.ethereum) {  
  8.       App.web3Provider = window.ethereum;  
  9.       try {  
  10.         // Request account access  
  11.         await window.ethereum.enable();  
  12.       } catch (error) {  
  13.         // User denied account access...  
  14.         console.error("User denied account access")  
  15.       }  
  16.     }  
  17.     // Legacy dapp browsers...  
  18.     else if (window.web3) {  
  19.       App.web3Provider = window.web3.currentProvider;  
  20.     }  
  21.     // If no injected web3 instance is detected, fall back to Ganache  
  22.     else {  
  23.       App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');  
  24.     }  
  25.     // App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');  
  26.     web3 = new Web3(App.web3Provider);  
  27.   
  28.     return App.initContract();  
  29.   },  
Extend app.js with the following code.
  1. initContract: function() {  
  2.     $.getJSON('news.json'function(data) {  
  3.       // Get the necessary contract artifact file and instantiate it with truffle-contract  
  4.       App.contracts.news = TruffleContract(data);  
  5.       
  6.       // Set the provider for our contract  
  7.       App.contracts.news.setProvider(App.web3Provider);  
  8.       
  9.       // Use our contract to retrieve and mark the adopted pets  
  10.       // return App.markAdopted();  
  11.       return App.init();  
  12.   
  13.     });  
  14.   
  15.     // return App.bindEvents();  
  16.       return App.AddNewsButton();  
  17.   
  18.   },  
When we compile our contract “news.json” is created in the build folder. Truffle has a library called “TruffleContract” that keeps information about the contract. So using this library we set web3 provider for our contract. This enables our client-side application to interact with our smart contract deployed on blockchain.
 
Move forward and add the following code in app.js,
  1. AddNewsButton: function() {  
  2.     $(document).on('click''.addNews', App.AddNews);  
  3.   },  
  4.   AddNews:function(event){  
  5.     var post = document.getElementById('post').value  
  6.     var postInstance;  
  7.     App.contracts.news.deployed().then(function(instance){  
  8.       postInstance = instance;  
  9.       return postInstance.addnews(post);  
  10.     });   
  11.     console.log("News posted");  
  12.   },  
  13. };  
This code will take the user-entered news and pass it to our add news function in smart contract. Smart contract will write the publisher address and news on blockchain using mapping.
 
Finally, add the following code in app.js to render the HTML template with data on every page reload so your news will be displayed.
  1.   init: async function() {  
  2.     // Load Products.  
  3.     var postInstance;  
  4.   
  5.     App.contracts.news.deployed().then(function(instance){  
  6.       postInstance = instance;  
  7.       return postInstance.newsCount();  
  8.     }).then(function(result){  
  9.   
  10.       var counts = result.c[0];  
  11.       console.log("Total News : "+counts);  
  12.   
  13.       for (var i = 1; i <= counts; i ++) {  
  14.         postInstance.newsfeeds(i).then(function(result)  
  15.         {  
  16.           console.log("Publisher Address:" +result[0]);  
  17.           console.log("News:" +result[1]);  
  18.   
  19.           var newsRow = $('#newsRow');  
  20.           var postTemplate = $('#postTemplate');  
  21.   
  22.           postTemplate.find('.panel-title').text(result[0]);  
  23.           postTemplate.find('.desc').text(result[1]);  
  24.           newsRow.append(postTemplate.html());  
  25.          });  
  26.       }  
  27.     });   
  28. },  
‘i’ initialized with 1 is passed as a key to newsfeeds mapping. This will fetch the structure details on index i. Structure details are just like an array having “publisher address” at 0 index and “newsdesc” at 1 index. This data will be retrieved from smart contract and append to “postTemplate” in index.html.
 
Now, in your console, type “npm run dev” to run your DApp.
 
Build Your Ethereum DApp On Windows With Truffle, Ganache And Metamask
 
This will open the DApp in your browser. Make sure you are logged in with metamask and it's running on port 7545.
 
Build Your Ethereum DApp On Windows With Truffle, Ganache And Metamask
 
Kudos! You have successfully developed your Dapp. Happy Coding!