v4-core icon indicating copy to clipboard operation
v4-core copied to clipboard

Optimize `TickMath`

Open shuhuiluo opened this issue 2 years ago • 3 comments
trafficstars

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.

shuhuiluo avatar Jun 18 '23 10:06 shuhuiluo

Please accept this pull request @snreynolds

wjmelements avatar Dec 02 '23 11:12 wjmelements

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?

hensha256 avatar Apr 03 '24 18:04 hensha256

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.

shuhuiluo avatar Apr 03 '24 18:04 shuhuiluo