[Ethereum] Convert JavaScript number to uint256

etheretherscanremixsolidityweb3js

I'm trying to deploy ERC20 contract by using Web3.

Here's the contract constructor fun:

constructor(
        string memory name,
        string memory symbol,
        uint8 decimals,
        uint256 totalSupply
        uint256 tokenCap,
    )

And here's the input variables using Web3:

const tx = erc20.deploy({
    data: erc20Contract.bytecode,
    arguments: [
      name,
      symbol,
      decimalPrecision,
      web3.utils.toBN(totalSupply), 
      web3.utils.toBN(tokenCap),
    ]
  });

// Input variables
{
    "name": "leo",
    "symbol": "LEO",
    "totalSupply": 123,
    "tokenCap": 220000,
    "decimalPrecision": 11
}

And after checking it in Etherscan I got the following decimal number,

Output: 0.00000000123 LEO

Expected: 123 LEO

so my question here is that because of a missing conversion required between JavaScript number to Solidity uint256?

enter image description here

Best Answer

Is that because of a missing conversion required between JavaScript number to Solidity uint256?

No, when using web3.js in order to interact with a contract function, you can pass:

  • An integer number
  • A string representing an integer number in decimal format
  • A string representing an integer number in hexadecimal format
  • A BN object (or a BigNumber object on web3.js older version v0.x)

Your problem stems from the fact that for ERC20 functions, input and output amounts are always specified in "10 ^ decimals" resolution, while you are using "token" resolution.

In other words, you need to:

  • Convert every amount from "token" resolution to "10 ^ decimals" resolution before passing it as input to an ERC20 function
  • Convert every amount from "10 ^ decimals" resolution to "token" resolution after receiving it as output from an ERC20 function

In your case, you can simply change this:

arguments: [
    name,
    symbol,
    decimalPrecision,
    web3.utils.toBN(totalSupply), 
    web3.utils.toBN(tokenCap)
]

To this:

arguments: [
    name,
    symbol,
    decimalPrecision,
    web3.utils.toBN(String(totalSupply) + "0".repeat(decimalPrecision)), 
    web3.utils.toBN(String(tokenCap) + "0".repeat(decimalPrecision))
]