8

I am trying to fetch the balance of signers in a test locally. I didn't change the default value of eth for accounts in the hardhat configuration. Yet when I query the balance, I see that the accounts do not have any balance.

Here is my code:

        [owner, alice, bob, chuck, ...others] = await ethers.getSigners();
        
        provider = ethers.getDefaultProvider();

        balance = await provider.getBalance(owner.address);
        console.log(balance.toString()); // 0

What am I missing?

2 Answers 2

8

The issue was the provider returned by getDefaultProvider connected to the main net, while I was trying to test locally. I ended up at this conclusion by calling the getNetwork call on the provider, seeing that the network being used was in fact, the main net.

To fix this, I looked up hardhat docs, and hardhat provides a custom provider in ethers object which can be accessed using ethers.provider.

So the fix was using:

    provider = ethers.provider;
1
  • this helped me get account balance.
    – oldpride
    Commented Mar 25, 2023 at 18:02
1

You might be running tests on hardhat and trying to fetch balance of an address. The best way to get your actual balance is:


 import { ethers } from 'hardhat'


 const provider = ethers.provider;
 const balance = await provider.getBalance("pasteYourAddressHere");

// returns BigNumber { value: someValueInWei }

You'll want to make sure you are inside an async function to get the best out of this code block. Using provider.getDefaultProvider() returns an Ethereum mainnet provider.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.