I'm trying to process pool reserves on uniswapV2.
On the pool: WETH - USDC on UniswapV2.
address of the pool: 0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc
https://etherscan.io/address/0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc
I have this two consecutive swaps:
SWAP 0:
transaction_hash = 0x07104ffdf32b06b90e604f23c7b4e21fc985b68c5bb8c13140d0d3d2e151a385
block = 10370933
log_index = 40
dx = -3000.0 (USDC reserve pool variation)
dy = 13.45013459746252 (WETH reserve pool variation)
https://etherscan.io/tx/0x07104ffdf32b06b90e604f23c7b4e21fc985b68c5bb8c13140d0d3d2e151a385
SWAP 1:
transaction_hash = 0x9b0048c83a0a1a55d9de4966dc40eff15a97b58a54ecf4dff82409b525202b24
block = 10370933
log_index = 55
dx = 1574.167134 (USDC reserve pool variation)
dy = -7.0218022209976825 (WETH reserve pool variation)
https://etherscan.io/tx/0x9b0048c83a0a1a55d9de4966dc40eff15a97b58a54ecf4dff82409b525202b24
This two swaps are consecutive (there are no swaps/mint/burn in between for this pool).
If I understand correctly how Uniswap V2 works, we have this set of equations:
X * Y = K
(X + dx0) * (Y + dy0) = K
(X + dx0 + dx1) * (Y + dy0 + dy1) = K
With X the initial reserves of token X, Y the initial reserves of token Y. So I have 3 equations with 3 unknown variables (K, X, Y). After solving this equation system i get:
X = -(dy1 * dx0) * (dx0 + dx1) / (dx0*dy1 - dx1*dy0)
Y = -X * (dy0 / dx0) - dy0
Which gives on this example:
X = -279784.46893471375
Y = -1267.8297230812861
The result is obviously wrong (as reserves in pool can not be negative). But why ?
The formula does not work for swaps with different directions (in this example, sign of dx0 is different than sign of dx1).
But every time i use the formula for swaps with same direction, it works. Here is a plot, each point correspond reserves processed with consecutive swaps. In blue when swaps have same direction, black when swaps have different direction (same as example given):
Why this formula works for swaps with same direction and not for swaps with different directions ?
Is there a a way to get pool reserves with consecutive swaps with different direction ?