Submitted by KIntern_NA, also found by hansfriese, Jeiwan, and cccz
Function LBRouter._getAmountsIn is a helper function to return the amounts in with given amountOut. This function will check the pair of _token and _tokenNext is JoePair or LBPair using _binStep.
As we can see when _binStep == 0 and _token < _tokenPath[i] (in another word  we swap through JoePair and pairstoken0 is _token and token1 is _tokenPath[i]), it will
But unfortunately the denominator _reserveOut - amountOut_ * 997 seem incorrect. It should be (_reserveOut - amountOut_) * 997.
We will do some math calculations here to prove the expression above is wrong.
Input:
Output:
Generate Formula:
Cause JoePair takes 0.3% of amountIn as fee, we get
Following the constant product formula, we have
As we can see rAmountIn is different from amountsIn[i - 1], the denominator of rAmountIn is (rOut - amountOut_) * 997 when the denominator of amountsIn[i - 1] is _reserveOut - amountOut_ * 997 (Missing one bracket)
Loss of fund: User will send a lot of tokenIn (much more than expected) but just gain exact amountOut in return.
Let dive in the function swapTokensForExactTokens() to figure out why this scenario happens. I will assume I just swap through only one pool from JoePair and 0 pool from LBPair.
Here is our test script to describe the impacts
You can place this file into /test folder and run it using
Explanation of test script: (For more detail you can read the comments from test script above)
Foundry
Modify function LBRouter._getAmountsIn as follow
0x0Louis (Trader Joe) confirmed
Alex the Entreprenerd (judge) commented:
