Select Page

How to build an Ethereum dApp with integrated Web3 monitoring?

How to build an ethereum dApp

Ethereum is an exceptional blockchain-based platform. With its multiple features and offerings like virtual machines and ether (its native cryptocurrency), it enables developers to build and deploy decentralized applications (dApps), smart contracts, decentralized autonomous organizations (DAOs).

As a second-generation blockchain platform, Ethereum enables developers to build highly reliable dApps and smart contracts. It has revolutionized the blockchain ecosystem and can be implemented in several use cases from varying industries.

You must know that Ethereum smart contracts are accessible and transparent, like open APIs. Hence, an Ethereum dApp can also include smart contracts written by different authors. Ethereum dApps are:

  • Decentralized
    No one, individual or group, can control them, and they are independent.

  • Isolated
    Ethereum dApps are executed in the Ethereum Virtual Machine. It is a virtual environment that makes sure the normal functioning of the blockchain network isn’t hampered in case of a bug in a smart contract.

  • Turing Complete
    An Ethereum dApp can perform any action if it is given the required resources.

  • Deterministic
    The environment in which they are being executed does not hinder or stop them from performing the same functions. So, they function well irrespective of their executing environment.

Smart contracts can act as the dApps backend. Ethereum’s dApps offer people several benefits: resistance to censorship, zero downtime, privacy, trustless computation, verifiable behavior, and complete data integrity. Made possible by cryptographic primitives, malicious actors cannot forge transactions due to the benefit of immutability. Similarly, other data that has already been made public on the blockchain cannot be forged as well.

The development of dApps requires several different pieces of technology, and development frameworks are a significant component of it. There are several development frameworks available for Ethereum dApp development, such as:

  • Truffle 

    • A Testing Framework

    • A Development Environment

    • Build Pipeline, etc.

  •  Etherlime
    It is a framework for dApp development (Solidity and Vyper), testing, debugging, deployment, etc., based on Ethers.js.

  • Web3j
    It is a platform for blockchain applications development on the JVM.

  • Brownie
    It is a Python-based testing framework and development environment.

  • Embark
    A Testing Framework

  • Other tools integrated with Ethereum, IPFS, and Whisper.
  • OpenZeppelin SDK
    It is referred to as the ultimate Smart Contract toolkit as it is a suite of tools to help developers with compilation, development, upgradation, deployment and interactions with smart contracts.

  • Alchemy
    It is an Ethereum Development Platform.

  • The Graph
    It is a framework for querying blockchain data efficiently.

This article will take a closer look at how you can build an Ethereum dApp integrated with web3 monitoring. Let’s begin.

How to build an Ethereum dApp with integrated Web3 monitoring?

Ethereum is a unique implementation of blockchain technology that can run smart contracts, unlike a few other platforms. Also, as we discussed earlier in this article, it has a virtual machine that is Turing complete and can run computations directly on Ethereum’s blockchain network. With Ethereum smart contracts, developers can specify the kind of transactions they want their contract to perform. Also, it enables users to exchange money, property and conduct procedures like voting without the presence of a central authority.

Solidity is the main language using which smart contracts are defined on the Ethereum platform. Before we move on to the step-by-step procedure, let’s understand a few basics about Ethereum Client APIs – JavaScript API, Back-end APIs, and JSON-RPC API, all of which are used in one form or the other throughout the tutorial.

Ethereum Client APIs

1. JSON -RPC
It is important for software applications to connect to an Ethereum node if they want to interact with the Ethereum blockchain by sending transactions to the network or reading blockchain data.

Every Ethereum client implements a JSON-RPC specification for this purpose in order to ensure that all applications have a uniform set of methods on which they can rely.

JSON-RPC is a lightweight and stateless remote procedure call (RPC) protocol that uses JSON (RFC 4627) as the data format. This specification defines several data structures and the rules around the processing of those data structures. It facilitates the use of concepts within the same processes, over HTTP or sockets, or several varied messages passing environments.

What are the resources for JSON-RPC?
Here are two important resources for JSON-RPC:

What are convenience libraries?
While implementing the JSON-RPC specification, several Ethereum clients may use different programming languages. So, while you may like to interact directly with Ethereum clients through the JSON-RPC API, there are other easy options that dApp developers can use.

Several back-end API libraries and JavaScript APIs provide developers with wrappers on top of the JSON-RPC API. Developers can write one-line intuitive methods in their chosen programming language with these libraries in order to initialize JSON-RPC requests that interact with Ethereum.

The JSON-RPC protocol uses JSON for payload. So, unlike the resource-centric RESTful APIs, JSON-RPC APIs are procedural and can be coupled more tightly than RESTful APIs.

Using JSON-RPC, front-end apps communicate with the Ethereum cluster. Web3 is the API compatible with Ethereum, and its bindings are built using the JSON-RPC specification.

2. JavaScript API Libraries

Several convenience libraries within the Ethereum ecosystem make it easy to use JavaScript to connect with an Ethereum node. Developers can write one-line intuitive methods in their chosen programming language with these libraries in order to initialize JSON-RPC requests that interact with Ethereum.

Are there any prerequisites?

It can be helpful if developers understand JavaScript, the Ethereum stack, and Ethereum clients.

Why should developers use a library?

 Developers should use a library because:

 They take away a lot of complexity that comes with direct interactions with an Ethereum node.

  • They provide utility functions.

  • Developers can spend more focused time on the unique functionalities of their applications instead of dealing with Ethereum clients’ intricacies.

What are the features of libraries?

Here are a few noteworthy features of libraries:

  • Connect to Ethereum Nodes
    These libraries allow developers to connect to Ethereum and read its data irrespective of its over, whether JSON-RPC, Alchemy, Etherscan or MetaMask. By leveraging these libraries, developers can query the blockchain for gas estimates, network id, block numbers, smart contract events, etc.

  • Wallet Functionality
    Developers get access to multiple functionalities with these libraries, such as creating wallets, signing transactions and managing keys. Developers can create accounts, sign and send transactions after setting up.

  • Interactions with Smart Contract Functions
    With JavaScript client libraries, developers can call smart contract functions by reading a compiled contract’s Application Binary Interface (ABI), which describes the contract’s functions in a JSON format and allows developers to use it as a JavaScript object. As a result, developers can send transactions to smart contracts, deploy a contract, execute its method, call it to estimate the gas that will be used to execute a method in the EVM, etc.

  •  Utility functions
    Utility functions are responsible for giving handy shortcuts to developers through which building on Ethereum can become easier.

Available Libraries
Here are a few JavaScript API libraries available for developers:

  • Web3.js – It is the Ethereum JavaScript API.

  • The Graph – It is a protocol for indexing Ethereum data, IPFS data and querying it via GraphQL.

  • Alchemyweb3 – It offers the wrapper around Web3.js with enhanced APIs and automatic retries.

  • Ethers.js – It is the library with complete Ethereum wallet implementation and utilities in JavaScript and TypeScript.

  • Web3-wrapper – It is the Typescript alternative to Web3.js.

  • light.js – It is a high-level reactive JS library that is optimal f0or light clients.

3. Back-End APIs
There are several convenience libraries within the Ethereum ecosystem that make it easy for developers to connect with an Ethereum node using their preferred programming language. Developers can write one-line intuitive methods in their chosen programming language with these libraries in order to initialize JSON-RPC requests that interact with Ethereum.

Are there any prerequisites?

It can be helpful if developers have a thorough understanding of the Ethereum stack and Ethereum clients.

Why should developers use a library?

Developers should use a library because:

  • They take away a lot of complexity that comes with direct interactions with an Ethereum node.

  • They provide utility functions.

  • Developers can spend more focused time on the unique functionalities of their applications instead of dealing with Ethereum clients’ intricacies.

Available Libraries

Here are a few Backend API libraries available for developers:

Cloudflare Ethereum Gateway.

  • Alchemy – It is an Ethereum Development Platform.

  • BlockCypher – It provides developers with Ethereum Web APIs.

  • web3j – It is a Java/Android/Kotlin/Scala integration library for Ethereum.

  • Infura – It offers the Ethereum API as a service.

  • Chainstack – It offers shared and dedicated Ethereum nodes as a service.

  • Nodesmith – It offers JSON-RPC API access to Ethereum mainnet and testnets.

  • Ethercluster – With this library, developers can run their own Ethereum API service supporting both ETH and ETC.

  • QuikNode – It is a blockchain developer platform.

  • Python Tooling – It offers a variety of libraries for Ethereum interaction through Python.

  • Nethereum – It is an open-source .NET integration library for blockchain.

  • Rivet – It offers Ethereum and Ethereum Classic APIs as a service powered by open-source software.

For browser-based dApps, a Web3 SDK like Web3.js must be used. Having said that, we have covered an extensive background of Ethereum dApps. However, before we discuss how you can build an Ethereum dApp with integrated Web3 monitoring, you must be aware of a few considerations.

Considerations
Here are three important considerations developers must take into account before beginning with the development:

  • Does the dApp have a UI component?
    If the dApp is not an automated process, then developers usually keep a UI component like a mobile or web app. This UI component helps people to interact with the Ethereum network or the smart contract.

    Developers should build their UI in JavaScript if they wish to run it in a browser, like traditional SPAs.

  • Have you carefully designed the dApp’s Smart Contract?
    As the piece of the dApp that runs in the EVM (Ethereum Virtual Machine), smart contracts are responsible for defining the transactions and rules for the dApp. Hence, it is important to design them carefully without putting any unimportant logic in them. If developers end up putting unnecessary logic into their dApp’s smart contract, they might face high costs of gas required to run the computation.

  • Have you leveraged a test environment?
    All transactions on an Ethereum smart contract will cost gas. Hence, developers should consider setting up a test network to avoid it.

For our guide, we will use the following:

Development Framework
Truffle (It offers an extensive set of tools and boilerplate code for scaffolding Ethereum dApps, and provides a boilerplate called “truffle-react,” which is derived from the create-react-app boilerplate code generator.)

  • Single Page Application (SPA) Framework: React

  • Smart Contract: SimpleStorage (A simple, smart contract from Truffle stores unsigned integer stored data and provided a setter and a getter.)

pragma solidity ^0.4.18;contract SimpleStorage {uint storedData;function set(uint x) public {storedData = x;}function get() public view returns (uint) {return storedData;}}

Step by Step Guide

Here is the step-by-step guide to building an Ethereum dApp with integrated Web3 monitoring:

Step 1: Truffle Framework Installation

Use the following to install the truffle framework:

npm install -g truffle

In order to ensure that you can keep using this framework for other projects, you should use the -g flag here.

Step 2: Boilerplate Code Generation

Boilerplates are known as “boxes” in the Truffle framework. Use the following:

truffle unbox react

Based on the create-react-app boilerplate from Facebook, the React boilerplate should generate a set of files and folders.

You must pay attention to the following folders:

  • src/
    The folder where the React code is stored.

  • Contracts/
    The folder where smart contracts are stored. These smart contracts are written in Solidity. You must notify the SimpleStorage.sol file here.

  • Migrations/
    This folder includes the scripts required to manage the deployment of the smart contracts onto the Ethereum network.

  • Public/
    Here, pay attention to the index.html file. It is the entry point for the React app.

Step 3: Starting the Development Environment

Use the following:

truffle develop

This function starts:

  • The Ethereum node emulator at http://127.0.0.1:9545.

  • The truffle command line prompt.

It also creates ten test accounts and seeds each of them with 100 ethers.

Step 4: Compiling the Smart Contracts

Use the following at the Truffle development command prompt:

compile

This function is responsible for compiling your dApps solidity contracts into JSON artifacts, including the Ethereum Virtual Machine (=EVM) bytecode. These compiled smart contracts can then be found in the build/contracts folder.

Step 5: Deploying the Smart Contracts

Use the following at the Truffle development command prompt:

migrate

This function is responsible for deploying your smart contracts to the emulated Ethereum network. Later on, you can also deploy your smart contracts to the real Ethereum network by modifying the truffle-config.js file.

Once you’re done with this, you can start adding your desired interactive features into your dApp.

Step 6: Running the dApp

Now, you can start running the DApp in your browser. Use the following:

npm run start

However, you’ll need to add some interactive features as it doesn’t interact with Ethereum yet. To do so, you’ll have to get a handle on the Web3 object and set up a provider to connect to an Ethereum network.

You can leverage utils/getWeb3.js if you want to see how your dApp connects to the Web3.js. Web3 ensures that a Web3 object has been injected in the browser window and later uses the same object. However, if no Web3 instance is injected, it tries to connect with the http://127.0.0.1/9545, which acts as the network provider.

The extension or browser you’re using plays a role as well. For example, if you use a MetaMask extension or the Mist browser, the Web3 object will surely be injected. Later, you can configure your extension or browser to connect to your dApp on your choice of network.

Step 7: Modifying the dApp code

In App.js, you receive a reference to the Web3 object. It is received in the React component WillMount() life cycle method and stored locally. You can also instantiate a local version of the contract.

getWeb3.then(results => {this.setState({web3: results.web3  }) // Instantiate contract once web3 provided.this.instantiateContract()}).catch(() => {console.log('Error finding web3.')})

Once you’re done with it, you can add a small form:

 

 

{ this.storageAmountInput = c }} />

 

The above-mentioned form allows users to set the value they wish to store in the SimpleStorage contract. The following is the action handler for the button:

addToSimpleStorage() {  if (this.state.simpleStorageInstance && this.state.accounts) {    const value = this.storageAmountInput.value;    this.state.simpleStorageInstance.set(value, {from: this.state.accounts[0]})      .then((result) => {        return this.state.simpleStorageInstance.get.call(this.state.accounts[0])      }).then((result) => {        this.setState(prevState => ({          ...prevState,          storageValue: result.c[0]        }));      }).catch((err) => {        console.log('error');        console.log(err);      });  } else {    this.setState(prevState => ({      ...prevState,      error: new Error('simple storage instance not loaded')    }))  }}

In the handler, you will receive the instantiated contract for SimpleStorage and the accounts from the local state. Then, you can set the storageValue by using the value you obtained from the HTML form.

You must also pay attention to the following:

  • The set method of the simpleStorage contract is triggered by simpleStorageInstance.set

  • The Truffle contract library may act as a wrapper for Web3js. Hence, you must go through it to extract details about the function mentioned above.

Step 8: Running the Modified dApp

Use the following:

npm run start

The function mentioned above can set a smart contract’s storageValue. It is then stored on the Ethereum blockchain.

Step 9: Setting Up the Ethereum Web3 API Monitoring 

dApps don’t have centralized servers. So, there won’t be any servers to installs monitoring tools when you deploy the dApp in production. Hence, it is important to install monitoring solutions that support dApps so that you can monitor your interactions with the Ethereum network and the smart contract.

One such solution can be compatible APIs that facilitate analytics and monitoring. Developers can leverage APIs that call data from the client-side directly with a browser SDK. As a result, they can be used to monitor issues, debug them, and alert their teams in case of any oddities.

Conclusion

Ethereum is an exceptionally popular platform in the cryptocurrency and blockchain space. It provides developers with enough flexibility and robustness to innovate and come up with new and scalable applications.

Ethereum dApps can be applicable in a myriad of industries, all thanks to its deterministic, Turing complete, isolated and decentralized nature. By providing utility and value in industries ranging from real estate and entertainment to finance and healthcare, the range of Ethereum dApps is unbelievable. So, phenomenal results can be expected when Ethereum dApps are paired with technology like Web 3.0, which is essentially based on decentralization. With the absence of mediators and intermediaries in all shapes and forms, Ethereum dApps and Web3 can realize decentralization optimally.

As discussed in this article multiple times, it is important for developers to thoroughly understand the Ethereum stack and Ethereum clients to develop dApps successfully with their preferred choice of language. While the guide only describes developing a dApp by using the Truffle framework, with the help of multiple libraries and frameworks discussed above, developers can build dApps on Ethereum efficiently with their preferences in mind.

However, it is also noteworthy that developing Ethereum dApps and maintaining them is not an easy task. It requires a significant amount of effort, careful work and expert supervision for seamless proceedings. Hence, it is always helpful to partner with an Ethereum development team or firm that can help you with all the complexities of developing an Ethereum dApp.

LeewayHertz is a leading software development company in the blockchain space. With highly experienced developers, our team of experts can help you with any Ethereum development service that you require. If you are searching for a blockchain development partner for Ethereum dApp development, please feel free to contact our experts.

Webinar Details

Author’s Bio

Akash Takyar
Akash Takyar
CEO LeewayHertz
Akash Takyar is the founder and CEO at LeewayHertz. The experience of building over 100+ platforms for startups and enterprises allows Akash to rapidly architect and design solutions that are scalable and beautiful.
Akash's ability to build enterprise-grade technology solutions has attracted over 30 Fortune 500 companies, including Siemens, 3M, P&G and Hershey’s. Akash is an early adopter of new technology, a passionate technology enthusiast, and an investor in AI and IoT startups.

Start a conversation by filling the form

Once you let us know your requirement, our technical expert will schedule a call and discuss your idea in detail post sign of an NDA.
All information will be kept confidential.

Insights

Follow Us