0

I am tryin to call a function of a contract. I am hosting a local node with hardhat, to which I obviously deploy the contract. Connecting MetaMask and all works without a problem. In the console I can also see, that the contract gets called on the node. In the documenation it says that the returned value should be the actual integer. But I am only getting the following output:

Object { _hex: "0x042deee8d42de3f0", _isBigNumber: true }

The contract call looks like this:

const contractAddress = "address",
const abi = ["function getBalance() public view returns (uint256)"]

const provider = new ethers.providers.Web3Provider(window.ethereum)
await provider.send("eth_requestAccounts", [])

let contract = new ethers.Contract(contractAddress, abi, provider)

const balance = await contract.getBalance()
console.log("Balance: ", balance)

How can I get the actual integer value?

1 Answer 1

0

The ethers.js methods return a ethers.BigNumber instance not a native JavaScript number, because native JavaScript numbers don't support the grand numbers we use in crypto and will silently overflow producing numbers that are catastrophically wrong.

You can get your balance variable as a string with balance.toString(). You may instead want a human-readable number in ETH (not the number you just got which will be in wei, which is 10 to the power of 18 bigger), in which case you can do something like ethers.utils.formatUnits(balance, 18)

You could turn it into a JavaScript number with balance.toNumber(), but you shouldn't do that unless you're certain it won't overflow, which you probably aren't.

To do anything else with these numbers, read the ethers.BigNumber documentation. You should read the whole thing, because there are various traps for the unwary. Also be aware that ethers.BigNumber is subtly different from the more common BigNumber.js library, and the alternative BN.js library.

https://docs.ethers.io/v5/api/utils/bignumber/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.