Skip to content
Business logic Audit finding Advanced

PositionAction4626::_onDecreaseLever wrongly updates tokenOut forcing user’s funds to be stuck in the position action contract

The PositionAction4626::_onDecreaseLever function incorrectly updates tokenOut when an auxiliary action (like exiting a Balancer pool) is used, causing the contract to misreport the amount of tokens received. This can lead to user funds being stuck in the contract, as the contract sends less residual collateral to the user than it should.

0xAlix2 Follow with pkqs90

Originally disclosed on Code4rena

Submitted by 0xAlix2, also found by pkqs90

Users can use PositionAction::decreaseLever to decrease the leverage of their positions when the collateral is an ERC4626, that position action interacts with PositionAction4626::_onDecreaseLever. With that, the protocol gives the ability to join/exit Balancer pools, leveraging down an ERC4626 position is handled in PositionAction4626::_onDecreaseLever.

This first step is that tokenOut is set to the redeemed 4626 amount; however, when auxAction exists, (i.e. the user wants to exit a Balancer pool), the tokenOut is updated to return the amount of the exit position, this poses multiple issues:

  1. If the token out from Balancer is not the same as 4626’s underlying this will wrongly update to another token’s amount.
  2. If the recipient is not in the position action contract, the tokens would be sent to another address, while it assumes that it received them.
  3. If the token = 4626’s underlying, the recipient is the user, and the amount of from Balancer is less than the redeemed tokenOut, the contract would set the tokenOut as the Balancer return amount, which is less than the original tokenOut. This will return the wrong tokenOut in PositionAction::onCreditFlashLoan, sending the user a residual amount less than the real amount (the POC below is for this scenario).

The user’s “extra” collateral amount will end up stuck in the position action contract forever.

Proof of Concept

The following test assuming 3 reported bugs are fixed, to workaround this:

  1. In PositionAction4626::_onDecreaseLever, replace:
uint256 withdrawnCollateral = ICDPVault(leverParams.vault).withdraw(address(this), subCollateral);

with:

uint256 withdrawnCollateral = ICDPVault(leverParams.vault).withdraw(leverParams.position, subCollateral);
  1. In PositionAction4626::_onIncreaseLever, replace:
return ICDPVault(leverParams.vault).deposit(address(this), addCollateralAmount);

with:

return addCollateralAmount;
  1. At the top of PoolAction::updateLeverJoin, add:
poolToken = balancerVault.getPool(poolId);

POC Contract

contract PositionAction4626_Lever_Test is IntegrationTestBase {
    using SafeERC20 for ERC20;

    PRBProxy userProxy;
    address user;
    CDPVault vault;
    StakingLPEth stakingLPEth;
    PositionAction4626 positionAction;
    PermitParams emptyPermitParams;
    SwapParams emptySwap;
    PoolActionParams emptyPoolActionParams;

    bytes32[] weightedPoolIdArray;

    address constant wstETH_bb_a_WETH_BPTl = 0x41503C9D499ddbd1dCdf818a1b05e9774203Bf46;
    address constant wstETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
    address constant bbaweth = 0xbB6881874825E60e1160416D6C426eae65f2459E;
    bytes32 constant poolId = 0x41503c9d499ddbd1dcdf818a1b05e9774203bf46000000000000000000000594;

    function setUp() public override {
        super.setUp();
        setGlobalDebtCeiling(15_000_000 ether);

        token = ERC20PresetMinterPauser(wstETH);

        stakingLPEth = new StakingLPEth(address(token), "Staking LP ETH", "sLPETH");
        stakingLPEth.setCooldownDuration(0);
        vault = createCDPVault(stakingLPEth, 5_000_000 ether, 0, 1.25 ether, 1.0 ether, 1.05 ether);
        createGaugeAndSetGauge(address(vault), address(stakingLPEth));

        user = vm.addr(0x12341234);
        userProxy = PRBProxy(payable(address(prbProxyRegistry.deployFor(user))));

        positionAction = new PositionAction4626(
            address(flashlender),
            address(swapAction),
            address(poolAction),
            address(vaultRegistry)
        );

        weightedUnderlierPoolId = _createBalancerPool(address(token), address(underlyingToken)).getPoolId();

        oracle.updateSpot(address(token), 1 ether);
        oracle.updateSpot(address(stakingLPEth), 1 ether);
        weightedPoolIdArray.push(weightedUnderlierPoolId);
    }

    function test_wrongTokenOutAmount_decreaseLeverLossOfFunds() public {
        uint256 depositAmount = 250 ether;
        uint256 borrowAmount = 100 ether;

        uint256 flashLoanAmount = borrowAmount / 2;

        deal(address(token), user, depositAmount);

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

        address[] memory tokens = new address[](3);
        tokens[0] = wstETH_bb_a_WETH_BPTl;
        tokens[1] = wstETH;
        tokens[2] = bbaweth;

        vm.startPrank(user);

        // Deposit `wstETH` to get `sLPETH`
        // Deposit 250 `sLPETH` to vault
        {
            token.approve(address(stakingLPEth), depositAmount);
            stakingLPEth.approve(address(userProxy), depositAmount);

            stakingLPEth.deposit(depositAmount, user);

            userProxy.execute(
                address(positionAction),
                abi.encodeWithSelector(
                    positionAction.deposit.selector,
                    address(userProxy),
                    address(vault),
                    CollateralParams({
                        targetToken: address(stakingLPEth),
                        amount: depositAmount,
                        collateralizer: address(user),
                        auxSwap: emptySwap
                    }),
                    emptyPermitParams
                )
            );
        }

        // Borrow 100 ETH
        {
            userProxy.execute(
                address(positionAction),
                abi.encodeWithSelector(
                    positionAction.borrow.selector,
                    address(userProxy),
                    address(vault),
                    CreditParams({amount: borrowAmount, creditor: user, auxSwap: emptySwap})
                )
            );

            // Collateral is 250 ETH, debt is 100 ETH
            (uint256 collateral, uint256 debt, , , , ) = vault.positions(address(userProxy));
            assertEq(collateral, depositAmount);
            assertEq(debt, borrowAmount);
        }

        // Increase leverage
        // Takes a flash loan of 50 ETH borrow tokens (adds that as a debt)
        // Swap the borrow tokens to collateral tokens, and join Balancer pool
        // (around 49 collateral tokens are deposited into the balancer position)
        {
            uint256[] memory maxAmountsIn = new uint256[](3);
            maxAmountsIn[0] = 0;
            maxAmountsIn[1] = borrowAmount / 2 - 1 ether;
            maxAmountsIn[2] = 0;
            uint256[] memory tokensIn = new uint256[](2);
            tokensIn[0] = borrowAmount / 2 - 1 ether;
            tokensIn[1] = 0;

            userProxy.execute(
                address(positionAction),
                abi.encodeWithSelector(
                    positionAction.increaseLever.selector,
                    LeverParams({
                        position: address(userProxy),
                        vault: address(vault),
                        collateralToken: address(stakingLPEth),
                        primarySwap: SwapParams({
                            swapProtocol: SwapProtocol.BALANCER,
                            swapType: SwapType.EXACT_IN,
                            assetIn: address(underlyingToken),
                            amount: flashLoanAmount,
                            limit: 0,
                            recipient: address(positionAction),
                            deadline: block.timestamp,
                            args: abi.encode(weightedPoolIdArray, assets)
                        }),
                        auxSwap: emptySwap,
                        auxAction: PoolActionParams(
                            Protocol.BALANCER,
                            0,
                            user,
                            abi.encode(poolId, tokens, tokensIn, maxAmountsIn)
                        )
                    }),
                    address(0),
                    0,
                    address(user),
                    emptyPermitParams
                )
            );

            // Collateral remains the same, debt increases by 50 ETH
            // User has around 56 Balancer LP tokens
            (uint256 collateral, uint256 debt, , , , ) = vault.positions(address(userProxy));
            assertEq(collateral, depositAmount);
            assertEq(debt, borrowAmount + flashLoanAmount);
            assertEq(IERC20(wstETH_bb_a_WETH_BPTl).balanceOf(user) / 1 ether, 56);
        }

        {
            // Verify that the position action contract and the user don't hold any collateral tokens
            assertEq(token.balanceOf(address(positionAction)), 0);
            assertEq(token.balanceOf(user), 0);

            uint256[] memory minAmountsOut = new uint256[](3);
            minAmountsOut[0] = 0;
            minAmountsOut[1] = 0;
            minAmountsOut[2] = 0;

            // Send the Balancer LP tokens to the position action contract, to exit the Balancer pool
            uint256 bptAmount = IERC20(wstETH_bb_a_WETH_BPTl).balanceOf(user);
            IERC20(wstETH_bb_a_WETH_BPTl).transfer(address(positionAction), bptAmount);

            // Leverage down the position
            // Takes a flash loan of 40 ETH borrow tokens (decreases the debt), withdraws 70 ETH collateral tokens (residual should be sent to the user)
            // Swap collateral tokens to borrow tokens, to repay the flash loan
            // Exits the Balancer pool, and sends the residual collateral tokens to the user (this is where the loss of funds occurs)
            userProxy.execute(
                address(positionAction),
                abi.encodeWithSelector(
                    positionAction.decreaseLever.selector,
                    LeverParams({
                        position: address(userProxy),
                        vault: address(vault),
                        collateralToken: address(stakingLPEth),
                        auxSwap: emptySwap,
                        primarySwap: SwapParams({
                            swapProtocol: SwapProtocol.BALANCER,
                            swapType: SwapType.EXACT_OUT,
                            assetIn: address(token),
                            amount: 40 ether,
                            limit: 50 ether,
                            recipient: address(positionAction),
                            deadline: block.timestamp,
                            args: abi.encode(weightedPoolIdArray, assets)
                        }),
                        auxAction: PoolActionParams(
                            Protocol.BALANCER,
                            0,
                            user,
                            abi.encode(poolId, wstETH_bb_a_WETH_BPTl, bptAmount, 0, tokens, minAmountsOut)
                        )
                    }),
                    70 ether,
                    address(user)
                )
            );

            // Collateral is 180 ETH, debt is 110 ETH
            (uint256 collateral, uint256 debt, , , , ) = vault.positions(address(userProxy));
            assertEq(collateral, depositAmount - 70 ether);
            assertEq(debt, borrowAmount + flashLoanAmount - 40 ether);

            // All balancer LP tokens are burnt
            assertEq(IERC20(wstETH_bb_a_WETH_BPTl).balanceOf(user), 0);
            assertEq(IERC20(wstETH_bb_a_WETH_BPTl).balanceOf(address(positionAction)), 0);

            // User has 59 collateral tokens, Balancer's exit tokens (49 from above) + residual ~(50 - 40)
            assertEq(token.balanceOf(user) / 1 ether, 59);
            // Position action now holds 20 collateral tokens that are stuck (70 - ~50)
            assertEq(token.balanceOf(address(positionAction)) / 1 ether, 20);
        }
    }

    function _createBalancerPool(address t1, address t2) internal returns (IComposableStablePool pool_) {
        uint256 amount = 5_000_000_000 ether;
        deal(t1, address(this), amount);
        deal(t2, address(this), amount);

        uint256[] memory maxAmountsIn = new uint256[](2);
        address[] memory assets = new address[](2);
        assets[0] = t1;
        uint256[] memory weights = new uint256[](2);
        weights[0] = 500000000000000000;
        weights[1] = 500000000000000000;

        bool tokenPlaced;
        address tempAsset;
        for (uint256 i; i < assets.length; i++) {
            if (!tokenPlaced) {
                if (uint160(assets[i]) > uint160(t2)) {
                    tokenPlaced = true;
                    tempAsset = assets[i];
                    assets[i] = t2;
                } else if (i == assets.length - 1) {
                    assets[i] = t2;
                }
            } else {
                address placeholder = assets[i];
                assets[i] = tempAsset;
                tempAsset = placeholder;
            }
        }

        for (uint256 i; i < assets.length; i++) {
            maxAmountsIn[i] = ERC20(assets[i]).balanceOf(address(this));
            ERC20(assets[i]).safeApprove(address(balancerVault), maxAmountsIn[i]);
        }

        pool_ = weightedPoolFactory.create(
            "50WETH-50TOKEN",
            "50WETH-50TOKEN",
            assets,
            weights,
            3e14, // swapFee (0.03%)
            address(this) // owner
        );

        balancerVault.joinPool(
            pool_.getPoolId(),
            address(this),
            address(this),
            JoinPoolRequest({
                assets: assets,
                maxAmountsIn: maxAmountsIn,
                userData: abi.encode(JoinKind.INIT, maxAmountsIn),
                fromInternalBalance: false
            })
        );
    }

    function getForkBlockNumber() internal pure virtual override(IntegrationTestBase) returns (uint256) {
        return 17870449; // Aug-08-2023 01:17:35 PM +UTC
    }
}

Recommended Mitigation Steps

Handle the multiple scenarios where the recipient might not be the position actions contract or where the tokenOut from Balancer isn’t the same as the 4626’s underlying token. In the if block, just set the tokenOut as the contract’s balance which should handle all edge cases.

function _onDecreaseLever(
    LeverParams memory leverParams,
    uint256 subCollateral
) internal override returns (uint256 tokenOut) {
    ...

    if (leverParams.auxAction.args.length != 0) {
        bytes memory exitData = _delegateCall(
            address(poolAction),
            abi.encodeWithSelector(poolAction.exit.selector, leverParams.auxAction)
        );

-       tokenOut = abi.decode(exitData, (uint256));
+       tokenOut = IERC20(IERC4626(leverParams.collateralToken).asset()).balanceOf(address(this));
    }
}

Assessed type

Error

amarcu (LoopFi) confirmed

Koolex (judge) decreased severity to Medium

Note: For full discussion, see here.


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

Likely, the code sets tokenOut to the amount returned by the auxiliary action (e.g., Balancer exit) without verifying that the token and recipient match the expected underlying asset and contract, leading to incorrect accounting.

Impact

The user loses a portion of their collateral, which becomes permanently stuck in the position action contract, as demonstrated by the proof of concept where 20 tokens remained stuck.

What the attacker needed

User has a leveraged position with ERC4626 collateral; User uses Balancer pool as auxiliary action; User calls decreaseLever

The fix

The code should be fixed by setting tokenOut to the contract's balance of the underlying asset after the auxiliary action, rather than using the returned amount from the exit.

How it was found

  1. Deposit collateral and borrow to create a leveraged position.
  2. Increase leverage by taking a flash loan, swapping, and joining a Balancer pool.
  3. Transfer Balancer LP tokens to the position action contract.
  4. Call decreaseLever with an auxiliary action to exit the Balancer pool.
  5. Observe that the contract holds residual collateral tokens that should have been sent to the user.

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 use a feature to reduce leverage on a loan, the contract sometimes gives you back less than it should because it miscalculates how much it received from an external pool. The extra money stays stuck in the contract instead of being returned to you.

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 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.