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?
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.
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.
You also can use:
import { ethers } from "hardhat";
const provider = ethers.getDefaultProvider();
const balance = await provider.getBalance("address");
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)
With Wagmi and React :
const provider = useProvider()
const [balance, setBalance] = useState<BigNumber>()
useEffect(() => {
const run = async () => {
setBalance(await provider.getBalance(address))
}
run()
}, [provider, address])
I think Your Contract Name and Your Solidity File name are not the same because i had get this error before
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");