Skip to content

Commit

Permalink
Livepeer: correct handling of X96 Price
Browse files Browse the repository at this point in the history
  • Loading branch information
kyriediculous committed Sep 29, 2023
1 parent a043cb4 commit 3c2eefa
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/adapters/LivepeerAdapter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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
});

Expand Down
6 changes: 5 additions & 1 deletion src/utils/TWAP.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 3c2eefa

Please sign in to comment.