Tutorial: Web3 Endpoints & Web3.js

The purpose of this tutorial is to provide a walkthrough of how to interact with a blockchain using a Web3 endpoint. To cover the most users at once, we will focus on JavaScript and EVM-compatible chains.

Before we get started, you’re going to need these tools:

  1. Node.js & Web3.js

  2. An EVM-compatible endpoint (If unsure, just grab Ethereum)

  3. A text editor (We’ll use Virtual Studio Code here)

  4. Command Line

 

Below is a short script to fetch the latest block (aka block height) from the network:

var Web3 = require('web3'); var provider = 'ADD_YOUR_EVM_NODE_URL'; var web3Provider = new Web3.providers.HttpProvider(provider); var web3 = new Web3(web3Provider); web3.eth.getBlockNumber().then((result) => { console.log("Latest block is ",result); });

 

A brief rundown of what we’re doing:

  • Line 1 imports the Web3 library into our file.

  • Line 2 saves the endpoint into a variable.

    • This is where you paste the endpoint URL over 'ADD_YOUR_EVM_NODE_URL' (But keep the single quotation marks 🙂)

  • Line 3 instantiates a Web3 HttpProvider instance.

  • Line 4 creates a Web3 instance

  • Lines 5 - 7 call getBlockNumber and log a successful result to the console.

 

Once you’ve got your endpoint pasted into line 2, save your file. For the purposes of this tutorial, I’m saving it as “testing.js”.

Open the command line and run the file:

node testing.js

 

If you’ve done everything correctly up to now, you should see something like the following:

Congrats! You’ve just interacted with a Web3 network. Visit Web3.js on Github to find API’s that will allow you to build real applications on an EVM-compatible blockchain.