Content
@
0 reply
0 recast
0 reaction
Paul Vijender
@paulvijender
Attack vector #2 on this list - Rounding errors. Rounding errors can be a tricky pitfall for developers. Some best practices and guidance below to avoid attacks stemming from these errors. ๐
1 reply
0 recast
2 reactions
Paul Vijender
@paulvijender
2/ First up: Understanding the problem. Solidity doesn't handle decimals like traditional programming languages. Instead, it uses fixed-point math, meaning we need to think differently about arithmetic operations to avoid precision loss.
1 reply
0 recast
0 reaction
Paul Vijender
@paulvijender
3/ Use SafeMath, ABDK and FixedPoint libraries. While Solidity 0.8.x auto-prevents overflow and underflow, SafeMath can still help with explicit rounding control. It's a must for versions before 0.8 and a good practice for clarity and explicitness in your code.
1 reply
0 recast
2 reactions
Paul Vijender
@paulvijender
4/ Stick to integers for monetary amounts. Represent values in the smallest unit (like wei in Ethereum) and only convert to larger units when necessary. This helps maintain precision and avoid rounding errors.
1 reply
0 recast
1 reaction
Paul Vijender
@paulvijender
5/ When division is unavoidable, multiply before you divide. If you need to calculate a percentage, for instance, rearrange your equation to do the multiplication first. This minimizes loss of precision.
1 reply
0 recast
0 reaction
Paul Vijender
@paulvijender
6/ Understand the order of operations. In Solidity, as in other languages, the order in which you perform arithmetic operations matters. Plan your calculations to minimize the impact of rounding.
1 reply
0 recast
0 reaction
Paul Vijender
@paulvijender
7/ When downcasting from one type to another, Solidity will not revert but overflow, resulting in unexpected behavior and exploitable bugs.ย When downcasting developers should consider using OpenZeppelin'sย SafeCastย library which reverts if downcasting would overflow.
1 reply
0 recast
1 reaction