Skip to content
Business logic Audit finding Advanced

`UniswapImplementation::beforeSwap()` might revert when swapping native tokens to collection tokens

The beforeSwap hook in UniswapImplementation compares the wrong variable when deciding whether to convert accumulated collection token fees, causing swaps from native tokens to collection tokens to revert under certain conditions. An attacker could trigger these reverts, disrupting swaps.

0xAlix2 Follow with 0xc0ffEE, ComposableSecurity and 6 others

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-08-flayer-judging/issues/517

Found by

0xAlix2, 0xc0ffEE, ComposableSecurity, JokerStudio, alexzoid, g, h2134, zarkk01, zzykxx

Summary

UniswapImplementation::beforeSwap() performs a wrong check which can lead to swaps from native tokens to collection tokens reverting.

Root Cause

UniswapImplementation::beforeSwap() swaps the internally accumulated collection token fees into native tokens when:

  1. The hook accumulated at least 1 wei of fees in collection tokens
  2. An user is swapping native tokens for collection tokens

When the swap is performed by specifing the exact amount of native tokens to pay (ie. amountSpecified < 0) the protocol should allow the internal swap only when the amount of native tokens being paid is enough to convert all of the accumulated collection token fees. The protocol however does this incorrectly, as the code checks the amountSpecified against tokenOut instead of ethIn:

Solidity
if (params.amountSpecified >= 0) {
    ...
else {
    (, ethIn, tokenOut, ) = SwapMath.computeSwapStep({
        sqrtPriceCurrentX96: sqrtPriceX96,
        sqrtPriceTargetX96: params.sqrtPriceLimitX96,
        liquidity: poolManager.getLiquidity(poolId),
        amountRemaining: int(pendingPoolFees.amount1),
        feePips: 0
    });

@>  if (tokenOut <= uint(-params.amountSpecified)) {
        // Update our hook delta to reduce the upcoming swap amount to show that we have
        // already spent some of the ETH and received some of the underlying ERC20.
        // Specified = exact input (ETH)
        // Unspecified = token1
        beforeSwapDelta_ = toBeforeSwapDelta(ethIn.toInt128(), -tokenOut.toInt128());
    } else {
        ethIn = tokenOut = 0;
    }
}

This results in the UniswapImplementation::beforeSwap() reverting in the situations explained in internal pre-conditions below.

Internal pre-conditions

  1. User is swapping native tokens for collection tokens
  2. The hook accumulated at least 1 wei of collection tokens in fees
  3. tokenOut is lower than uint(-params.amountSpecified) and ethIn is bigger than uint(-params.amountSpecified)

External pre-conditions

No response

Attack Path

No response

Impact

All swaps that follow the internal pre-conditions will revert.

PoC

To copy-paste in UniswapImplementation.t.sol:

Solidity
function test_swapFails() public {
    address alice = makeAddr("alice");
    address bob = makeAddr("bob");

    ERC721Mock erc721 = new ERC721Mock();
    CollectionToken ctoken = CollectionToken(locker.createCollection(address(erc721), 'ERC721', 'ERC', 0));




    //### APPROVALS
    //-> Alice approvals
    vm.startPrank(alice);
    erc721.setApprovalForAll(address(locker), true);
    ctoken.approve(address(poolSwap), type(uint256).max);
    ctoken.approve(address(uniswapImplementation), type(uint256).max);
    vm.stopPrank();
    _approveNativeToken(alice, address(locker), type(uint).max);
    _approveNativeToken(alice, address(poolManager), type(uint).max);
    _approveNativeToken(alice, address(poolSwap), type(uint).max);

    //-> Bob approvals
    vm.startPrank(bob);
    erc721.setApprovalForAll(address(locker), true);
    ctoken.approve(address(uniswapImplementation), type(uint256).max);
    ctoken.approve(address(poolSwap), type(uint256).max);
    vm.stopPrank();
    _approveNativeToken(bob, address(locker), type(uint).max);
    _approveNativeToken(bob, address(poolManager), type(uint).max);
    _approveNativeToken(bob, address(poolSwap), type(uint).max);

    // uniswapImplementation.setAmmFee(1000);
    // uniswapImplementation.setAmmBeneficiary(BENEFICIARY);



    //### MINT NFTs
    //-> Mint 10 tokens to Alice
    uint[] memory _tokenIds = new uint[](10);
    for (uint i; i < 10; ++i) {
        erc721.mint(alice, i);
        _tokenIds[i] = i;
    }

    //-> Mint an extra token to Alice
    uint[] memory _tokenIdToDepositAlice = new uint[](1);
    erc721.mint(alice, 10);
    _tokenIdToDepositAlice[0] = 10;


    //### [ALICE] COLLECTION INITIALIZATION + LIQUIDITY PROVISION
    //-> alice initializes a collection and adds liquidity: 1e19 NATIVE + 1e19 CTOKEN
    uint256 initialNativeLiquidity = 1e19;
    _dealNativeToken(alice, initialNativeLiquidity);
    vm.startPrank(alice);
    locker.initializeCollection(address(erc721), initialNativeLiquidity, _tokenIds, 0, SQRT_PRICE_1_1);
    vm.stopPrank();



    //### [ALICE] ADDING CTOKEN FEES TO HOOK
    //-> alice deposits an NFT to get 1e18 CTOKEN and then deposits 1e18 CTOKENS as fees in the UniswapImplementation hook
    vm.startPrank(alice);
    locker.deposit(address(erc721), _tokenIdToDepositAlice, alice);
    uniswapImplementation.depositFees(address(erc721), 0, 1e18);
    vm.stopPrank();



    //### [BOB] SWAP FAILS 
    _dealNativeToken(bob, 1e18);

    //-> bob swaps `1e18` NATIVE tokens for CTOKENS but the swap fails
    vm.startPrank(bob);
    poolSwap.swap(
        PoolKey({
            currency0: Currency.wrap(address(ctoken)),
            currency1: Currency.wrap(address(WETH)),
            fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
            tickSpacing: 60,
            hooks: IHooks(address(uniswapImplementation))
        }),
        IPoolManager.SwapParams({
            zeroForOne: false,
            amountSpecified: -int(1e18),
            sqrtPriceLimitX96: (TickMath.MAX_SQRT_PRICE - 1)
        }),
        PoolSwapTest.TestSettings({
            takeClaims: false,
            settleUsingBurn: false
        }),
        ''
    );
}

Mitigation

In UniswapImplementation::beforeSwap() check against ethIn instead of tokenOut:

Solidity
@>  if (ethIn <= uint(-params.amountSpecified)) {
        // Update our hook delta to reduce the upcoming swap amount to show that we have
        // already spent some of the ETH and received some of the underlying ERC20.
        // Specified = exact input (ETH)
        // Unspecified = token1
        beforeSwapDelta_ = toBeforeSwapDelta(ethIn.toInt128(), -tokenOut.toInt128());
    } else {
        ethIn = tokenOut = 0;
    }

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

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 the code checks tokenOut instead of ethIn when deciding whether the native input is sufficient to cover the accumulated fees.

Impact

Swaps that meet the internal pre-conditions will revert, preventing users from swapping native tokens for collection tokens.

What the attacker needed

User swaps native tokens for collection tokens; hook has at least 1 wei of collection token fees; tokenOut < amountSpecified and ethIn > amountSpecified

The fix

The check should compare ethIn instead of tokenOut.

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.

This is a smart contract bug in a Uniswap hook. When someone swaps native tokens for collection tokens, the contract tries to convert some accumulated fees, but it checks the wrong number, so the swap fails and reverts. This means users cannot complete their swaps in those situations.

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.

More by 0xAlix2

View all

39 more disclosed reports, best first.

More from Flayer

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.