As you are reading this guide, I assume you have a keen interest in exploring the buzzword of modern-day technology called web3.
Think about the Facebook app launch in 2004 and its evolution today. Or you may notice the emergence of online stores like Amazon or Alibaba out of nowhere.
Web3 is expected to be the next wave of its predecessors. If you want to build your career in a future-proof technology or if you want to grab the new opportunities arising in the development sector, then I assume it’s the best time to know about the starting point of web3.
What is web3.js?
According to the web3.js documentation, web3.js is a collection of libraries that allow us to interact with a local or remote Ethereum node using HTTP, IPC or WebSocket. In simple words, it’s a collection of libraries that enable us to interact with the Ethereum node. You can use it serverside or in a web browser.
Assume you are a developer and have made a soothing website for a purpose. You want to connect it with blockchain or with a smart contract written on a decentralized app already deployed on the blockchain.
Now, The question is: How will you establish communication between them?
That’s the time when web3.js comes into play. web3.js acts as an interface between the website space and the blockchain world. Interacting with the blockchain world means communicating with an Ethereum node as written in the documentation.
You may notice from the image above a bunch of nodes are running Inside the Ethereum Network. That mean’s a single server is not acting as a database or storage. Multiple nodes are available inside the Ethereum network. Those serve the same purpose as databases or storage.
We used to talk to that node or Ethereum client through the web3.js library over a remote procedure call protocol named JSON-RPC. It’s very similar to an API, but you have an RPC for every node potentially instead of one server.
Here, We have the client-side application as the frontend, and the web browser accepts crypto with a plugin like Metamask. Web3 helps us interact with the Ethereum blockchain network by contracting API calls or subscribing to the event.
Blockchain is maintained by blockchain nodes. Other application clients like Metamask and Coinbase connect to these nodes in order to query and update the blockchain data. Usually, these clients run their own node.
Then there are some other clients like Infura. Infura allows accessing their blockchain node via an API.
We will use Ganache today to connect to a personal blockchain. Ganache is a personal blockchain for rapid Ethereum distributed application development.
How to install web3.js
Let’s move to the visual studio code and open the terminal. On the terminal type:
If node.js is installed on your computer, you will get the version number as a return. If not, you must visit the link below and follow the procedure to install node.js on your operating system. You can choose the LTS version over the current one since LTS will provide long-term support.
Before installing web3, we need to create a
package.json file where we will install all the dependencies. For this, we need an
npm package installer that comes automatically with node.js installation.
Run the following code on the terminal:
npm init -y
package.json file will be created inside the folder.
Now we will install web3.js inside the
npm install -save web3
Web3 will be installed, and it will be added as a dependency inside the
package.json. But to use web3, we need to import it.
Let’s run the node in the terminal.
const Web3= require("web3");
We have created a
Web3 class here. From this
Web3 class, we can instantiate objects.
How to Install Ganache
Let’s try to connect web3.js with a test blockchain. The test blockchain basically helps us build our testing environment so that we can write our smart contract code, deploy it to the test blockchain locally without impacting anybody else and determine if it’s working correctly.
We are going to use Ganache here for this purpose. Ganache is a product that gives us a test blockchain, as well as some utilities to help us deploy contracts to that test blockchain, develop applications and then execute tests against this local environment. If you can understand how web3.js interacts with Ganache, then it will be easier for you to understand the interaction between web3.js and any blockchain.
Let’s move to the https://trufflesuite.com/ganache/index.html and click the download windows button if you are a windows user. Just follow the procedure; it will be installed on your system.
After installation, it will ask you to choose between the “Quick start” or “New workspace” option. Creating workspaces allows us to generate multiple test blockchains. For simplicity, we will use the “Quick start” option here. That’s it.
We have created and launched our test blockchain successfully!
Have a look at the GUI of the Ganache. Here we have multiple addresses and their balances available in the accounts section. Although it’s not real accounts, we can use those to connect with web3.js and get the balance from the account. We may use web3.js to transfer some amounts also. The blocks and transactions sections are currently empty. It will show some data when we initiate some transactions.
But first things first. Let’s connect Ganache with web3.js first.
Connect web3.js with Ganache
We can connect to a node by passing a provider into the web3 constructor. This provider can be either a
HttpProvider– allows us to talk to the node via HTTP endpoints
WebSocketProvider– similar to HTTP but allows subscription
IpcProvider– connects to a node via IPC calls( for a blockchain node running on a local machine in a separate process)
Let’s create a new object now and try to connect it with Ganache with the help of
let myweb3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"));
We have taken the RPC server URL from ganache GUI and placed it inside the
Web3() constructor as a
How to Get the balance of an account with Node.js and Web3.js
Now we will try to get the balance of an account from the ganache with the help of web3.js.
To fetch the balance of an account just type
Web3.eth.getBalance() and pass an account address as a parameter.
You have to
console.log the function to get the output on the terminal.
We will get the balance in terms of wei. One ether = 1,000,000,000,000,000,000 wei (1018).
If you want to convert it to eth then you need to use another pre-installed package of
We have written a function here and used the
web3.utils package to convert the Wei in Ether. You will get the balance in the ether now.
Move to the Ganache and check the balance. You will find the balances of those addresses are changed. If you visit the transaction tab above, you will see one transaction hash is available now. That means the last transaction was valid. If you visit the block tab, you will see more blocks have been added to the chain.
How to transfer account balance with Node.js and Web3.js
It is possible to transfer the balance from one address to another address with the help of the
Here we used the
sendTransaction method of
web3.eth to transfer an amount. We used
web3.utils library to declare the amount we are transferring and to convert the amount into wei.
That was a brief introduction and some primary use cases of web3.js.
We will try to explore some more interesting topics related to web3.js in future blogs. In the meantime, you can read the documentation links below to get familiar with the web3.js library.
Learn Solidity Course
Solidity is the programming language of the future.
It gives you the rare and sought-after superpower to program against the “Internet Computer”, i.e., against decentralized Blockchains such as Ethereum, Binance Smart Chain, Ethereum Classic, Tron, and Avalanche – to mention just a few Blockchain infrastructures that support Solidity.
In particular, Solidity allows you to create smart contracts, i.e., pieces of code that automatically execute on specific conditions in a completely decentralized environment. For example, smart contracts empower you to create your own decentralized autonomous organizations (DAOs) that run on Blockchains without being subject to centralized control.
NFTs, DeFi, DAOs, and Blockchain-based games are all based on smart contracts.
This course is a simple, low-friction introduction to creating your first smart contract using the Remix IDE on the Ethereum testnet – without fluff, significant upfront costs to purchase ETH, or unnecessary complexity.
Yassin Mahmud is a blockchain enthusiast and content creator in the blockchain space. Driven by his passion for distributed technology, he switched to the blockchain sector from the MERN stack development. With over half a decade of experience at present, he is trying to contribute to the blockchain community with his writing. When Yassin is not writing, he can be found walking along the beaches or touring spectacular travel destinations.