Skip to content
Business logic Audit finding Intermediate

PositionAction.decreaseLever() fails to consider the loan fee in Flashlender when calculating loanAmount , as a result, the functionality will not work when protocolFee != 0

The decreaseLever function incorrectly calculates the loan amount by not subtracting the flash loan fee, causing the transaction to revert when the protocol fee is non-zero. An attacker could not exploit this; it is a functionality bug that prevents users from decreasing leverage.

chaduke Follow with 0xAlix2, 13u9 and 11 others

Originally disclosed on Code4rena

Submitted by chaduke, also found by 0xAlix2, 13u9, zhaojohnson, lian886, lanrebayode77, Nyx, 0xbepresent, 0xpiken, 0xc0ffEE, gumgumzum, hash, pkqs90, and nnez

PositionAction.decreaseLever() allows one to decrease the leverage for a position by doing the following:

  1. Perform a creditFlashLoan to loan loanAmount of underlying tokens;
  2. Perform a modifyCollateralAndDebt (inside PositionAction.onCreditFlashLoan() to reduce the debt of the position by loanAmount.
  3. Withdraw collateral from the position in the amount of withdrawnCollateral.
  4. Swap the withdrawn collateral to underlying tokens with the exact output amount of leverParams.primarySwap.amount = loanAmount + fee using input collateral in the amount of swapAmountIn.
  5. The remainng collateral withdrawnCollateral - swapAmountIn is either sent to the residualRecipient or swap to the specified tokens and sent to the receiver.
  6. Return the loan loanAmount + protocolFee back to the pool.

The first problem lies in PositionAction.increaseLever(): loanAmount uses leverParams.primarySwap.amount, it does not consider the protocol fee. leverParams.primarySwap.amount is the amount of underlying tokens that needs to be swapped out that will be returned back to the pool, which includes the protocol fee. In other words, the correct formula is loanAmount = leverParams.primarySwap.amount - fee.

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/proxy/PositionAction.sol#L364

Meanwhile, function positionAction.onCreditFlashLoan() has a similar problem:

  1. subDebt, the debt to be reduced from the position should be the same as loanAmount, which is leverParams.primarySwap.amount - fee. However, the function uses leverParams.primarySwap.amount as subDebt, which is wrong.

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/proxy/PositionAction.sol#L444C17-L444C25

In summary, both functions do not consider the impact of protcolFee, as a result, these functions will fail.

POC:

  1. In TestBase.sol, change the following line to make protcolFee = 1%:
        flashlender = new Flashlender(IPoolV3(address(liquidityPool)), 0.01 ether); // 1/100 fee
  1. Run forge test --match-test testDecreaseLever1 -vv. (It will revert due to insufficient allowance/balance).
  2. When we revised the two functions as follows, everything run smoothly with the correct numbers for all parties.
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;

import "forge-std/console2.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

import {PRBProxy} from "prb-proxy/PRBProxy.sol";

import {IntegrationTestBase} from "./IntegrationTestBase.sol";
import {wdiv, WAD} from "../../utils/Math.sol";
import {Permission} from "../../utils/Permission.sol";

import {CDPVault} from "../../CDPVault.sol";

import {PermitParams} from "../../proxy/TransferAction.sol";
import {SwapAction, SwapParams, SwapType, SwapProtocol} from "../../proxy/SwapAction.sol";
import {LeverParams, PositionAction} from "../../proxy/PositionAction.sol";
import {PoolActionParams} from "../../proxy/PoolAction.sol";

import {PositionAction20} from "../../proxy/PositionAction20.sol";

contract PositionAction20_Lever_Test is IntegrationTestBase {
    using SafeERC20 for ERC20;

    // user
    PRBProxy userProxy;
    address user;
    uint256 constant userPk = 0x12341234;
    address Bob = makeAddr("Bob");

    CDPVault vault;

    // actions
    PositionAction20 positionAction;

    // common variables as state variables to help with stack too deep
    PermitParams emptyPermitParams;
    SwapParams emptySwap;
    PoolActionParams emptyPoolActionParams;

    bytes32[] weightedPoolIdArray;

    function setUp() public override {
        super.setUp();

        // configure permissions and system settings
        setGlobalDebtCeiling(15_000_000 ether);

        // deploy vault
        vault = createCDPVault(
            token, // token
            5_000_000 ether, // debt ceiling
            0, // debt floor
            1.25 ether, // liquidation ratio
            1.0 ether, // liquidation penalty
            1.05 ether // liquidation discount
        );
        createGaugeAndSetGauge(address(vault));
        // setup user and userProxy
        user = vm.addr(0x12341234);
        userProxy = PRBProxy(payable(address(prbProxyRegistry.deployFor(user))));

        vm.prank(address(userProxy));
        token.approve(address(user), type(uint256).max);
        vm.prank(address(userProxy));
        mockWETH.approve(address(user), type(uint256).max);

        // deploy actions
        positionAction = new PositionAction20(
            address(flashlender),
            address(swapAction),
            address(poolAction),
            address(vaultRegistry)
        );

        // configure oracle spot prices
        oracle.updateSpot(address(token), 1 ether);

        weightedPoolIdArray.push(weightedUnderlierPoolId);

        vm.label(address(userProxy), "UserProxy");
        vm.label(address(user), "User");
        vm.label(address(vault), "CDPVault");
        vm.label(address(positionAction), "PositionAction");
    }

    function printPosition(CDPVault v, address p, string memory name) public{
        console2.log("\n =================================================");
        console2.log("position infor for ", name);

        (uint256 collateral, // [wad]
        uint256 debt, // [wad]
        uint256 lastDebtUpdate, // [timestamp]
        uint256 cumulativeIndexLastUpdate,
        uint192 cumulativeQuotaIndexLU,
        uint128 cumulativeQuotaInterest
        ) = v.positions(p);

        console2.log("collateral: ", collateral);
        console2.log("debt: ", debt);
        console2.log("cumulativeQuotaInterest: ", cumulativeQuotaInterest);
        console2.log("lastUpdate: ", lastDebtUpdate);

        console2.log("cumulativeIndexLastUpdate:", cumulativeIndexLastUpdate);
        console2.log("cumulativeQuotaIndexLU: ", cumulativeQuotaIndexLU);
        console2.log("=================================================\n ");
    }

   // simple helper function to increase lever
    function _increaseLever(                // 111111111111111
        PRBProxy proxy,
        CDPVault vault_,
        uint256 upFrontUnderliers,
        uint256 amountToLever,
        uint256 amountToLeverLimit
    ) public returns (uint256 expectedAmountIn) {
        LeverParams memory leverParams;
        {
            address upFrontToken = address(vault_.token());

            address[] memory assets = new address[](2);
            assets[0] = address(underlyingToken);
            assets[1] = address(upFrontToken);

            // mint directly to swap actions for simplicity
            if (upFrontUnderliers > 0) deal(upFrontToken, address(proxy), upFrontUnderliers);  // upfront collateral

            leverParams = LeverParams({
                position: address(proxy),
                vault: address(vault_),
                collateralToken: address(vault_.token()),
                primarySwap: SwapParams({
                    swapProtocol: SwapProtocol.BALANCER,
                    swapType: SwapType.EXACT_IN,
                    assetIn: address(underlyingToken),
                    amount: amountToLever, // amount of stablecoin to swap in             // amount of flashload undelrying tokens
                    limit: amountToLeverLimit, // min amount of tokens to receive         // amount of flashloaded colalteral limit
                    recipient: address(positionAction),
                    deadline: block.timestamp + 100,
                    args: abi.encode(weightedPoolIdArray, assets)
                }),
                auxSwap: emptySwap, // no aux swap
                auxAction: emptyPoolActionParams
            });

            expectedAmountIn = _simulateBalancerSwap(leverParams.primarySwap);
        }

        vm.startPrank(proxy.owner());
        proxy.execute(
            address(positionAction),
            abi.encodeWithSelector(
                positionAction.increaseLever.selector,
                leverParams,
                address(vault_.token()),
                upFrontUnderliers,
                address(proxy),
                emptyPermitParams
            )
        );
        vm.stopPrank();
    }

function testDecreaseLever1() public {      // 22222222222222222222222
        // create 1st position (this is the user that will lever up the other users position)
        address bob = user;
        PRBProxy bobProxy = userProxy;

        // create 2nd position. This is the user that will be levered up by bob
        address alice = vm.addr(0x56785678);
        PRBProxy aliceProxy = PRBProxy(payable(address(prbProxyRegistry.deployFor(alice))));

        // create alice's initial position
        _increaseLever(
            aliceProxy,
            vault,
            20_000 ether, // upFrontUnderliers
            40_000 ether, // borrowAmount
            39_000 ether // amountOutMin
        );
        (uint256 initialCollateral, uint256 initialNormalDebt, , , , ) = vault.positions(address(aliceProxy));

        printPosition(vault, address(aliceProxy), "AliceProxy"); // 79,000 / 40,000

        uint256 amountOut = 5_000 ether;       // this is the loan + fee
        uint256 maxAmountIn = 5_100 ether;
        LeverParams memory leverParams;
        {
            // now decrease alice's leverage as bob
            address[] memory assets = new address[](2);
            assets[0] = address(underlyingToken);
            assets[1] = address(token);

            leverParams = LeverParams({
                position: address(aliceProxy),
                vault: address(vault),
                collateralToken: address(token),
                primarySwap: SwapParams({
                    swapProtocol: SwapProtocol.BALANCER,
                    swapType: SwapType.EXACT_OUT,
                    assetIn: address(token),             // swap collteral tokens for underlying toksn to return back to flashCreditloan
                    amount: amountOut,                  // ????
                    limit: maxAmountIn,
                    recipient: address(positionAction),
                    deadline: block.timestamp + 100,
                    args: abi.encode(weightedPoolIdArray, assets)
                }),
                auxSwap: emptySwap,
                auxAction: emptyPoolActionParams
            });
        }

        // call setPermissionAgent as alice to allow bob to modify alice's position
        vm.prank(address(aliceProxy));
        vault.setPermissionAgent(address(bobProxy), true);

        // now call decreaseLever on alice's position as bob and expect success because alice gave bob permission
        vm.prank(bob);
        vm.expectRevert();
        bobProxy.execute(
            address(positionAction),
            abi.encodeWithSelector(positionAction.decreaseLever.selector, leverParams, maxAmountIn, address(bob))
        );

        printPosition(vault, address(aliceProxy), "AliceProxy");
    }
}

Tools Used

Foundry

Recommended Mitigation Steps

Correct the two functions as follows, focusing on calculating the correct loanAmount and subDebt and returnAmount:

function decreaseLever(
        LeverParams calldata leverParams,
        uint256 subCollateral,
        address residualRecipient
    ) external onlyDelegatecall {
        // validate the primary swap
        if (leverParams.primarySwap.swapType != SwapType.EXACT_OUT || leverParams.primarySwap.recipient != self)
            revert PositionAction__decreaseLever_invalidPrimarySwap();

        // validate aux swap if it exists
        if (leverParams.auxSwap.assetIn != address(0) && (leverParams.auxSwap.swapType != SwapType.EXACT_IN))
            revert PositionAction__decreaseLever_invalidAuxSwap();

        /// validate residual recipient is provided if no aux swap is provided
        if (leverParams.auxSwap.assetIn == address(0) && residualRecipient == address(0))
            revert PositionAction__decreaseLever_invalidResidualRecipient();

        // take out credit flash loan
        IPermission(leverParams.vault).modifyPermission(leverParams.position, self, true);

        uint protocolFee = flashlender.protocolFee();
        // loanAmount (WAD + protocolFee)/WAD = leverParams.primarySwap.amount
        uint loanAmount = leverParams.primarySwap.amount * (10**18) / (10**18 + protocolFee);  // loanamount should be smaller

        flashlender.creditFlashLoan(
            ICreditFlashBorrower(self),
            loanAmount,
            abi.encode(leverParams, subCollateral, residualRecipient)
        );
        IPermission(leverParams.vault).modifyPermission(leverParams.position, self, false);
    }

 function onCreditFlashLoan(
        address /*initiator*/,
        uint256 /*amount*/,
        uint256 /*fee*/,
        bytes calldata data
    ) external returns (bytes32) {
        if (msg.sender != address(flashlender)) revert PositionAction__onCreditFlashLoan__invalidSender();
        (
            LeverParams memory leverParams,
            uint256 subCollateral,
            address residualRecipient
        ) = abi.decode(data,(LeverParams, uint256, address));

        uint protocolFee = flashlender.protocolFee();
        // loanAmount (WAD + protocolFee)/WAD = leverParams.primarySwap.amount
        uint loanAmount = leverParams.primarySwap.amount * (10**18) / (10**18 + protocolFee);  // loanamount should be smaller

        underlyingToken.forceApprove(address(leverParams.vault), loanAmount); //  // should be equal to loanAmount
        // sub collateral and debt
        ICDPVault(leverParams.vault).modifyCollateralAndDebt(
            leverParams.position,
            address(this),
            address(this),
            0,
            -toInt256(loanAmount)        // should be equal to loanAmount
        );

        // withdraw collateral and handle any CDP specific actions
        uint256 withdrawnCollateral = _onDecreaseLever(leverParams, subCollateral);

        bytes memory swapData = _delegateCall(
            address(swapAction),
            abi.encodeWithSelector(
                swapAction.swap.selector,
                leverParams.primarySwap
            )
        );
        uint256 swapAmountIn = abi.decode(swapData, (uint256));

        // swap collateral to stablecoin and calculate the amount leftover
        uint256 residualAmount = withdrawnCollateral - swapAmountIn;

        // send left over collateral that was not needed to payback the flash loan to `residualRecipient`
        if (residualAmount > 0) {

            // perform swap from collateral to arbitrary token if necessary
            if (leverParams.auxSwap.assetIn != address(0)) {
                _delegateCall(
                    address(swapAction),
                    abi.encodeWithSelector(
                        swapAction.swap.selector,
                        leverParams.auxSwap
                    )
                );
            } else {
                // otherwise just send the collateral to `residualRecipient`
                IERC20(leverParams.primarySwap.assetIn).safeTransfer(residualRecipient, residualAmount);
            }
        }

        underlyingToken.forceApprove(address(flashlender), leverParams.primarySwap.amount); // returnAmoutn is the output amount of the swap

        return CALLBACK_SUCCESS_CREDIT;
    }

Assessed type

Math

amarcu (LoopFi) confirmed


The original report as published on Code4rena, by chaduke. 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

Root cause

The code uses the swap output amount as the loan amount without subtracting the flash loan fee, so the loan plus fee exceeds the amount available to repay.

What the attacker needed

Protocol fee is non-zero; user has a leveraged position

The fix

The fix is to calculate the loan amount as the swap output amount divided by (1 + fee), and use that for both the loan and the debt reduction.

How it was found

  1. Set the flash lender protocol fee to 1% in the test setup.
  2. Run the test `testDecreaseLever1`.
  3. Observe the transaction reverts due to insufficient allowance or balance.

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 where a function that reduces leverage fails because it miscalculates the amount to borrow. The code forgets to subtract the flash loan fee, so the numbers don't add up and the transaction reverts. It's like trying to pay back a loan but forgetting the interest, so the repayment is short.

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 chaduke

View all

21 more disclosed reports, best first.

More from LoopFi

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.