20

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?

porton
  • 1,774
  • 5
  • 17
  • 38

7 Answers7

32

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.

clement
  • 4,302
  • 2
  • 17
  • 35
8

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.

MetaZebre
  • 181
  • 1
  • 2
4

You also can use:

import { ethers } from "hardhat";

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

smallyu
  • 59
  • 1
  • 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 Apr 11 '23 at 00: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)
Ismael
  • 30,570
  • 21
  • 53
  • 96
FreeTech
  • 11
  • 2
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])

pom421
  • 101
  • 2
0

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

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");