I would start with a sample on exact UniswapV2
pair SHIB/WETH (SushiSwap). I use local hardhat node and there's no possibility of 3-rd party effect on LP.
I have this toSwapTokensAmount = 2857840823995360316751873
amount of SHIB.
The liquidity pool has the next amount of reserves: SHIB=109916954769052324620139928
, WEI=887807065530129372
.
I call the getAmountsOut
uniswap-v2 router contract function and receive outputWeiAmount = 22432246070044323
WEI as the result.
I use two approaches in my code:
- Price calculation approach based on the amount of the tokens to sell and received amount of
Wei
s:
myPrice = toSwapTokensAmount / outputWeiAmount = 2857840823995360316751873 / 22432246070044323 = 127398781.873
- Price calculation approach based on the amount of the reserves (including the changes in reserves):
initialShibReserves = 109916954769052324620139928
initialWeiReserves = 887807065530129372
toSwapTokensAmount = 2857840823995360316751873
outputWeiAmount = routerContract.functions.getAmountsOut() # 22432246070044323
// change LP reserves according to swap operation direction: sell SHIB, receive WETH
newShibReserves = initialShibReserves + toSwapTokensAmount // 112774795593047684936891801
newWeiReserves = initialWeiReserves - outputWeiAmount // 865374819460085049
priceFromReserves = newShibReserves / newWeiReserves // 130319016.750925
The both approaches results are not equal: myPrice != priceFromReserves
-> 127398781.873 != 130319016.750925
.
I found the way to calculate the price based on reserves very popular in the other repositories: reserve0/reserve1 (or vice versa), so it looks like the issue is not here, which means the issue is with toSwapTokensAmount / outputWeiAmount
.
Worth to mention that after the actual swap I see almost the same price as priceFromReserves
, but probably because the calculation depends on the amount of the reserves.
So the question is why the results are different. Why I can't calculate the price using the amount of the tokens to sell and Wei amount to receive which is common when you buy something in a shop/market?