How can I calculate the sqrtPriceX96 value for the initial square root price of a newly created BTC/USDc pool where 1BTC = 20k USDC and BTC is 8 Decimal and USDC is 6 Decimal.
sqrtPriceX96 is need to createAndInitializePoolIfNecessary function
How can I calculate the sqrtPriceX96 value for the initial square root price of a newly created BTC/USDc pool where 1BTC = 20k USDC and BTC is 8 Decimal and USDC is 6 Decimal.
sqrtPriceX96 is need to createAndInitializePoolIfNecessary function
If you have the blockNumber
of when the pool where created you can perfom a call like this:
const slot0 = await pool.slot0({blockTag: blockNumber})
And then
const price = slot0.sqrtPricex96._hex
Or you can do:
const price = 1/20000
And then call priceToSqrtPrice
export const priceToSqrtPrice = (price: number, token0Decimals: number, token1Decimals: number) => {
const decimalAdjustment = 10 ** (token0Decimals - token1Decimals);
const mathPrice = price / decimalAdjustment;
let sqrtPriceX96 = Math.floor(Math.sqrt(mathPrice) * 2 ** 96);
return BigInt(sqrtPriceX96);
};
createAndInitializePoolIfNecessary
with parameters price = 1/20000 and token0Decimals = 8 and token1Decimals = 6 and now by using '@uniswap/v3-sdk' if I am calculating mint amounts like "position.mintAmounts" amount0 (BTC) and amount1 (USDC) aren’t in the price range. question is the desired amounts of BTC and USDC required by the mint function for 'any' amount of liquidity should be minted should be in the price range of 1BTC ~ 20k USDC but it's not.
Commented
Mar 20, 2023 at 10:57
You can use a modified version of the encodePriceSqrt utility function in Uniswap/v3-core
Below the calculateSqrtPriceX96
function calculates the sqrtPriceX96
using this modified encodePriceSqrt
function.
import bn from 'bignumber.js'
import { BigNumber } from 'ethers'
function encodePriceSqrt(priceRatio: bn): BigNumber {
return BigNumber.from(
priceRatio
.sqrt()
.multipliedBy(new bn(2).pow(96))
.integerValue(3)
.toString()
)
}
interface Token {
address: string;
decimals: number;
}
function calculateSqrtPriceX96(tokenA: Token, tokenB: Token, priceOfTokenBInTermsOfTokenA: number): BigNumber {
const [token0, token1] = tokenA.address.toLowerCase() < tokenB.address.toLowerCase() ? [tokenA, tokenB] : [tokenB, tokenA];
let priceRatio = priceOfTokenBInTermsOfTokenA * (10 ** (tokenB.decimals - tokenA.decimals));
if (token0.address === tokenB.address) {
// Invert the price ratio if the order of tokens is switched
priceRatio = 1 / priceRatio;
}
const priceRatioBN = new bn(priceRatio)
return encodePriceSqrt(priceRatioBN)
}
// Usage for 1 BTC = 20,000 USDC
const btc: Token = {
address: "0xYourBtcTokenAddress",
decimals: 8,
};
const usdc: Token = {
address: "0xYourUsdcTokenAddress",
decimals: 6,
};
const btcPriceInUsdc = 20000.0; // i.e. 20_000 USDC/BTC
const sqrtPriceX96 = calculateSqrtPriceX96(btc, usdc, btcPriceInUsdc);