package uniswap import ( "math/big" "sync" ) var ( // Cached constants to avoid recomputing them q96 *big.Int q192 *big.Int once sync.Once ) // initConstants initializes the cached constants func initConstants() { once.Do(func() { q96 = new(big.Int).Exp(big.NewInt(2), big.NewInt(96), nil) q192 = new(big.Int).Exp(big.NewInt(2), big.NewInt(192), nil) }) } // SqrtPriceX96ToPriceCached converts sqrtPriceX96 to a price using cached constants func SqrtPriceX96ToPriceCached(sqrtPriceX96 *big.Int) *big.Float { // Initialize cached constants initConstants() // price = (sqrtPriceX96 / 2^96)^2 // price = sqrtPriceX96^2 / 2^192 // Convert to big.Float for precision sqrtPrice := new(big.Float).SetInt(sqrtPriceX96) // Calculate sqrtPrice^2 price := new(big.Float).Mul(sqrtPrice, sqrtPrice) // Divide by 2^192 using cached constant q192Float := new(big.Float).SetInt(q192) price.Quo(price, q192Float) return price } // PriceToSqrtPriceX96Cached converts a price to sqrtPriceX96 using cached constants func PriceToSqrtPriceX96Cached(price *big.Float) *big.Int { // Initialize cached constants initConstants() // sqrtPriceX96 = sqrt(price) * 2^96 // Calculate sqrt(price) sqrtPrice := new(big.Float).Sqrt(price) // Multiply by 2^96 using cached constant q96Float := new(big.Float).SetInt(q96) sqrtPrice.Mul(sqrtPrice, q96Float) // Convert to big.Int sqrtPriceX96 := new(big.Int) sqrtPrice.Int(sqrtPriceX96) return sqrtPriceX96 }