Reputation: 105
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?
Upvotes: 0
Views: 5892
Reputation: 1
Here is how you can check connection between your Metamask wallet and get account balance using Ethers Js v6.13.1
Make sure you had installed Metamask on your browser.
Here is a simple Next Js 14 code.
directory: app/page.tsx
"use client";
import { ethers } from "ethers";
import { BrowserProvider, parseUnits } from "ethers";
import { useEffect, useState } from "react";
export default function Home() {
const [provider, setProvider] = useState(null);
const [signer, setSigner] = useState(null);
const [balance, setBalance] = useState(null);
const [address, setAddress] = useState(null);
useEffect(() => {
const fetchData = async () => {
if (window.ethereum == null) {
console.log("MetaMask not installed; using read-only defaults");
setProvider(ethers.getDefaultProvider());
} else {
console.log("HEllo");
let providerSetter: any = new BrowserProvider(window.ethereum);
setProvider(providerSetter);
let signerSetter: any = await providerSetter.getSigner();
setAddress(signerSetter.address);
setSigner(signerSetter);
const balanceData: any = await provider.getBalance(address);
setBalance(balanceData);
}
};
fetchData();
}, []);
return (
<div className="mt-5">
<h1 className="text-center">
Your Balance is {balance.toString() / 10 ** 18} ETH
</h1>
</div>
);
}
In latest version of Ethers Js you need to use
balance = await provider.getBalance("YOUR_WALLET_ADDRESS")
make sure to set the provider and signer variables!
Upvotes: 0
Reputation: 1
The error suggest that injected window object is not obtained.
Ensure that MetaMask
is installed and properly configured in your browser. Make sure you have the MetaMask
extension installed and are logged in with your desired account.
Check if the Ethereum provider (window.ethereum
) is available and connected. You can check this using ethereum.isConnected()
or ethereum.request({ method: 'eth_accounts' })
. If it returns false or an empty array, it means that the provider is not connected.
Here's an example code snippet that shows how to connect to MetaMask
and fetch the balance using ethers.js:
import { ethers } from 'ethers';
async function getAccountBalance() {
try {
// Check if MetaMask is installed and connected
if (!window.ethereum || !window.ethereum.isConnected()) {
throw new Error('Please install MetaMask and connect to an Ethereum network');
}
// Create a new ethers provider with MetaMask's provider
const provider = new ethers.providers.Web3Provider(window.ethereum);
// Get the signer object for the connected account
const signer = provider.getSigner();
// Fetch the account balance
const address = '0x7C76C63DB86bfB5437f7426F4C37b15098Bb81da'; // Replace with your desired address
const balance = await provider.getBalance(address);
const formattedBalance = ethers.utils.formatEther(balance);
console.log(`Account balance: ${formattedBalance} ETH`);
} catch (error) {
console.error('Error occurred while fetching the account balance:', error);
}
}
getAccountBalance();
Make sure you have the latest version of ethers.js
installed
Upvotes: 0
Reputation: 1274
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");
Upvotes: 2