Creating dApps using the Truffle Framework
Last Updated :
05 Apr, 2023
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:
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:
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
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.
Similar Reads
Hardhat Vs Truffle - Frameworks For Developing dApps
Hardhat and Truffle are equipped with sets of features aimed at developing, testing, and deploying smart contracts on the Ethereum platform. These frameworks consist of not only the code structure but also utilities and libraries which make developers work easier and save dApps from hacks. It is als
9 min read
Freelancer Portfolio Builder Application using MERN Stack
In today's digital age, having a professional portfolio is essential for freelancers to showcase their skills and attract potential clients. In this article, we'll dive into the process of building a Freelancer Portfolio Builder using the MERN (MongoDB, Express.js, React.js, Node.js) stack. This pro
5 min read
How to create mock servers using Postman
Postman is a comprehensive API platform used by developers; this platform provides a set of tools that support API design, testing, documentation, mocking, and API Monitoring. It also simplifies each step of the API lifecycle and streamlines collaboration, enabling developers to create and use APIs
7 min read
Building a Toll Road Management System using Node.js
In this article, we are going to build a simple Toll Road Management System using Node.js, where the data will be stored in a local MongoDB database.Problem Statement: In a toll tax plaza, it is difficult to record all the transactions and store them in a single place, along with that, if required,
15+ min read
Real Estate Management using MERN
In this article, we will guide you through the process of building a Real Estate Management Application using the MERN stack. MERN stands for MongoDB, Express, React, and Node. MongoDB will serve as our database, Express will handle the backend, React will create the frontend, and Node.js will be th
9 min read
Describe the MVC framework in Angular
In Angular, when we build websites or web apps with HTML, CSS, and JavaScript, things can get really complicated. Imagine hundreds or even thousands of lines of code, all working together. That's where frameworks and patterns come in to help us organize our code and make it easier to manage. One pop
4 min read
How to create routes using Express and Postman?
In this article we are going to implement different HTTP routes using Express JS and Postman. Server side routes are different endpoints of a application that are used to exchange data from client side to server side.Express.js is a framework that works on top of Node.js server to simplify its APIs
3 min read
Design First Application Using Express
In NodeJS, the task of designing a server was very difficult, but after the introduction of ExpressJS, which is a lightweight web application framework for NodeJS used to build the back-end of web applications relatively fast and easily. PrerequisitesTo get started with an ExpressJS application, Nod
4 min read
Todo list app using Flask | Python
There are many frameworks that allow building your webpage using Python, like Django, flask, etc. Flask is a web application framework written in Python. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. Its modules and libraries that help the developer to writ
3 min read
Travel Planning App API using Node & Express.js
In this article, weâll walk through the step-by-step process of creating a Travel Planning App With Node and ExpressJS. This application will provide users with the ability to plan their trips by searching for destinations, booking flights and hotels, submitting reviews, receiving notifications, sha
10 min read