4

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?

solidityguy
  • 199
  • 1
  • 3
  • 8

2 Answers2

7

You can use:

const getBalance = async (address) => {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const balance = await provider.getBalance(address);
    const balanceInEth = ethers.utils.formatEther(balance);
    console.log(balanceInEth);
}

You set the provider, then you ask for balance through the provider (account must be logged in), and finally you format the result of BigNumber to Eth.

Pang
  • 9,564
  • 146
  • 81
  • 122
josanbaq
  • 226
  • 3
  • 7
  • this is correct answer, but often when a network halted or error, the balance is not visible in the console. the solution is replace rpc node or use another network – alvin Christianto Apr 18 '23 at 02:16
-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)
Rafał Leszko
  • 4,939
  • 10
  • 19