Jacky Gu

UniswapV3价格计算

26 Jun 2023 Share to

1- 获取sqrlPriceX96价格

IUniswapV3Pool pool = IUniswapV3Pool(uniswapV3Factory.getPool(address(token0), address(token1), 3000));
(uint160 sqrlPriceX96, , , , , , ) = pool.slot0();

2- 把sqrlPriceX96转换成uint

// python中:
print sqrlPriceX96**2 / 2 ** 192

3- 把uint价格转换成sqrlPriceX96和tick https://codesandbox.io/s/uniswap-sqrtpricex96-tool-w8zjmc?file=/src/App.js 在前端js

import "./styles.css";
import { encodeSqrtRatioX96, TickMath } from "@uniswap/v3-sdk";
import { useState } from "react";

// 参考:https://y1cunhui.github.io/uniswapV3-book-zh-cn/docs/milestone_3/user-interface/

export default function App() {
  const [price, setPrice] = useState("120");
  const tickSpace = 60;
  const priceToSqrtP = () => encodeSqrtRatioX96(parseFloat(price), 1);
  const priceToTick = () => TickMath.getTickAtSqrtRatio(priceToSqrtP());

  return (
    <div className="App">
      <h1>From price to sqrtPriceX96</h1>
      <div>
        Price
        <input value={price} onChange={(e) => setPrice(e.target.value)} />
      </div>
      <div>{"sqrtPriceX96 " + priceToSqrtP()}</div>
      <div>{"tick " + Math.round(priceToTick() / tickSpace) * tickSpace}</div>
    </div>
  );
}

4- 根据tick计算价格

//python
print 1.0001 ** tick