22

I am trying to get the ETH balance of a contract:

const balance = await contract.getBalance();

but it fails:

TypeError: contract.getBalance is not a function

What I do wrong and how to fix the error?

7 Answers 7

34

getBalance is a function of the Ether.js blockchain provider object, it is used this way :

const balance = await provider.getBalance("address");

Note that you can use contract.address to obtain the address of the contract instance.

2
  • what chain is this balance for?
    – Tobi
    Commented Feb 25, 2022 at 4:07
  • Late to this. The chain depends on the provider. When creating the provider you specify the network (through the RPC URL or otherwise).
    – Mark
    Commented Apr 27, 2022 at 7:54
9

In the context of testing a contract with Hard Hat:

const { ethers, waffle} = require("hardhat");

const provider = waffle.provider;
const balanceInWei = await provider.getBalance(contract.address);

where contract is a deployed contract instance.

5

You also can use:

import { ethers } from "hardhat";

const provider = ethers.getDefaultProvider();
const balance = await provider.getBalance("address");
1
  • This actually seems wrong as using ethers.getDefaultProvider provides the default provider an not the one in use. You really should be calling ethers.provider
    – Ritzy Dev
    Commented Apr 11, 2023 at 0:43
1
const address1 = "0x042523DB4F3Effc33d2742022B2490258494f8B3"
const bal = provider.getBalance(address1) //balance in wei
const balance = ethers.formatEther(bal) // wei balance convert to eth balance
console.log(balance)
0

With Wagmi and React :

  const provider = useProvider()
  const [balance, setBalance] = useState<BigNumber>()

  useEffect(() => {
    const run = async () => {
      setBalance(await provider.getBalance(address))
    }
    run()
  }, [provider, address])
0

I think Your Contract Name and Your Solidity File name are not the same because i had get this error before

1
0

TypeError: contract.getBalance is not a function

You can try:

npm install @ethersproject/units

Then import it:

import { formatUnits } from "@ethersproject/units";

And then:

const balance = await provider.getBalance(address);

const ethbalance = formatUnits(balance, "ether");

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.