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

Fix vault orderbook flickering #1638

Closed
wants to merge 21 commits into from

Conversation

chenyaoy
Copy link
Contributor

@chenyaoy chenyaoy commented Jun 6, 2024

Changelist

  1. Make the vault orders cancelled and place in each block have the same order IDs
  2. If a vault replacement order has the same price as before, don't send an order removal message to Indexer

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

    • Improved order handling with new parameters for internal orders.
    • Enhanced logging and verification in order placement tests.
  • Bug Fixes

    • Fixed issues with vault order handling to ensure correct replacement of cancelled orders.
  • Tests

    • Updated test cases to reflect changes in order handling and logging expectations.

Copy link
Contributor

coderabbitai bot commented Jun 6, 2024

Walkthrough

The recent updates introduce new parameters and logic adjustments across various components, focusing on internal order handling, event management, and test enhancements. Key changes include adding parameters for internal orders, updating event manager integrations, refining order placement and cancellation logic, and enhancing test cases for better validation.

Changes

File(s) Change Summary
.github/workflows/indexer-build-and-push-dev-staging.yml Added a trigger for the branch chenyao/fix-vault-orderbook-flickering.
indexer/packages/redis/src/scripts/place_order.lua Changed value from _false to _true in the place_order.lua script.
indexer/services/vulcan/__tests__/handlers/order-place-handler.test.ts Updated expectedPriceLevelQuantums calculation, adjusted quantums field, and added log message verification.
indexer/services/vulcan/src/handlers/order-place-handler.ts Added imports and new methods to the OrderPlaceHandler class.
protocol/app/app.go Added app.IndexerEventManager parameter to the New function call.
protocol/mocks/ClobKeeper.go Updated HandleMsgCancelOrder to include a boolean parameter isInternalOrder.
protocol/testutil/keeper/vault.go Added IndexerEventManager to createVaultKeeper function arguments.
protocol/x/clob/keeper/msg_server_cancel_orders.go Added isInternalOrder parameter to HandleMsgCancelOrder function in the Keeper struct.
protocol/x/clob/keeper/msg_server_place_order.go Updated logic to handle vault orders replacing cancelled orders with the same order ID.
protocol/x/clob/keeper/msg_server_place_order_test.go Modified test case descriptions to indicate success for placing an internal order already cancelled.
protocol/x/clob/types/clob_keeper.go Added isInternalOrder parameter to HandleMsgCancelOrder method in the ClobKeeper interface.
protocol/x/vault/keeper/keeper.go Added indexerEventManager field to Keeper struct and GetIndexerEventManager() method.
protocol/x/vault/keeper/orders.go Modified logic in RefreshVaultClobOrders and adjusted calculation in GetVaultClobOrderClientId.
protocol/x/vault/keeper/orders_test.go Removed simulation of vault orders placed in the last block and adjusted client ID calculations.
protocol/x/vault/types/expected_keepers.go Added isInternalOrder parameter to HandleMsgCancelOrder function in the ClobKeeper interface.

Poem

🐇
In the code where changes loom,
Internal orders find their room.
Event managers now in place,
Enhancing tests with greater grace.
Vaults refreshed and logic tight,
Our system shines with newfound light.
🌟


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 2

Outside diff range and nitpick comments (2)
protocol/testutil/keeper/vault.go (1)

Line range hint 26-26: Resolve undefined references to initKeepers and GenesisInitializer.

It appears that the initKeepers function and GenesisInitializer type are not defined within this file or the imports. You might need to define these or ensure they are correctly imported if they are located in another part of the codebase.

Also applies to: 32-32, 35-35

indexer/services/vulcan/__tests__/handlers/order-place-handler.test.ts (1)

1090-1094: Ensure consistent logging for error conditions.

The logging for an error condition related to order quantums is handled well. However, consider adding similar detailed logging for other potential error scenarios within the order handling logic to maintain consistency and aid in debugging.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e673b9d and b35da5e.

Files selected for processing (16)
  • .github/workflows/indexer-build-and-push-dev-staging.yml (1 hunks)
  • .github/workflows/protocol-build-and-push.yml (1 hunks)
  • indexer/packages/redis/src/scripts/place_order.lua (1 hunks)
  • indexer/services/vulcan/tests/handlers/order-place-handler.test.ts (2 hunks)
  • indexer/services/vulcan/src/handlers/order-place-handler.ts (4 hunks)
  • protocol/app/app.go (1 hunks)
  • protocol/mocks/ClobKeeper.go (1 hunks)
  • protocol/testutil/keeper/vault.go (1 hunks)
  • protocol/x/clob/keeper/msg_server_cancel_orders.go (3 hunks)
  • protocol/x/clob/keeper/msg_server_place_order.go (2 hunks)
  • protocol/x/clob/keeper/msg_server_place_order_test.go (1 hunks)
  • protocol/x/clob/types/clob_keeper.go (1 hunks)
  • protocol/x/vault/keeper/keeper.go (2 hunks)
  • protocol/x/vault/keeper/orders.go (6 hunks)
  • protocol/x/vault/keeper/orders_test.go (3 hunks)
  • protocol/x/vault/types/expected_keepers.go (1 hunks)
Files skipped from review due to trivial changes (2)
  • .github/workflows/indexer-build-and-push-dev-staging.yml
  • .github/workflows/protocol-build-and-push.yml
Additional context used
golangci-lint
protocol/testutil/keeper/vault.go

26-26: undefined: initKeepers (typecheck)


32-32: undefined: GenesisInitializer (typecheck)


35-35: undefined: GenesisInitializer (typecheck)

Additional comments not posted (17)
protocol/testutil/keeper/vault.go (1)

61-61: Addition of IndexerEventManager to the Keeper constructor aligns with the PR's objectives to enhance order handling.

protocol/x/vault/types/expected_keepers.go (1)

26-26: Addition of isInternalOrder parameter to HandleMsgCancelOrder enhances order handling specificity.

protocol/x/vault/keeper/keeper.go (1)

24-24: The integration of IndexerEventManager into the Keeper structure and its exposure through GetIndexerEventManager method are well-implemented and align with the PR's focus on improving event management.

Also applies to: 37-37, 48-48, 53-55

indexer/packages/redis/src/scripts/place_order.lua (1)

69-69: Changing the order data suffix from _false to _true in place_order.lua script aligns with the PR's objectives to refine order handling and should ensure more accurate order state management.

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

49-49: Parameter addition to HandleMsgCancelOrder method enhances order handling flexibility.

Verification successful

The verification confirms that the isInternalOrder parameter has been correctly integrated into all instances of the HandleMsgCancelOrder method across the relevant files.

  • protocol/x/vault/types/expected_keepers.go
  • protocol/x/vault/keeper/orders.go
  • protocol/x/clob/types/clob_keeper.go
  • protocol/x/clob/keeper/msg_server_cancel_orders.go
  • protocol/mocks/ClobKeeper.go

All instances include the new parameter, ensuring consistent handling of internal and external orders.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration of `isInternalOrder` parameter across the system.

# Test: Search for the method usage. Expect: All usages include the new parameter.
rg --type go $'HandleMsgCancelOrder'

Length of output: 945



Script:

#!/bin/bash
# Verify the integration of `isInternalOrder` parameter in each instance of `HandleMsgCancelOrder`.

# Check `protocol/x/vault/types/expected_keepers.go`
echo "Checking protocol/x/vault/types/expected_keepers.go"
rg --context 5 --type go 'HandleMsgCancelOrder' protocol/x/vault/types/expected_keepers.go

# Check `protocol/x/vault/keeper/orders.go`
echo "Checking protocol/x/vault/keeper/orders.go"
rg --context 5 --type go 'HandleMsgCancelOrder' protocol/x/vault/keeper/orders.go

# Check `protocol/x/clob/types/clob_keeper.go`
echo "Checking protocol/x/clob/types/clob_keeper.go"
rg --context 5 --type go 'HandleMsgCancelOrder' protocol/x/clob/types/clob_keeper.go

# Check `protocol/x/clob/keeper/msg_server_cancel_orders.go`
echo "Checking protocol/x/clob/keeper/msg_server_cancel_orders.go"
rg --context 5 --type go 'HandleMsgCancelOrder' protocol/x/clob/keeper/msg_server_cancel_orders.go

# Check `protocol/mocks/ClobKeeper.go`
echo "Checking protocol/mocks/ClobKeeper.go"
rg --context 5 --type go 'HandleMsgCancelOrder' protocol/mocks/ClobKeeper.go

Length of output: 3174

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

40-40: Enhanced order cancellation handling with isInternalOrder parameter and conditional event emission.

Also applies to: 115-127

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

91-99: Conditional logic for order replacements and event emissions based on isInternalOrder parameter enhances system integrity.

Also applies to: 120-131, 137-148

Verification successful

To ensure the conditional logic based on the isInternalOrder parameter is correctly implemented and behaves as expected, we need to review the implementation of HandleMsgPlaceOrder and its usage in tests.


To ensure the conditional logic based on the isInternalOrder parameter is correctly tested, we need to extract the test cases for HandleMsgPlaceOrder.


The implementation of HandleMsgPlaceOrder includes conditional logic based on the isInternalOrder parameter, and the test cases for this function are present in protocol/x/clob/keeper/msg_server_place_order_test.go. The tests cover scenarios with both true and false values for isInternalOrder, ensuring that the conditional logic is exercised.

  • protocol/x/clob/keeper/msg_server_place_order_test.go:func TestHandleMsgPlaceOrder(t *testing.T)

The test cases confirm that the conditional logic for isInternalOrder is correctly implemented and tested.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the conditional logic of `isInternalOrder` in order replacements and event emissions.

# Test: Search for the method usage with different parameter values. Expect: Correct conditional logic.
rg --type go $'HandleMsgPlaceOrder'

Length of output: 1133



Script:

#!/bin/bash
# Description: Verify the implementation and test coverage of `HandleMsgPlaceOrder` with `isInternalOrder` parameter.

# Extract the implementation of `HandleMsgPlaceOrder`
ast-grep --lang go --pattern $'func (k Keeper) HandleMsgPlaceOrder($_, $_, $_) $_' 

# Extract test cases for `HandleMsgPlaceOrder`
rg --type go 'HandleMsgPlaceOrder(' --context 5

Length of output: 10451



Script:

#!/bin/bash
# Description: Verify the test coverage of `HandleMsgPlaceOrder` with `isInternalOrder` parameter.

# Extract test cases for `HandleMsgPlaceOrder`
rg --type go 'HandleMsgPlaceOrder\(' --context 5

Length of output: 6078

indexer/services/vulcan/src/handlers/order-place-handler.ts (1)

171-231: Addition of updatePriceLevel method enhances dynamic price level adjustments based on order placements.

Verification successful

The updatePriceLevel method is well-integrated and tested across multiple files, ensuring its functionality and behavior are validated.

  • indexer/services/vulcan/src/handlers/order-place-handler.ts
  • indexer/services/vulcan/src/handlers/order-update-handler.ts
  • indexer/services/vulcan/src/handlers/order-remove-handler.ts
  • Various test files in indexer/services/vulcan/__tests__ and indexer/packages/redis/__tests__
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the integration and behavior of `updatePriceLevel` method.

# Test: Search for the method usage. Expect: Correct integration and behavior.
rg --type ts $'updatePriceLevel'

Length of output: 11743

protocol/x/vault/keeper/orders.go (3)

10-11: LGTM! Good use of logging for error handling and conditions to skip unnecessary operations.

Also applies to: 31-31


375-377: LGTM! The function is well-documented and handles errors appropriately.


87-89: Verify the use of isInternalOrder flag across the system.

Also applies to: 93-97, 110-111, 121-122, 123-124, 125-126, 127-128, 129-130, 131-132, 133-134, 135-136, 137-138, 139-140, 141-142, 143-144, 145-146, 147-148

Verification successful

The isInternalOrder flag is used consistently across multiple files in the system. Here are the relevant locations:

  • protocol/x/vault/types/expected_keepers.go
  • protocol/x/clob/types/clob_keeper.go
  • protocol/x/clob/keeper/msg_server_place_order_test.go
  • protocol/x/clob/keeper/msg_server_cancel_orders.go
  • protocol/x/clob/keeper/msg_server_place_order.go
  • protocol/x/clob/keeper/orders.go
  • protocol/mocks/ClobKeeper.go

The usage appears to be consistent and correctly implemented across these files.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the use of `isInternalOrder` flag across the system.

# Test: Search for the usage of `isInternalOrder` flag. Expect: Consistent usage across all relevant files.
rg --type go $'isInternalOrder'

Length of output: 3199

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

438-438: LGTM! Comprehensive test coverage for various scenarios.

protocol/x/vault/keeper/orders_test.go (4)

Line range hint 1-1: LGTM! The test scenarios in TestRefreshAllVaultOrders are comprehensive and well-structured.


Line range hint 1-1: LGTM! The test scenarios in TestRefreshVaultClobOrders effectively cover both success and error cases.


Line range hint 1-1: LGTM! The test scenarios in TestGetVaultClobOrders are comprehensive and well-structured.


688-716: LGTM! The test scenarios in TestGetVaultClobOrderClientId correctly validate the generation of client IDs using bitwise operations.

protocol/app/app.go (1)

1091-1091: Ensure proper initialization and usage of IndexerEventManager.

Verification successful

The IndexerEventManager is properly initialized and used throughout the application. The initialization is done using indexer_manager.NewIndexerEventManager, and it is utilized in various places within the protocol/app/app.go file and other related files.

  • Initialization in protocol/app/app.go:
    • app.IndexerEventManager = indexer_manager.NewIndexerEventManager(...)
  • Usage in protocol/app/app.go:
    • app.IndexerEventManager.ProduceBlock(ctx)
    • app.IndexerEventManager.SendOnchainData(block)
    • app.IndexerEventManager.ClearEvents(ctx)

The initialization and usage of IndexerEventManager appear to be correctly implemented.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that `IndexerEventManager` is properly initialized and used throughout the application.

# Test: Search for initialization and usage of `IndexerEventManager`.
rg --type go 'IndexerEventManager'

Length of output: 40911

Comment on lines +539 to +546
// After replacing the order the quantums at the price level of the old order should be:
// initial quantums - (old order quantums - old order total filled)
const expectedPriceLevelQuantums: number = (
oldPriceLevelInitialQuantums - (Number(initialOrderToPlace.quantums) - oldOrderTotalFilled)
);
const expectedPriceLevel: PriceLevel = {
humanPrice: expectedRedisOrder.price,
quantums: oldPriceLevelInitialQuantums.toString(),
quantums: expectedPriceLevelQuantums.toString(),
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor to simplify the calculation of expectedPriceLevelQuantums.

The calculation of expectedPriceLevelQuantums can be simplified for better readability. Consider using a helper function to encapsulate the logic, which can also be reused in other tests if needed.

- const expectedPriceLevelQuantums: number = (
-   oldPriceLevelInitialQuantums - (Number(initialOrderToPlace.quantums) - oldOrderTotalFilled)
- );
+ const expectedPriceLevelQuantums: number = calculateNetQuantums(oldPriceLevelInitialQuantums, initialOrderToPlace.quantums, oldOrderTotalFilled);

+ function calculateNetQuantums(initialQuantums, orderQuantums, totalFilled) {
+   return initialQuantums - (Number(orderQuantums) - totalFilled);
+ }
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.

Suggested change
// After replacing the order the quantums at the price level of the old order should be:
// initial quantums - (old order quantums - old order total filled)
const expectedPriceLevelQuantums: number = (
oldPriceLevelInitialQuantums - (Number(initialOrderToPlace.quantums) - oldOrderTotalFilled)
);
const expectedPriceLevel: PriceLevel = {
humanPrice: expectedRedisOrder.price,
quantums: oldPriceLevelInitialQuantums.toString(),
quantums: expectedPriceLevelQuantums.toString(),
// After replacing the order the quantums at the price level of the old order should be:
// initial quantums - (old order quantums - old order total filled)
const expectedPriceLevelQuantums: number = calculateNetQuantums(oldPriceLevelInitialQuantums, initialOrderToPlace.quantums, oldOrderTotalFilled);
function calculateNetQuantums(initialQuantums, orderQuantums, totalFilled) {
return initialQuantums - (Number(orderQuantums) - totalFilled);
}
const expectedPriceLevel: PriceLevel = {
humanPrice: expectedRedisOrder.price,
quantums: expectedPriceLevelQuantums.toString(),

Comment on lines +629 to +638
func (_m *ClobKeeper) HandleMsgCancelOrder(ctx types.Context, msg *clobtypes.MsgCancelOrder, isInternalOrder bool) error {
ret := _m.Called(ctx, msg, isInternalOrder)

if len(ret) == 0 {
panic("no return value specified for HandleMsgCancelOrder")
}

var r0 error
if rf, ok := ret.Get(0).(func(types.Context, *clobtypes.MsgCancelOrder) error); ok {
r0 = rf(ctx, msg)
if rf, ok := ret.Get(0).(func(types.Context, *clobtypes.MsgCancelOrder, bool) error); ok {
r0 = rf(ctx, msg, isInternalOrder)
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The new isInternalOrder parameter is not consistently integrated across all usages of HandleMsgCancelOrder. Please update the following:

  • protocol/x/vault/types/expected_keepers.go: Update the function signature to include the isInternalOrder parameter.
  • protocol/x/clob/types/clob_keeper.go: Update the function signature to include the isInternalOrder parameter.
  • protocol/x/vault/keeper/orders.go: Update the call to HandleMsgCancelOrder to include the isInternalOrder parameter.
Analysis chain

Ensure the new isInternalOrder parameter is integrated correctly across all usages of HandleMsgCancelOrder.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the new parameter `isInternalOrder` is used correctly in all calls to `HandleMsgCancelOrder`.

# Test: Search for the function usage. Expect: All occurrences should pass a boolean argument.
rg --type go $'HandleMsgCancelOrder'

Length of output: 945



Script:

#!/bin/bash
# Description: Verify the function signature and calls for HandleMsgCancelOrder in the identified files.

# Check function signature in expected_keepers.go
echo "Checking expected_keepers.go..."
rg --type go 'HandleMsgCancelOrder' protocol/x/vault/types/expected_keepers.go

# Check function signature and calls in orders.go
echo "Checking orders.go..."
rg --type go 'HandleMsgCancelOrder' protocol/x/vault/keeper/orders.go

# Check function signature in clob_keeper.go
echo "Checking clob_keeper.go..."
rg --type go 'HandleMsgCancelOrder' protocol/x/clob/types/clob_keeper.go

# Check function signature and calls in msg_server_cancel_orders.go
echo "Checking msg_server_cancel_orders.go..."
rg --type go 'HandleMsgCancelOrder' protocol/x/clob/keeper/msg_server_cancel_orders.go

# Check function signature and calls in ClobKeeper.go
echo "Checking ClobKeeper.go..."
rg --type go 'HandleMsgCancelOrder' protocol/mocks/ClobKeeper.go

Length of output: 1268

@chenyaoy chenyaoy closed this Jun 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

1 participant