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

Orderbook Fills emission #1448

Merged
merged 12 commits into from
May 8, 2024
Merged

Orderbook Fills emission #1448

merged 12 commits into from
May 8, 2024

Conversation

jonfung-dydx
Copy link
Contributor

@jonfung-dydx jonfung-dydx commented Apr 30, 2024

Emit orderbook fills through grpc stream.

Tested via
https://github.com/dydxprotocol/v4-chain/pull/1471/commits

@jonfung-dydx jonfung-dydx changed the base branch from main to jonfung/streamFillsV2 April 30, 2024 18:30
Copy link
Contributor

coderabbitai bot commented Apr 30, 2024

Walkthrough

The recent updates focus on enhancing the orderbook streaming functionalities within a protocol. Key modifications include adding detailed comments, introducing new interfaces for orderbook updates and fills, and implementing methods across various components to handle these updates efficiently. The changes aim to streamline the process of sending and managing orderbook fills through gRPC streams, improving the robustness and clarity of the system's data handling capabilities.

Changes

File Path Change Summary
.../v4-protos/src/codegen/dydxprotocol/clob/query.rpc.Query.ts Added detailed comment to streamOrderbookUpdates method.
.../v4-protos/src/codegen/dydxprotocol/clob/query.ts New interfaces for orderbook updates and fills; modified response structure.
proto/dydxprotocol/clob/query.proto Added new GRPC messages for stream updates and fills.
protocol/mocks/MemClobKeeper.go, protocol/mocks/PricesKeeper.go, .../grpc/grpc_streaming_manager.go, .../grpc/noop_streaming_manager.go, .../grpc/types/manager.go, .../testutil/memclob/keeper.go, .../x/clob/keeper/keeper.go, .../x/clob/types/mem_clob_keeper.go Added or modified functions for sending orderbook fill updates.
protocol/x/clob/memclob/memclob.go, protocol/x/clob/memclob/memclob_grpc_streaming.go Added logic and methods for generating and sending orderbook fills.
protocol/x/clob/types/operations_to_propose.go Modified method to handle operations queue with new return types and parameters.

This table groups files with similar changes to provide a concise overview of the modifications made across the system.


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:

Note: Auto-reply has been disabled for this repository by the repository owner. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

Comment on lines +522 to +526
func (f *FakeMemClobKeeper) SendOrderbookFillUpdates(
ctx sdk.Context,
orderbookFills []types.StreamOrderbookFill,
) {
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The method SendOrderbookFillUpdates is currently empty.

This method is defined but does not contain any implementation. If this is intentional (e.g., for a mock or placeholder), it should be documented clearly. Otherwise, it should be implemented or removed if not needed.

Comment on lines 389 to 402
internalOperation := m.operationsToPropose.MustAddMatchToOperationsQueue(takerOrder, makerFillWithOrders)
// If orderbook updates are on, send an orderbook update with the fill to grpc streams.
if m.generateOrderbookUpdates {
clobMatch := internalOperation.GetMatch()
orderbookMatchFill := m.GenerateStreamOrderbookFill(ctx, *clobMatch, takerOrder, makerFillWithOrders)
m.clobKeeper.SendOrderbookFillUpdates(ctx, []types.StreamOrderbookFill{orderbookMatchFill})
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The changes from lines 389 to 395 introduce a new logic to send orderbook updates with fills to GRPC streams if orderbook updates are enabled. This is a significant change as it directly affects how orderbook fills are communicated to external systems.

- internalOperation := m.operationsToPropose.MustAddMatchToOperationsQueue(takerOrder, makerFillWithOrders)
+ internalOperation, err := m.operationsToPropose.MustAddMatchToOperationsQueue(takerOrder, makerFillWithOrders)
+ if err != nil {
+     return nil, err
+ }

Ensure that errors from MustAddMatchToOperationsQueue are handled appropriately to prevent potential issues during order matching.


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
internalOperation := m.operationsToPropose.MustAddMatchToOperationsQueue(takerOrder, makerFillWithOrders)
// If orderbook updates are on, send an orderbook update with the fill to grpc streams.
if m.generateOrderbookUpdates {
clobMatch := internalOperation.GetMatch()
orderbookMatchFill := m.GenerateStreamOrderbookFill(ctx, *clobMatch, takerOrder, makerFillWithOrders)
m.clobKeeper.SendOrderbookFillUpdates(ctx, []types.StreamOrderbookFill{orderbookMatchFill})
}
internalOperation, err := m.operationsToPropose.MustAddMatchToOperationsQueue(takerOrder, makerFillWithOrders)
if err != nil {
return nil, err
}
// If orderbook updates are on, send an orderbook update with the fill to grpc streams.
if m.generateOrderbookUpdates {
clobMatch := internalOperation.GetMatch()
orderbookMatchFill := m.GenerateStreamOrderbookFill(ctx, *clobMatch, takerOrder, makerFillWithOrders)
m.clobKeeper.SendOrderbookFillUpdates(ctx, []types.StreamOrderbookFill{orderbookMatchFill})
}

@jonfung-dydx jonfung-dydx force-pushed the jonfung/checkTxFills branch from b6f3203 to ea262ba Compare April 30, 2024 20:01
@jonfung-dydx jonfung-dydx force-pushed the jonfung/checkTxFills branch from ea262ba to 9c34203 Compare April 30, 2024 20:17
@jonfung-dydx jonfung-dydx changed the title Orderbook Fills checkTx fills emission Orderbook Fills emission May 1, 2024
@jonfung-dydx jonfung-dydx requested a review from jayy04 May 7, 2024 03:07
@@ -174,45 +174,6 @@ func PrepareCheckState(
offchainUpdates,
)

// For orders that are filled in the last block, send an orderbook update to the grpc streams.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Axed this whole section to send out order updates.
Reason being:

  • PCS check state is set to deliver state, so no additional updates are needed.
  • since fills are directly emitted immediately on orderbook update, matched orders don't need to be updated

@@ -276,6 +276,19 @@ func (k Keeper) RemoveOrderFillAmount(ctx sdk.Context, orderId types.OrderId) {
[]byte(types.OrderAmountFilledKeyPrefix),
)
memStore.Delete(orderId.ToStateKey())

// If grpc stream is on, zero out the fill amount.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Zero'ing out fill amounts when fill amounts are removed. I added this to the innermost statewrite/remove method. I could have added it to each of the 3-4 callsites but this might be cleaner. Let me know if the other approach is preferred.

}
}
k.SendOrderbookUpdates(ctx, allUpdates, false)
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

No need since this zero'ing out fills is punted to the innermost state remove method

@@ -141,6 +141,63 @@ func (sm *GrpcStreamingManagerImpl) SendOrderbookUpdates(
}
}

// SendOrderbookFillUpdates groups fills by their clob pair ids and
// sends messages to the subscribers.
func (sm *GrpcStreamingManagerImpl) SendOrderbookFillUpdates(
Copy link
Contributor

Choose a reason for hiding this comment

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

similar looking functions - worth to create helper?

nbd - will let you make the call

orderId := shortTermOrderPlacement.GetOrder().OrderId
orderIdSet[orderId] = struct{}{}
}
if clobMatch := operation.GetMatch(); clobMatch != nil {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added all the order ids involved in a match, but technically there were no errors in dev without this statement.
I think technically we can remove this since I think it's an invariant that every short term order Id that shows up in the any opqueue matches must appear before as a short term order placement. Additionally, there would be no short term order placements that show up without being involved in a match.

What do you think?

// If grpc streams are on, send absolute fill amounts from local + proposed opqueue to the grpc stream.
// This must be sent out to account for checkState being discarded and deliverState being used.
if streamingManager := k.GetGrpcStreamingManager(); streamingManager.Enabled() {
localValidatorOperationsQueue, _ := k.MemClob.GetOperationsToReplay(ctx)
Copy link
Contributor Author

@jonfung-dydx jonfung-dydx May 7, 2024

Choose a reason for hiding this comment

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

Venn diagram. Update both proposed and local. I believe we need both.

streamingManager.SendOrderbookFillUpdates(
ctx,
[]types.StreamOrderbookFill{
streamOrderbookFill,
Copy link
Contributor Author

@jonfung-dydx jonfung-dydx May 7, 2024

Choose a reason for hiding this comment

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

DeliverTx send fills out.

m.operationsToPropose.MustAddMatchToOperationsQueue(takerOrder, makerFillWithOrders)
internalOperation := m.operationsToPropose.MustAddMatchToOperationsQueue(takerOrder, makerFillWithOrders)
// If orderbook updates are on, send an orderbook update with the fill to grpc streams.
if m.generateOrderbookUpdates {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Optimistic fill emission for any matches that occur on this validator

updates := m.GetOrderbookUpdatesForOrderUpdate(ctx, fill.MakerOrderId)
allUpdates.Append(updates)
}
m.clobKeeper.SendOrderbookUpdates(ctx, allUpdates, false)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removing this didn't trigger any errors, but i think we still should have this -- It makes sense that we need to reset fill amounts if state was discarded.

2 qns

  • do we need to reset anything else other than the order ids in the fills?
  • do we need to reset orderbook placements for your side of streaming?

Copy link
Contributor

Choose a reason for hiding this comment

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

  1. I don't think so? think we only persist fills, right? other info (rewards, fees, etc) are irrelevent
  2. no - because orderbook updates are persisted and not reverted even with failed placement

Base automatically changed from jonfung/streamFillsV2 to main May 7, 2024 18:09
// If grpc streams are on, send absolute fill amounts from local + proposed opqueue to the grpc stream.
// This must be sent out to account for checkState being discarded and deliverState being used.
if streamingManager := k.GetGrpcStreamingManager(); streamingManager.Enabled() {
localValidatorOperationsQueue, _ := k.MemClob.GetOperationsToReplay(ctx)
Copy link
Contributor

Choose a reason for hiding this comment

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

so one issue that I just thought of is we are probably going to enable optimistic block execution in the near term, which means that the whole FinalizedBlock will be done in a separate go routine. Accessing k.MemClob here (and in other deliver state ABCI callbacks) is dangerous and can potentially lead to race conditions.

are there any alternatives here?

Copy link
Contributor

Choose a reason for hiding this comment

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

we can merge to unblock first, but should prob keep this in mind. grpc streams and OE might not co-exist

@jonfung-dydx jonfung-dydx merged commit cffdb5f into main May 8, 2024
17 checks passed
@jonfung-dydx jonfung-dydx deleted the jonfung/checkTxFills branch May 8, 2024 19:11
jonfung-dydx added a commit that referenced this pull request May 13, 2024
* new protos

* fix prev use case

* proto lint

* emit stream fills when clob match appended to opqueue

* more explicit function signature

* uint32 -> 64

* deliverTx process opqueue clob match emissions

* bugfixes from feature branch to emit fill amounts correctly

* pr comments

* fix tests

* fixup sample pregenesis json
@jonfung-dydx
Copy link
Contributor Author

@Mergifyio backport release/protocol/v4.1.x

Copy link
Contributor

mergify bot commented May 21, 2024

backport release/protocol/v4.1.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request May 21, 2024
* new protos

* fix prev use case

* proto lint

* emit stream fills when clob match appended to opqueue

* more explicit function signature

* uint32 -> 64

* deliverTx process opqueue clob match emissions

* bugfixes from feature branch to emit fill amounts correctly

* pr comments

* fix tests

* fixup sample pregenesis json

(cherry picked from commit cffdb5f)

# Conflicts:
#	protocol/mocks/PricesKeeper.go
#	protocol/scripts/genesis/sample_pregenesis.json
#	protocol/x/clob/memclob/memclob_purge_invalid_memclob_state_test.go
jonfung-dydx added a commit that referenced this pull request May 21, 2024
* new protos

* fix prev use case

* proto lint

* emit stream fills when clob match appended to opqueue

* more explicit function signature

* uint32 -> 64

* deliverTx process opqueue clob match emissions

* bugfixes from feature branch to emit fill amounts correctly

* pr comments

* fix tests

* fixup sample pregenesis json
jonfung-dydx added a commit that referenced this pull request May 21, 2024
Co-authored-by: Jonathan Fung <121899091+jonfung-dydx@users.noreply.github.com>
Co-authored-by: Jonathan Fung <jonathan@dydx.exchange>
jonfung-dydx added a commit that referenced this pull request May 31, 2024
* new protos

* fix prev use case

* proto lint

* emit stream fills when clob match appended to opqueue

* more explicit function signature

* uint32 -> 64

* deliverTx process opqueue clob match emissions

* bugfixes from feature branch to emit fill amounts correctly

* pr comments

* fix tests

* fixup sample pregenesis json
jonfung-dydx added a commit that referenced this pull request Jun 3, 2024
…#1473) (#1610)

Co-authored-by: Jonathan Fung <121899091+jonfung-dydx@users.noreply.github.com>
Co-authored-by: Jonathan Fung <jonathan@dydx.exchange>
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.

2 participants