Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptCreating dApps using the Truffle Framework

Creating dApps using the Truffle Framework

dApps (Decentralized Applications) are applications that do not rely on traditional servers. Instead, dApps make use of Blockchain to host the data traditionally stored on the servers. The data is stored across the network of nodes connected to the Blockchain. Various tools and frameworks are used to write full-stack, decentralized applications. One such popular framework for writing dApps using the Solidity programming language is Truffle. Truffle provides a basic scaffolding to design dApp projects. Using Truffle, we can create the smart contracts required to create the blockchain functionality, write unit tests for the functions, and design the front-end design of the dApp. 
The basic steps for designing a full-stack dApp are as follows: 
 

Overview of steps in designing a dApp

Fig 01: A sequence of steps that are followed in general to write dApps

Step 1: Setting up the Development Environment: The requirements before starting a Truffle project are as follows: 

  • Node.js
  • Ganache — For simulating a Blockchain locally.
  • Metamask — For handling Blockchain transactions via the browser.

To set up the Truffle framework, run the following command:

npm install -g truffle

For the purposes of development, instead of using the real Ethereum blockchain, we rely on the use of either a test network or a local, private Blockchain. To simulate an Ethereum Blockchain locally on your computer, you can use Ganache. Ganache, once installed, may be used either through the command line or using the provided GUI. With Ganache, you get a set of test accounts, each with up to 100 Ether by default, for the process of development. 

Step 2: Use a Truffle Box to generate boilerplate code: To simplify the process of creating a dApp in Truffle, instead of manually creating the files and including the dependencies, you can use a Truffle Box. A Truffle Box provides useful boilerplate code with which you can directly start designing your dApp. These “boxes” also contain other useful components, such as commonly used Solidity Contracts, libraries, front-end views, etc. Depending on the requirements of your project, you can choose a Truffle box from their official website 

truffle unbox pet-shop
truffle unbox react

Step 3: Writing the Solidity Smart Contracts: Once a truffle box is downloaded and unpacked, it creates a Truffle specific directory structure. The general structure of a Truffle project is shown in the figure below:

Truffle Directory Structure

Fig 02: Truffle Directory Structure

  • The contracts directory, all the Solidity smart contracts are written and stored as .sol files.
  • The migrations directory contains code to migrate and deploy the designed contracts.
  • node_modules directory stores all the required node dependencies to run the project.
  • src directory is used to store the front-end components of the project, such as HTML and CSS files.
  • test directory stores the unit tests written by the developer.

The first step, in general, is to design the contract and save it as a .sol file in the contracts directory. A simple example of a Solidity smart contract is shown below:

javascript




pragma solidity ^0.4.4;
 
contract TestContract {
  uint my_id;
 
  function setId(uint x) public {
    my_id = x;
  }
 
  function getId() public view returns (uint) {
    return my_id;
  }
}


Step 4: Compile and Migrate the Contracts: Once the contracts have been written, we can compile and then migrate them to store them on our blockchain. To compile a Solidity contract in Truffle, run the command 

truffle compile

Once successfully compiled, the contracts are converted into bytecode which is executed by the Ethereum Virtual Machine (EVM). After successful compilation, the contracts need to be saved on the Blockchain such that users may access the functions provided by the contract. Once migrated to the Blockchain, each deployed contract is assigned a unique address to reference its location on the Blockchain. When a user wishes to call functions from a certain deployed contract, they are required to call invoke the functions corresponding to the deployed contracts address on the blockchain.
To specify which contracts have to be migrated, we need to specify their references in the migrations directory inside a new file. The file is named as “2_deploy_contracts.js” and is structured as follows

javascript




// Instantiating the compiled contract to be deployed
const TestContract = artifacts.require("TestContract ");
 
module.exports = function (deployer) {
 
    // Deploying the contract to the blockchain
    deployer.deploy(TestContract);
};


This is followed by executing the command: 

truffle migrate

Note: Since we are simulating the blockchain locally on Ganache, the Ganache service should be running before performing migrations. 

Step 5: Writing Unit Tests: Test-Driven Development is a highly recommended approach in all scopes of software development. It is of paramount importance in the case of dApps. By design of the blockchain, changes once made to the blockchain are stored permanently and immutably on the chain. Thus, if a buggy contract was deployed on the blockchain by a developer, the contract would become unfixable once migrated. The only way to fix bugs is to create a new contract, deploy and migrate it on a new address and request all users to use the new address instead of the older, buggy contract’s address. Hence, consistent testing must be done in dApp development.

All test files are written and stored in the test directory. Unit Testing in Truffle can be done with the help of the Chai and Mocha libraries, which provide a range of assertions and other tools to perform testing. Once written the test are run by executing

truffle test
Tech Stack used for developing dApps with Truffle and web3js

Fig 03: Tech Stack used for developing dApps with Truffle and web3js

Step 6, 7: Creating a UI and integrating with the contracts: The UI design of the dApp is done as usual using tools and languages like HTML, CSS, Bootstrap, JavaScript, etc. To interface the front end with the deployed contracts, we rely on the web3 JavaScript library. Using web3js, we can instantiate the deployed Ethereum contracts inside a front-end JS file and subsequently call functions and exchange data with the blockchain. The code for initializing web3js and instantiating the deployed contract is as follows:

javascript




App = {
  web3Provider: null,
  contracts: {},
  init: async function() {
    return await App.initWeb3();
  },
 
  initWeb3: async function() {
    if (window.ethereum) {
      App.web3Provider = window.ethereum;
      try {
        await window.ethereum.enable();
      } catch (error) {
        console.error("User denied account access")
      }
    }
    else if (window.web3) {
      App.web3Provider = window.web3.currentProvider;
    }
    else {
      App.web3Provider = new Web3.providers
        .HttpProvider('http://localhost:7545');
    }
    web3 = new Web3(App.web3Provider);
    return App.initContract();
  },
 
  initContract: function() {
    $.getJSON("TestContract.json", function(data) {
      var TestContractArtifact = data;
      App.contracts.TestContract =
        TruffleContract(TestContractArtifact);
         
      App.contracts.TestContract
        .setProvider(App.web3Provider);
    });
    return App.callFunctionFromContract();
  },
 
  callFunctionFromContract: function() {
    App.contracts.TestContract.deployed()
      .then(function(instance) {
      console.log(instance.getId());
    }
  }
};


To interact with the blockchain and carry out transactions through a web browser, we require a browser extension capable of handling such transactions. For this, a popular choice is MetaMask. Once the MetaMask account is set up, every time a transaction is to be carried out on the blockchain, MetaMask displays a prompt, detailing the requested transaction, along with the Gas price as well as any other Ether amount that might have to be sent 
With this, we can set up a dApp running on the local Ganache Blockchain.

RELATED ARTICLES

Most Popular

Recent Comments