web3.js
and ethers.js
. Therefore, it’s essential to ensure a well-configured development environment before proceeding. Go over our node.js setup guide for Web3 projects, Web3 node.js: From zero to a full-fledged project, if you are starting from zero.
npm i web3
.Install the ethers.js library with npm i ethers
..env
file located in your project’s root directory. If you haven’t already, install the dotenv
package using the command npm i dotenv
.
This approach helps us manage sensitive information, preventing accidental pushes to a version control platform.
index.js
file and insert the following code.
For illustrative purposes, we’re employing a fairly straightforward use case. The script executes the eth_getBlockByNumber
method every 10 seconds to fetch details of the latest block. Notably, each request is served by a different endpoint.
RPC_NODES
that maps the variables of the Web3 instances to their respective RPC URLs, which are fetched from environment variables. This is mostly done so we can print in the console which variable we are using each time we send a request.web3Instances
object. This object’s keys are the instances’ names, and the values are the instances themselves. This way, the instances are all created at once when the script is started; this logic also keeps the code more maintainable as you only need to edit the RPC_NODES
object if you want to add or remove endpoints.web3Instances
object and the counter variable keep track of the current Web3 instance.node index.js
command in your terminal; the script will start and call the function every 10 seconds.
Here is an example of what the response looks like: