Interact with the Ethereum blockchain from Web apps

Web 3 is one of the biggest Internet platforms of the future. Most experts believe that decentralized applications based on Web 3 can transform the virtual world. It’s known as the last and third phase of the Internet in the world.

Web 1 is static 🌐 Web 2 is dynamic 🌍 Web 3 is decentralized 🌌  

What is Web3.JS?

Web3.js is a collection of libraries that allow you to interact with a local or remote Ethereum node using different protocols HTTP, IPC or WebSocket.

In this article, we will see quickly how to write a web application that displays the balance of any Ethereum address. So we need first to connect to the Ethereum blockchain to read this data ( balance ) then we will display it to the user who asking for it (front-end)

Demo:

Let's do it!

As requirement, we’ll need to use: Node Js, Web3.Js, Express Js to manage Routes,  EJS as template engine and body-parser as middleware to parse the data of an incoming request. 

The scenario is the next :

  1. We catch the address sent by user
  2. To connect to the mainnet we use infura as RPC Server
  3. We connect to the mainnet using Web3.js
  4. We check if the address provided by user is correct
  5. If yes, we convert the balance from wei to ether
  6. Then we display it ! 👍

Step 1: Open Node Js and install modules


$ npm install --save express web3 body-parser ejs

Step 2: Get RPC Server

To get access to the Ethereum mainnet we will need to connet on JSON-RCP provider. I use Infura.io, it’s free and very simple to setup. You can create your free account here and generate your API key.

If you want to do your tests locally, you can install a local blockchain network with Ganache

Step 3: Create our Web App

Once everything installed, On the root of your project folder, create new file and name it server.js :

const app = require('express')()
const bodyParser = require('body-parser')
const Web3 = require('web3')

// Set port listener
const port = 3000
app.listen(port, () => console.log('ok'))

// Middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// Template engine
app.set('view engine', 'ejs')

// Routes 
app.get('/', (req, res) => res.render('index.ejs'));
app.post('/', (req, res) => {
    // Handel posted data (address)
    let address = req.body.address

    /* Connect to Ethereurm mainnet
    ** If you use Ganache: Update const network= '' By the RPC SERVER created by Ganache.
    */
    const network = 'https://mainnet.infura.io/v3/_YOUR_API_KEY_HERE_'
    const web3 = new Web3(Web3.givenProvider || network);

    // Check if the address is valid
    if (web3.utils.isAddress(address)) {
        web3.eth.getBalance(address, (err, bal) => {
            //Convert the blance fromWei toEther and send it to the frontend
            res.render('index.ejs', { balance: Web3.utils.fromWei(bal, 'ether') + " ether" })
        });

    } else {
        res.render('index.ejs', { error: `Invalid address: "${address}"` })
    }
})



Now we will manage our view, remember that we installed EJS previously, w’ll use it to pass the data easily. 
As ejs tradition want we need to create a new folder in the root of your folder project and name it “/views” inside of it we create our “index.ejs”. views/index.ejs


<form action="/" method="post">
    <input class="w-90 border p-3 rounded-l-full" name="address" required="" type="text" placeholder="0x" />
    <button class="bg-indigo-600 text-white p-3 rounded-r-full">Get Balance</button>
</form>

<!-- Display balance if address is valid -->
<% if (locals.balance) { %>
    <p class="text-green-600 font-bold">Balance: <%= balance %> ETH</p>
<% } %> 

<!-- Display error if address is invalid -->
<% if (locals.error) { %>
    <p class="text-red-600"><%= error %></p>
<% } %>

How to interact whith ERC20 Tokens using Web3.JS?

The approach is basically the same as the one we saw with Ethereum in the previous example.

The difference is that when we want to interact with an ERC20 token, we have to indicate to our web3.js library what are the functions we can use to interact with this smart contract. We call this list of functions ABI (Application Binary Interface).

It’s an interface specific to each ER20 token that defines the functionality of the token and allows us to interact with it.

So if we want to get balance of ERC20 Token (Tether USDT,  for example) we need to create an instance of this smart contract to interact with it, to do that we need to indicate the ABI and the contract address of Tether.

// Tether UDST, Contract address and ABI
const contractAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7'
const abi = [...]

// Create an instance of the contract
let contract = new web3.eth.Contract(abi, contractAddress);

// Get balance of Tether address
let walletAddress = '0x702f25a8c9c090239be779b567e5246ebb7e31cd'
contract.methods.balanceOf(  walletAddress ).call( (err, res) => console.log(res) )

How to get ABI of any ERC20 ?

  1. Open www.etherscan.io
  2. Use the search bar to find the token you asking for.
  3. It’s will display the smart contract address.
  4. Click on it, then open the “contract tab” to get the ABI JSON file fo the token you looking for

Leave a Reply