Skip to content

Fix: Stop Double-Counting Balances When Creating Orders#119

Merged
avernikoz merged 9 commits intomainfrom
fix/create-order-core-bm-balances-accounting
Sep 18, 2025
Merged

Fix: Stop Double-Counting Balances When Creating Orders#119
avernikoz merged 9 commits intomainfrom
fix/create-order-core-bm-balances-accounting

Conversation

@bathord
Copy link
Copy Markdown
Collaborator

@bathord bathord commented Sep 18, 2025

The Bug: What Was Wrong?

When a user placed an order where the input coin was SUI or DEEP, our code would attempt to use the same funds for both the order amount and its associated fees. This "double-counting" meant we didn't actually have enough money to cover both, causing the transaction to fail.

A Real-World Example

Here’s a simple scenario where this bug would occur:

  1. A user has exactly 1 SUI in their Balance Manager.
  2. They place a sell order for that 1 SUI.
  3. Since they have no DEEP tokens, they must pay a coverage fee of 0.001 SUI.
  4. The system would see the 1 SUI balance and approve both actions: taking 0.001 SUI for the fee and 1 SUI for the order.
  5. During execution, the fee is paid first, leaving only 0.999 SUI in the balance.
  6. The system then tries to submit the 1 SUI order to Deepbook, but with only 0.999 SUI available.
  7. Deepbook correctly rejects this, causing the entire transaction to fail with an EBalanceManagerBalanceTooLow error.

How We Fixed It

The fix is simple: we now subtract any fees from the user's balance before we calculate the amount available for the trade. This ensures we only use funds that are actually available.

How We Know It's Fixed

We added a new test, sell_order_from_balance_manager, that perfectly recreates this failure. The test now passes. Before this fix, running the same test on the old code would cause it to predictably fail with an EBalanceManagerBalanceTooLow error from Deepbook.

Add from_balance_manager field to DeepPlan and update get_deep_plan to calculate it.
Fix balance_manager_input_coin amount management by taking into account whether the input coin is DEEP or SUI.
If it is one of them, we decrease balance_manager_input_coin by corresponding amount (which is planned to be consumed)
before using it in InputCoinDepositPlan calculation.
@bathord bathord changed the title Fix/create order core bm balances accounting Fix: Prevent Order Failures from Double-Counting Balance Manager Balances Sep 18, 2025
@bathord bathord changed the title Fix: Prevent Order Failures from Double-Counting Balance Manager Balances Fix: Stop Double-Counting Balances When Creating Orders Sep 18, 2025
@avernikoz avernikoz merged commit 33a1b96 into main Sep 18, 2025
2 checks passed
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.

2 participants