Skip to content

fix(perps): record native liquidation bad debt#142

Draft
rndrntwrk wants to merge 2 commits into
mainfrom
security/native-perps-liquidation-bad-debt
Draft

fix(perps): record native liquidation bad debt#142
rndrntwrk wants to merge 2 commits into
mainfrom
security/native-perps-liquidation-bad-debt

Conversation

@rndrntwrk

Copy link
Copy Markdown
Collaborator

Summary

Fixes the native perps liquidation accounting gap identified during the contracts audit.

Before this change, AgentPerpEngineNative.liquidate() used realized PnL only to decide whether a position was liquidatable. The liquidation path then paid the reward from raw margin and credited any remaining raw margin to insuranceFund, even when the position's realized loss exceeded margin. That made insolvent liquidations look solvent and left badDebt at zero.

This PR makes native liquidation apply the same accounting invariant as the ERC20 perps engine:

  • realized liquidation loss consumes trader margin first
  • residual loss consumes market insurance next
  • any remaining residual is recorded in market.badDebt
  • liquidation reward is capped after loss accounting, using remaining margin plus a bounded insurance draw
  • loss-absorbing margin is no longer credited to withdrawable insurance

Tests

  • forge test --match-path test/perps/AgentPerpEngineNative.t.sol
  • forge test --match-path test/perps/AgentPerpEngine.t.sol
  • forge test --match-path test/perps/AgentPerpEngineFuzz.t.sol
  • forge test --match-path test/perps/PmPerpsAdversarial.t.sol
  • forge test --match-path 'test/perps/*.t.sol'
  • forge build
  • git diff --check

forge fmt --check contracts/perps/AgentPerpEngineNative.sol test/perps/AgentPerpEngineNative.t.sol still reports pre-existing formatting drift in untouched portions of AgentPerpEngineNative.sol, so the patch keeps formatting minimal instead of reformatting the broader file.

Audit Notes

This PR is intentionally narrow. It does not include the separate security/native-perps-equity-health withdrawal-health fix, and it does not change the ERC20 perps engine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant