PriceMath.sol
37 lines · sha256 4e3d12942a310f6fe0cf0a184a1480dcb4194cd0991fefeb0497f33f065568b5 · Raw
| 1 | // SPDX-License-Identifier: MIT |
| 2 | pragma solidity ^0.8.26; |
| 3 | |
| 4 | import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol"; |
| 5 | import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol"; |
| 6 | import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; |
| 7 | |
| 8 | /// @title PriceMath |
| 9 | /// @notice Conversions between the v4 pool price (sqrt(KIBBLE per HYPE) in Q64.96, currency0 = native HYPE) |
| 10 | /// and the protocol price unit: HYPE per KIBBLE scaled by 1e18. |
| 11 | library PriceMath { |
| 12 | uint256 internal constant Q96 = 1 << 96; |
| 13 | |
| 14 | /// @notice HYPE per KIBBLE (1e18 scaled) from sqrtPriceX96. |
| 15 | function priceFromSqrt(uint160 sqrtPriceX96) internal pure returns (uint256) { |
| 16 | if (sqrtPriceX96 == 0) return 0; |
| 17 | return FullMath.mulDiv(FullMath.mulDiv(1e18, Q96, sqrtPriceX96), Q96, sqrtPriceX96); |
| 18 | } |
| 19 | |
| 20 | /// @notice sqrtPriceX96 for a pool holding `amount0` HYPE against `amount1` KIBBLE (price = amount1 / amount0). |
| 21 | function sqrtFromAmounts(uint256 amount0, uint256 amount1) internal pure returns (uint160) { |
| 22 | return _clamp(Math.sqrt(FullMath.mulDiv(amount1, 1 << 192, amount0))); |
| 23 | } |
| 24 | |
| 25 | /// @notice sqrtPriceX96 for a HYPE-per-KIBBLE price (1e18 scaled). |
| 26 | function sqrtFromPrice(uint256 hypePerKibble) internal pure returns (uint160) { |
| 27 | if (hypePerKibble == 0) return TickMath.MAX_SQRT_PRICE - 1; |
| 28 | return _clamp(Math.sqrt(FullMath.mulDiv(1e18, 1 << 192, hypePerKibble))); |
| 29 | } |
| 30 | |
| 31 | function _clamp(uint256 s) private pure returns (uint160) { |
| 32 | if (s <= TickMath.MIN_SQRT_PRICE) return TickMath.MIN_SQRT_PRICE + 1; |
| 33 | if (s >= TickMath.MAX_SQRT_PRICE) return TickMath.MAX_SQRT_PRICE - 1; |
| 34 | return uint160(s); |
| 35 | } |
| 36 | } |
| 37 |