// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol"; import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; /// @title PriceMath /// @notice Conversions between the v4 pool price (sqrt(KIBBLE per HYPE) in Q64.96, currency0 = native HYPE) /// and the protocol price unit: HYPE per KIBBLE scaled by 1e18. library PriceMath { uint256 internal constant Q96 = 1 << 96; /// @notice HYPE per KIBBLE (1e18 scaled) from sqrtPriceX96. function priceFromSqrt(uint160 sqrtPriceX96) internal pure returns (uint256) { if (sqrtPriceX96 == 0) return 0; return FullMath.mulDiv(FullMath.mulDiv(1e18, Q96, sqrtPriceX96), Q96, sqrtPriceX96); } /// @notice sqrtPriceX96 for a pool holding `amount0` HYPE against `amount1` KIBBLE (price = amount1 / amount0). function sqrtFromAmounts(uint256 amount0, uint256 amount1) internal pure returns (uint160) { return _clamp(Math.sqrt(FullMath.mulDiv(amount1, 1 << 192, amount0))); } /// @notice sqrtPriceX96 for a HYPE-per-KIBBLE price (1e18 scaled). function sqrtFromPrice(uint256 hypePerKibble) internal pure returns (uint160) { if (hypePerKibble == 0) return TickMath.MAX_SQRT_PRICE - 1; return _clamp(Math.sqrt(FullMath.mulDiv(1e18, 1 << 192, hypePerKibble))); } function _clamp(uint256 s) private pure returns (uint160) { if (s <= TickMath.MIN_SQRT_PRICE) return TickMath.MIN_SQRT_PRICE + 1; if (s >= TickMath.MAX_SQRT_PRICE) return TickMath.MAX_SQRT_PRICE - 1; return uint160(s); } }