0

Using web3js v1.2.1

const contract = new web3.eth.Contract(abi, '0x29...');
const amount = 1 * 10 ** 18;
const data = contract.methods.transfer(recipient, amount).encodeABI();

I get error :

invalid number value (arg="value", coderType="uint256", val


 reason: 'invalid number value',
  code: 'INVALID_ARGUMENT',
  arg: 'value',
  coderType: 'uint256',
  value: 1000000000000000000 }

This should work:

const amount = web3.utils.toHex(1e18)
1
  • use web3 method to convert ether to wei
    – Majd TL
    Oct 17, 2019 at 6:44

3 Answers 3

2

javascript cannot handle those big numbers, Use the method web3.utils.toWei(number [, unit]).

const amount = web3.utils.toWei(1, 'ether');
3
  • Error: Please pass numbers as strings or BigNumber objects to avoid precision errors.
    – Alvin
    Oct 17, 2019 at 9:58
  • vlt web3.utils.toBN(web3.utils.toWei(1, 'ether'));
    – Majd TL
    Oct 17, 2019 at 13:35
  • oder (web3.utils.toWei(1, 'ether')).toString());
    – Majd TL
    Oct 17, 2019 at 13:37
0

You should pass a string or a BN object, not an integer.

Also note that this specific integer (10 ** 18) is larger than Number.MAX_SAFE_INTEGER and should therefore not be used for any other purpose.

Here are a few options which you can choose from:

const amount = "1e18";
const amount = Web3.utils.toBN("1e18");
const amount = Web3.utils.toBN(10).pow(18);

Or with a variable x = 18 (which you can change of course):

const amount = `1e${x}`;
const amount = Web3.utils.toBN(`1e${x}`);
const amount = Web3.utils.toBN(10).pow(x);
3
  • All the above give me the same error. or error : num.bitLength is not a function
    – Alvin
    Oct 17, 2019 at 9:59
  • @Alvin: Well maybe you are passing recipient and amount in the wrong order. It's hard to say, because you haven't posted your implementation of function transfer (the standard function indeed uses this order of parameters, but perhaps you've implemented your own version, who knows...). Oct 17, 2019 at 10:14
  • how would toBN ever work if you have a float number. Let's say you want to send 10000.123 tokens with 8 decimals. You won't be able to do Web3.utils.toBN(10000.123).pow(8) as toBN only accepts whole numbers.
    – Iulian
    Aug 7, 2021 at 15:39
0

Just convert it toLocaleString("fullwide", { useGrouping: false })) and You will get numbers as string.

console.log((1000000 * 1e18).toLocaleString("fullwide", { useGrouping: false }));

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.