Wrong calculation in function LBRouter._getAmountsIn make user lose a lot of tokens when swap through JoePair (most of them will gifted to JoePair freely)
The LBRouter contract's _getAmountsIn function used an incorrect formula when calculating the required input amount for swaps through a JoePair (Uniswap V2 style pair). This caused users to send far more tokens than necessary, with the excess effectively gifted to the pair.
KIntern_NA Follow with hansfriese, Jeiwan and 1 other
Originally disclosed on Code4rena
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.
- If
_binStep == 0, it will be aJoePairotherwise it will be anLBPair.
if (_binStep == 0) {
(uint256 _reserveIn, uint256 _reserveOut, ) = IJoePair(_pair).getReserves();
if (_token > _tokenPath[i]) {
(_reserveIn, _reserveOut) = (_reserveOut, _reserveIn);
}
uint256 amountOut_ = amountsIn[i];
// Legacy uniswap way of rounding
amountsIn[i - 1] = (_reserveIn * amountOut_ * 1_000) / (_reserveOut - amountOut_ * 997) + 1;
} else {
(amountsIn[i - 1], ) = getSwapIn(ILBPair(_pair), amountsIn[i], ILBPair(_pair).tokenX() == _token);
}
As we can see when _binStep == 0 and _token < _tokenPath[i] (in another word we swap through JoePair and pair’stoken0 is _token and token1 is _tokenPath[i]), it will
- Get the reserve of pair (
reserveIn,reserveOut) - Calculate the
_amountInby using the formula
amountsIn[i - 1] = (_reserveIn * amountOut_ * 1_000) / (_reserveOut - amountOut_ * 997) + 1
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:
_reserveIn (rIn): reserve of_tokenin pair_reserveOut (rOut): reserve of_tokenPath[i]in pairamountOut_: the amount of_tokenPaththe user wants to gain
Output:
rAmountIn: the actual amount of_tokenwe need to transfer to the pair.
Generate Formula:
Cause JoePair takes 0.3% of amountIn as fee, we get
amountInDeductFee = amountIn' * 0.997
Following the constant product formula, we have
rIn * rOut = (rIn + amountInDeductFee) * (rOut - amountOut_)
==> rIn + amountInDeductFee = rIn * rOut / (rOut - amountOut_) + 1
<=> amountInDeductFee = (rIn * rOut) / (rOut - amountOut_) - rIn + 1
<=> rAmountIn * 0.997 = rIn * amountOut / (rOut - amountOut_) + 1
<=> rAmountIn = (rIn * amountOut * 1000) / ((rOut - amountOut_) * 997) + 1
<=>
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)
Impact
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.
-
Firstly function will get the list
amountsInfrom function_getAmountsIn. SoamountsInwill be [incorrectAmountIn,userDesireAmount].amountsIn = _getAmountsIn(_pairBinSteps, _pairs, _tokenPath, _amountOut); -
Then it transfers
incorrectAmountInto_pairs[0]to prepare for the swap._tokenPath[0].safeTransferFrom(msg.sender, _pairs[0], amountsIn[0]); -
Finally it calls function
_swapTokensForExactTokento execute the swap.uint256 _amountOutReal = _swapTokensForExactTokens(_pairs, _pairBinSteps, _tokenPath, amountsIn, _to);In this step it will reach to line 841 which will set the expected
amountOut = amountsIn[i+1] = amountsIn[1] = userDesireAmount.amountOut = _amountsIn[i + 1];So after calling
IJoePair(_pair).swap(), the user just gets exactlyamountOutand wastes a lot of tokenIn that (s)he transfers to the pool.
Proof of concept
Here is our test script to describe the impacts
You can place this file into /test folder and run it using
forge test --match-test testBugSwapJoeV1PairWithLBRouter --fork-url https://rpc.ankr.com/avalanche --fork-block-number 21437560 -vv
Explanation of test script: (For more detail you can read the comments from test script above)
- Firstly we get the Joe v1 pair WAVAX/USDC from JoeFactory.
- At the forked block, price
WAVAX/USDCwas around 15.57. We try to use LBRouter functionswapTokensForExactTokensto swap10$WAVAX (10e18 wei) to1$USDC (1e6 wei). But it reverts with the errorLBRouter__MaxAmountInExceeded. But when we swap directly to JoePair, it swap successfully10$AVAX (10e18 wei) to155$USDC (155e6 wei). - We use LBRouter function
swapTokensForExactTokensagain with very largeamountInMaxto swap1$USDC (1e6 wei). It swaps successfully but needs to pay a very large amount WAVAX (much more than price).
Tools Used
Foundry
Recommended Mitigation Steps
Modify function LBRouter._getAmountsIn as follow
if (_binStep == 0) {
(uint256 _reserveIn, uint256 _reserveOut, ) = IJoePair(_pair).getReserves();
if (_token > _tokenPath[i]) {
(_reserveIn, _reserveOut) = (_reserveOut, _reserveIn);
}
uint256 amountOut_ = amountsIn[i];
// Legacy uniswap way of rounding
// Fix here
amountsIn[i - 1] = (_reserveIn * amountOut_ * 1_000) / ((_reserveOut - amountOut_) * 997) + 1;
} else {
(amountsIn[i - 1], ) = getSwapIn(ILBPair(_pair), amountsIn[i], ILBPair(_pair).tokenX() == _token);
}
0x0Louis (Trader Joe) confirmed
Alex the Entreprenerd (judge) commented:
The warden has shown how, due to an incorrect order of operation, the math for the router will be incorrect.
While the error could be considered a typo, the router is the designated proper way of performing a swap, and due to this finding, the math will be off.
Because the impact shows an incorrect logic, and a broken invariant (the router uses incorrect amounts, sometimes reverting, sometimes costing the end user more tokens than necessary), I believe High Severity to be appropriate.
Mitigation will require refactoring and may be aided by the test case offered in this report.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely a missing pair of parentheses in the denominator of the input amount formula, causing the multiplication by 997 to apply only to amountOut_ instead of the entire difference (reserveOut - amountOut_).
Impact
Users could lose a significant amount of tokens when swapping through JoePair, as the excess input is effectively gifted to the pair; the report demonstrates this with a test showing a swap that required far more WAVAX than the market price.
What the attacker needed
User swaps through a JoePair pool; User calls swapTokensForExactTokens
The fix
The formula should be corrected by adding parentheses around the subtraction before multiplying by 997, as shown in the recommended mitigation.
How it was found
- Call swapTokensForExactTokens with a JoePair pool.
- The router computes amountsIn using the faulty formula.
- The router transfers the inflated input amount from the user to the pair.
- The swap executes and the user receives only the desired output amount, losing the excess input.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
When you swap tokens, the router calculates how many tokens you need to put in to get the exact amount you want out. A mistake in that calculation made the router ask for too many tokens, so users lost extra money. The fix is a small change to the formula.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.