# Incorrect implementation of the `PositionMarginProcess.updatePositionFromBalanceMargin()` function.

Elfi Protocol's updatePositionFromBalanceMargin early-returns when initialMarginInUsd equals initialMarginInUsdFromBalance, so withdrawals never reduce balance margin, letting users over-utilize funds.

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

**Target:** PositionMarginProcess.updatePositionFromBalanceMargin in elfi-perp-contracts
**Root cause:** The guard uses `||` combining equality of initialMarginInUsd and initialMarginInUsdFromBalance with amount==0, so when the two margins are equal and amount<0 the function returns 0 instead of reducing initialMarginInUsdFromBalance.
**Steps:**
1. Read PositionMarginProcess.sol L303-L338.
2. Observe guard `if (position.initialMarginInUsd == position.initialMarginInUsdFromBalance || amount == 0) return 0;`.
3. Call path with amount<0 (withdrawal) where initialMarginInUsd == initialMarginInUsdFromBalance.
4. Note changeAmount stays 0 and initialMarginInUsdFromBalance is not decremented.
5. Withdraw assets repeatedly; position margin accounting no longer reflects deposited balance.
**How found:** Code review of the margin update logic; noticed the early-return condition incorrectly treats the equal-margin case as a no-op regardless of amount sign.
**Exploitation:** User withdraws assets while position margins are equal; the balance-margin accounting is not reduced, so the user retains margin credit for funds already withdrawn and can utilize more tokens than deposited.
**Insight:** When auditing accounting guards, check boolean conditions combining equality checks with sign-dependent amounts: an `||` that short-circuits on equality can silently skip decrements on negative deltas, breaking invariant that balance margin tracks actual deposits.
