我一直在尝试连接metamask和ethers.js来获取我当前的钱包余额
const provider = new ethers.providers.Web3Provider(window.ethereum)
const signer = provider.getSigner()
balance = provider.getBalance("0x7C76C63DB86bfB5437f7426F4C37b15098Bb81da")
当我尝试这个时,我收到错误
ReferenceError:窗口未定义
有人知道如何做到这一点吗?
您需要在本地主机或服务器上运行的 Web 应用程序上运行此代码。当然,您需要在浏览器上安装 MetaMask。
将此代码放在您网站的脚本部分:
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");
错误提示未获取注入的窗口对象。
确保您的浏览器中已安装并正确配置
MetaMask
。确保您已安装 MetaMask
扩展程序并使用所需帐户登录。
检查以太坊提供商 (
window.ethereum
) 是否可用并已连接。您可以使用 ethereum.isConnected()
或 ethereum.request({ method: 'eth_accounts' })
进行检查。如果返回 false 或空数组,则表示提供商未连接。
这是一个示例代码片段,展示了如何连接到
MetaMask
并使用 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();
确保您安装了最新版本的
ethers.js
以下是如何使用 Ethers Js v6.13.1
检查 Metamask 钱包之间的连接并获取帐户余额确保您已在浏览器上安装 Metamask。
这是一个简单的 Next Js 14 代码。
目录: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>
);
}
在最新版本的 Ethers Js 中你需要使用
balance = await provider.getBalance("YOUR_WALLET_ADDRESS")
确保设置提供者和签名者变量!