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?
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.