v4-core
v4-core copied to clipboard
Optimize `TickMath`
Related Issue
Which issue does this pull request resolve?
Description of Changes
The TickMath library has undergone extensive annotation and optimization, with the implementation ported from Aperture-Finance/uni-v3-lib. The optimizations primarily focus on eliminating branching code that involves conditional statements. An inlined and more efficient version of the mostSignificantBit function from Solady::LibBit has been incorporated, following its introduction in #257. Additional amendments have been made to reduce the number of opcodes and stack/memory operations.
New Forge tests for TickMath have been added to affirm equivalence with the reference implementation and to allow comparisons of gas usage. Gas snapshots were taken both before and after the changes to evaluate the effectiveness of these optimizations. The results are as follows:
Gas Usage Comparison
| Library | Test | Before | After | Gas Efficiency |
|---|---|---|---|---|
| TickMath | getSqrtRatioAtTick | 87496 | 74032 | 15.39% |
| TickMath | getTickAtSqrtRatio | 233945 | 188818 | 23.90% |
Note: Each test runs the corresponding function 100 times with deterministic inputs.
Please accept this pull request @snreynolds
Hey @shuhuiluo ! We're finally going through our final stages of development so are considering all your optimisations now 🙏 sorry for the delay here!
Would you mind please merging in main and updating the gas snapshots please so we can see what the new values would be?
Hey @shuhuiluo ! We're finally going through our final stages of development so are considering all your optimisations now 🙏 sorry for the delay here!
Would you mind please merging in main and updating the gas snapshots please so we can see what the new values would be?
Will do.