When I am using (await provider.getBalance(contractAddress)).toNumber()
I am getting a balance of zero. I have sent 1 Ether to the smart contract prior to this. What am I doing wrong?
2 Answers
I am no JavaScript expert, but I think the problem is that you are using .toNumber() on a promise (since the .toNumber() would run instantly and not wait for the promise to return), which will be undefined (or 0 I guess?)
I think this would work instead:
numStr = await provider.getBalance(contractAddress);
number = parseInt(numStr);
Where number
will be your balance as an integer, I think in wei, so you should expect ```number = 1000000000000000000````
If you want it in ether, you could do
numStr = await provider.getBalance(contractAddress);
wei = parseInt(numStr);
ether = web3.utils.fromWei(wei, "ether");
Where ether
should be 1 obviously
EthersJS stores balance in Wei as an object of BigNumber class. toNumber()
tries to cast input, in your case, to Integer, which is not enough to hold 1 ETH represented in Wei. Many operations in Ethereum operate on numbers that are outside the range of safe values to use in JavaScript.
1ETH = 1000000000000000000 WEI (vs a MAX_SAFE_INTEGER of 9007199254740991, see below)
console.log(Number.MAX_SAFE_INTEGER);
// Expected output: 9007199254740991
If you try to simply display the balance, you can cast it to String
:
(await provider.getBalance(contractAddress)).toString()
will return 1000000000000000000
A BigNumber is an object which safely allows mathematical operations on numbers of any magnitude. Here is the list of common methods to manipulate BigNumber class