Covert ERC-20 tokens with different decimals to amount to Wei

Viewed 44

For example when I want to send ERC-20 tokens to a contract, I specify the amount in Wei
So I have to convert 34678393 tokens to Wei. But it only works ok with tokens that have 18 decimals

I'm using web3's toWei() function like so

  const sendTokens = async (amount)  => {
    const contract = new web3.eth.Contract("ADDRESS",ABI)
    await contract.sendTokens(web3.utils.toWei(amount))
  }

How can I convert tokens amount with different decimals to Wei?

1 Answers

You need something like this function to convert the amount to WEI based on Token Decimal.

function tokenAmountToWei(amount, decimals) {
    return web3.utils.toBN("0x" + (amount * 10 ** decimals).toString(16)).toString();
}

let erc20_decimals = 6;
let amount = 5000;

console.log(tokenAmountToWei(amount, erc20_decimals))
Related