# Invalid handling of risdual amount in PositionAction::onCreditFlashLoan, forcing it to revert

decreaseLever's onCreditFlashLoan repays residual swap amount as extra debt, reverting when user repays full debt (cmBorrowed==0).

- Payout: Audit contest
- Severity: medium
- Program: LoopFi
- Found by: 0xAlix2
- Disclosed: 2025-02-17
- Write-up quality: 6/10
- Original: https://github.com/code-423n4/2024-10-loopfi-findings/issues/26
- Library page: https://bugbountylibrary.com/r/c4%3A2024-10-loopfi%3AM-02
- Tags: area:web3 domain:web3 impact:dos kind:contest platform:code4rena sev:medium tech:evm tech:solidity technique:source-review vuln:accounting-error vuln:dos

**Target:** PositionAction::onCreditFlashLoan / decreaseLever credit flash loan callback
**Root cause:** After the primary swap, the residual (swapped minus repaid debt) is force-approved and passed as negative delta to modifyCollateralAndDebt, attempting to repay debt that may not exist; when the user repays the entire debt, cmBorrowed becomes 0 and PoolV3 reverts with CallerNotCreditManagerException.
**Steps:**
1. Deploy PositionAction20 lever test setup with user depositing 1000 ether collateral and borrowing 200 ether.
2. Call decreaseLever via userProxy with primarySwap.amount = vault.virtualDebt(userProxy) (full debt) and residualRecipient = positionAction.
3. Flash lender calls onCreditFlashLoan; swap proceeds exceed repaid debt, producing residualAmount > 0.
4. Code forceApprove(vault, residualAmount) then modifyCollateralAndDebt(position, this, this, 0, -residualAmount).
5. PoolV3 sees cmBorrowed == 0 and reverts CallerNotCreditManagerException, DoSing full-debt deleverage.
**How found:** Code review of onCreditFlashLoan residual handling; noticed residual is used to repay extra debt rather than sent to residualRecipient, then wrote a Foundry PoC repaying full debt to trigger the revert, and rebutted sponsor's faulty-setup claim by pointing to the second CallerNotCreditManagerException at PoolV3 L588 (cmBorrowed==0).
**Insight:** When a callback computes a residual from swap output minus debt, check the boundary where debt is fully repaid: protocols often revert on zero-debt modifyCollateralAndDebt, turning a normal full-close into a DoS; test with amount == virtualDebt, not just partial.

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

**Foundry test triggering residual repayment revert**

```
function test_leverageDownWrongResidualHandling() public {
    uint256 depositAmount = 1_000 ether;
    uint256 borrowAmount = 200 ether;

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

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

    vm.startPrank(user);

    // User deposits 1k ETH collateral
    token.approve(address(vault), type(uint256).max);
    vault.deposit(address(userProxy), depositAmount);

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

    userProxy.execute(
        address(positionAction),
        abi.encodeWithSelector(
            positionAction.decreaseLever.selector,
            LeverParams({
                position: address(userProxy),
                vault: address(vault),
                collateralToken: address(token),
                primarySwap: SwapParams({
                    swapProtocol: SwapProtocol.BALANCER,
                    swapType: SwapType.EXACT_IN,
                    assetIn: address(token),
                    amount: vault.virtualDebt(address(userProxy)),
                    limit: 0,
                    recipient: address(positionAction),
                    residualRecipient: address(positionAction),
                    deadline: block.timestamp,
                    args: abi.encode(weightedPoolIdArray, assets)
                }),
                auxSwap: emptySwap,
                auxAction: emptyPoolActionParams
            }),
            201 ether,
            address(userProxy)
        )
    );

    vm.stopPrank();
}
```

