web3.js和ether.js连接MetaMask钱包,并查询余额!
一、web3.js
const web3_connect = async () => {
const rpcURL = "https://mainnet.infura.io/v3/xxxx"
let web3 = new Web3(window.ethereum || rpcURL);
//获取账号地址
let accounts = await web3.eth.requestAccounts()
let address = accounts[0];
//查询余额
let wei = await web3.eth.getBalance(address);
balance = web3.utils.fromWei(wei, 'ether')
console.log("balance: " + balance)
}
二、ether.js
const ether_connect = async () => {
const provider = new ethers.providers.Web3Provider(web3.currentProvider);
let signer = null;
let address = null;
if (!provider) {
return;
}
//请求获取账号
await provider.send('eth_requestAccounts', []);
signer = provider.getSigner();
// 获取账号地址
address = await signer.getAddress();
//查询余额
provider.getBalance(address).then((balance) => {
// 余额是 BigNumber (in wei); 格式化为 ether 字符串
let etherString = ethers.utils.formatEther(balance);
console.log("Balance: " + etherString);
});
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!