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