Resources

People often ask me "How did you learn how to hack?" The answer: by reading. This page is a collection of the blog posts and other articles that I have accumulated over the years of my journey. Enjoy!

Precision Loss Errors- 1138

DacianPosted 2 Years Ago
  • Solidity only has integers and there is a lot of money going around. So, precision is very important when dealing with money. Sometimes, this benefits the protocol. Other times, funds disappear entirely. But worst of all, funds may be stolen. What are all the ways this can go wrong? This article dives into it.
  • Division Before Multiplication. All division in Solidity will round down by default. So, if we do division then multiplication, there is a chance of lost value along the way. The example shows a multiplication, division and two multiplications afterwards that result in precision loss.
  • Rounding Down To Zero. Since division rounds down to zero, small values may cause problems. In a loan application, an attacker could repay their funds. However, they could subtract a small amount. The result was that the loanCollateral was being subtracted when it was zero and the loanAmount could still be subtracted from.
  • The solution to the precision problem is to have a check to ensure that values do not round down to zero.
  • No Precision Scaling. Tokens have different decimal places, such as USDC with 6 and ETH with 18. In the example, two tokens are used to calculate the value of an LP token. A loss in precision can occur if computation is done by combining the amounts of two tokens with different precision without scaling the the secondary token to the primary tokens precision.
  • When combining amounts of tokens with different precision, convert the amounts to the primary token's precision before any computation. Otherwise, value could be added or removed from the contract.
  • Excessive Precision Scaling. Scaling too many times. If you scale ETH twice, then you will receive too many funds. An example can be found at here.
  • Mismatched Precision Scaling. One location may have the precision hard-coded while another is dynamic. If this mismatch can be abused, then the values could get messed up. If the values get messed up, it likely leads to loss of funds. In the example, a dynamic decimal and a hardcoded 1e18 token causes problems.
  • Downcast Overflow. When explicitly casting from one integer type to another, an unchecked overflow can occur. In the example on Balancer, a require was ran on a non-truncated value and the actual usage was done on the truncated value.
  • Overall, an amazing article on precision issues in Solidity. In particular, I enjoy the multiple examples per vulnerability.