# Uniswap V2 AmountIn Calculation Procedure

So, I was working on a project which heavily uses uniswap. I have to show the calculations and derivations of stuff that is happening inside uniswap.

So, I was reading it's whitepaper, seeing it contract code, etc.

Now, There is one issue that I stumbled upon. First of all, assume this scenario:-

We have a pair RI : RO
[Here, RI and RO mean two things. 1) Name of Input token and output token respectively AND 2) Their inital reserves]

Say we want to borrow B amount of output token, for which, we have to return Re amount of Input token.

Now, The formulas that i was able to derive from the whitepaper and the code for swap function in UniswapV2Pair,

I get this result: -

This result is consistent with the final check that is beign perform in swap function that i mentioned about. Hence, I have some confidence that this formula is not wrong, yet I have verified it at least 6 times.

BUT, here is where the things start to get weird. The uniswap V2 router 02 uses a library which probably all know of as UniswapLibrary In that library, there is a function that is used to get the value of Re and the formula that their library is using is this: -

uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);


Which basically means,

And I am just not able to understand from where did that  + 1 came from?

Can some experts in this field shed some light on this problem. What am I doing wrong here? (Or, Do I need to provide more part of derivation, as to how I got my formula?) Just in case, here is the starting equation that I used: -

• I am not sure if this is correct or not, but many times we add +1 in the implementation when we don't want the result to be 0. because 0 can kind of lock up things Commented Jul 12, 2021 at 2:25
• @Nulik Thanks for reply. I just realised one thing. I was thinking of this 1 as 1 Eth or 1 * 10^18. Now that you mention it, this 1 is actually very very negligible so it just doesn't matter, and saves us from getting any 0 values. Commented Jul 12, 2021 at 4:07