solidityguy
solidityguy

Reputation: 319

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?

Upvotes: 5

Views: 12052

Answers (2)

josanbaq
josanbaq

Reputation: 266

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.

Upvotes: 8

Rafał Leszko
Rafał Leszko

Reputation: 5541

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)

Upvotes: -1

Related Questions