Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize absTick calculation in TickMath.getSqrtPriceAtTick #663

Merged
merged 3 commits into from
May 21, 2024

Conversation

shuhuiluo
Copy link
Contributor

Part of #273.

Related Issue

Which issue does this pull request resolve?

Description of changes

The getSqrtPriceAtTick function in the TickMath library has been refactored with a more efficient assembly implementation. This optimization significantly reduces the gas usage by using bitwise operations for computing absolute value of a tick.

@@ -46,7 +46,15 @@ library TickMath {
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you add 1 test to show that the behaviour for type(int24).min is unchanged - just bc thats the 1 number that performs -1 weirdly. Something like


    function test_getSqrtPriceAtTick_throwsForMinIn24() public {
        vm.expectRevert(TickMath.InvalidTick.selector);
        tickMath.getSqrtPriceAtTick(type(int24).min);
    }

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do. But note that in both the original code and the current code, before negation type(int24).min will first be sign-extended to int256. Negating type(int24).min as a int256 would not revert. However, it will be rejected after comparing to MAX_TICK.

hensha256
hensha256 previously approved these changes May 20, 2024
The getSqrtPriceAtTick function in the TickMath library has been refactored with a more efficient assembly implementation. This optimization significantly reduces the gas usage by using bitwise operations for computing absolute value of a tick.
The new test case asserts that the function `getSqrtPriceAtTick` throws an error when called with the minimum valid input. This ensures that the function behaves as expected for all possible input values, enhancing the overall test coverage.
@hensha256 hensha256 merged commit fa5164a into Uniswap:main May 21, 2024
5 of 6 checks passed
@shuhuiluo shuhuiluo deleted the get-sqrt-ratio-at-tick-0 branch May 21, 2024 20:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants