# `InvariantLib` uses current position for margin check allowing to withdraw collateral while the position decrease is only pending and can cause unexpected immediate user liquidation.

InvariantLib margin check uses currentPosition while liquidation uses latestPosition, so reducing a position and withdrawing collateral makes the account instantly liquidatable.

- Payout: Audit contest
- Severity: high
- Program: Perennial
- Found by: panprog
- Disclosed: 2025-01-14
- Write-up quality: 8/10
- Original: https://github.com/sherlock-audit/2025-01-perennial-v2-4-update-judging/issues/30
- Library page: https://bugbountylibrary.com/r/sherlock%3A2025-01-perennial-v2-4-update%3AH-2
- Tags: area:web3 domain:web3 impact:funds-loss kind:contest platform:sherlock sev:high tech:evm tech:solidity technique:source-review vuln:accounting-error vuln:business-logic vuln:liquidation

**Target:** Perennial V2 core market InvariantLib margin/liquidation checks
**Root cause:** InvariantLib.validate margin check uses currentPosition (latest + pending) while the liquidation maintenance check uses latestPosition, so the two checks disagree on position size.
**Steps:**
1. Open position size 10 with collateral 30 (margin 2%, maintenance 1%).
2. Call `update(user,0,5,0,-15,false)` to reduce position to 5 and withdraw collateral.
3. Margin check passes using currentPosition=5, but liquidation maintenance check uses latestPosition=10.
4. Call `update(user,0,0,0,0,true)` from another account to liquidate immediately.
**How found:** Code reading of InvariantLib.validate comparing the margined() call (currentPosition) against the maintained() call (latestPosition) in the liquidation path, spotting the inconsistency between the two checks.
**Exploitation:** User reduces position and withdraws collateral keeping the reduced position healthy; the account is instantly liquidatable because liquidation evaluates the pre-reduction latestPosition, letting a liquidator (or self-liquidator from a second account) seize liquidation fees.
**Escalation:** Repeated self-liquidation can drain market funds via liquidation fees when bonus exceeds trading fees.
**Insight:** When a protocol tracks both a committed 'latest' state and a pending 'current' state, verify every risk check (margin vs maintenance, update vs liquidation) uses the same state; a mismatch lets one path approve an action the other path penalizes.

