[Ethereum] Ethers.js – Error: invalid BigNumber string

bignumbererc-20erc-20-approveerrorethers.js

I am trying to approve a larger amount of erc-20 tokens (it has 18 decimals).

await token.connect(signer).approve(contractAddress, BigNumber.from((1000*(tenToPowerOf18Digits)).toString())) :

If I try to approve more than 999 tokens, it gives me this err

Uncaught (in promise) Error: invalid BigNumber string (argument="value", value="1e+21", code=INVALID_ARGUMENT, version=bignumber/5.5.0)

Can anyone help me with this issue? How can I approve more than 999 tokens?

Best Answer

The problem is that the toString of the number will convert it to a scientific representation which cannot be interpreted by the BigNumber.

The cleanest way to get around this is to use BigNumber when adding the decimals:

const decimals = 18;
const input = 999;
const amount = BigNumber.from(input).mul(BigNumber.from(10).pow(decimals));

Another way is using ethers to parse this:

const decimals = 18;
const input = "999"; // Note: this is a string, e.g. user input
const amount = ethers.utils.parseUnits(input, decimals)