I'm trying to understand how uniswap can compute the best trade. I found the code here : https://github.com/Uniswap/v2-periphery/blob/master/contracts/libraries/UniswapV2LiquidityMathLibrary.sol
function computeProfitMaximizingTrade(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) pure internal returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
uint256 leftSide = Babylonian.sqrt(
FullMath.mulDiv(
invariant.mul(1000),
aToB ? truePriceTokenA : truePriceTokenB,
(aToB ? truePriceTokenB : truePriceTokenA).mul(997)
)
);
uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997;
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price to the profit-maximizing price
amountIn = leftSide.sub(rightSide);
}
Why they use price to determinate aToB ? I don't understand the formula