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

decreaseLever() and onCreditFlashLoan() treat primarySwap.amount as loanAmount, ignoring the flashlender protocolFee, so the flash loan repayment exceeds the swapped amount and the call reverts whenever protocolFee != 0.

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

**Target:** PositionAction proxy contract (decreaseLever / onCreditFlashLoan)
**Root cause:** loanAmount and subDebt are set to leverParams.primarySwap.amount, which is the swap output that must cover loanAmount + protocolFee; the fee is never subtracted, so the flash loan repayment and debt reduction are both overstated.
**Steps:**
1. Set flashlender protocolFee to 1% in TestBase: `new Flashlender(IPoolV3(address(liquidityPool)), 0.01 ether)`.
2. Open a leveraged position via `_increaseLever` (e.g. 20k upfront, 40k borrow).
3. Grant agent permission: `vault.setPermissionAgent(address(bobProxy), true)` from alice.
4. Call `positionAction.decreaseLever(leverParams, maxAmountIn, address(bob))` with `primarySwap.swapType = EXACT_OUT`, `amount = loanAmount + fee`.
5. Observe revert: swap output equals primarySwap.amount but flashlender expects loanAmount + fee returned, and subDebt reduction mismatches loanAmount, causing insufficient allowance/balance.
**How found:** Reading decreaseLever/onCreditFlashLoan flow: noticed primarySwap.amount is documented as the amount returned to the pool (loan + fee), yet the code passes it directly as loanAmount and subDebt, so the fee term is unaccounted for; confirmed by setting protocolFee nonzero in the test harness.
**Insight:** When a flash-loan callback parameter is described as 'amount to return to pool', check whether it includes the fee; the borrowed principal must be derived as amount * WAD / (WAD + fee), and any debt/collateral adjustment must use that principal, not the gross repayment figure.

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

**Set protocolFee to 1% in TestBase**

```
flashlender = new Flashlender(IPoolV3(address(liquidityPool)), 0.01 ether); // 1/100 fee
```

