Last active
December 18, 2023 17:31
-
-
Save tienshaoku/e823bec06e5492dbfe8832687bf9764b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; | |
import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; | |
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; | |
import "@uniswap/v3-core/contracts/libraries/FullMath.sol"; | |
contract TwapGetter { | |
function getSqrtTwapX96(address uniswapV3Pool, uint32 twapInterval) public view returns (uint160 sqrtPriceX96) { | |
if (twapInterval == 0) { | |
// return the current price if twapInterval == 0 | |
(sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0(); | |
} else { | |
uint32[] memory secondsAgos = new uint32[](2); | |
secondsAgos[0] = twapInterval; // from (before) | |
secondsAgos[1] = 0; // to (now) | |
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapV3Pool).observe(secondsAgos); | |
// tick(imprecise as it's an integer) to price | |
sqrtPriceX96 = TickMath.getSqrtRatioAtTick( | |
int24((tickCumulatives[1] - tickCumulatives[0]) / twapInterval) | |
); | |
} | |
} | |
function getPriceX96FromSqrtPriceX96(uint160 sqrtPriceX96) public pure returns(uint256 priceX96) { | |
return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment