10 给定一个Uniswap V3的池子地址,如何计算代币的价格呢?

给定一个Uniswap V3的池子地址,如何使用合约提供的原始信息计算代币的价格呢?能有参数和公式就可以了,非常感谢!

请先 登录 后评论

最佳答案 2021-11-01 08:32

使用:

function getPrice(address tokenIn, address tokenOut)
      external
      view
      returns (uint256 price)
  {
      IUniswapV3Pool pool = IUniswapV3Pool(factory.getPool(tokenIn, tokenOut, fee));
      (uint160 sqrtPriceX96,,,,,,) =  pool.slot0();
      return uint(sqrtPriceX96).mul(uint(sqrtPriceX96)).mul(1e18) >> (96 * 2);
  }

可能, 你更想知道一个币可兑换另一个币的数量, 可以这样:

function getQuote(address tokenA, uint amountA, address tokenB) public view override returns (uint256 amountB) {
    int24 tick = OracleLibrary.consult(factory.getPool(tokenIn, tokenOut, fee), 60);
    return OracleLibrary.getQuoteAtTick(tick, uint128(amountA), tokenA, tokenB);
  }

OracleLibrary 是 uniswap/v3 里提供的方法库。

请先 登录 后评论

其它 6 个回答

fox
请先 登录 后评论
Ethereal - Solidity智能合约开发工程师
请先 登录 后评论
zoro
请先 登录 后评论
路远 - 开发
请先 登录 后评论
tom - 科学家
请先 登录 后评论
Scott - CTO
请先 登录 后评论
  • 9 关注
  • 0 收藏,10398 浏览
  • johnny 提出于 2021-10-28 11:44