Skip to content

Validate debt type before withdrawal credit-to-debit flip#200

Open
liobrasil wants to merge 2 commits intonialexsan/multi-debtfrom
lionel/fix-withdraw-validation-order
Open

Validate debt type before withdrawal credit-to-debit flip#200
liobrasil wants to merge 2 commits intonialexsan/multi-debtfrom
lionel/fix-withdraw-validation-order

Conversation

@liobrasil
Copy link
Contributor

@liobrasil liobrasil commented Mar 4, 2026

Summary

Prevent confusing "Internal error" reverts by validating debt type before a withdrawal flips a balance into debt.

Previous behavior (bug example)

Example position state:

  • Existing debt type: FLOW debt
  • Existing collateral type being withdrawn: MOET credit

Action:

  • User withdraws MOET in a flow that would flip MOET from Credit to Debit.

Before this fix:

  1. withdrawAndPull first called recordWithdrawal.
  2. The position could temporarily contain two debt types (FLOW + MOET).
  3. Then validateDebtType ran and hit this invariant assert:
    • "Internal error: Position has multiple debt types"

User-facing error improvement

  • Before: invalid flow could fail with invariant assert
    • "Internal error: Position has multiple debt types"
  • After: the same invalid flow fails with the intended domain constraint message from validateDebtType
    • "Position already has debt type X. Cannot borrow Y. Only one debt type allowed per position."

Result: transaction still reverts safely (no fund loss), but now returns a clearer and actionable error.

Why this fix is needed

PR #184 adds temporary one-debt-type guardrails. Validation should happen before mutation on flip paths (check-before-effect) so users get deterministic, domain-specific errors and we avoid relying on post-mutation invariant panics.

What changed

  • In withdrawAndPull:
    • Detect when a credit withdrawal would flip to debit by comparing withdraw amount vs true credit balance before mutation.
    • Run position.validateDebtType(type) before recordWithdrawal for that flip path.
    • Remove the post-mutation flip validation block.

Tests

  • Ran:
    • flow test cadence/tests/single_token_constraint_test.cdc
    • flow test cadence/tests/debt_type_constraint_three_token_test.cdc

@liobrasil liobrasil requested a review from a team as a code owner March 4, 2026 23:05
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