Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CT-1327] place post only orders first in prepare check state #2618

Merged
merged 6 commits into from
Dec 2, 2024

Conversation

jayy04
Copy link
Contributor

@jayy04 jayy04 commented Nov 27, 2024

Changelist

[Describe or list the changes made in this PR]

Test Plan

[Describe how this PR was tested (if applicable)]

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • New Features

    • Introduced a new method IsPostOnlyOrder to determine if an order is post-only.
    • Enhanced order placement logic with a new parameter postOnlyFilter for conditional processing of orders.
    • Updated replay operations to conditionally skip non-post-only orders based on the new parameter.
    • Added new long-term orders with a "post-only" time-in-force option.
  • Bug Fixes

    • Improved error handling and telemetry for order placement and removal processes.
  • Tests

    • Updated test cases to cover new functionality related to post-only order processing and ensure robustness against edge cases.
    • Expanded tests for conditional order removals to reflect new business logic.

@jayy04 jayy04 requested a review from a team as a code owner November 27, 2024 15:31
Copy link

linear bot commented Nov 27, 2024

Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

Walkthrough

The changes in this pull request primarily involve modifications to the order handling functionality within the CLOB (Central Limit Order Book) system. Key updates include the addition of a boolean parameter postOnlyFilter to several methods, enabling conditional operations based on order types. The ReplayOperations method in both MemClob and MemClobPriceTimePriority has been updated to incorporate this parameter. Additionally, the PrepareCheckState function has been restructured for enhanced order processing clarity. The test suite has also been updated to reflect these changes and ensure comprehensive coverage.

Changes

File Path Change Summary
protocol/mocks/MemClob.go Updated ReplayOperations method signature to include postOnlyFilter parameter.
protocol/x/clob/abci.go Modified PrepareCheckState function to implement a two-pass order placement approach, focusing on post-only orders, and updated method signature.
protocol/x/clob/keeper/orders.go Added postOnlyFilter parameter to PlaceStatefulOrdersFromLastBlock and PlaceConditionalOrdersTriggeredInLastBlock methods, affecting order placement logic.
protocol/x/clob/keeper/orders_test.go Updated tests to accommodate new parameters in order placement methods, ensuring various scenarios are tested, including regression tests for previously identified issues.
protocol/x/clob/memclob/memclob.go Updated ReplayOperations method in MemClobPriceTimePriority to include postOnlyFilter parameter and added telemetry measurements.
protocol/x/clob/types/memclob.go Modified ReplayOperations method in MemClob interface to accept postOnlyFilter parameter.
protocol/x/clob/types/order.go Introduced new method IsPostOnlyOrder to Order type to check if an order is post-only based on its time-in-force.
protocol/testutil/constants/stateful_orders.go Added new long-term orders with "post-only" time-in-force option.
protocol/x/clob/e2e/conditional_orders_test.go Updated tests for conditional orders to include new scenarios and validate behavior with post-only orders.
protocol/x/clob/e2e/order_removal_test.go Renamed constants in tests to reflect post-only status and updated logic for order removals.

Possibly related PRs

Suggested labels

feature:optimistic_execution

Suggested reviewers

  • vincentwschau
  • roy-dydx

Poem

In the meadow where orders play,
A new flag joins the fray! 🐇
Post-only orders take the lead,
As we hop along with speed.
With each change, we grow and thrive,
In the CLOB, we come alive! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (7)
protocol/x/clob/types/memclob.go (1)

113-113: Breaking change: New parameter added to ReplayOperations interface method.

The addition of onlyPlacePostOnly parameter is well-aligned with the PR objective of prioritizing post-only orders. However, this is a breaking change that requires updates to all implementations of the MemClob interface.

Consider adding this change to the state-breaking changes documentation if not already done.

protocol/x/clob/types/order.go (1)

183-186: LGTM! Consider adding unit tests.

The IsPostOnlyOrder method is well-implemented and aligns with the PR objectives to modify post-only order processing. The implementation is clean, concise, and follows the codebase's conventions.

Consider adding unit tests to verify the behavior of this method for both post-only and non-post-only orders. I can help generate the test cases if needed.

protocol/x/clob/keeper/orders.go (2)

499-499: LGTM! Consider adding documentation for the new parameter.

The implementation correctly filters orders based on the onlyPlacePostOnly flag, aligning with the PR objective to modify post-only order processing.

Consider adding documentation for the onlyPlacePostOnly parameter in the function's comment block to explain its purpose and behavior:

// PlaceStatefulOrdersFromLastBlock validates and places stateful orders from the last block onto the memclob.
// Note that stateful orders could fail to be placed due to various reasons such as collateralization
// check failures, self-trade errors, etc. In these cases the `checkState` will not be written to.
// This function is used in:
// 1. `PrepareCheckState` to place newly placed long term orders from the last
// block from ProcessProposerMatchesEvents.PlacedStatefulOrderIds. This is step 3 in PrepareCheckState.
// 2. `PlaceConditionalOrdersTriggeredInLastBlock` to place conditional orders triggered in the last block
// from ProcessProposerMatchesEvents.ConditionalOrderIdsTriggeredInLastBlock. This is step 4 in PrepareCheckState.
+//
+// Parameters:
+// - onlyPlacePostOnly: When true, only post-only orders will be placed, skipping all other orders.
+//   This is used to prioritize post-only orders in the prepare check state.

Also applies to: 525-530


589-589: LGTM! Consider adding documentation for the new parameter.

The implementation correctly forwards the onlyPlacePostOnly parameter to PlaceStatefulOrdersFromLastBlock.

Consider adding documentation for the onlyPlacePostOnly parameter in the function's comment block:

// PlaceConditionalOrdersTriggeredInLastBlock takes in a list of conditional order ids that were triggered
// in the last block, verifies they are conditional orders, verifies they are in triggered state, and places
// the orders on the memclob.
+//
+// Parameters:
+// - onlyPlacePostOnly: When true, only post-only orders will be placed, skipping all other orders.
+//   This parameter is forwarded to PlaceStatefulOrdersFromLastBlock.

Also applies to: 619-624

protocol/x/clob/memclob/memclob.go (1)

927-931: Consider improving readability with a descriptive variable.

While the logic is correct, readability could be enhanced by extracting the condition into a descriptive variable.

Consider this refactor:

-if onlyPlacePostOnly && !order.IsPostOnlyOrder() {
+shouldSkipNonPostOnlyOrder := onlyPlacePostOnly && !order.IsPostOnlyOrder()
+if shouldSkipNonPostOnlyOrder {
   continue
}
protocol/x/clob/keeper/orders_test.go (2)

2221-2222: Enhance test clarity by using subtests

Consider using subtests or separate test cases to distinguish between the scenarios when PlaceStatefulOrdersFromLastBlock is called with true and false. This will improve the readability and maintainability of your tests.


2380-2381: Improve test organization by separating parameter variations

Similarly, for PlaceConditionalOrdersTriggeredInLastBlock, consider splitting the calls with true and false into separate subtests or test cases. This will make it clearer what each test is validating and aid future enhancements.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3566800 and f511a2c.

📒 Files selected for processing (7)
  • protocol/mocks/MemClob.go (1 hunks)
  • protocol/x/clob/abci.go (3 hunks)
  • protocol/x/clob/keeper/orders.go (4 hunks)
  • protocol/x/clob/keeper/orders_test.go (2 hunks)
  • protocol/x/clob/memclob/memclob.go (2 hunks)
  • protocol/x/clob/types/memclob.go (1 hunks)
  • protocol/x/clob/types/order.go (1 hunks)
🔇 Additional comments (9)
protocol/x/clob/types/memclob.go (1)

113-113: Verify all MemClob implementations are updated.

Let's verify that all implementations of the MemClob interface have been updated with the new parameter.

✅ Verification successful

All MemClob implementations are properly updated with the new parameter

Based on the search results, I can confirm that all implementations of the MemClob interface have been properly updated with the new onlyPlacePostOnly parameter:

  1. The interface definition in protocol/x/clob/types/memclob.go includes the parameter
  2. The main implementation MemClobPriceTimePriority in protocol/x/clob/memclob/memclob.go includes the parameter
  3. The mock implementation in protocol/mocks/MemClob.go has also been updated

All implementations are consistent with the interface change, and no issues were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all implementations of MemClob interface and verify they include the new parameter

# Search for struct types that implement MemClob
ast-grep --pattern 'type $_ struct {
  $$$
}

func ($_ $_) ReplayOperations(ctx sdk.Context, localOperations []InternalOperation, shortTermOrderTxBytes map[OrderHash][]byte, existingOffchainUpdates *OffchainUpdates$_) $_ {'

# Also check mock implementations
fd -e go -E 'mock.*\.go' --exec rg -A 5 'ReplayOperations'

Length of output: 6350


Script:

#!/bin/bash
# Let's search for all MemClob interface implementations more effectively

# First, find the MemClob interface definition
ast-grep --pattern 'type MemClob interface {
  $$$
}'

# Then find all struct implementations
ast-grep --pattern 'type $_ struct {
  $$$
}

func ($_ $_) ReplayOperations'

# Also search for any ReplayOperations function implementations
rg "func.*ReplayOperations" -A 5

Length of output: 10712

protocol/x/clob/abci.go (4)

188-213: LGTM: First pass implementation for post-only orders

The implementation correctly prioritizes post-only orders by processing them first, which aligns with the PR objective. The approach is consistent across all three order placement operations.


188-188: LGTM: Clear step organization and documentation

The step numbering and comments have been updated to clearly reflect the new two-pass approach while maintaining the logical flow of operations.

Also applies to: 215-215, 238-238, 246-246, 258-258, 271-271, 278-278


188-188: Verify the keeper parameter type change

The function signature changed from pointer to value receiver for the keeper parameter. This change seems unrelated to the PR objective and could have performance implications.

Let's check the size of the keeper struct and its usage across the codebase:


Line range hint 215-256: Verify the completeness of second pass order processing

The second pass processes non-post-only orders using the same functions. However, we should verify that orders aren't accidentally processed twice.

Let's check the implementation of these functions:

✅ Verification successful

Let me gather more specific information about the order processing implementation.


Let me gather one more piece of information about how orders are placed on the memclob.


Let me gather more specific information about how orders are processed in the second pass.


Based on the code analysis, I can now generate the final response:

Orders are safely processed in both passes without duplication

The implementation prevents double processing through:

  1. The onlyPlacePostOnly parameter in PlaceStatefulOrdersFromLastBlock which controls whether only post-only orders or non-post-only orders are processed in each pass
  2. Each order is processed exactly once in each pass since the orders are taken from distinct slices (longTermOrderIds and conditionalOrderIdsTriggeredInLastBlock) that are populated during block processing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check implementation of order placement functions
ast-grep --pattern 'func $_(ctx $_, $_, $_, postOnly bool) $_ {
  $$$
}'

# Check for potential duplicate processing prevention
rg -A 5 'postOnly.*bool'

Length of output: 3073


Script:

#!/bin/bash
# Check the implementation of PlaceStatefulOrdersFromLastBlock and PlaceConditionalOrdersTriggeredInLastBlock
rg -A 20 "func.*PlaceStatefulOrdersFromLastBlock|func.*PlaceConditionalOrdersTriggeredInLastBlock" protocol/

# Check if there's any tracking of processed orders
rg "ProcessedOrders|processedOrders|processed_orders" protocol/

# Look for any order state tracking in memclob
rg -A 10 "type MemClob struct" protocol/

Length of output: 7979


Script:

#!/bin/bash
# Check the implementation of order placement in memclob
rg -A 15 "func.*PlaceOrder" protocol/

# Look for any order filtering based on postOnly
rg -B 2 -A 5 "if.*postOnly" protocol/

Length of output: 101790


Script:

#!/bin/bash
# Check the implementation of PlaceStatefulOrdersFromLastBlock to see how orders are processed
rg -B 5 -A 15 "func.*PlaceStatefulOrdersFromLastBlock" protocol/x/clob/keeper/

# Look for any state tracking or order processing in the memclob implementation
rg -B 2 -A 10 "func.*ReplayOperations" protocol/x/clob/memclob/

Length of output: 5042

protocol/mocks/MemClob.go (2)

581-582: LGTM: Method signature updated correctly.

The ReplayOperations method signature has been properly updated to include the new onlyPlacePostOnly boolean parameter, maintaining consistency with the interface changes.


590-591: LGTM: Implementation handles new parameter correctly.

The type assertion and function call have been properly updated to include the new onlyPlacePostOnly parameter in the mock implementation.

protocol/x/clob/memclob/memclob.go (2)

882-882: LGTM! Method signature change is clear and purposeful.

The new parameter onlyPlacePostOnly is well-named and aligns with the PR's objective to modify post-only order processing.


Line range hint 882-931: Verify all callers of ReplayOperations are updated.

The addition of the onlyPlacePostOnly parameter requires updates to all callers of this method.

Let's verify all callers are properly updated:

✅ Verification successful

Let me gather more context about the actual calls to verify if they are properly updated.


All callers of ReplayOperations are properly updated

The verification shows that all callers of ReplayOperations have been updated to include the new onlyPlacePostOnly parameter. The method is called in two places in abci.go, and both calls properly set the parameter:

  • One call with true for post-only orders
  • One call with false for all orders
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all calls to ReplayOperations to ensure they include the new parameter
rg -A 2 "ReplayOperations\(" 

Length of output: 1210


Script:

#!/bin/bash
# Get more context around the ReplayOperations calls in abci.go
rg -B 2 -A 5 "ReplayOperations\(" protocol/x/clob/abci.go

Length of output: 441

@@ -521,6 +522,12 @@ func (k Keeper) PlaceStatefulOrdersFromLastBlock(
}

order := orderPlacement.GetOrder()

// Prioritize placing post-only orders if the flag is set.
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit:

Suggested change
// Prioritize placing post-only orders if the flag is set.
// Only place post-only orders if the flag is set.

@@ -521,6 +522,12 @@ func (k Keeper) PlaceStatefulOrdersFromLastBlock(
}

order := orderPlacement.GetOrder()

// Prioritize placing post-only orders if the flag is set.
if onlyPlacePostOnly && !order.IsPostOnlyOrder() {
Copy link
Contributor

Choose a reason for hiding this comment

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

We call this function twice, second time with onlyPlacePostOnly = false, which doesn't exclude the PO stateful orders. Does that mean PO orders are placed twice and is that an issue?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ah good catch. Meant to do this for all orders

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
protocol/x/clob/memclob/memclob.go (1)

927-931: Correct the misleading comment about skipping orders

The comment on line 927 incorrectly states:

// Skip the order if it is a post-only order and we are only replaying post-only orders.

However, the condition in the code is:

if onlyPlacePostOnly && !order.IsPostOnlyOrder() {
    continue
}

This logic skips non-post-only orders when onlyPlacePostOnly is true. Please update the comment to accurately reflect the code behavior, such as:

// Skip the order if it is not a post-only order and we are only replaying post-only orders.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f511a2c and 88dcf1a.

📒 Files selected for processing (1)
  • protocol/x/clob/memclob/memclob.go (4 hunks)
🔇 Additional comments (3)
protocol/x/clob/memclob/memclob.go (3)

882-883: Addition of onlyPlacePostOnly parameter to ReplayOperations

The addition of the onlyPlacePostOnly boolean parameter to the ReplayOperations function enhances its functionality by allowing conditional replay of post-only orders. This change is well-integrated and properly updates the method signature.


1022-1026: Correct the misleading comment about skipping orders

The comment in this block similarly misrepresents the code logic. The comment should be updated to correctly describe that non-post-only orders are skipped when onlyPlacePostOnly is true.


1080-1084: Correct the misleading comment about skipping orders

As noted previously, the comment here should be corrected to accurately reflect the code logic, indicating that non-post-only orders are skipped when onlyPlacePostOnly is true.

Copy link
Contributor

@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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 88dcf1a and 4809274.

📒 Files selected for processing (3)
  • protocol/testutil/constants/stateful_orders.go (2 hunks)
  • protocol/x/clob/e2e/conditional_orders_test.go (1 hunks)
  • protocol/x/clob/e2e/order_removal_test.go (2 hunks)
🔇 Additional comments (5)
protocol/x/clob/e2e/order_removal_test.go (3)

46-46: LGTM: Constant renamed to reflect post-only status

The constant has been appropriately renamed from LongTermOrder_Alice_Num0_Id0_Clob0_Buy5_Price10_GTBT5 to LongTermOrder_Alice_Num0_Id0_Clob0_Buy5_Price10_GTBT5_PO to clearly indicate it's a post-only order.


632-632: LGTM: Consistent naming convention for post-only orders

The constant renaming follows the same pattern, maintaining consistency in the codebase for post-only order identifiers.


Line range hint 1-1000: Verify test coverage for post-only order scenarios

The test suite comprehensively covers various order removal scenarios. However, let's verify the coverage of post-only specific test cases.

✅ Verification successful

Let me verify the test coverage for post-only orders by checking the test assertions and expected behaviors.


Let me check one more aspect of post-only order testing by looking at the conditional order scenarios.


Based on the analysis of the test coverage for post-only orders, I can now provide the final response:

Post-only order removal scenarios are well tested

The test suite provides comprehensive coverage for post-only order removal scenarios including:

  • Basic post-only order crossing with maker orders
  • Conditional post-only order behaviors
  • Invalid post-only order removal validations
  • Post-only order state verification after removal
  • Error cases for non post-only orders being removed with post-only reasons
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for post-only order scenarios
# Test: Search for post-only related test cases and assertions
rg -A 5 "post-only.*order" protocol/x/clob/e2e/

Length of output: 5391


Script:

#!/bin/bash
# Search for post-only order removal test assertions and behaviors
rg -A 10 "expectedFirstOrderRemoved|expectedSecondOrderRemoved|expectedOrderRemovals.*true.*PO" protocol/x/clob/e2e/

Length of output: 7944


Script:

#!/bin/bash
# Search for post-only conditional order test assertions
rg -B 2 -A 5 "expectedOrderRemovals.*true.*conditional.*PO|expectedErr.*post-only" protocol/x/clob/e2e/

Length of output: 571

protocol/testutil/constants/stateful_orders.go (2)

1311-1323: LGTM! Well-structured post-only order definition.

The order definition follows the established pattern and correctly sets all required fields, including the post-only time-in-force flag.


1376-1388: LGTM! Well-structured post-only order definition with appropriate BTC test values.

The order definition correctly sets up a post-only sell order for 0.25 BTC with appropriate price and time parameters.

@@ -1869,7 +1869,7 @@ func TestConditionalOrder_TriggeringUsingMatchedPrice(t *testing.T) {
constants.Order_Dave_Num1_Id0_Clob0_Sell1BTC_Price49997_GTB10,
constants.Order_Carl_Num1_Id0_Clob0_Buy1BTC_Price50003_GTB10,
// Place the conditional order.
constants.LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10,
constants.LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10_PO,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential issue with using a post-only order in this test case

In the test case "TakeProfit/Buy post-only conditional order can place, trigger, cross, and be removed from state", you have changed the order to a post-only order by using LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10_PO. Post-only orders are intended to add liquidity and will not execute immediately against existing orders. This may prevent the expected cross and removal from state, which contradicts the test's objective to verify that the conditional order can cross and be removed from state.

Consider using a non-post-only order to ensure the test behaves as intended.

Apply this diff to fix the issue:

-				constants.LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10_PO,
+				constants.LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constants.LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10_PO,
constants.LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10,

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
protocol/x/clob/e2e/conditional_orders_test.go (1)

Line range hint 1-2618: Consider improving test maintainability

The test suite is comprehensive but could benefit from the following improvements:

  1. Add comments explaining the test logic and expected behavior for complex test cases
  2. Extract common setup code into helper functions to reduce duplication
  3. Consider grouping related test cases into subtests using t.Run()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4809274 and a93998d.

📒 Files selected for processing (1)
  • protocol/x/clob/e2e/conditional_orders_test.go (2 hunks)
🔇 Additional comments (2)
protocol/x/clob/e2e/conditional_orders_test.go (2)

1872-1872: Duplicate issue with post-only order usage

The same issue exists here where a post-only order is used in a test case that expects order crossing behavior.


708-708: ⚠️ Potential issue

Potential issue with using a post-only order in this test case

The test case "TakeProfit/Buy post-only conditional order can place, trigger, cross, and be removed from state" uses a post-only order LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10_PO. However, post-only orders are designed to add liquidity and should not cross the book. This seems to contradict the test's objective of testing order crossing.

Consider using a regular limit order instead of a post-only order to properly test the crossing scenario:

-constants.LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10_PO,
+constants.LongTermOrder_Dave_Num0_Id0_Clob0_Sell025BTC_Price50000_GTBT10,

Likely invalid or redundant comment.

teddyding
teddyding previously approved these changes Nov 27, 2024
@teddyding teddyding dismissed their stale review November 28, 2024 00:59

offline convo

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (2)
protocol/x/clob/keeper/orders.go (1)

499-500: Consider adding documentation for the new parameter.

The new onlyPlacePostOnly parameter should be documented in the function's comment block to explain its purpose and behavior.

// PlaceStatefulOrdersFromLastBlock validates and places stateful orders from the last block onto the memclob.
// Note that stateful orders could fail to be placed due to various reasons such as collateralization
// check failures, self-trade errors, etc. In these cases the `checkState` will not be written to.
// This function is used in:
// 1. `PrepareCheckState` to place newly placed long term orders from the last
// block from ProcessProposerMatchesEvents.PlacedStatefulOrderIds. This is step 3 in PrepareCheckState.
// 2. `PlaceConditionalOrdersTriggeredInLastBlock` to place conditional orders triggered in the last block
// from ProcessProposerMatchesEvents.ConditionalOrderIdsTriggeredInLastBlock. This is step 4 in PrepareCheckState.
+// @param onlyPlacePostOnly If true, only post-only orders will be placed. If false, only non-post-only orders will be placed.
protocol/x/clob/memclob/memclob.go (1)

882-883: Consider adding documentation for the new parameter.

The new onlyPlacePostOnly parameter should be documented in the function's comment block to explain its purpose and behavior.

// ReplayOperations will replay the provided operations onto the memclob.
// This is used to replay all local operations from the local `operationsToPropose` from the previous block.
// The following operations are supported:
// - Short-Term orders.
// - Newly-placed stateful orders.
// - Pre-existing stateful orders.
// - Stateful cancelations.
// Note that match operations are no-op.
+// @param onlyPlacePostOnly If true, only post-only orders will be replayed. If false, only non-post-only orders will be replayed.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a93998d and 498f72a.

📒 Files selected for processing (3)
  • protocol/x/clob/keeper/orders.go (4 hunks)
  • protocol/x/clob/keeper/orders_test.go (2 hunks)
  • protocol/x/clob/memclob/memclob.go (4 hunks)
🔇 Additional comments (5)
protocol/x/clob/keeper/orders.go (2)

525-529: LGTM! Clean implementation of post-only order filtering.

The logic correctly implements the filtering of orders based on the onlyPlacePostOnly flag, ensuring that orders are processed in the desired order.


589-590: LGTM! Consistent parameter propagation.

The onlyPlacePostOnly parameter is correctly propagated through to PlaceStatefulOrdersFromLastBlock, maintaining consistent behavior for both regular stateful orders and conditional orders.

Also applies to: 619-624

protocol/x/clob/keeper/orders_test.go (2)

2221-2222: LGTM! Comprehensive test coverage for both flag values.

The test correctly verifies the behavior by calling the method twice with different onlyPlacePostOnly values, ensuring both post-only and non-post-only orders are properly handled.


2251-2353: LGTM! Well-structured test cases for post-only order handling.

The test cases thoroughly cover all scenarios:

  • Places PO orders when onlyPlacePostOnly = true
  • Skips non-PO orders when onlyPlacePostOnly = true
  • Skips PO orders when onlyPlacePostOnly = false
  • Places non-PO orders when onlyPlacePostOnly = false
protocol/x/clob/memclob/memclob.go (1)

927-931: LGTM! Consistent implementation of post-only filtering across all operation types.

The logic correctly and consistently implements the filtering of orders based on the onlyPlacePostOnly flag for:

  • Short-term order placements
  • Pre-existing stateful orders
  • Order removals

This ensures uniform handling of post-only orders throughout the replay process.

Also applies to: 1022-1026, 1080-1084

@@ -496,6 +496,7 @@ func (k Keeper) PlaceStatefulOrdersFromLastBlock(
ctx sdk.Context,
placedStatefulOrderIds []types.OrderId,
existingOffchainUpdates *types.OffchainUpdates,
onlyPlacePostOnly bool,
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: current naming might suggest that if false, the function processes ALL orders including post-only. How abt sth like postOnlyFilter and comment explicitly what this var does?

@@ -521,6 +522,12 @@ func (k Keeper) PlaceStatefulOrdersFromLastBlock(
}

order := orderPlacement.GetOrder()

// Skip the order if it is a post-only order and we are only placing post-only orders.
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: comment could be more accurate/complete - right now it just describes one of the two scenarios

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (4)
protocol/x/clob/memclob/memclob.go (2)

878-885: Improve comment clarity for postOnlyFilter parameter

Consider rephrasing the comment to enhance clarity. For example:

"This function now accepts a postOnlyFilter parameter. When true, it places post-only orders; when false, it places non-post-only orders."


930-934: Consider reducing code duplication in filtering logic

The filtering logic for postOnlyFilter is repeated in multiple places. To improve maintainability and reduce code duplication, consider extracting this logic into a helper function.

Also applies to: 1025-1029, 1083-1087

protocol/x/clob/keeper/orders_test.go (2)

2267-2273: Fix grammatical error in test description

In the test description, change "does not places non-PO stateful orders when postOnlyFilter = true" to "does not place non-PO stateful orders when postOnlyFilter = true" for correct grammar.


2274-2280: Fix grammatical error in test description

In the test description, change "does not places PO stateful orders from last block, when postOnlyFilter = false" to "does not place PO stateful orders from last block when postOnlyFilter = false" to correct the grammar.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 498f72a and 73add8f.

📒 Files selected for processing (5)
  • protocol/mocks/MemClob.go (1 hunks)
  • protocol/x/clob/keeper/orders.go (5 hunks)
  • protocol/x/clob/keeper/orders_test.go (2 hunks)
  • protocol/x/clob/memclob/memclob.go (4 hunks)
  • protocol/x/clob/types/memclob.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • protocol/x/clob/types/memclob.go
  • protocol/mocks/MemClob.go
🔇 Additional comments (3)
protocol/x/clob/keeper/orders.go (2)

490-492: Enhance comment to cover both scenarios

The comment currently describes one scenario. To improve completeness, rephrase it to explicitly state both scenarios:

"This function takes a postOnlyFilter parameter and places post-only orders when postOnlyFilter is true, and non-post-only orders when postOnlyFilter is false."


625-630: Code logic appears correct for postOnlyFilter usage

The call to PlaceStatefulOrdersFromLastBlock with postOnlyFilter correctly filters orders based on their post-only status.

protocol/x/clob/keeper/orders_test.go (1)

2251-2353: Test cases effectively validate postOnlyFilter functionality

The added test cases in TestPlaceStatefulOrdersFromLastBlock_PostOnly comprehensively validate the behavior of the postOnlyFilter parameter for both post-only and non-post-only orders.

@jayy04 jayy04 merged commit b062a1c into main Dec 2, 2024
21 checks passed
@jayy04 jayy04 deleted the jy/ct-1327 branch December 2, 2024 18:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

3 participants