𝗣𝗿𝗲𝗰𝗶𝘀𝗶𝗼𝗻 𝗟𝗼𝘀𝘀 𝗮𝗻𝗱 𝗥𝗼𝘂𝗻𝗱𝗶𝗻𝗴 𝗘𝘅𝗽𝗹𝗼𝗶𝘁𝘀

Smart contracts do not need a bug in access control to lose money.

Sometimes the exploit is hidden in a simple division.

Financial smart contracts use integer arithmetic. Fractions are discarded. This rounding direction changes who receives value. An error of one unit can repeat across thousands of transactions.

In a financial protocol, rounding is a value-transfer policy.

Every division must answer three questions:

  • Which direction does the calculation round?
  • Which party benefits from that direction?
  • Can an attacker repeat or amplify that advantage?

Common math errors include:

  1. Dividing too early If you divide before multiplying, you lose precision. Example: (amount / 1e18) * rate. The intermediate division discards data before the multiplication happens. Rule: Always multiply before you divide.

  2. Intermediate overflows Multiplying first can cause an overflow even if the final result fits in a uint256. Use a library like OpenZeppelin Math to perform full-precision multiplication and division in one step.

  3. Rounding in the wrong direction Rounding is not a suggestion. It is a security rule. A conservative protocol follows these principles:

  • Round debt upward.
  • Round required payments upward.
  • Round collateral value downward.
  • Round assets paid to users downward.
  • Round shares charged to users upward.

When an exact result is impossible, round against the party trying to extract value.

  1. Inflation attacks In vaults with low liquidity, attackers can use donations to manipulate exchange rates. They donate assets to increase the total asset count without increasing the share count. This makes new deposits round down to zero shares. Mitigation: Use virtual assets or shares to establish a stable initial rate.

  2. Frequency attacks If interest accrues every block and rounds down, an attacker might trigger accrual constantly to keep interest at zero. Mitigation: Use a high-precision index or carry the remainder forward.

Secure financial engineering requires:

  • Explicit units and decimal scales.
  • Full-precision multiplication and division.
  • Operation-specific rounding.
  • Remainder tracking.
  • Invariant and fuzz testing.

Do not just ask if a calculation is close enough. Ask where the discarded value goes and who receives it.

Source: https://dev.to/stablenaira/precision-loss-and-rounding-exploits-in-financial-smart-contracts-4c93