i have been trying to connect metamask and ethers.js to fetch my current wallet balance
const provider = new ethers.providers.Web3Provider(window.ethereum)
const signer = provider.getSigner()
balance = provider.getBalance("0x7C76C63DB86bfB5437f7426F4C37b15098Bb81da")
when i try this i am getting a error
ReferenceError: window is not defined
Anyone has idea how to do this?
You need to run this code on a web application running on localhost or on a server. And, of course, you need to have MetaMask installed on your browser.
Put this code on a script section of your site:
await window.ethereum.request({method: 'eth_requestAccounts'});
const provider = new ethers.providers.Web3Provider(window.ethereum);
const contract = new ethers.Contract(smartContractAddress, abi, provider);
balance = await contract.getBalance("0x7C76C63DB86bfB5437f7426F4C37b15098Bb81da");