0

Code can be seen here: https://github.com/Uniswap/v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol#L53

What I don't understand is that if you use the constant product formula, you arrive at a different formula:

  • invariant formula: resIn * resOut = k
  • therefore, (resIn+amountIn)*(resOut-amountOut)=k
  • solving for amountIn, we get amountIn = (resIn*resOut) / (resOut-amountOut) - resIn
  • But the contract has a version that's not equivalent, even after accounting for fees.

Note: the above doesn’t include fees

    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
        require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
        require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
        uint numerator = reserveIn.mul(amountOut).mul(1000);
        uint denominator = reserveOut.sub(amountOut).mul(997);
        amountIn = (numerator / denominator).add(1);
    }
0

1 Answer 1

1

You can take a look at this calculation for the version of the contract:

what is math for uniswap calculates the amountout and amountin why 997 and 1000

In addition, the contract's version also added +1 .add(1) to round up as Uniswap pool strictly enforces k and make you pay one more wei to the LPs:

https://www.reddit.com/r/UniSwap/comments/rjzkcj/why_does_it_have_add1_uniswapv2library_getamountin/

1
  • sweet. Thanks so much for the answer. I see it was because once you take the fees into account the math slightly changes
    – U Avalos
    Oct 10, 2022 at 3:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.