Access Ethereum Data via Web3.js and Infura.io

Access Ethereum Data via Web3.js and Infura.io

5 minutes to kickstart the blockchain journey.

Recently I have been playing with Ethereum log and with the emergence of blockchain, a lot of tools around those are emerging some being beneficial. To build tools sometimes we need to access contracts for those Ethereum projects. One easy way to interact and pull data from this contract is through web3.js.
There are APIs that etherscan.io does expose, but to execute or interact with contract web3.js is one of the best and easy solutions available. Be executing the function of a contract to get data, events, etc.

As per official documentation

web3.js is a collection of libraries that allow you to interact with a local or remote Ethereum node using HTTP, IPC, or WebSocket.

We will use an HTTP provider via Infura.io service, though one can host their own nodes. Infura.io provides a powerful Blockchain Development Suite.

Pre-requisites

  • NodeJS (with NPM or YARN installed)
  • Infura.IO account (it's free to start with!)

Setup Project on Infura.io

Sign up for free on Infura.io. Once done we will create a sample project which will give us an endpoint to register in our code for executing our request to access Ethereum Data.

On signing in to the dashboard, you will see a dashboard like below 1_infura_dashboard.JPG

Click on the ETHEREUM tab on the left top menu, and then Click CREATE A PROJECT. Give a meaningful name of your choice. We will name eth-contract-test

2_eth_create_project.JPG

On Create it will take you to project details, we are more interested in the HTTP endpoint. For this blog purpose, we are keeping Mainnet as the default Ethereum network. Copy HTTPS endpoint which is form https://mainnet.infura.io/v3/<project-id>

3_project_details.png

We are now ready to use this project in our codebase. Before starting on the development part we will pick a random Ethereum project to capture details of the contract. We will use this contract of Hashmasks https://etherscan.io/address/0xc2c747e0f7004f9e8817db2ca4997657a7746928 to execute some functions return by Contract Application Binary Interface(ABI).

ABI is the standard way to interact with contracts in the Ethereum ecosystem, both from outside the blockchain and for contract-to-contract interaction.

NodeJS interaction with Ethereum contract via web3.js

We will be using NodeJS in this case but web3.js equivalent for few other languages is available too as per their Github documentation.

Initialize NodeJS project with default values as below:

npm init -y

We will install 2 dependencies one to interact with Ethereum Contract obviously which is web3 and Axios to make an HTTP call to fetch ABI contract from etherscan.io.
Though ABI contracts for different Ethereum token standards are mostly the same, but rather than maintaining JSON files in code for ABI, we will make calls to etherscan.io portal to fetch and pass to our web3 Contract read API.

npm install web3 --save
npm install axios --save

NodeJS Code

Bring in required imports as below

const Web3 = require("web3")
const axios = require('axios');

Initialize our web provider to access Ethereum Data via Infura.io

const web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/<your_project_id>"))

Define const and check if Ethereum contract address is valid, optional check if required

const CONTRACT_ADDRESS = "0xc2c747e0f7004f9e8817db2ca4997657a7746928"
if(!web3.utils.isAddress(CONTRACT_ADDRESS)){
    console.log("Not Valid Contract Address")
    return
}

Below we now first make a call to etherscan.io using their APIs to get ABI for a given contract, using promise we then call Function named "symbol" to return symbol of given Ethereum contract which returns HM. Also, we make parameterized Function call isMintedBeforeReveal which takes uint256, we pass the index as 1 which returns true.

axios.get(`https://api.etherscan.io/api?module=contract&action=getabi&address=${CONTRACT_ADDRESS}`)
    .then(response => {
        var contractABI = "";
        contractABI = JSON.parse(response.data.result);
        if (contractABI != ''){
            console.log(contractABI) // prints ABI to reveal functions, event and other data we can play with.
            console.log("\n\n")
            const contractDetails = new web3.eth.Contract(contractABI, CONTRACT_ADDRESS)

            //get symbol for given contract 
            contractDetails.methods.symbol().call({ from: CONTRACT_ADDRESS }, function (error, result) {
                console.log("Result of symbol: " + result)
            });

            //get isMintedBeforeReveal for given contract  against Index 1
            contractDetails.methods.isMintedBeforeReveal(1).call({ from: CONTRACT_ADDRESS }, function (error, result) {
                console.log("Result of isMintedBeforeReveal: " + result)
            });
        } 
        else {
            console.log(`Error fetching ABI contract for address ${CONTRACT_ADDRESS}`);
        }            
    })
    .catch(error => {
        console.log(error);
});

You can compare results for the same by going to etherscan.io URL for that contract you specified --> then Contract tab --> Read Contract tab which will show the same function returned as part of ABI.

Complete server.js file

Entire code can be found on github

const Web3 = require("web3")
const axios = require('axios');

const web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/<your-infura-project-id>"))

const CONTRACT_ADDRESS = "0xc2c747e0f7004f9e8817db2ca4997657a7746928" //contract address of your choice of ethereum

if(!web3.utils.isAddress(CONTRACT_ADDRESS)){
    console.log("Not Valid Contract Address")
    return
}

axios.get(`https://api.etherscan.io/api?module=contract&action=getabi&address=${CONTRACT_ADDRESS}`)
    .then(response => {
        var contractABI = "";
        contractABI = JSON.parse(response.data.result);
        if (contractABI != ''){
            console.log(contractABI) // prints ABI to reveal functions, event and other data we can play with.
            console.log("\n\n")
            const contractDetails = new web3.eth.Contract(contractABI, CONTRACT_ADDRESS)

            //get symbol for given contract 
            contractDetails.methods.symbol().call({ from: CONTRACT_ADDRESS }, function (error, result) {
                console.log("Result of symbol: " + result)
            });

            //get isMintedBeforeReveal for given contract  against Index 1
            contractDetails.methods.isMintedBeforeReveal(1).call({ from: CONTRACT_ADDRESS }, function (error, result) {
                console.log("Result of isMintedBeforeReveal: " + result)
            });
        } 
        else {
            console.log(`Error fetching ABI contract for address ${CONTRACT_ADDRESS}`);
        }            
    })
    .catch(error => {
        console.log(error);
});

Now execute file server.js with node server.js

On execution we see it logs ABI, along with the result of the method/function of an Ethereum contract to get data against the same to the console.

4_Node_result.JPG

Voila, we have ABI which we can play around with, to get Ethereum Data. This is just a base to get started, we will keep experimenting on this area to come up with a more exciting blog related to Blockchain.

Web3.js has equivalent libraries in Haskell, Java, PHP, Purescript, Python, Ruby, Scala.

Resouces

Thank you for reading, If you have reached it so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback and suggestions!

I would love to connect with you at Twitter | LinkedIn.

Did you find this article valuable?

Support Virendra Oswal by becoming a sponsor. Any amount is appreciated!