Home > Blockchain >  When JS passes numeric values as arguments to Solidity function, why is it better to wrap them in qu
When JS passes numeric values as arguments to Solidity function, why is it better to wrap them in qu

Time:08-24

I defined a function in Solidity:

function store(uint256 _favoriteNumber) public {}

Then call the function with argument 7 in JavaScript:

contract.store(7);

But, according to the Patrick Collins JS video, it's better to wrap number 7 with quotes like this:

contract.sotre("7");

So here are two things confused me:

  1. Why it's better to wrap number with quotes when passing a number to a solidity contract function?
  2. Why ehter.js can automatically convert string to number?

CodePudding user response:

Javascript supports a smaller set of numbers than Solidity. Specificially, the maximal safe value in JS is 2^53 - 1, while the maximal numeric value in Solidity is 2^256.

So if you were to for example transfer 1 token with 18 decimals, the resulting decimal value that you'd need to pass to the Solidity contract is 1000000000000000000 - which is somewhere between 2^59 and 2^60, already higher than the maximal safe JS integer of 2^53 - 1.

For this reason, ethers.js and other JS smart contract libraries accept numeric values either as native JS string or an instance of a helper library called BigNumber - but not as integers.

Note: Some libraries in some versions might be able to convert the native integer to a string or BigNumber at first. But generally, it's always safer to pass the non-integer values.

  • Related