0

I made a page where you can enter an amount of token and it gets swapped to another token. It works until I use a number above 999. My smartcontract gets wei, so I have to transform the normal number to wei with the function below.

const toWei = amount => {
    return amount * Math.pow(10, 18)
}

I get huge numbers out and I get this error

Error: invalid BigNumber string (argument="value", value="2e+21", code=INVALID_ARGUMENT, version=bignumber/5.6.0)

What can I do that this does not appear and is best practice?

1 Answer 1

0

The string "2e+21" is not valid for the BigNumber class.

JavaScript uses IEEE 754 numbers, which means any value above around 0.009 would suffer precision loss, and Ethereum is quite picky about numbers not being approximate.

You should use strings for large values, or use the convenience functions provided for converting units, such as ethers.utils.parseEther("1.0") which handles string values.

Here is more info on why you need Big Number: https://docs.ethers.io/v5/api/utils/bignumber/#BigNumber--notes-safenumbers

1
  • This worked tyvm I have checked the documentation, but I used formatUnit/formatEther instead of parseEther Commented May 15, 2022 at 13:22

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.