The Web3 library is a powerful toolkit that provides developers a number of functions to read and write to/from Ethereum and Ethereum Classic. Web3 also allows users to interact with smart contracts on websites and other front-end applications, and powers software like MetaMask.
First-time users will need to activate a Bloq account and subscribe to a Connect plan. See the Getting Started guide for more information.
Additionally, first-time Web3 users must install the web3.js library. Navigate to the directory where you’d like to install it and download with
npm install web3.
As mentioned previously, web3.js requires a connected node to execute calls to/from the network. The above code checks that Web3 is properly installed, then initializes the ‘web3’ value with the Bloq Connect Ethereum address, which is a node designed to interact with Connect API calls.
You’ll need to supply your own project id. Create a new one and manage existing project ids through the Bloq console.
Ethereum Calls with Web3
For example, the code below finds and prints the current Ethereum block number:
To execute more calls, like to find the number of transactions for the most recent block, just append the relevant call:
Some calls, like
getBlockTransactionCount, support or require one or more parameters. For a list of all web3.eth commands, and the parameters/return values, please see this web3 documentation.
Ethereum Classic on Web3
The Web3 library is interoperable with Ethereum, Ethereum Classic, and other Ethereum-derived chains. Bloq Connect supports ETC alongside ETH, and as such, our above code can easily be modified to instead interact with the Ethereum Classic chain.
All you have to do is change the Connect node address from
etc, like so:
You can also modify the code to incorporate a
coin value, so that ETH/ETC may be used interchangeably:
Lastly, using the same strategy we deployed to query BTC and BCH simultaneously, you can package your code into a function that takes a
coin input and call to ETH/ETC at the same time. Make sure to update your console.log outputs to highlight which chain is queried:
The above code is a “kickstarter” for interesting and powerful programs fueled by Web3 and Bloq Connect. Incorporate more nuanced functions or implant the web3.js into larger projects to build analytics tools, interact with smart contracts, create trading alerts and bots, and more.