Skip to content

margin_pool: clamp decrease_supply_absolute to total_supply#978

Draft
tonylee08 wants to merge 1 commit into
mainfrom
tlee/fix-bad-debt-supply-underflow
Draft

margin_pool: clamp decrease_supply_absolute to total_supply#978
tonylee08 wants to merge 1 commit into
mainfrom
tlee/fix-bad-debt-supply-underflow

Conversation

@tonylee08
Copy link
Copy Markdown
Collaborator

Summary

  • Clamp the subtraction in margin_state::decrease_supply_absolute at total_supply. Previously it could underflow (raw arithmetic_error) when repay_liquidation recorded bad debt larger than the current supplier pool.
  • Add a unit test (decrease_supply_absolute_clamps_at_zero) asserting the clamp holds and repeated over-decrements stay at zero.

Key decisions

  • Fix at the leaf, not the caller. decrease_supply_absolute is a public(package) primitive; per the leaf-guard convention in .claude/rules/move.md, it should be self-consistent regardless of which sibling module reaches it. The only caller (margin_pool::repay_liquidation) was relying on a cross-module invariant (bad_debt ≤ total_supply) that isn't guaranteed — total_supply drifts below total_borrow over time because update() skims protocol spread only from the supply side. Rather than add caller-side math, the leaf now enforces its own bound.
  • No API change, no new error constant, no event. Silent clamp is the minimal correct behavior: when bad debt exceeds total_supply, suppliers are already fully written down (worst case for them); the residual was never backed by vault cash so it's uncollectible by definition. The existing default return from repay_liquidation still reflects the economic shortfall, which remains accurate.
  • Not scoping in drift mitigation. The total_borrow vs. total_supply drift from protocol spread is intentional (it's how the fee model works). This PR only fixes the bad-debt path's handling of the resulting state, not the drift itself.

Test plan

  • sui move test --gas-limit 100000000000 in packages/deepbook_margin — all 301 tests pass
  • New decrease_supply_absolute_clamps_at_zero test exercises over-decrement + follow-up decrement from zero
  • bunx prettier-move -c on modified files — clean

🤖 Generated with Claude Code

Prevents an arithmetic_error when a full-share liquidation records bad
debt larger than the current total_supply. The write-off is now capped
at total_supply; excess is uncollectible by design (never backed by
vault cash).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
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