I am using the ethers.js documentation: https://docs.ethers.io/ethers.js/html/cookbook-providers.html . I am getting the error when setting up the provider -: Uncaught ReferenceError: web3 is not defined I want to connect my Decentralized Application with the metamask. For that I am trying to connect the metamask with ethers.js by setting the provider as per the documentation. I have used provider = new ethers.providers.Web3Provider(web3.currentProvider). But it throws error for the web3 object in the code. This code is exactly as per the documentation. But still isn't working.
Getting this error while setting the provider-Uncaught ReferenceError: web3js is not defined
I too have found this confusing. According to the ethers.js documentation for Metamask the following is required:
const provider = new ethers.providers.Web3Provider(web3.currentProvider);
const signer = provider.getSigner();
But this causes an error: specifically the web3.currentProvider
not being recognised.
The Ethers.js github issue log has a similar complaint at Issue #433. Using this as a guide I've therefore used window.ethereum
in place of web3.currentProvider
and also included the .enable()
beforehand:
await window.ethereum.enable()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
Or alternatively (outside of an async function):
let provider;
window.ethereum.enable().then(provider = new ethers.providers.Web3Provider(window.ethereum));
const signer = provider.getSigner();
This clears the error, and ensures that Metamask asks for permission prior to connecting to the browser/DApp.