In this post I show an easy way to interact with any Ethereum-compatible blockchain using TypeScript and Node.js.
I have recently been developing an app that interacts with an Ethereum blockchain and was expecting it to be incredibly complicated. But it’s not.
Here is the surprisingly simple setup. All we need are three things:
We are going to use TypeScript and
ts-node which require a little bit of extra setup but a big pay-off in helping with code correctness.
Create a file called
tsconfig.json with the following configuration:
Create a file called
index.ts with the following script, replacing the Infura Project ID and wallet address where indicated:
We can now run the script:
… an should expect the following output to the console:
That is all there is to it, but read on for a bit more of a code breakdown and examples of using other Layer 2 chains.
There are a few concepts to break down:
This is creating a
provider using Infura Mainnet, the main Ethereum blockchain. There are other test networks available.
Ethers has a specific Infura provider however we will use
JsonRpcProvider as it is more generic.
For example with one small change we can now also query a balance on the Layer 2 Polygon network by changing just the RPC:
…or any other Layer 2 chain, e.g. Gnosis Beacon Chain
Once we have the
provider we use it to fetch the raw balance in Wei which is the smallest unit.
Thankfully ethers provides a convenient way to convert this to more familiar ETH:
In this post we learned an easy way to interact with any Ethereum blockchain using TypeScript and Node.js. We fetched a balance from an Ethereum-compatible wallet address by using ethers.js (a library for interacting with Ethereum nodes) and Infura (a service providing access to Ethereum nodes).
Finally we learned how to convert the balance from Wei into ETH.
This gives the basic building blocks and a starting point for interacting with any Ethereum blockchain.
I am an experienced Product Designer and Software Engineer with a passion for making and crafting digital products, tools and services that are useful, empowering or inspiring to others.