I've been revisiting ethers.js
recently to refresh my understanding of the details and to write a simple tutorial called "WTF Ethers" for beginners.
Twitter: @0xAA_Science
Community: Website wtf.academy | WTF Solidity | discord | WeChat Group Application
All the code and tutorials are open-sourced on GitHub: github.com/WTFAcademy/WTF-Ethers
In this lesson, we will introduce the Provider
class in ethers.js and use it to connect to a node to retrieve information from the blockchain.
Provider
Class
The Provider
class provides an abstraction for connecting to the Ethereum network and offers a concise and consistent interface for standard Ethereum node functionality. In ethers
, the Provider
class does not handle user private keys and can only read information from the blockchain, making it safer compared to web3.js
.
The most commonly used provider in ethers
is jsonRpcProvider
, which allows users to connect to a specific node service provider.
jsonRpcProvider
Creating an API Key for the Node Service Provider
First, you need to register and create an API Key on the website of the node service provider (e.g INFURA, ALCHEMY). In the "Tools" section of the "WTF Solidity" tutorial, we introduced the methods to create API Keys for two projects, Infura and Alchemy. You can refer to the tutorial for more information.

Connecting to Infura Node
Here, we will use Infura as an example. After creating the Infura API Key, you can create a Provider
variable using the ethers.JsonRpcProvider()
method, which takes the URL of the node service as a parameter.
In the following example, we create providers to connect to the ETH
mainnet and the Sepolia
testnet:
Using the Provider
to Retrieve Blockchain Data
The Provider
class provides convenient methods to retrieve data from the blockchain:
1. Use the getBalance()
function to retrieve the ETH
balance of Vitalik on the mainnet and the Sepolia testnet:

2. Use the getNetwork()
function to check which chain the provider is connected to.

3. Use the getBlockNumber()
function to retrieve the current block number:

4. Use the getTransactionCount()
function to retrieve the transaction count of a wallet address.

5. Use the getFeeData()
function to retrieve the current recommended gas settings, which are returned as bigint
.

6. Use the getBlock()
function to retrieve information about a specific block. The parameter is the block number:

7. Use the getCode()
function to retrieve the bytecode of a contract at a specific address. In the example below, we use the contract address of WETH
on the mainnet:

Summary
In this lesson, we introduced the Provider
class of ethers.js and created a jsonRpcProvider
with Infura's node API key to read on-chain information from the ETH
main network and Sepolia
test network.