fix: Fix UniswapV4 dynamic fee calculation #428
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Some pools were triggering a decoder panic with the following error:
thread 'tokio-runtime-worker' panicked at src/evm/protocol/utils/uniswap/swap_math.rs:26:24: attempt to subtract with overflowThe reason was bc pools with dynamic fees are initialized with 0x800000 - where the expected value should be 0, together with the 23rd bit as a flag indicating that the pool has dynamic fees.
On decoding, we weren't considering this case, making the fee overflow (since 0x800000 is higher than Uniswap's max fee of 100%).
During this investigation, was also noticed that Uniswap's fee implementation is not correct.
According to https://raw.githubusercontent.com/Uniswap/v4-core/main/src/libraries/ProtocolFeeLibrary.sol - the fee formula is:
// protocolFee + lpFee - (protocolFee * lpFee / 1_000_000)and our current implementation is
// protocolFee + lpFeecausing a wrong fee calculation, and overflow on protocols where protocolFee + lpFee > 100%.