How to create a DApp in NodeJS for MetaMask

How to create a DApp in NodeJS for MetaMask

DAppsor decentralized applications are applications that do not rely on a single server for their operation and security. Instead, they use blockchain and oracles as the backbone of their system, making them more secure from malicious activities and hacks.

This tutorial shows the steps to create a basic end-to-end decentralized application. With this app, users can check the current Ethereum price and store it in a smart contract.

Initially, make sure you have NodeJS and MetaMask installed:

https://nodejs.org/en/

https://metamask.io/

What is a decentralized application (dApp)?

In a dApp, the backend code runs on a blockchain, unlike a traditional application where the backend code runs on centralized servers. A dApp can have external code and user interfaces written in any language and deployed on any server or servers to interact with internal logic.

Because the backend logic is housed in highly secure, tamper-proof smart contracts, dApps have many advantages not available to traditional Web2 systems:

  • zero downtime
  • greater privacy
  • resistance to censorship
  • performing logic with a minimum level of confidence

However, these advantages also have some disadvantages. Maintaining dApps requires more effort because the code deployed on the blockchain is not modifiable by default. In addition, because the logic is executed on a distributed network rather than on a centralized server, maintenance costs also increase. In addition, the user experience can suffer because the dApp user has to go through the hassle of creating a Web3 wallet and funding it with enough cryptocurrency to pay transaction fees.

DApp Components

The components of a dApp can be divided into three different categories: smart contracts, frontend logic and user interface, and data storage.

Smart contracts Smart contracts store the DAPP business logic, as well as the state of the application. This is the biggest difference between DAPP and the traditional web application, and this is what Dapp gives all the advantages mentioned above.

Front-end/user interface while the logic of the DAPP bachelor requires the spelling of the smart contract code for deploying on the blockchain, the front-end or customer part of the DAPP can use standard web technologies such as HTML and JavaScript. This allows the developers to use familiar tools, libraries and frameworks. The user interface on the client side is usually associated with smart contracts through client libraries, such as Web3.js or Ethers.js

https://web3js.readthedocs.io/en/v1.7.4/

https://docs.ethers.org/v5/

They come bundled with frontend resources and are sent to the browser along with the user interface. Interactions with smart contracts, such as signing messages and sending transactions to smart contracts, are usually done through a browser-based Web3 wallet, such as MetaMask.

data storage Most applications need to store data, but due to the distributed nature of the blockchain, storage of large volumes of data on the chain is inappropriate and can be very expensive. Therefore, many DAPPs that need to store data use off-shain data storage services, such as IPFS or Filecoin, leaving blockchain only to store an important business logic and condition.

Traditional cloud storage services can also be used. However, many developers choose decentralized options to preserve and extend the trust minimization properties that blockchain-based dApp provides.

Now that we know the components of the dApp, let’s look at an example of creating a simple end-to-end contract.

Creation of smart contract

The smart contract in our DAPP will be a simple example used to search for data and reflect the state changes on the blockchain. In this case, we will look for the cost of ETH/USD using eth/USD Data Feed , and then constantly maintain the result in a smart contract.

https://data.chain.link/ethereum/mainnet/crypto-usd/eth-usd

The first thing to do is to open the documentation and go to the Using Data Feeds page:

https://docs.chain.link/data-feeds/price-feeds

From there, you can copy the example source code and paste it into a new file in the IDE of your choice (e.g. Visual Code), or click the “Open In Remix” button and work from the Remix web version.

https://code.visualstudio.com/

In this example, we will work with Visual Studio Code and Hardhat, the framework for developing the Ethereum virtual machine.

https://hardhat.org/

First, we create a new directory structure for our dApp with a backend folder for the smart contract code:

mkdir chainlink-dapp-example
cd chainlink-dapp-example
mkdir backend
cd backend

Next, we open the directory created for our dApp in the VS Code editor and then install Hardhat:

npm init -y
npm install --save-dev hardhat
npx hardhat
(choose create javascript project, choose default parameters)

After that, delete the Touch.sol file in the “contracts” folder, create a new file in that folder called PriceConsumerV3.sol and save it. Here we will create our smart contract, so copy the code from the example in the Chainlink documentation into this file and save it.

In the example code, you will see that the demo contract already has the getLatestPrice function to find the current Ethereum price on the Rinkeby ETH/USD Data Feed.

function getLatestPrice() public view returns (int) {
        (
            /*uint80 roundID*/,
            int price,
            /*uint startedAt*/,
            /*uint timeStamp*/,
            /*uint80 answeredInRound*/
        ) = priceFeed.latestRoundData();
        return price;

We need to create a new variable and a new function to store this value in the smart contract. The first step is to create a new variable under the existing priceFeedone to store the Ethereum price:

int public storedPrice;

Next, we need to create a new function that will be called by the dApp frontend. This function should search for the latest Ethereum price by calling the existing getLatestPrice function. It should then store that value in the new storedPrice parameter:

function storeLatestPrice() external {
        storedPrice = getLatestPrice();
    }

Your new contract should look like this:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

    AggregatorV3Interface internal priceFeed;
    int public storedPrice;

    /**
     * Network: Rinkeby
     * Aggregator: ETH/USD
     * Address: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
     */
    constructor() {
        priceFeed =
AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
    }

    /**
     * Returns the latest price
     */
    function getLatestPrice() public view returns (int) {
        (
            /*uint80 roundID*/,
            int price,
            /*uint startedAt*/,
            /*uint timeStamp*/,
            /*uint80 answeredInRound*/
        ) = priceFeed.latestRoundData();
        return price;
    }

    function storeLatestPrice() external {
        storedPrice = getLatestPrice();
    }
}

Defense of the smart contract

Now you’re ready to compile and deploy your contract in the Rinkeby test network. Don’t forget to top up your MetaMask wallet with some Rinkeby ETH first.

https://faucets.chain.link/

If you are using Remix, you can compile and deploy your contract using the standard Remix process. If you are using an IDE such as Visual Studio Code, we recommend using Hardhat to manage your contracts.

The first step to compile and deploy your contract is to install the Hardhat tool library, the Chainlink contract library, and the dotenv library for storing passwords and secret keys in a separate .env file:

npm install --save-dev @nomicfoundation/hardhat-toolbox
npm install @chainlink/contracts --save
npm install dotenv

Then replace the contents of the hardhat-config.js file with the following:

The next step is to create an .env file in the backend folder. Then you need to extract your private key from the Web3 wallet and paste it into the value section of the PRIVATE_KEY field in the .env file. Please make sure that you are using a new Web3 wallet that has no funds in mainnet.

After that you need to get an RPC endpoint to access the Rinkeby network. You can do this by inserting the RPC URL in the RINKEBY_RPC_URL field in the .env file. We recommend signing up for a free Infura or Alchemy account to get the RPC URL.

https://www.infura.io/

https://www.alchemy.com/

The next step is to change the contents of the deploy.js file in the ‘scripts’ folder to make sure it deploys your new contract. Open the file and make sure the following code replaces what you already have. This will simply take your compiled PriceConsumerV3 contract and try to deploy it. Don’t forget to save your changes.

Now you’re ready to build and deploy your smart contract on the Rinkeby network with Hardhat:

npx hardhat compile
npx hardhat run --network rinkeby scripts/deploy.js

You should see a message like the one below, with the address on the Rinkeby to which your smart contract has been deployed. Make a note of this address, we will need it for the next step.

Congratulations, you’re now ready to move on to the frontend part of your dApp!

Creation of a front-end application

The frontend logic and user interface of your dApp can be built using a wide variety of different frameworks.

React is one of the most popular JavaScript libraries for creating feature-rich web user interfaces, so it is used in many Web3 dApps.

https://reactjs.org/

Additionally, Ethers.js is a JavaScript library for connecting and interacting with EVM-based blockchains and smart contracts. If you combine these two components, you get a reasonable starting point for building the frontend of your dApp.

In this section, we’ll create a new React application using the create-react-app template generator.

https://create-react-app.dev/

We will then implement off-chain logic using Ethers.js to link the UI to the deployed smart contract, allowing us to create a full end-to-end dApp.

Creating a React application The first step to create a frontend is to install and implement the create-react-app boilerplate project and then modify it for our dApp. The first step is to install the library in the new “frontend” folder:

cd ..
npx create-react-app frontend

After that, a new “frontend” folder should appear in your project with all the React code associated with it. Expand the “frontend” folder and do the following:

  • Delete /src/setupTests.js
  • Delete /src/ReportWebVitals.js
  • Delete /src/logo.svg
  • Delete /src/App.test.js
  • Delete /src/App.css

The folder structure should look like this:

Now we’re almost ready to start modifying the React application code. But first don’t forget to install the libraries for Bootstrap and Ethers.js.

https://getbootstrap.com/

Bootstrap is a popular CSS frontend framework that comes with React-friendly UI widgets with superimposed CSS styling, and Ethers.js allows us to connect our frontend to deployed smart contracts on the blockchain. Make sure to run these commands from the “frontend” folder.

cd frontend
npm install bootstrap
npm install ethers

Now we are ready to modify the React application code. Open the App.js file in /src/ and delete its contents. We will start creating it from scratch.

The first step is to tell the application that we want to use React (including the useEffect and useState libraries) and Ethers.js:

import React, { useEffect, useState } from 'react';
import { ethers } from "ethers";

Then create a function called “App” and export it:

Now we will start filling the contents of the “App” function. Add the following code to it. This code does the following:

Installs StoreDPRICE and SetStoreSprice reactive hooks. Creates a connection with your Metamask Web3 wallet. Sets the address of the detailed smart contract and ABI. Both of these parameters need Ethers.js to interact with a detailed smart contract. The address of the smart contract can be obtained from the deployment step described earlier in this guide. Insert this value instead of a string of replace_with_deployed_contract_address. ABI smart contract can be obtained from the file /Backend/artifacts/contracts/priceconsumerv3.json, in the ABI element. You can use the code minifier.

https://codebeautify.org/jsonminifier

This will help format it in the best way to store it in your application.

const [storedPrice, setStoredPrice] = useState('');
  const provider = new ethers.providers.Web3Provider(window.ethereum)
  const signer = provider.getSigner()
  const contractAddress = ’';
  const ABI =
'[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"getLatestPrice","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"storeLatestPrice","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"storedPrice","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"}]'
  const contract = new ethers.Contract(contractAddress, ABI, signer);

We will now create two functions that will be used in our application:

GetStoredPrice will connect to a detailed smart contract and get the current value of the StoreDPRICE () gutter function. The SetNewPrice function will cause the StorelaTestPrice function of a detailed smart contract, wait for the transaction to complete, and then call the GetStoredPrice function to obtain a price saved in a smart contract. We will also add a GetStoredPrice call to our APP function so that it initially causes the Getter function when loading the page:

The last step in creating a front-end is the return of the JSX code for rendering with a browser. Insert the next code in the lower part of the App, under the call of GetstorePrice (). This code makes the following:

Returns a simple two-column grid layout. The first column contains the current stored price of ETH/USD in the smart contract. The second column contains a button that the user can use to interact with the smart contract and update the stored price. Clicking the button calls the setNewPrice function described above.

Your application is ready. You are now ready to run your dApp. Launching your dApp After making sure that all files have been saved, launch your dApp locally by running the following command from the frontend folder:

npm run start

After downloading the application, you should see a new window in your browser displaying the dApp user interface. You should also receive a pop-up notification from MetaMask asking you to connect your wallet to the application.

Once you are satisfied that you have funded your MetaMask account with some Rinkeby ETH, click the “Refresh” button in the dApp user interface to interact with the deployed smart contract on the Rinkeby network. You should receive a notification from MetaMask asking you to confirm the transaction. After that, your dApp should update automatically within a few seconds and the current Ethereum price should appear in the “Saved Price” section:

Congratulations, you have now successfully created, deployed and interacted with a simple dApp! In this tutorial, you simply run the frontend locally on your computer, but you can deploy it to a cloud server if you want, or even decentralize the frontend and deploy it to IPFS!

https://ipfs.tech/

You can also work with the application’s CSS to change the appearance of the user interface.

https://www.w3schools.com/css/

Summary

Decentralized applications are applications that replace traditional back-end processing with Web3 technologies such as blockchain and smart contracts, giving them unique guarantees of security and resistance to censorship that are not possible with traditional Web applications.

In this technical demonstration, we created a simple dApp containing a smart contract that gets the latest price from the ETH/USD Data Feed and stores the result in the smart contract. We then created a simple UI that uses React and Ethers.js to connect to and interact with the deployed smart contract.


If you like to read such articles and want to support the author, then you can subscribe to our telegram channel and recommend us to your friends, this will help a lot to support our project! Telegram: CRYPTO WIKIES | Bitcoin & Altcoins Mining

Be the first to know all the news, read more about cryptocurrencies and mining at CRYPTO-MINING.BLOG.

Subscribe to CryptoWikies now and get exclusive access to a wealth of knowledge from our team of experts. They will keep you up to date with all the latest trends, strategies and ideas regarding bitcoin and altcoin mining and trading.

Subscribe to our Telegram: CRYPTO WIKIES | Bitcoin & Altcoins Mining

CRYPTO-MINING.BLOG – Stay up to date with the latest news about cryptocurrencies and mining!

Leave a Reply

Your email address will not be published. Required fields are marked *