Use Ethers.js InfuraProvider or Web3Provider
In this tutorial, you'll create a simple React app to show the differences between using the
Ethers.js library's InfuraProvider and Web3Provider methods to send a transaction.
The key difference is that with Web3Provider, you can load the private key from a web3 wallet
(for example, MetaMask), while InfuraProvider needs a wallet created locally with a stored private key.
This tutorial uses the Sepolia testnet.
Prerequisites
- Install MetaMask and create an Ethereum account for testing purposes.
- Load Sepolia ETH into your wallet from the MetaMask faucet.
- Node.js and npm installed.
You can run the following to confirm that Node and npm are installed:
node -v && npm -v
This tutorial was tested using ethers v5.7.2 and Node.js v16.17.0.
Steps
1. Create the React app
In the terminal, run the following command to create an app called my-app:
npx create-react-app my-app
Change into the project directory:
cd my-app
2. Install ethers.js
Install ethers.js in the project directory.
npm install --save ethers
3. Create the environment variables
Create a .env file in your project directory to store the project and Ethereum account details.
REACT_APP_API_KEY="<YOUR-API-KEY>"
REACT_APP_PRIVATE_KEY="<PRIVATE-KEY>"
Ensure you replace the following values in the .env file:
<YOUR-API-KEY>with the API key of the Ethereum project.<PRIVATE-KEY>with the private key of your Ethereum account.
Never disclose your private key. Anyone with your private keys can steal any assets held in your account.
4. Build the app
Import dependencies and create providers
Import the required dependencies and create the providers for communicating with the blockchain.
In the src directory open the App.js file. Remove the existing code and add the following code:
import React, { useState } from "react"
import "./App.css"
function App() {
const ethers = require("ethers")
const API_KEY = process.env.REACT_APP_API_KEY
const PRIVATE_KEY = process.env.REACT_APP_PRIVATE_KEY
const provider_Metamask = new ethers.providers.Web3Provider(window.ethereum)
const infuraProvider = new ethers.providers.InfuraProvider("sepolia", API_KEY)
}
export default App
Maintain the app state
Next, use the useState hook function to maintain the state of the app. Add the following code below the const declarations (inside the App() declaration):
// Use the useState hook function to add state variables to a functional component.
const [blockNumber, setBlockNumber] = useState(null)
const [txSent, setTxSent] = useState(null)
const [txSentInfura, setTxSentInfura] = useState(null)