What is web3.js?

Web3.js is an open-source library of JavaScript built by the Ethereum foundation to allow end users to interact with a local or remote Ethereum node using HTTP, IPC, or WebSocket.

The web3.js library is integral to decentralized apps (Dapps) as it helps connect the backendBlockchain i.e. Ethereum to the frontend. It provides functions that allow the frontend to communicate with an Ethereum node via the JavaScript Object Notation-Remote Procedure Call (JSON-RPC) protocol.

The architecture of a Dapp

JSON-RPC

For better understanding, JSON-RPC is divided into two parts: JSON and RPC. JSON is the more commonly known term of the two. It is a lightweight format representing and transporting data from the server to an application.

RPC represents the execution of a procedure on a remote server. In the case of a peer-to-peer network like Ethereum, a single node is considered to be the server. Execution of procedures remotely decouples the frontend from the backend, thus decreasing the complexity of implementing a Dapp and increasing security. However, the client must tell the server which procedure to execute and pass the required parameters to achieve this.

// JSON-RPC Request
{
"jsonrpc" : "2.0",
"method" : "Addition",
"params" : [1, 2, 5],
"id" : "121"
}
//JSON response
{
"jsonrpc" : "2.0",
"result" : 8,
"id" : "121",
"error" : null
}

The example above shows a JSON-RPC request being sent to the server, asking to execute the addition procedure with input parameters 1, 2, and 5. After execution, the server returns the result of the procedure in JSON format.

Similarly, web3.js sends JSON-RPC requests to the Ethereum node to execute a particular procedure within a smart contract deployed on the network. The node executes the procedures and returns the result to the Dapp.

The web3.js packages

A web3.js contains multiple packages, each providing functions to do specific tasks. The important packages of web3.js are as follows:

  • eth

  • shh

  • bzz

  • utils

The eth package

The eth package is primarily used to interact with Ethereum and smart contracts. It contains functions to get the balance of a particular Ethereum account, check if a node is mining or not, and subscribe to specific events. This package can further be divided into more categories shown below:

  • Contract: The contract object makes interacting with the smart contracts deployed on the blockchain easier. This object can further be used to call functions to create new contracts or sign transactions locally.

  • Accounts: The accounts object contains functions to generate Ethereum accounts and sign transactions.

  • Personal: The personal package allows the Dapp to interact with the Ethereum node’s accounts.

The shh package

The shh package allows the Dapp to interact with the whisper protocol. Whisper is a peer-to-peer communication protocol to allow Dapps built on Ethereum to communicate with each other. It is also used for broadcasting information and money with messages.

The bzz package

The bzz package allows the Dapp to interact with Swarm. Swarm is a peer-to-peer network used for decentralized storage and communication services.

The utils package

The utils package contains utility functions to convert between number systems and more. These functions are implemented to be used within the Dapp and other web3.js packages.

Example

In this example, we will use web3.js to connect with a node on the mainnet of Ethereum. After the connection, we will get the balance of an account on the Ethereum account.

Before we proceed with the example, we need a few details listed below:

  • web3.js: web3.js is an external library that needs to be installed using the npm install web3 command. However, we do not need to do that right now, as the environment provided below already contains web3.js.

  • The Ethereum node's address: To interact with Ethereum, we need to connect to a node on the Ethereum network. We can set up a node on the Ethereum network, but that would be time-consuming and expensive. However, we can use services like Moralis and Infura, which offer the web3 backend’s infrastructure as a service. In this Answer, we will use Infura. To get the address of a node, create an account on Infura and then create a project of Web3 API (Formerly Ethereum). Then we will get an API key. This API key will be used to form a connection to the Ethereum node.

  • Address of an Ethereum account: Etherescan.io contains information about all the Ethereum accounts and their transactions. We can find account addresses under the Latest transactions.

Note: The Infura API key is provided for testing purposes only. If you want to explore this further, you can get your own free API key from Infura.

const Web3 = require('web3')
const jsonRpcURL = 'https://mainnet.infura.io/v3/917c4f75f17a4e28b78263cddd8f1b46' 
const web3 = new Web3(jsonRpcURL)
// Feel free to change the account address
const address = '0xd5268a476aadd1a6729df5b3e5e8f2c1004139af' 

async function GetAccountBalance(accountAddress)
{
    wei = await web3.eth.getBalance(address)
    console.log("Wei : ", wei)
    ether = web3.utils.fromWei(wei, 'ether')
    console.log("Ether : ", ether)
}

GetAccountBalance(address)
Get the balanace of an account on the Ethereum mainnet

Explanation

  • Line 2: We save The Infura API key in jsonRpcURL.

  • Line 3: We connect web3 to Infura using the API key.

  • Line 5: We save the address of an Ethereum account in address.

  • Line 9: The getBalance() returns a promise as it takes time to execute, so the await keyword is added to ensure that the execution stops until the balance is fetched and stored in wei. To use await, we make the function GetAccountBalance() asynchronous by adding the async keyword.

  • Line 11: The value returned by getBalance() is in wei, so it is converted to Ether using fromWei().

Note: Wei is a smaller part of Ether. Consider an Ether to be a dollar and wei a penny. One hundred pennies are equal to a dollar. However, in this case 1,000,000,000,000,000,0001,000,000,000,000,000,000 wei is equal to one Ether.

Copyright ©2024 Educative, Inc. All rights reserved