VS code and connecting to Ethereum mainnet with ether.js and Infura

140 Views Asked by At

I don't know why it does not run and I get an error.

Network and API was declared and ethers.js library was imported.

import { ethers } from "ethers";
const network = "homestead";  
const API_KEY = "mykey"; 
const provider = new ethers.providers.InfuraProvider(network, API_KEY);
const blocknumber = away provider.getBlocknumber();
console.log(blocknumber);
2

There are 2 best solutions below

5
albat On BEST ANSWER

I don't know what specific error you are getting, but assuming you spelled "await" correctly in your original code, the issue could be that you are accessing InfuraProvider with

ethers.providers.InfuraProvider

That is the way it is in ethers v5, but in v6 the providers are directly under the ethers class.

If you are using v6 try

const provider = new ethers.InfuraProvider(network, apikey);
0
Litt Cloud Canada On

In line 6 I deleted provider, so it's now new.ethers.infuraprovider(); before, I was using ethers.providers.InfuraProvider.

import { ethers } from "ethers";
import { InfuraProvider } from "ethers";
const API_KEY = "1c30bd8247e34d948122ec917e222b3f";
const  network = "homestead";
const provider = new ethers.InfuraProvider(network, API_KEY);
const blockNumber = await provider.getBlockNumber();
console.log(blockNumber);