The default arithmetic overflow and underflow checks in Solidity v0.8 are great. One has to wrap some arithmetic operations in an unchecked
block if one wishes to avoid the default checks. That is healthy - the compiler makes users err on the side of caution.
The downside is that this makes libraries verbose. For obvious reasons, library developers want to save as much gas as possible, which leads to lots of function that look like this:
function avg(uint256 x, uint256 y) internal pure returns (uint256 result) {
unchecked {
result = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
Or worse - see the log2 function in PRBMath.
My proposal is to add a new modifier that is built in the language called, say, unchecked
, which can be applied directly to functions. With that we would not have to add an extra nested block when we want the entire body of the function to avoid the default arithmetic overflow and underflow checks. In fact, that might even lead to a bit of gas saved, since (at least in my head), not enabling the checks in the first place sounds cheaper than enabling them and disabling them immediately (what effectively happens when the entire body of the function is wrapped in unchecked
).
What do you think?