⚡️ Optimize SignedWadMath
edge case check
#381
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
I've changed the
SignedWadMul.wadMul
to do the overflow & edge case check in oneif
:This saves gas at runtime for all cases except the edge case because the resulting bytecode only uses 1
JUMPI
vs. 2 to check the conditions. Branches are currently quite expensive making it worth the slightly higher cost of combining multiple expressions.To save further gas I've transformed the
!(x == -1 && y == type(int256).min)
check intox != -1 || y != type(int256).min
to minimize the use ofISZERO
. The inequality checks both need to have binary results so the resulting bitwise expressionand(no_overflow, or(x_not_neg1, y_not_min_signed))
equates the logical expression across the whole set of values. To achieve thisLT
andSGT
are abused as!=
operators, this is possible here as-1
represents the highest possible unsigned integer and0x8000000000000000000000000000000000000000000000000000000000000000
the lowest signed number.The final inline-assembly expression represents:
Checklist
forge snapshot
?npm run lint
?forge test
?Pull requests with an incomplete checklist will be thrown out.