Before we begin, register an account at Infura to get access to Ethereum node endpoints for testing.

Dependencies:

yarn add web3

1. Create a Network Instance

You can listen to transactions and events across the entire blockchain:

const Web3 = require("web3");

const { INFURA_WSS_ENDPOINT } = process.env;

const web3Instance = new Web3(INFURA_WSS_ENDPOINT);

web3Instance.eth
	.getBlockNumber()
	.then((blockNumber) => console.log("Current block number: ", blockNumber));

2. Create an ERC-20 Contract Instance

You can listen to events and call methods on a given smart contract:

const Web3EthContract = require("web3-eth-contract");
const ContractABI = require("./ContractABI.json");

const { INFURA_WSS_ENDPOINT } = process.env;

Web3EthContract.setProvider(INFURA_WSS_ENDPOINT);

//https://goerli.etherscan.io/address/0xa05F7df24D81438CB2306A07d1204967b48f20d2
const CONTRACT_ADDRESS = "0xa05F7df24D81438CB2306A07d1204967b48f20d2";

const contractInstance = new Web3EthContract(ContractABI, CONTRACT_ADDRESS);

contractInstance.events
	.Transfer()
	.on("data", (event) => console.log("Transfer: ", event))
	.on("changed", (changed) => console.log("Changed: ", changed))
	.on("error", (err) => console.log("Error: ", err.message, err.stack))
	.on("connected", (str) => console.log("Connected: ", str));

Repository on GitHub: https://github.com/vanduc1102/samples/tree/master/nodejs/web3-nodejs