Get ETH Balance with Ethersjs
Asked Answered
H

2

5

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?

Homocercal answered 12/1, 2022 at 22:53 Comment(0)
D
8

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.

Diorama answered 8/6, 2022 at 15:37 Comment(1)
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 networkMotoneuron
S
-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)
Saliva answered 13/1, 2022 at 8:45 Comment(6)
I know how to get the account. I need to get the balance once I have it.Homocercal
Ahh, I see, I updated my answer to get the account balance.Grew
Error: Objects are not valid as a React child (found: object with keys {_hex, _isBigNumber}). If you meant to render a collection of children, use an array instead.Homocercal
Is balance a key-value pair?Homocercal
In Etherjs 5, it should be a single value, not an array. docs.ethers.io/v5/api/providers/provider/#Provider-getBalanceGrew
Thanks. Yeah, started with the docs, so I don't know. That's the error I get.Homocercal

© 2022 - 2024 — McMap. All rights reserved.