sherlock-audit / 2024-02-jala-swap-judging

6 stars 4 forks source link

cheatcode - Incorrect Swap Executions Due to Misalignment between `amounts` and `path` #238

Closed sherlock-admin closed 6 months ago

sherlock-admin commented 6 months ago

cheatcode

medium

Incorrect Swap Executions Due to Misalignment between amounts and path

Summary

The _swap function is designed to facilitate token swaps through a series of liquidity pools represented by token pairs along a specified path. It calculates the output amount for each swap in the path and executes these swaps sequentially. However, a critical assumption underlying this function's correct operation is the alignment between the amounts array and the path array. Specifically, for a path of N tokens, there should be N-1 swaps, and thus, the amounts array should contain N elements (the input amount for the first swap and the output amounts for all subsequent swaps).

Vulnerability Detail

The function assumes that the length of the amounts array is directly related to the length of the path array, with the former being exactly one element longer than the number of swaps to perform (since the last token's amount represents the amount received at the end of the swap chain). This assumption is not explicitly validated within the function.

Impact

  1. If amounts.length is less than path.length - 1, the function will attempt to access an index of amounts that does not exist, leading to a runtime error and reverting the transaction.

  2. If amounts.length is greater than path.length, some amounts will not be used, potentially indicating a logic error or a misinterpretation of how the function should be called. Conversely, if amounts.length is less than path.length, it could result in attempting swaps without valid output amounts, leading to incorrect behavior or transaction failure.

Code Snippet

https://github.com/sherlock-audit/2024-02-jala-swap/blob/main/jalaswap-dex-contract/contracts/JalaRouter02.sol#L229

function _swap(uint256[] memory amounts, address[] memory path, address _to) internal virtual {
        for (uint256 i; i < path.length - 1; i++) {
            (address input, address output) = (path[i], path[i + 1]);
            (address token0, ) = JalaLibrary.sortTokens(input, output);
            uint256 amountOut = amounts[i + 1];
            (uint256 amount0Out, uint256 amount1Out) = input == token0
                ? (uint256(0), amountOut)
                : (amountOut, uint256(0));
            address to = i < path.length - 2 ? JalaLibrary.pairFor(factory, output, path[i + 2]) : _to;
            IJalaPair(JalaLibrary.pairFor(factory, input, output)).swap(amount0Out, amount1Out, to, new bytes(0));
        }
    }

Tool used

Manual Review

Recommendation

Add a validation step at the beginning of the function to ensure that amounts.length == path.length.

nevillehuang commented 6 months ago

Invalid, user input error