1

I need to multiple and divide a big number in a safe way - without overlow.

It won't have to result in an accurate amount to suit me; namely, if it gets round by some function to remain integer rather than more precise float or decimal, it'd still do for me.

Currently this code will result in overflow:

  let amountToSendPercent = provider.getBalance(wallet.address);
  //let amountToSendPercent = contract.balanceOf(wallet.address);

  //minus gas.... - doesn't matter here....


  let amountToSendPercent = 45;

  // !!!
  //sometimes - overflow
  // !!
  if (amountToSendPercent < 100) {
     amountToSend = Math.round(amountToSend / 100 * amountToSendPercent);
  }

I'm using ethers. I'd prefer to refrain from using any additional library, if possible.


I need this for both ERC20 tokens and ETH.

1 Answer 1

1

ethers.js is good here, I have modified your code slightly to show you how you could do it.

const ethers = require("ethers");

// ... (Set up your provider, wallet, and contract as needed)

let balance = await provider.getBalance(wallet.address); // Replace with contract.balanceOf for ERC20 tokens
let amountToSendPercent = 45;

if (amountToSendPercent < 100) {
  let amountToSend = balance.mul(ethers.BigNumber.from(amountToSendPercent)).div(100);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.