Skip to content
Business logic Audit finding Intermediate

PositionAction.sol#onCreditFlashLoan may end up with stuck funds for EXACT_IN primary swaps

In the onCreditFlashLoan function, when the primary swap is EXACT_IN, the contract attempts to repay debt with the swap output. If the repayment amount exceeds the actual debt, the excess is capped and remains stuck in the contract, inaccessible to the user.

pkqs90 Follow

Originally disclosed on Code4rena

Submitted by pkqs90

Note: This is a new issue that was introduced by the latest code diff.

When conducting a decreaseLever action, the final swap inside onCreditFlashLoan() is from collateral token to debt token. If the swap is EXACT_IN type, this means all collateral token is used for the swap. The output tokens are then split to two parts:

  1. Repay the flashloan (and fees).
  2. Send back to CDPVault to repay debt.

However, the second part have some issues. Mainly because if the repaid amount is larger than debt amount, the repayed amount will be capped to the debt amount (See CDPVault.sol code below). This means there may be some debt tokens ending up dangling in the PositionAction.sol contract, which the user does not have access to.

To explain a bit more, this is a reasonable scenario, because the amount of collateral tokens used for swap comes from uint256 withdrawnCollateral = _onDecreaseLever(leverParams, subCollateral);, and for PositionAction4626, _onDecreaseLever() supports gathering collateral tokens by exiting from pools (e.g., Balancer). This means it is totally possible that the amount of collateral tokens used for swap values more than the user’s debt in CDPVault.

PositionAction.sol:

    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)
        );

        uint256 subDebt = leverParams.primarySwap.amount;
        underlyingToken.forceApprove(address(leverParams.vault), subDebt + fee);
        // sub collateral and debt
        ICDPVault(leverParams.vault).modifyCollateralAndDebt(
            leverParams.position,
            address(this),
            address(this),
            0,
            -toInt256(subDebt)
        );

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

        if (leverParams.primarySwap.swapType == SwapType.EXACT_IN) {
            leverParams.primarySwap.amount = withdrawnCollateral;

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

            uint256 swapAmountOut = abi.decode(swapData, (uint256));
            uint256 residualAmount = swapAmountOut - subDebt;

            // sub collateral and debt
@>          if (residualAmount > 0) {
                underlyingToken.forceApprove(address(leverParams.vault), residualAmount);
                ICDPVault(leverParams.vault).modifyCollateralAndDebt(
                    leverParams.position,
                    address(this),
                    address(this),
                    0,
                    -toInt256(residualAmount)
                );
            }
        }
        ...
    }

PositionAction4626.sol:

    function _onDecreaseLever(
        LeverParams memory leverParams,
        uint256 subCollateral
    ) internal override returns (uint256 tokenOut) {
        // withdraw collateral from vault
        uint256 withdrawnCollateral = ICDPVault(leverParams.vault).withdraw(leverParams.position, subCollateral);

        // withdraw collateral from the ERC4626 vault and return underlying assets
        tokenOut = IERC4626(leverParams.collateralToken).redeem(withdrawnCollateral, address(this), address(this));

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

            tokenOut = IERC20(IERC4626(leverParams.collateralToken).asset()).balanceOf(address(this));
        }
    }

CDPVault.sol:

    function modifyCollateralAndDebt(
        address owner,
        address collateralizer,
        address creditor,
        int256 deltaCollateral,
        int256 deltaDebt
    ) public {
        ...
        if (deltaDebt > 0) {
            ...
        } else if (deltaDebt < 0) {
            uint256 debtToDecrease = abs(deltaDebt);

            uint256 maxRepayment = calcTotalDebt(debtData);
@>          if (debtToDecrease >= maxRepayment) {
                debtToDecrease = maxRepayment;
                deltaDebt = -toInt256(debtToDecrease);
            }

            uint256 scaledDebtDecrease = wmul(debtToDecrease, poolUnderlyingScale);
            poolUnderlying.safeTransferFrom(creditor, address(pool), scaledDebtDecrease);
        }
    }

Recommended Mitigation Steps

Send the residual tokens back to residualRecipient instead of trying to repay debt.

Assessed type

Token-Transfer

amarcu (LoopFi) confirmed and commented:

The scenario is valid if the case where the debt repayment is capped, but not sure about the severity.

Koolex (judge) decreased severity to Medium and commented:

@pkqs90 - Please clarify the likelihood and the following in PJQA:

To explain a bit more, this is a reasonable scenario, because the amount of collateral tokens used for swap comes from uint256 withdrawnCollateral = _onDecreaseLever(leverParams, subCollateral);, and for PositionAction4626, _onDecreaseLever() supports gathering collateral tokens by exiting from pools (e.g., Balancer). This means it is totally possible that the amount of collateral tokens used for swap values more than the user’s debt in CDPVault.

pkqs90 (warden) commented:

@Koolex For PositionAction4626 actions, this issue is more likely to occur because:

  1. Uses a redeem() call for ERC4626 vaults to get collateral tokens. Users cannot know exactly how much tokens are withdrawn beforehand, this is a dynamic value.
  2. If auxAction.args exists, it will perform a pool exit to get collateral tokens. Both balancer and pendle pool exits use a dynamic output value (e.g., Balancer uses EXACT_BPT_IN_FOR_ONE_TOKEN_OUT)

Also considering the general use case:

  1. When conducting collateral token -> debt token swap, the output of swapped out debt token is a dynamic value.
  2. If the position was liquidate-able, and is partially liquidated by other users by accidentally frontrunning, the required repay amount would be smaller than expected.

All above makes it more likely the user over repays his position.

    function _onDecreaseLever(
        LeverParams memory leverParams,
        uint256 subCollateral
    ) internal override returns (uint256 tokenOut) {
        // withdraw collateral from vault
        uint256 withdrawnCollateral = ICDPVault(leverParams.vault).withdraw(leverParams.position, subCollateral);

        // withdraw collateral from the ERC4626 vault and return underlying assets
@>      tokenOut = IERC4626(leverParams.collateralToken).redeem(withdrawnCollateral, address(this), address(this));

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

            tokenOut = IERC20(IERC4626(leverParams.collateralToken).asset()).balanceOf(address(this));
        }
    }
    function _balancerExit(PoolActionParams memory poolActionParams) internal returns (uint256 retAmount) {
        ...
        balancerVault.exitPool(
            poolId,
            address(this),
            payable(poolActionParams.recipient),
            ExitPoolRequest({
                assets: assets,
                minAmountsOut: minAmountsOut,
@>              userData: abi.encode(ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, bptAmount, outIndex),
                toInternalBalance: false
            })
        );
    }

The original report as published on Code4rena, by pkqs90. 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 contract does not check if the swap output exceeds the debt before attempting repayment, and the vault caps the repayment, leaving excess tokens in the contract.

Impact

Users could lose funds that become stuck in the contract, but the likelihood depends on dynamic swap amounts and partial liquidations.

What the attacker needed

EXACT_IN swap type; swap output exceeds debt; dynamic collateral amount

The fix

The residual tokens should be sent back to the residualRecipient instead of attempting to repay debt.

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 tries to pay back a loan but accidentally sends more money than needed. The extra money gets stuck in the contract and the user cannot get it back.

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 pkqs90

View all

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