使用:
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
里提供的方法库。