DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Deploying Smart Contract on Ethereum Blockchain
  • How To Use Ethereum Events Properly: An Solidity Dapp Tutorial
  • The Power of Zero-Knowledge Proofs: Exploring the New ConsenSys zkEVM
  • How To Deploy an ERC-20 Smart Contract on Avalanche With Infura

Trending

  • A Complete Guide to Modern AI Developer Tools
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Integration Isn’t a Task — It’s an Architectural Discipline
  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. Tutorial for Building an Ethereum DApp With Integrated Web3 Monitoring

Tutorial for Building an Ethereum DApp With Integrated Web3 Monitoring

This post walks through the steps and reasoning for creating a simple Ethereum DApp using Web3.js and Truffle and setting up API transaction monitoring.

By 
Xing Wang user avatar
Xing Wang
·
Nov. 08, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
1.4K Views

Join the DZone community and get the full member experience.

Join For Free

This post walks through the steps to creating a simple Ethereum DApp using Web3.js and Truffle and setting up monitoring of the API transactions sent to the blockchain. This article also provides an explanation of various pieces of technology involved in developing DApps.

What Is Blockchain?

Decentralized Applications (or DApps) are applications that do not rely on a centralized backend running in AWS or Azure that power traditional web and mobile applications (outside of hosting the frontend code itself). Instead, the application interacts directly with a blockchain, which can be thought of as a distributed cluster of nodes analogous to applications interacting directly with a “masterless” cluster of Cassandra nodes with full replication on every peer in an untrusted peer-to-peer network.

These blockchain nodes do not require a leader, which would defeat the purpose of being truly decentralized. Unlike leader election in various consensus protocols like Raft and Paxos, blockchain transactions are sent to and processed by “random” nodes via Proof of Work or Proof of Stake. These nodes are untrusted nodes running in an arbitrary-sized network on various compute devices around the world.

Such technology can enable true decentralized ledgers and systems of records.

DApps are the frontend apps that interact with these blockchains over an API. For Ethereum, this API is a JSON-RPC layer called the Ethereum Web3 API.

What Is Ethereum?

Ethereum is an implementation of blockchain technology that can run smart contracts. The Ethereum virtual machine is Turing complete and can run arbitrary computations directly on the blockchain network. Whereas Bitcoin has a limited set of commands, an Ethereum contract allows an application developer to specify exactly what transactions can be performed on a contract. Simple smart contracts can be thought of as a Finite State Machine (FSM) with a set of custom transitions.

What Are Smart Contracts?

Smart contracts can enable blockchain users to exchange money and property or perform other actions among a group of users, such as voting without any central authority.

For the Ethereum platform, the smart contracts are defined using a language called Solidity.

What Is JSON-RPC?

JSON-RPC is a stateless, lightweight remote procedure call (RPC) protocol using JSON for payload. Unlike RESTful APIs, which are resource-centric, RPC APIs like JSON-RPC are procedural and can be more tightly coupled than RESTful APIs.

Frontend apps communicate with the Ethereum cluster using JSON-RPC. Web3 is the Ethereum-compatible API and bindings, which is built using the JSON-RPC spec.

Any decentralized app must use a Web3 SDK such as Web3.js for browser-based DApps.

How the Pieces Fit Together

DApp Ethereum Architecture Ecosystem

Above is a diagram of the ecosystem and how all the pieces of technology fit together.

Tutorial for Building an DApp

Now that you have some background on Ethereum DApps let’s walk through the tutorial.

We’ll use Truffle Framework, which provides a set of tools and boilerplate code for scaffolding DApps for Ethereum. Before we dive in, let’s go through some of the considerations.

  • Does the DApp have an UI?Unless your DApp is an automated process. DApps often have a UI component, such as a web or mobile app, since often its a way for humans to interact with the smart contracts or the Ethereum network. If your DApp is intended to be run in a browser, then you’ll build your UI in Javascript like any traditional Single Page App. As one of the most popular SPA frameworks, we’ll go with React.
    • The Truffle framework provides a boilerplate (called boxes), truffle-react, which derived from the create-react-appboilerplate code generator.
  • Have you designed your Smart Contract? The smart contracts define the rules and transitions for your DApp and is the piece that runs within the Ethereum virtual machine. Avoid putting unnecessary logic into your Smart Contracts, as the gas to run its computation can be very expensive. We’ll start with the simple smart contract from Truffle called SimpleStorage. It stores an unsigned integer storedData and provides a setter and 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;
  }
}


  • What about the test environment? Since any written transaction on an Ethereum contract will cost gas, you’ll want a test network to avoid this. While Ethereum provides official test networks, Truffle Framework provides a local test environment.

Step-By-Step Guide

1. Install Truffle Framework

npm install -g truffle


We use -g flag here so that we can keep using the framework for other projects.

2. Generate the Boilerplate Code

truffle unbox react


Truffle frameworks calls boilerplates boxes. The react boilerplate is based on the create-react-app boilerplate from Facebook.

This should generate a set of files and folders.

There are few folders to pay attention to.

  • src/ folder is where the react code is stored.
  • contracts/ folder is where the smart contracts written in solidity are stored. Notice the SimpleStorage.sol file we mentioned earlier.
  • migrations/ are scripts to manage deployment of contracts onto the Ethereum network.
  • In public/, the index.html file is the entry point where the react app gets injected to.

3. Start the Development Environment

truffle develop


This starts with two things. First, Ethereum Node emulator at http://127.0.0.1:9545, and creates 10 test accounts seeded, each with 100 ether. Second, it starts the truffle command line prompt.

4. Compile the Contracts

At the truffle development command prompt:

compile


This will compile your solidity contracts into JSON artifacts, including the bytecode called Ethereum Virtual Machine (=EVM) bytecode. You’ll find the compiled contracts in the build/contracts folder.

5. Deploy the Contracts

At the truffle development command prompt:

migrate


This will deploy the contracts to the emulated Ethereum network. (Note: you can deploy to a real Ethereum network later on by modifying the truffle-config.js file.)

Now, you can add some interactive features to the DApp, such as editing the App.js file.

6. Run the DApp

At this point, you can run the DApp in your browser:

npm run start


However, it doesn’t have much interaction with Ethereum yet. So we’ll add some here.

First of all, we need to connect to an Ethereum network by getting a handle on the Web3 object and setting the provider.

Note: If you want to see how the DApp connects to the Web3.js, check out the utils/getWeb3.js. Web3 first checks to see if there is a Web3 object injected already in the browser window and uses that. But if no Web3 instance was injected, Web3 tries to connect to the http://127.0.0.1/9545 as the provider of the network. If you are using Mist browser or use Metamask extension, the web3 object would be injected. You would configure the Metamask extension (or the Mist Browser) on which network to connect your DApp to, etc.

7. Modify DApp Code

In App.js, we get a reference to the web3 object in the React componentWillMount() life cycle method and store it in the local state. We 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.')
})


Now, we can add a small form:

<form className="pure-form pure-form-stacked">
  <fieldset>
    <label htmlFor="storage">Storage Amount</label>
    <input id="storage" type="number" ref={c => { this.storageAmountInput = c }} />
    <button
      className="pure-button"
      onClick={(e) => {
        e.preventDefault();
        this.addToSimpleStorage()
      }}
    >
      Set Storage
    </button>
  </fieldset>
</form>


This form will let users set a value they want to store in the SimpleStorage contract. The action handler for the button is here:

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, we get the instantiated contract for SimpleStorage and accounts from the local state. Then, we set the storageValue using the value we obtain from the HTML form.

That is it, our small, simple DApp. Here are a few things to pay attention to:

  • simpleStorageInstance.set triggers the set method of the simpleStorage contract.
  • For details on how this works, check out Truffle’s contract library, which is somewhat of a wrapper for Web3js.

8. Run our Simple DApp

npm run start


You should be able to set a storageValue of a smart contract, which in turn is stored on the Ethereum blockchain.

Set Up Ethereum Web3 API Monitoring

Since DApp have no centralized servers, when you deploy your DApp in production, there would be no servers to install monitoring tools like traditional APM tools require. In order to monitor interactions with the smart contract and Ethereum network, we want to install a monitoring solution that can support DApps.

We will use the moesif-browser-js for integration of monitoring and analytics, available for free on GitHub.

1. Add the Following Code Snippet Into public/index.html

<script src="//unpkg.com/moesif-browser-js@1.2.0/moesif.min.js"></script>
<script type="text/javascript">
var options = {
  applicationId: 'Your Moesif application id'
  // add other option here.
};

// for options see below.
moesif.init(options);

// this starts the capturing of the data.
moesif.start();
</script>


2. Reload Your Application

json-rpc-dapp-call-instance

Source Code

The source code for this tutorial is available on GitHub.

FAQ and Common Issues With Metamask

I received a lot of questions on issues that people often run into, especially regarding switching from the default Truffle Development Network to Metamask. So, I wrote a blog post: FAQ on common pitfalls and solutions for Metamask and Web3.

Ethereum Smart contract Blockchain

Published at DZone with permission of Xing Wang. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Deploying Smart Contract on Ethereum Blockchain
  • How To Use Ethereum Events Properly: An Solidity Dapp Tutorial
  • The Power of Zero-Knowledge Proofs: Exploring the New ConsenSys zkEVM
  • How To Deploy an ERC-20 Smart Contract on Avalanche With Infura

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!