如何将元任务与ethers.js连接并获取余额



我一直在尝试连接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

最新更新