Ethers.js – How to Fix Overflow Errors in EthersJS

ethers.js

Im building a simple whale tracker that prints out transactions larger than x amount.

My code works really good for tokencontracts with 6 decimals(USDC) but when I try to use token with 18 decimals Im getting an overflow error.

Error: overflow [ See: https://links.ethers.org/v5-errors-NUMERIC_FAULT-overflow ]

Here is my code:

 const decimals = await contract.decimals()
    const DECIMAL = 10 ** decimals
    console.log(DECIMAL)

    const transferAmount = 100000 * DECIMAL
    console.log(transferAmount)


    console.log(`Whale tracker started!\nListening for large transfer on ${name}`)

    contract.on('Transfer',(from, to, value,  data)=>{
        if(value.toNumber() >= transferAmount){
            console.log(`Trasnaction ${from} to ${to} was sent with a value of ${value / DECIMAL} of ${symbol}\n TransactionHash ${data.transactionHash}`)

I hae checked the link in the error message but for some reason I cant figure out why this is happening.
Does anyone have a fix for this problem?

Best Answer

This is your code rewritten using BigNumer (I haven't tested it)

const { BigNumber } = require("ethers")

    const decimals = await contract.decimals()
    const DECIMAL = BigNumber.from(10).pow(decimals)
    console.log(DECIMAL.toString())

    const transferAmount = BigNumber.from(100000).mul(DECIMAL)
    console.log(transferAmount.toString())


    console.log(`Whale tracker started!\nListening for large transfer on ${name}`)

    contract.on('Transfer',(from, to, value,  data)=>{
        if(value.gte(transferAmount)){
            console.log(`Trasnaction ${from} to ${to} was sent with a value of ${value.div(DECIMAL).toString()} of ${symbol}\n TransactionHash ${data.transactionHash}`)

The max number represented by javascript is around 0.009*10**18, that's why we almost always need to use the BigNumber library when dealing with ether or token amounts.

Converting from a normal number to BigNumber is done like this

BigNumber.from(100)

then we can use math operations between BigNumbers

a.add(b)  <==>  a+b
a.mul(b)  <==>  a*b
...

all listed here https://docs.ethers.io/v5/api/utils/bignumber/

Related Topic