Assume that you send X ERC20 SomeCoins and in exchange, you receive X/2 MyCoins. Both ERC20 have 4 decimals. My question is, if the user sends the minimum value or, a value that can't be divided by 2, will that result in an underflow attack?

For example, user sends 0.0001 SomeCoins which if you divide by 2, your smartcontract should return them 0.00005 MyCoins

Another scenario is when you return X/3 MyCoins. For example, user sends 1.0000 SomeCoins and your smart contract should return them 1/3 MyCoins, or 0.33333333333333333

Does an underflow attack happen in any of these cases? If yes, is there a way to avoid it? Would OpenZeppelin's safeMath function allow me to mitigate it?

  • 3
    Underflow refers to x - y where x < y and both are uint variables. Your example is just an inevitable precision-loss, which it at most 1/10000 of your token (since you define decimals = 4). SafeMath cannot be used here. The precision-loss is inherited in the fixed-point nature of Solidity. – goodvibration Jan 27 '19 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.