From 3c2eefa8c6ec35d0e3a19bf0c8f630d91e07c056 Mon Sep 17 00:00:00 2001 From: kyriediculous Date: Sat, 30 Sep 2023 02:42:33 +0700 Subject: [PATCH] Livepeer: correct handling of X96 Price --- src/adapters/LivepeerAdapter.sol | 5 +++-- src/utils/TWAP.sol | 6 +++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/adapters/LivepeerAdapter.sol b/src/adapters/LivepeerAdapter.sol index 6b6e4fc..954e34b 100644 --- a/src/adapters/LivepeerAdapter.sol +++ b/src/adapters/LivepeerAdapter.sol @@ -136,7 +136,8 @@ contract LivepeerAdapter is Adapter { WETH.deposit{ value: ethBalance }(); ERC20(address(WETH)).safeApprove(address(UNISWAP_ROUTER), ethBalance); // Calculate Slippage Threshold - uint256 twapPrice = TWAP.getPriceX96FromSqrtPriceX96(TWAP.getSqrtTwapX96(UNI_POOL, TWAP_INTERVAL)); + uint256 twapPrice = TWAP.getInversePriceX96(TWAP.getPriceX96(TWAP.getSqrtTwapX96(UNI_POOL, TWAP_INTERVAL))); + uint256 amountOut = ethBalance * twapPrice >> 96; // Create initial params for swap ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ tokenIn: address(WETH), @@ -145,7 +146,7 @@ contract LivepeerAdapter is Adapter { recipient: address(this), deadline: block.timestamp, amountIn: ethBalance, - amountOutMinimum: ethBalance * twapPrice * 90 / 100, // 10% slippage threshold + amountOutMinimum: amountOut * 897 / 1000, // 10% slippage threshold + 0.3% fee sqrtPriceLimitX96: 0 }); diff --git a/src/utils/TWAP.sol b/src/utils/TWAP.sol index 4999fe2..3422efd 100644 --- a/src/utils/TWAP.sol +++ b/src/utils/TWAP.sol @@ -33,7 +33,11 @@ library TWAP { } } - function getPriceX96FromSqrtPriceX96(uint160 sqrtPriceX96) internal pure returns (uint256 priceX96) { + function getPriceX96(uint160 sqrtPriceX96) internal pure returns (uint256) { return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96); } + + function getInversePriceX96(uint256 priceX96) internal pure returns (uint256) { + return FullMath.mulDiv(2 ** 96, 2 ** 96, priceX96); + } }