Skip to content

Commit

Permalink
Add gas benchmarks for TickMath functions (#668)
Browse files Browse the repository at this point in the history
* Add gas benchmarks for `TickMath` functions

This commit introduces gas benchmarks for the functions `getSqrtPriceAtTick` and `getTickAtSqrtPrice` within the TickMath library. Additionally, a dependency on `GasSnapshot.sol` has been added to the `TickMath.t.sol` file. This will aid in evaluating the performance of these critical functions.

* Fix incorrect threshold in `getTickAtSqrtPrice` test

* Uncheck math in `TickMath` gas benchmarks
  • Loading branch information
shuhuiluo committed May 20, 2024
1 parent 2df9bb3 commit 48c8986
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
1 change: 1 addition & 0 deletions .forge-snapshots/TickMathGetSqrtPriceAtTick.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
87496
1 change: 1 addition & 0 deletions .forge-snapshots/TickMathGetTickAtSqrtPrice.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
233945
28 changes: 26 additions & 2 deletions test/libraries/TickMath.t.sol
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import {GasSnapshot} from "forge-gas-snapshot/GasSnapshot.sol";
import {Test} from "forge-std/Test.sol";
import {Vm} from "forge-std/Vm.sol";
import {TickMathTest} from "src/test/TickMathTest.sol";
import {TickMath} from "src/libraries/TickMath.sol";
import {JavascriptFfi} from "test/utils/JavascriptFfi.sol";

contract TickMathTestTest is Test, JavascriptFfi {
contract TickMathTestTest is Test, JavascriptFfi, GasSnapshot {
int24 constant MIN_TICK = -887272;
int24 constant MAX_TICK = -MIN_TICK;

Expand Down Expand Up @@ -93,7 +94,7 @@ contract TickMathTestTest is Test, JavascriptFfi {

function test_getTickAtSqrtPrice_throwsForTooHigh() public {
vm.expectRevert(TickMath.InvalidSqrtPrice.selector);
tickMath.getTickAtSqrtPrice(MAX_SQRT_PRICE + 1);
tickMath.getTickAtSqrtPrice(MAX_SQRT_PRICE);
}

function test_getTickAtSqrtPrice_isValidMinSqrtPrice() public view {
Expand Down Expand Up @@ -173,4 +174,27 @@ contract TickMathTestTest is Test, JavascriptFfi {
assertLt(resultsDiff, 2);
}
}

/// @notice Benchmark the gas cost of `getSqrtPriceAtTick`
function test_getSqrtPriceAtTick_gasCost() public {
snapStart("TickMathGetSqrtPriceAtTick");
unchecked {
for (int24 tick = -50; tick < 50;) {
TickMath.getSqrtPriceAtTick(tick++);
}
}
snapEnd();
}

/// @notice Benchmark the gas cost of `getTickAtSqrtPrice`
function test_getTickAtSqrtPrice_gasCost() public {
snapStart("TickMathGetTickAtSqrtPrice");
unchecked {
uint160 sqrtPriceX96 = 1 << 33;
for (uint256 i; i++ < 100; sqrtPriceX96 <<= 1) {
TickMath.getTickAtSqrtPrice(sqrtPriceX96);
}
}
snapEnd();
}
}

0 comments on commit 48c8986

Please sign in to comment.