Skip to content

feat: cancel placed open orders#1268

Merged
MicBun merged 1 commit intomainfrom
cancelOrders
Nov 28, 2025
Merged

feat: cancel placed open orders#1268
MicBun merged 1 commit intomainfrom
cancelOrders

Conversation

@MicBun
Copy link
Member

@MicBun MicBun commented Nov 28, 2025

resolves: https://github.com/truflation/website/issues/2919

Summary by CodeRabbit

  • New Features
    • Added order cancellation functionality with automatic collateral refunds for buy orders and return of shares to holdings for sell orders.

✏️ Tip: You can customize this high-level summary in your review settings.

@MicBun MicBun self-assigned this Nov 28, 2025
@MicBun MicBun added the type: feat New feature or request label Nov 28, 2025
@holdex
Copy link

holdex bot commented Nov 28, 2025

Time Submission Status

Member Status Time Action Last Update
MicBun ✅ Submitted 9h Update time Nov 28, 2025, 11:09 AM

@coderabbitai
Copy link

coderabbitai bot commented Nov 28, 2025

Walkthrough

This PR introduces a new cancel_order action that enables users to cancel existing buy or sell orders in the order book system. For buy orders, the action refunds locked collateral; for sell orders, it returns shares to holdings. It includes comprehensive test coverage validating successful cancellations, error cases, and balance correctness.

Changes

Cohort / File(s) Summary
SQL Migration
internal/migrations/032-order-book-actions.sql
Introduces the cancel_order public action that validates caller permissions and market state, retrieves targeted orders, refunds collateral for buy orders or returns shares to holdings for sell orders, and deletes cancelled positions. Handles errors for invalid markets, settled markets, missing orders, and invalid prices.
Test Suite
tests/streams/order_book/cancel_order_test.go
Comprehensive test suite covering successful cancellations of buy and sell orders at multiple price levels, error cases (non-existent orders/markets, invalid prices, settled markets, price=0), and verification of collateral/share balance corrections. Includes helper utilities for invoking cancel_order and marking markets as settled.

Sequence Diagram

sequenceDiagram
    participant Caller as User
    participant Action as cancel_order Action
    participant Market as Market Lookup
    participant Order as Order Retrieval
    participant Refund as Collateral/Holdings
    participant DB as ob_positions DB

    Caller->>Action: Call cancel_order(query_id, outcome, price)
    
    Action->>Action: Validate caller address
    
    Action->>Market: Validate market exists & not settled
    alt Market Invalid or Settled
        Action-->>Caller: Error (invalid/settled market)
    end
    
    Action->>Order: Retrieve order by query_id
    alt Order Not Found
        Action-->>Caller: Error (order not found)
    end
    
    alt price < 0 (Buy Order)
        Action->>Refund: Calculate & unlock collateral
        Refund->>DB: Release locked funds
    else price > 0 (Sell Order)
        Action->>Refund: Update holdings (return shares)
        Refund->>DB: Upsert shares back to holdings
    else price == 0
        Action-->>Caller: Error (cannot cancel holdings)
    end
    
    Action->>DB: Delete cancelled order from ob_positions
    Action-->>Caller: Cancellation complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

  • SQL action logic: Review the conditional branching for buy vs. sell order handling, collateral refund calculations, and error validation paths.
  • Test coverage: Verify that test cases exercise all error conditions, boundary cases (e.g., price=0), and state transitions (holdings updates, collateral release).
  • Integration points: Confirm correct usage of helper functions (ob_unlock_collateral, position upserts) and consistency with existing order-book mechanisms.

Possibly related PRs

Suggested reviewers

  • pr-time-tracker

Poem

🐰 Hop, skip, and order we dance,
But whoops! Cancel quick—no second chance.
Collateral back, or shares returned with care,
The market unwinds with a hop and a flair!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: cancel placed open orders' directly and clearly summarizes the main change: implementing functionality to cancel open orders in the order book system.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cancelOrders

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
internal/migrations/032-order-book-actions.sql (1)

1-8: Update file header comment to include cancel_order action.

The header lists create_market, get_market_info, and list_markets but omits the newly added cancel_order action. Consider updating the documentation for discoverability.

 /*
  * ORDER BOOK ACTIONS
  *
  * User-facing actions for the prediction market:
  * - create_market: Create a new prediction market
  * - get_market_info: Get market details by ID
  * - list_markets: List markets with optional filtering
+ * - cancel_order: Cancel an open buy or sell order
  */
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78c20f1 and 1d2ca0f.

📒 Files selected for processing (2)
  • internal/migrations/032-order-book-actions.sql (1 hunks)
  • tests/streams/order_book/cancel_order_test.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
tests/streams/order_book/cancel_order_test.go (2)
tests/streams/utils/runner.go (1)
  • RunSchemaTest (37-116)
tests/streams/utils/utils.go (1)
  • GetTestOptionsWithCache (75-88)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: acceptance-test
🔇 Additional comments (13)
internal/migrations/032-order-book-actions.sql (1)

976-1116: LGTM! Well-structured cancel_order implementation.

The action follows established patterns in the codebase:

  • Validation order is correct (caller → parameters → market → participant → order)
  • Collateral refund calculation matches the lock calculation in place_buy_order
  • UPSERT pattern for returning shares is consistent with other actions
  • Proper use of helper functions (ob_get_participant_id, ob_unlock_collateral)
tests/streams/order_book/cancel_order_test.go (12)

28-40: Good test coverage with clear TODO for settlement test.

The test suite covers essential scenarios: success cases for buy/sell, multiple price levels, various error conditions, and balance/refund verification. The commented-out testCancelOrderMarketSettled with TODO is acceptable for now.


44-88: LGTM! Clean test structure with proper setup-action-verify pattern.


91-159: LGTM! Thorough verification of sell order cancellation and share return.


162-228: LGTM! Good test for selective cancellation across multiple price levels.


231-264: LGTM! Correctly tests the error case for non-existent orders.


307-322: LGTM! Test correctly validates market existence check ordering.

The SQL action validates market existence before checking participant, so this test correctly expects "Market does not exist" error.


325-357: LGTM! Tests boundary conditions for price validation.


360-389: LGTM! Verifies holdings cannot be cancelled.


392-445: LGTM! Comprehensive balance verification for refund flow.


448-515: LGTM! Thorough verification of shares returning to holdings after sell order cancellation.


522-551: LGTM! Helper follows established patterns from other order book tests.


554-568: LGTM! Test utility correctly simulates settlement state.

Using raw SQL UPDATE is appropriate for test setup to simulate settlement without depending on the actual settlement action implementation.

@MicBun MicBun merged commit 2065112 into main Nov 28, 2025
6 checks passed
@MicBun MicBun deleted the cancelOrders branch November 28, 2025 23:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feat New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant