'Get ETH Balance with Ethersjs

I'm trying to get the balance of my wallet address to render on my frontend. Here's what I have so far.


const [balance, setBalance] = useState("");

const handleWalletBalance = async () => {
      const { ethereum } = window;
      
      if(ethereum) {
        const balance = await ethereum.request({method: 'eth_getBalance'})
        const provider = new ethers.providers.Web3Provider(ethereum)
        await provider.getBalance(balance)
        setBalance(balance)
        console.log(balance)
     }
  }

The error I'm getting is MetaMask - RPC Error: missing value for required argument 0 .

I'm using a method for querying accounts. What am I missing?



Solution 1:[1]

I think that you need to specify the account you want to use from your MetaMask. You can do it with the following code.

const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
const accounts = await provider.send("eth_requestAccounts", []);

Then, to check the balance, you don't need MetaMask, you can do it with the following code.

const balance = await provider.getBalance(accounts[0])
ethers.utils.formatEther(balance)

Solution 2:[2]

const ethers = require('ethers')
const network = "" // json-rpc
const provider = ethers.getDefaultProvider(network)
const address = '<ADDRESS-OF-THE-ACCOUNT>'

provider.getBalance(address).then((balance) => {
 const balanceInEth = ethers.utils.formatEther(balance) // wei to ether
 console.log(balanceInEth)
})

Here is a code snippet that might help you...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 d0x471b