const provider = new ethers.providers.Web3Provider(window.ethereum)
while using this i am getting window is not defined error..and i dont know how to use it. Do anyone has idea how to do it
In my case I used web3. It works fine for me. Try for ethers...
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
// We are in the browser and metamask is running.
web3 = new Web3(window.web3.currentProvider);
} else {
// We are on the server OR the user is not running metamask
const provider = new Web3.providers.HttpProvider(
"https://rinkeby.infura.io/v3/MY_API_KEY"
);
web3 = new Web3(provider);
}
You can connect to meta mask very easily using ethers.js
Try This code:-
const connectWallet = async () => {
const provider = new ethers.providers.Web3Provider(window.ethereum)
await provider.send("eth_requestAccounts", [])
const signer = provider.getSigner()
const accountAddress = await signer.getAddress()
console.log(accountAddress)
}
window
global exists on a browser page, if you are executing a web script outside a browser it will fail like that.