0

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 2

1

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

0

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

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.