How to transform JavaScript number to token amount
Published
If you're starting buidling web3 applications and handling token amounts from a front-end, you've probably seen thie error:
Error: overflow (operation="setValue", fault="overflow", details="Assertion failed", version=4.0.27)
Let say you're building a web3 app with a form that users can use to transfer tokens. You'll probably have two inputs, one for the destination wallet and another one for the amount:
The user can enter any amount, something like "3", "340" or "12.5" and your app will have to transform that amount into something that your ERC20 token contract can understand.
ERC20 tokens use 18 decimals by default so, that's something we have to take into account before parsing the user's input in the tokens amount.
First, we have to make sure that the amount input is a text input and not a number. This is important as we want to use a string in our Javascript. Once we have the user input as a string, we can use ethers.utils.parseUnits()
to transform it to the correct token amount.
The parseUnits
method accepts two arguments:
- The first one is a string of the amount we want to send. It can be something like "100.56" or "150".
- The second parameter can be a string indicating the unit we are parsing (like "ether" or "wei"), or the number of decimals of our ERC20 token. As mentioned earlier, ERC20 tokens have 18 decimals by default but if yours is different, you can indicate that here.
The returned variable is a BigNumber which we can transform into a string with toString()
😉
Find below a code example:
import { ethers } from 'ethers';
import MyERC20Token from '@/artifacts/contracts/MyERC20Token.sol/MyERC20Token.json';
const myTokenAddress = '0x123456abcdef...';
const destination = document.getElementById('wallettInput').value;
const amount = document.getElementById('amountInput').value;
const decimals = 18;
// returns a BigNumber
const amountFormatted = ethers.utils.parseUnits(amount, decimals);
const provider = new ethers.providers.Web3Provider(window.ethereum);
// get the account that will pay for the trasaction
const signer = provider.getSigner();
let contract = new ethers.Contract(myTokenAddress, MyERC20Token.abi, signer);
// send the transaction amount as a string to the ERC20 contract
const transaction = await contract.transfer(
destination,
amountFormatted.toString()
);
TAGS