How to Use a Provider in Ethers.js
This guide will introduce you to use a Provider in Ethers.js and level up your Web3 stack!
What is a Provider in Ethers.js?
A Provider is an abstraction to the Ethereum Network that allows developers to connect to a standard Ethereum node permitting read-only access to the blockchain.
Ethers.js also offers providers for different services each connecting to their respected network. This includes the AlchemyProvider, EtherscanProvider, InfuraProvider, CloudflareProvider, PoketProvider and AnkrProvider - all providing a web API for connecting to the blockchain.
Ethers.js Provider Use Cases
The following consists of potential use cases with Provider within Ethers.js:
Account Methods
- provider.getBalances - retrieve the balances from specific addresses
- provider.getTransactionCount - retrieve the total number of transactions an address has sent
Network Status Methods
- provider.getGasPrice - retrieve the gas price for a transaction that is displayed to a user
- provider.getNetwork - retrieve the network to confirm an user can complete a transaction
Transactions Methods
- provider.call - read from the blockchain and execute smart contracts, but cannot publish to the blockchain.
- provider.getTransaction - retrieve the transaction hash to confirm the completion of an execution by the user.
There are many more use cases that can be explored by visiting the Provider docs, here.
How to Use a Provider with Ethers.js
The following code snippets require prior installation of ethers and alchemy-SDK.
1. Import ethers using Node.js.
2. Define network configurations via Mainnet.
3. Retrieve the API key from Alchemy. For this example, “demo” is used as the API key.
4. Define network configurations via Testnet.
How to Use a Provider with the Alchemy SDK
The following code snippets require prior installation of the alchemy-SDK.