Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kassandraoftroy/785e0ad88f62e741db12e0e615e416f5 to your computer and use it in GitHub Desktop.
Save kassandraoftroy/785e0ad88f62e741db12e0e615e416f5 to your computer and use it in GitHub Desktop.
0.8 compatibility, uniswap v3 oracle
function _checkSlippage(uint160 _swapThresholdPrice, bool zeroForOne)
private
view
{
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _observationSeconds;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
require(tickCumulatives.length == 2, "array length");
uint160 avgSqrtRatioX96;
unchecked {
int24 avgTick =
int24(
(tickCumulatives[1] - tickCumulatives[0]) /
int56(uint56(_observationSeconds))
);
avgSqrtRatioX96 = avgTick.getSqrtRatioAtTick();
}
uint160 maxSlippage = (avgSqrtRatioX96 * _maxSlippageBPS) / 10000;
if (zeroForOne) {
require(
_swapThresholdPrice >= avgSqrtRatioX96 - maxSlippage,
"unacceptable slippage"
);
} else {
require(
_swapThresholdPrice <= avgSqrtRatioX96 + maxSlippage,
"unacceptable slippage"
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment