# Lack of timely update borrowing fee when update position's margin

Elfi Protocol fails to settle accrued borrowing fees when margin is added, letting traders lower leverage before closing and pay less than owed.

- Payout: Contest reward
- Severity: high
- Program: Elfi Protocol
- Credited: CL001
- Disclosed: 2024-05-09
- Write-up quality: 6/10
- Original: https://github.com/sherlock-audit/2024-05-elfi-protocol-judging/issues/63
- Library page: https://bugbountylibrary.com/r/sherlock%3A2024-05-elfi-protocol%3AH-14
- Tags: domain:web3 impact:funds-loss kind:contest platform:sherlock sev:high tech:solidity technique:source-review vuln:business-logic vuln:fee-bypass

**Target:** Perpetual futures position margin update (PositionMarginProcess.sol)
**Root cause:** Borrowing fee accrues based on initialMargin and leverage, but _executeAddMargin changes leverage without first settling updateBorrowingFee, so the fee delta is recomputed at the new lower leverage.
**Steps:**
1. Open an isolated position at high leverage; borrowing fee begins accruing at that leverage.
2. Let time pass so cumulativeBorrowingFeePerToken grows.
3. Call executeUpdatePositionMarginRequest to add margin, which lowers position.leverage without calling updateBorrowingFee first.
4. Close the position; updateBorrowingFee computes fee using the new low leverage over the whole elapsed period, undercharging.
**How found:** Code reading of _executeAddMargin noting leverage is recomputed while positionFee.openBorrowingFeePerToken is not settled, combined with the fee formula's dependence on leverage.
**Exploitation:** Trader opens high-leverage isolated position, waits, adds margin to drop leverage right before closing, and pays borrowing fees computed at the reduced leverage for the entire accrual window.
**Insight:** When a fee formula depends on a mutable state variable (leverage/initialMargin), check every path that mutates that variable for a missing settle-before-mutate call; margin top-ups are a classic spot to reset the basis.
