Web3.js Ethereum JavaScript API
In simple terms, web3.js is a collection of libraries that allows us to interact with a local or remote Ethereum Node.
What is an Ethereum Node?
Let’s understand this with the help of the above picture.
The above figure is an Ethereum Blockchain Network where each and every system is connected with each other through a p2p network. In the Ethereum Blockchain world, these systems are called Ethereum Nodes.
So, web3.js helps us to interact with these Ethereum Nodes via HTTP, IPC, or Web Socket.
Now you must be wondering why anyone will want to interact with these Ethereum nodes. And why do we need web3.js?
Importance of web3.js
1) It helps you to query data from the Blockchain. For example – to get the balance of an account, to send ether to another account, etc.
The web3.js library is a collection of modules that contain functionality for the Ethereum ecosystem.
web3-eth
is for the Ethereum blockchain and smart contracts.web3-shh
is for the whisper protocol, to communicate p2p and broadcast.web3-bzz
is for the swarm protocol, the decentralized file storage.web3-utils
contains useful helper functions for Dapp developers.
2) It helps you to create Decentralized Applications (Dapps). Your real-world technology, i.e. your frontend cannot directly interact with blockchain world technology i.e. your smart contract. As both of these belong to two different worlds. The web3.js library acts as a bridge between your real world and the blockchain world.
Web3.js Installation
Following are the system requirements before installing the web3.js on your system:
- NodeJS v12 or later
- Install the latest version of Visual Studio
- Ganache – A local Blockchain Simulator
Create an empty folder and open the folder in the VS Code.
Run the following command in the VS code terminal.
npm init --yes
Code language: Bash (bash)
npm install web3
All the packages related to web3 will get installed using the above command.
Connecting To The Blockchain
Let us connect to the Blockchain using the web3.js library.
Step-1 – Create a web3.js
file in your VS code folder.
Step-2 – Open the Ganache and click on “Quickstart Ethereum”.
Step-3 – Copy the following code in the web3.js
file.
let Web3 = require("web3");
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"));
console.log(web3);
Code language: JavaScript (javascript)
Let us understand this code.
1st line – To import the web3 package.
2nd line – To create an instance of web3. In this, we have provided the RPC URL of the Ganache Blockchain i.e. HTTP://127.0.0.1:7545 which will help web3 to connect with the Ganache Blockchain.
3rd line – To write the web3 object on the VS code terminal.
Step-4 -Run the following command in the VS code terminal.
node web3.js
Code language: Bash (bash)
Getting The Balance Of An Account
Let us use the web3-eth
module to get the balance of an account.
To get the balance of an account just add the following code to our previous “Connecting To The Blockchain” code.
async function getBalance() {
const balance = await web3.eth.getBalance(
"Account Address From Ganache"
);
console.log(balance);
}
getBalance();
Code language: JavaScript (javascript)
The account balance that you will see on the terminal is in wei.
You can check by using ether to wei calculator.
Converting Wei To Ether
Let us use the web3.utils
module to convert wei to ether.
let Web3 = require("web3");
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"));
// console.log(web3);
async function getBalance() {
const balance = await web3.eth.getBalance(
"Ganache Account Address"
);
const balanceToEther = await web3.utils.fromWei(balance, "ether");
console.log(balanceToEther);
}
getBalance();
Code language: JavaScript (javascript)
Sending Ether From One Account To Another Account
Let us send ether from one account to another.
Copy the following code into your js
file.
let Web3 = require("web3");
let web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"));
// console.log(web3);
async function send() {
var txnHash = await web3.eth.sendTransaction({
from: "address 1",
to: "address 2",
value: web3.utils.toWei("1", "ether"),
});
console.log("Transfer successful");
}
send();
Code language: JavaScript (javascript)
Here we are sending 1 ether from address 1
to address 2
.
To send ether from one account to another we need to convert ether into wei.That’s why we are using value: web3.utils.toWei(“1”, “ether”) to convert ether into wei.
Before ether transfer.
Transfering ether.
After Ether Transfer.
Interacting With A Smart Contract
Let us interact with a smart contract using the web3.js library.
//SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.9.0;
contract demo {
uint private a;
function get() external view returns(uint){
return a;
}
function set(uint _a) external{
a=_a;
}
}
Code language: JavaScript (javascript)
We will require the ABI and Contract Address of the smart contract to interact with it. For that, you can use the Remix IDE. Deploy the smart contract on the Ganache using the Remix IDE.
Once you have the ABI and Contract Address of the smart contract use it in the below code to create the instance of your smart contract.
const Contract = require("web3-eth-contract");
Contract.setProvider("HTTP://127.0.0.1:7545");
async function instanceContract() {
ABI = Your ABI of code
ContractAddress = "Contract Address";
const contract = new Contract(ABI, ContractAddress);
console.log(contract);
contract.methods
.get()
.call({ from: "account address " })
.then(console.log);
}
instanceContract();
Code language: JavaScript (javascript)
contract.methods.get().call({ from: "account address " }).then(console.log)
– This is used to call the get()
from the deployed smart contract.
This is how we can interact with a smart contract using web3.js.
Conclusion
I hope by now you have understood how web3.js library works. We learned so many things such as what is web3.js library,types of modules in it, how to check account balance, how to transfer ether from one account to another, etc.
If you like my web3.js blog, you’d love our web3 learning path that helps you become an employable web3 developer in a few months. Try out the first solidity programming course.
Sharing is caring
Did you like what Kshitij wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses:
262 students learning
Kshitij
Learn web3.js | Introduction to Web3.js library
145 students learning
Kshitij
Ethereum and Solidity Test