Skip to content
Smart contracts Audit finding Beginner

Calling swapAVAXForExactTokens function while sending excess amount cannot refund such excess amount

The swapAVAXForExactTokens function is supposed to refund any excess AVAX sent, but the refund calculation subtracts the sent amount from the required amount, causing an underflow revert whenever more than the required amount is sent. An attacker could not exploit this for gain, but ordinary users sending extra AVAX would have their transactions fail.

rbserver Follow with lukris02, Trust and 11 others

Originally disclosed on Code4rena

Submitted by rbserver, also found by lukris02, Trust, hyh, pashov, TomJ, ElKu, m_Rassska, neumo, d3e4, Rahoz, 8olidity, cccz, and vv7

When calling the swapAVAXForExactTokens function, if (msg.value > amountsIn[0]) _safeTransferAVAX(_to, amountsIn[0] - msg.value) is executed, which is for refunding any excess amount sent in; this is confirmed by this function’s comment as well. However, executing amountsIn[0] - msg.value will always revert when msg.value > amountsIn[0] is true. Developers who has the design of the swapAVAXForExactTokens function in mind could develop front-ends and contracts that will send excess amount when calling the swapAVAXForExactTokens function. Hence, the users, who rely on these front-ends and contracts for interacting with the swapAVAXForExactTokens function will always find such interactions being failed since calling this function with the excess amount will always revert. As a result, the user experience becomes degraded, and the usability of the protocol becomes limited.

https://github.com/code-423n4/2022-10-traderjoe/blob/main/src/LBRouter.sol#L485-L521

    /// @notice Swaps AVAX for exact tokens while performing safety checks
    /// @dev will refund any excess sent
    ...
    function swapAVAXForExactTokens(
        uint256 _amountOut,
        uint256[] memory _pairBinSteps,
        IERC20[] memory _tokenPath,
        address _to,
        uint256 _deadline
    )
        external
        payable
        override
        ensure(_deadline)
        verifyInputs(_pairBinSteps, _tokenPath)
        returns (uint256[] memory amountsIn)
    {
        ...

        if (msg.value > amountsIn[0]) _safeTransferAVAX(_to, amountsIn[0] - msg.value);
    }

Proof of Concept

Please add the following test in test\LBRouter.Swaps.t.sol. This test will pass to demonstrate the described scenario.

    function testSwapAVAXForExactTokensIsUnableToRefund() public {
        uint256 amountOut = 1e18;

        (uint256 amountIn, ) = router.getSwapIn(pairWavax, amountOut, false);

        IERC20[] memory tokenList = new IERC20[](2);
        tokenList[0] = wavax;
        tokenList[1] = token6D;
        uint256[] memory pairVersions = new uint256[](1);
        pairVersions[0] = DEFAULT_BIN_STEP;

        vm.deal(DEV, amountIn + 500);

        // Although the swapAVAXForExactTokens function supposes to refund any excess sent,
        //   calling it reverts when sending more than amountIn
        //   because executing _safeTransferAVAX(_to, amountsIn[0] - msg.value) results in arithmetic underflow
        vm.expectRevert(stdError.arithmeticError);
        router.swapAVAXForExactTokens{value: amountIn + 1}(amountOut, pairVersions, tokenList, DEV, block.timestamp);
    }

Tools Used

VSCode

Recommended Mitigation Steps

https://github.com/code-423n4/2022-10-traderjoe/blob/main/src/LBRouter.sol#L520 can be updated to the following code.

        if (msg.value > amountsIn[0]) _safeTransferAVAX(_to, msg.value - amountsIn[0]);

0x0Louis (Trader Joe) confirmed, but disagreed with severity

Alex the Entreprenerd (judge) decreased severity to Low and commented:

The finding is valid, sending more than necessary will revert. No loss to end-users was shown, and the revert will prevent the tx from finishing.

Because of that, considering the fact that a accurate measure could be calculated, meaning that functionality can be side-stepped, despite recommending fixing, I think the finding is QA - Low Severity as the revert is self-inflicted.

Alex the Entreprenerd (judge) increased severity to Medium and commented:

Per discussion from backstage I’ve re-reviewed the finding.

I have poked around with the test provided and tweaked it a little, this is the last one I have

function testSwapAVAXForExactTokensIsUnableToRefund() public {
        uint256 amountOut = 1e18;

        (uint256 amountIn, ) = router.getSwapIn(pairWavax, amountOut, false);

        IERC20[] memory tokenList = new IERC20[](2);
        tokenList[0] = wavax;
        tokenList[1] = token6D;
        uint256[] memory pairVersions = new uint256[](1);
        pairVersions[0] = DEFAULT_BIN_STEP;

        vm.deal(DEV, 50 * amountIn + 500);


        // Although the swapAVAXForExactTokens function supposes to refund any excess sent,
        //   calling it reverts when sending more than amountIn
        //   because executing _safeTransferAVAX(_to, amountsIn[0] - msg.value) results in arithmetic underflow
        vm.expectRevert(stdError.arithmeticError);
        router.swapAVAXForExactTokens{value: amountIn + 1}(amountOut, pairVersions, tokenList, DEV, block.timestamp);

        router.swapAVAXForExactTokens{value: amountIn}(amountOut, pairVersions, tokenList, DEV, block.timestamp);

        vm.expectRevert(stdError.arithmeticError);
        router.swapAVAXForExactTokens{value: amountIn + 100000}(amountOut, pairVersions, tokenList, DEV, block.timestamp);


    }

Ultimately we can conclude that any amount below amountIn will result in a revert due to insufficient amountOut, and any amount above amountIn will revert due to the highlighted overflow.

The function is a routing function, which is meant to allow some degree of slippage.

My original downgrade was based on the idea that the function can run, however, after it being flagged, I must agree that the availability of the function is impaired in the majority of ordinary cases (a .10% / .5% slippage is expected under most operations / FEs).

For this reason, I agree with upgrading back to Medium Severity.

I’d like to thank @shung and @hyh for their feedback.


The original report as published on Code4rena, by rbserver. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

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

Impact

Users sending more than the required AVAX will have their transactions revert, degrading user experience and limiting protocol usability; no loss of funds was shown.

What the attacker needed

User sends more AVAX than required; calling swapAVAXForExactTokens

The fix

The refund calculation should be corrected to subtract the required amount from the sent amount.

How it was found

  1. Calculate the required input amount for a desired output using getSwapIn.
  2. Prepare token list and pair bin steps for the swap.
  3. Send more AVAX than the required input amount when calling swapAVAXForExactTokens.
  4. Observe that the transaction reverts with an arithmetic underflow error.

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 call a function that swaps one cryptocurrency for another, you might send a bit more than needed, expecting the extra to be returned. Here, the code that returns the extra does the subtraction in the wrong order, so it tries to subtract a larger number from a smaller one. That causes the whole transaction to fail, so you lose nothing but the swap never happens.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by rbserver

View all

51 more disclosed reports, best first.

More from Trader Joe v2 contest

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.