UniswapV3 incorrect price in slot0() sqrtPriceX96

I want to get a price of token in uniswapV3 pair. As example, i have pair https://etherscan.io/address/0x409634ea16d98b0b245f345079c8f3cfe3ef1fa6. Result of calling slot0() is [12934124507235850032763499380293, 101910, 0, 1, 1, 0, True], where 12934124507235850032763499380293 is sqrtPriceX96. I use this formula: price = (sqrtPriceX96 ** 2) / (2 ** 192). And result is 26666 in ETH, while real price is 0.09$. Token has 18 decimals, WETH as well. Where is the problem?

Correct formula to calculate price

Upvotes: 2

Views: 1014

Answers (2)

Pavel Fedotov
Pavel Fedotov

Reputation: 885

The price in data is correct. Here is an explanation:

.slot0() returns the following type

type Slot0RawType = [bigint, number, number, number, number, number, boolean];

which can further be converted to

type Slot0ReturnType = {
  sqrtPriceX96: BigInt; // Returns a bigint representation of the sqrt price
  tick: number; // Returns the current tick (usually a number)
  observationIndex: number; // Returns the last observation index
  observationCardinality: number; // Returns the max observations that can be stored
  observationCardinalityNext: number; // Returns the next cardinality
  feeProtocol: number; // Returns the protocol fee
  unlocked: boolean; // If the pool is unlocked
};

Install @evmexplorer/uniswap to import the types. The package also contains convertSlot0() to convert an array to object.

Upvotes: 1

I got it. If token0 in pair is base token, WETH in this example, you need to make reverse operation. 1 / price. Here i got 26666 -> 1 / 26666 * 2400 (ETH price) = 0.09$.

Upvotes: 2

Related Questions