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: historical events ordering #384

Merged
merged 1 commit into from
Jan 28, 2025
Merged

Conversation

MartianGreed
Copy link
Collaborator

@MartianGreed MartianGreed commented Jan 27, 2025

Closes #

Introduced changes

Checklist

  • Linked relevant issue
  • Updated relevant documentation
  • Added relevant tests
  • Add a dedicated CI job for new examples
  • Performed self-review of the code

Summary by CodeRabbit

  • Patch Updates

    • Updated multiple Dojo Engine packages with minor improvements
    • Enhanced historical events handling and parsing
    • Improved event subscription and data management logic
  • Bug Fixes

    • Fixed ordering of historical events
    • Streamlined event parsing and retrieval processes
  • Performance

    • Simplified event state management
    • Optimized event processing in SDK components

Copy link

coderabbitai bot commented Jan 27, 2025

Walkthrough

This pull request introduces patch updates across multiple Dojo Engine packages, focusing on improvements to historical event handling. The primary changes involve modifying the parseHistoricalEvents function in the SDK, updating how events are parsed and processed. The modifications simplify event retrieval, introduce more flexible event parsing, and add logging capabilities. The changes affect event subscription methods, testing, and how historical events are represented in components.

Changes

File Change Summary
.changeset/neat-moose-press.md Patch updates for multiple Dojo Engine packages
examples/example-vite-react-sdk/src/historical-events.tsx Simplified events state management, changed from 2D to 1D array
packages/sdk/src/__tests__/parseHistoricalEvents.test.ts Added test suite for parseHistoricalEvents and orderKeys functions
packages/sdk/src/experimental/index.ts Updated subscribeEvents method to handle historical events more flexibly
packages/sdk/src/parseHistoricalEvents.ts Significant refactoring of event parsing logic, added logging, modified return type

Possibly related PRs

Poem

🐰 Hop, hop, through events so neat,
Historical data now complete!
Keys sorted with rabbit-like grace,
SDK dancing at lightning pace
Code flows smooth as carrot juice 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

@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 (7)
packages/sdk/src/parseHistoricalEvents.ts (3)

22-25: Consider restricting console logs during production builds.
You appear to be logging the raw historical events (line 23) conditionally via options?.logging, yet line 25 unconditionally logs entities regardless of options.logging. This can clutter production logs or risk unintended data exposure.

 if (options?.logging) {
   console.log("Raw historical events", entities);
+  console.log(entities);
 }
-console.log(entities);

32-33: Avoid excessive debugging logs.
The console.log(model); within the loop can fill the logs excessively. Consider either removing it or selectively restricting it to debug mode.


69-79: Return a new array to avoid side effects.
orderKeys sorts the array in-place. If you want to avoid mutating the input, clone the array first. Otherwise, specify in the docstring that orderKeys mutates the original object reference.

-export function orderKeys(keys: string[]) {
-    keys.sort((a, b) => {
+export function orderKeys(inputKeys: string[]) {
+    const keys = [...inputKeys];
     // existing logic
     return keys;
 }
packages/sdk/src/experimental/index.ts (1)

71-77: Avoid repeated calls to await client.getEventMessages().
Instead of calling await client.getEventMessages(query, historical) twice in the ternary expression, assign the result to a local constant and parse accordingly. This improves clarity and reduces duplication.

 const rawEvents = await client.getEventMessages(query, historical);
 const events = historical
-    ? parseHistoricalEvents<T>(await client.getEventMessages(query, historical))
-    : parseEntities<T>(await client.getEventMessages(query, historical));
+    ? parseHistoricalEvents<T>(rawEvents)
+    : parseEntities<T>(rawEvents);
packages/sdk/src/__tests__/parseHistoricalEvents.test.ts (3)

7-18: Consider adding more specific test assertions.

While the test verifies that the results are equal, it would be more robust to also assert:

  1. The specific ordering of events
  2. The structure of the parsed results

Consider adding these assertions:

 it("should preserve order", () => {
     const res1 = parseHistoricalEvents(
         toriiResultUnsorted as torii.Entities,
         { logging: false }
     );
     const res2 = parseHistoricalEvents(
         toriiResultSorted as torii.Entities,
         { logging: false }
     );

     expect(res1).toEqual(res2);
+    // Verify specific ordering
+    const events1 = Object.keys(res1);
+    expect(events1).toEqual([
+        "dojo_starter-Moved",
+        "dojo_starter-Moved-1",
+        // ... other expected events in order
+    ]);
+    // Verify structure
+    expect(res1["dojo_starter-Moved"]).toHaveProperty("direction");
+    expect(res1["dojo_starter-Moved"]).toHaveProperty("player");
 });

19-35: Consider extracting the repeated entity key to a constant.

The long hex string is repeated and could be made more maintainable.

Apply this refactor:

+const ENTITY_KEY = "0x681d68850e9c98f4383832aa206f00de22040754d6094f7b9a5a6802c25d2a3";
+
 it("should order keys", () => {
     const key1Unsorted = Object.keys(
-        toriiResultUnsorted[
-            "0x681d68850e9c98f4383832aa206f00de22040754d6094f7b9a5a6802c25d2a3"
-        ]
+        toriiResultUnsorted[ENTITY_KEY]
     );
     const key2Sorted = Object.keys(
-        toriiResultSorted[
-            "0x681d68850e9c98f4383832aa206f00de22040754d6094f7b9a5a6802c25d2a3"
-        ]
+        toriiResultSorted[ENTITY_KEY]
     );
     expect(key1Unsorted).not.toEqual(key2Sorted);

38-793: Consider reducing test fixture size and improving maintainability.

The test fixtures are quite large and repetitive. Consider:

  1. Creating helper functions to generate test data
  2. Using a smaller subset of events for testing
  3. Extracting common structures into reusable objects

Here's a suggested approach to reduce duplication:

const createMoveEvent = (direction: "Up" | "Down" | "Right", index?: number) => ({
    [`dojo_starter-Moved${index ? `-${index}` : ""}`]: {
        direction: {
            type: "enum",
            type_name: "Direction",
            value: {
                option: direction,
                value: {
                    type: "tuple",
                    type_name: "()",
                    value: [],
                    key: false,
                }
            },
            key: false,
        },
        player: {
            type: "primitive",
            type_name: "ContractAddress",
            value: "0x013d9ee239f33fea4f8785b9e3870ade909e20a9599ae7cd62c1c292b73af1b7",
            key: true,
        }
    }
});

const toriiResultUnsorted = {
    [ENTITY_KEY]: {
        ...createMoveEvent("Up"),
        ...createMoveEvent("Up", 1),
        // ... other events
    }
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 772e2ee and 257d02a.

📒 Files selected for processing (5)
  • .changeset/neat-moose-press.md (1 hunks)
  • examples/example-vite-react-sdk/src/historical-events.tsx (2 hunks)
  • packages/sdk/src/__tests__/parseHistoricalEvents.test.ts (1 hunks)
  • packages/sdk/src/experimental/index.ts (1 hunks)
  • packages/sdk/src/parseHistoricalEvents.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/neat-moose-press.md
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: check
🔇 Additional comments (4)
packages/sdk/src/parseHistoricalEvents.ts (1)

27-46: Validate the array-based type definition.
The function’s docstring indicates returning StandardizedQueryResult<T>, but it is instantiated as an array [] and populated with spread pushes. Ensure the type definition or docstring alignment is correct (if StandardizedQueryResult<T> is indeed an array type, clarifying that in documentation would help).

examples/example-vite-react-sdk/src/historical-events.tsx (2)

12-12: Ensure the updated array shape is used consistently.
Changing from a 2D to a 1D array simplifies state management. Verify that other logic expecting a nested array of events has been updated accordingly.


85-86: Great simplification of the event rendering logic.
This change eliminates the need for nested indexing and improves readability.

packages/sdk/src/__tests__/parseHistoricalEvents.test.ts (1)

1-5: LGTM! Clean and minimal imports.

The imports are well-organized and include only the necessary dependencies.

@MartianGreed MartianGreed merged commit 87be73b into main Jan 28, 2025
6 checks passed
@MartianGreed MartianGreed deleted the fix/historical-events-order branch January 28, 2025 13:05
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.

1 participant