A Quick Recipe To A Simple Decentralized Application

Kerala Blockchain Academy
Blockchain Stories
Published in
7 min readAug 10, 2022

By Sumi Maria Abraham, Research and Development Engineer Kerala Blockchain Academy.

Hoping you’re literate on how to write a smart contract in solidity and deploy it to a test network, lemme start guiding you to build a simple decentralized application or DApp around a smart contract. Let’s get started.

Image Courtesy: https://www.freepik.com/

Aim: Build an application which allows any Ethereum user to write a message and also see the previous value of the message.

If you are novice to the smart contract coding, refer our early blog on How To Interact With An Ethereum Smart Contract.

Here we will be building an interface for MyContract. Let’s see how.

Ingredients Needed:

Are you missing any of the above? Check out the corresponding references for installation guidelines.

Note: Some npm modules need to be compiled using c/cpp while installation. This may need python and make tools, python is available by default in Ubuntu 20, to install make tools execute the following:

sudo apt install build-essential

Initializing a truffle project

Truffle provides a framework for coding, compiling, deploying, testing and interacting with a smart contract.

  1. Create a new folder MyDapp and change to it.
mkdir MyDapp && cd MyDapp

2. Initialize truffle.

truffle init

This command will create a folder structure.

3. Write the smart contract.

truffle create contract MyContract

You can use the same contract that we mastered in the previous blog.

Please turn on VSCode Solidity extension for syntax highlighting.

4. Compile the smart contract.

truffle compile

Once the compilation is successful, the compilation outputs will be available under the build/contracts folder.

Smart Contract Deployment using Truffle

Our smart contract is now ready to be deployed. The deployment settings are specified in the truffle-config.js file. Default settings for various deployment options are already defined in this file.

We will see how to deploy our smart contract to the Goerli testnet.

To deploy our contract, we need to connect to a full node of the particular blockchain network (Goerli). For this, we are seeking the help of Infura service. Create a new project and choose Web3 API. If you do not have an account, go to this link and do the sign up.

Note the API key, an alphanumeric number which allows you access to the APIs.

We need an HDWalletProvider for interacting with the MetaMask. Update the truffle-config.js with the below code:

const HDWalletProvider = require(‘@truffle/hdwallet-provider’);const mnemonic = “xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx"; //replace with your secret phase copied from MetaMask

The mnemonic phrase will be accessible from the security/privacy section under MetaMask settings.

Now let us configure the test network. Include the below code under the network in the truffle-config file. Don’t forget to edit the project-id.

testnet: {provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
network_id: 5, // Goerli's id
gas: 5500000,
confirmations: 2, // no of confirmations to wait between deployments.
timeoutBlocks: 200, // no of blocks before a deployment times out (minimum/default: 50)skipDryRun: true // Skip dry run before migrations? (default: false for public nets )},

Now install the hdwallet-provider dependency.

npm i @truffle/hdwallet-provider

Let us deploy our smart contract in the test network.

truffle migrate --network testnet

Make sure that your MetaMask wallet is open, connected to the test network and has sufficient ether balance.

You will receive the transaction details in the terminal if the deployment is successful.

Confirm the transaction by checking etherscan.

Integrating UI

Let’s try to include a minimal simple user interface to learn how to interact with the smart contract.

The UI code is available at this link.

Create a new folder (ui) under the current project directory and copy the contents from the above link.

The interface will require ABI to invoke the smart contract functions. So let us denote a new location for storing the compilation outputs. In the truffle-config file, add the below line before the network’s sub-section.

contracts_build_directory: “./ui/src/abi”,

Now you may delete the previous build folder.

Re-compile and migrate the contract using the below command.

truffle migrate --network testnet.

It will generate the ABI at ui/src/abi/MyContract.json

The build location is updated just to align with the ready made code shared with you. The code will work irrespective of the location as long as the references are updated accordingly.

Invoking the smart contract

The smart contract interactions are coded in the ui/src/App.js file. Let us do a quick code walk-through.

The contract address and ABI can be accessed through the build file referred to as MyContractJSON in the code.

const MyContractJSON = require(“./abi/Storage.json”);

Contract interactions are facilitated by Web3 object connected to the blockchain via MetaMask provider (ethereum).

const web3 = new Web3(ethereum);

The web3 helps to provide a contract instance based on the contract address and ABI.

const myContract = new web3.eth.Contract(contractAbi, contractAddress);

Time delay is a major concern regarding blockchain operations. The smart contract interactions are asynchronous and should be enclosed in async functions. Method invocations should be using await keyword.

Wallet connectivity is required to send transactions when a user needs to access the smart contract. This is handled by the function enableMetaMask(). The MetaMask will pop up and request signing in by the user.

The setValue() function invokes the setMessage() method of smart contract. It sends the value entered by the user in the textbox as the input parameter of the transaction. Transactions are invoked using the send( ) function with the currently active address in the user’s MetaMask as the sender’s address.

The getValue() function calls the getMessage() method of smart contract. It reads the value of the message from the blockchain and displays it on screen. Since this is a read-only operation (view), it uses the call () function.

Running the DApp

Change to ui directory and install the dependencies

cd uinpm i

Upon successfully installing the dependencies, the folder hierarchy of MyDapp should look like the below.

Common errors occur due to:

  • issues in smart contract deployment (verify the migrations file)
  • time-out errors due to network issues (retry after some time)
  • inconsistent code due to unsaved changes (save your changes and restart the terminal)
  • incompatible versions of node (works best in node version 16.13.0). If it is reinstalled, make sure other dependencies are also updated accordingly.

Once your code is error-free, go ahead and run it.

npm start

By default, the application will open up in localhost:3000.

I hope you liked our simple DApp.

I am interested in knowing whether you can add to our DApp??? Do you have something in mind that can make our DApp more luscious? If so, here is an activity for you

<< Activity for Readers>>

Currently, the app displays only the recent message. Can you update the app so that users can view the message history? All the values assigned to the message variable should be listed along with the corresponding transaction identifier and sender address.

The content discussed so far needs to be considered only as a primary reference for building your app. You are free to use any tool of your choice to make the app. Share the GitHub link and short screen recording of your DApp demo to kba.dlab@duk.ac.in In case, you need any knowledge assistance, check out our Ethereum Foundation Program & Certified Ethereum Developer Program, I am sure you’ll find something handy inside. Also do checkout our blog contents on Ethereum programming here.

--

--

Kerala Blockchain Academy
Blockchain Stories

One-stop solution for quality blockchain education and research. Offers best in class blockchain certification programs in multiple blockchain domains.