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

Event fields as key #2280

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open

Conversation

remybar
Copy link
Contributor

@remybar remybar commented Aug 9, 2024

Closes #2228.

Depends on dojoengine/dojo-core#12.

TODO: dojo-core should be removed as it has been moved to dojo-core repo.

Tests

  • Yes
  • No, because they aren't needed
  • No, because I need help

Added to documentation?

  • README.md
  • Dojo Book
  • No documentation needed

Checklist

  • I've formatted my code (scripts/prettier.sh, scripts/rust_fmt.sh, scripts/cairo_fmt.sh)
  • I've linted my code (scripts/clippy.sh, scripts/docs.sh)
  • I've commented my code
  • I've requested a review after addressing the comments

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced event handling in the smart contract framework by marking key fields for several event structures, improving clarity and efficiency in event processing.
    • Introduced a unified Event enum for streamlined event handling in tests, enhancing type safety and modularity.
    • Updated data structure in the event processing functions for improved performance and clarity.
  • Bug Fixes

    • Improved testing accuracy and reliability for various functionalities by ensuring proper ownership handling and enhancing event log assertions.
  • Chores

    • Updated configuration files with new addresses and class hashes, reflecting changes in the deployment environment.

Copy link

coderabbitai bot commented Aug 9, 2024

Walkthrough

Ohayo, sensei! The recent updates to the dojo-core project enhance the world module by refining event handling, ownership management, and data structure categorization. Key changes include using namespace.clone() in the register_namespace function for improved ownership handling, implementing #[key] attributes in event structures for clearer identification, and transitioning to a unified event handling mechanism utilizing an Event enum for better scalability.

Changes

Files Change Summary
crates/dojo-core/src/tests/world.cairo, crates/dojo-core/src/tests/world/resources.cairo Updated event handling logic to use a generalized Event enum, simplifying assertions and enhancing maintainability across various test functions.
crates/dojo-core/src/world/world_contract.cairo Added #[key] attributes to event struct fields, improving key identification for StarkNet events, which optimizes how these are indexed and accessed.
crates/dojo-lang/src/manifest_test_data/compiler_cairo/manifests/dev/base/abis/dojo-world.json, examples/spawn-and-move/manifests/dev/base/dojo-world.toml, examples/spawn-and-move/manifests/dev/deployment/manifest.json Changed multiple fields' kind from "data" to "key", emphasizing their roles as identifiers.
examples/spawn-and-move/manifests/dev/deployment/manifest.json, examples/spawn-and-move/manifests/dev/deployment/manifest.toml Updated class_hash and original_class_hash values, reflecting changes in class identifiers for improved versioning and data integrity.
examples/spawn-and-move/dojo_dev.toml Modified world_address configuration to new hexadecimal addresses, indicating updates in network or environment settings.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Contract
    participant EventLog

    User->>Contract: Call register_namespace(namespace)
    Contract->>Contract: Process namespace
    Contract->>EventLog: Log event with namespace
    EventLog-->>Contract: Event logged
    Contract-->>User: Confirm registration
Loading

Assessment against linked issues

Objective Addressed Explanation
Make fields as keys in events where possible (#[2228])
Improve retrieval of events by reclassifying fields (#[2228])

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e5c4871 and 8ee0ab7.

Files ignored due to path filters (2)
  • spawn-and-move-db.tar.gz is excluded by !**/*.gz
  • types-test-db.tar.gz is excluded by !**/*.gz
Files selected for processing (12)
  • crates/dojo-core/src/world/world_contract.cairo (4 hunks)
  • crates/dojo-lang/src/event.rs (3 hunks)
  • crates/dojo-types/src/event.rs (1 hunks)
  • crates/dojo-world/src/manifest/mod.rs (3 hunks)
  • crates/torii/core/src/processors/event_message.rs (4 hunks)
  • crates/torii/core/src/processors/metadata_update.rs (2 hunks)
  • examples/spawn-and-move/manifests/dev/base/contracts/dojo_examples-actions-40b6994c.toml (1 hunks)
  • examples/spawn-and-move/manifests/dev/base/contracts/dojo_examples-others-61de2c18.toml (1 hunks)
  • examples/spawn-and-move/manifests/dev/deployment/manifest.json (18 hunks)
  • examples/spawn-and-move/manifests/dev/deployment/manifest.toml (5 hunks)
  • examples/spawn-and-move/manifests/release/base/contracts/dojo_examples-actions-40b6994c.toml (1 hunks)
  • examples/spawn-and-move/manifests/release/base/contracts/dojo_examples-others-61de2c18.toml (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • crates/dojo-core/src/world/world_contract.cairo
  • crates/dojo-world/src/manifest/mod.rs
  • examples/spawn-and-move/manifests/dev/deployment/manifest.toml
Additional comments not posted (20)
examples/spawn-and-move/manifests/dev/base/contracts/dojo_examples-others-61de2c18.toml (2)

2-3: LGTM! These changes look solid, sensei.

Assuming the verification checks out, the updates to class_hash and original_class_hash are approved. Nice work on keeping our contract metadata up-to-date!


2-3: Ohayo, sensei! Let's verify these hash updates.

The class_hash and original_class_hash have been updated. We should ensure these new hashes are correct and consistent with the latest contract implementation.

Run this script to check the hash consistency:

Verification successful

Ohayo, sensei! Hash update verified across the codebase.

The new hash 0x25395f6651e97bc6ada3d5de989a1e73cb35f75621097d4e19017c70a285ed6 is consistently updated across multiple TOML files, and the old hash is no longer present. This indicates a comprehensive update. If further verification of the hash's correctness is needed, please consider manual checks.

  • New hash found in:
    • examples/spawn-and-move/manifests/release/base/contracts/dojo_examples-others-61de2c18.toml
    • examples/spawn-and-move/manifests/dev/deployment/manifest.toml
    • examples/spawn-and-move/manifests/dev/base/contracts/dojo_examples-others-61de2c18.toml
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new hash across the codebase

# Test: Search for occurrences of the new hash
rg --type toml "0x25395f6651e97bc6ada3d5de989a1e73cb35f75621097d4e19017c70a285ed6"

# Test: Check if the old hash is still present anywhere
rg --type toml "0x40e824b8814bafef18cce2cf68f5765e9c9a1c86f55a8491b0c2a4faebdcc87"

Length of output: 1164

examples/spawn-and-move/manifests/release/base/contracts/dojo_examples-others-61de2c18.toml (2)

2-3: LGTM! The hash updates look good, sensei.

Assuming the hash updates were intentional and properly tested, the changes look good to me.


2-3: Ohayo, sensei! Verify the intention behind the hash updates.

I noticed that both class_hash and original_class_hash have been updated to the same new value. This change might have significant implications for the contract's behavior and interactions.

Could you confirm if this update was intentional? Also, have you thoroughly tested the contract with these new hash values to ensure everything works as expected?

examples/spawn-and-move/manifests/dev/base/contracts/dojo_examples-actions-40b6994c.toml (1)

2-3: Ohayo, sensei! The hash update looks solid!

The class_hash and original_class_hash have been updated to the same new value. This change is likely intentional and represents a new version of the contract.

Let's make sure this new hash is consistent across the project, sensei:

Verification successful

Ohayo, sensei! The new hash is consistently used across the project, which is a good sign. The update seems intentional and well-applied. If you know the old hash, it might be worth doing a quick manual check to ensure it's fully replaced. Keep up the great work!

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new hash is used consistently across the project.

# Test: Search for the new hash in all files. Expect: Consistent usage of the new hash.
rg --type toml "0x270c8ffb9f92d3711fd67d9842f7519c663ddb17f15ddafd08bfc2aeb7d86d9"

# Test: Search for any occurrences of the old hash (if known). Expect: No occurrences of the old hash.
# Note: Replace <old_hash> with the actual old hash value if known.
# rg --type toml "<old_hash>"

Length of output: 1085

crates/dojo-types/src/event.rs (1)

3-3: Ohayo, sensei! New constant for system event identification.

The addition of SYSTEM_EVENT_SELECTOR looks good. It'll help distinguish system events from others.

Let's check if this constant is used elsewhere in the codebase:

Verification successful

Ohayo, sensei! Constant SYSTEM_EVENT_SELECTOR is well-integrated.

The SYSTEM_EVENT_SELECTOR constant is actively used in the codebase, particularly in event processing logic. Its presence in comments and macros highlights its importance in distinguishing system events.

  • Files using the constant:
    • crates/torii/core/src/processors/event_message.rs
    • crates/dojo-lang/src/event.rs
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for usage of SYSTEM_EVENT_SELECTOR
rg --type rust "SYSTEM_EVENT_SELECTOR"

Length of output: 825

crates/torii/core/src/processors/event_message.rs (1)

3-3: Ohayo, sensei! Nice import addition!

The import of SYSTEM_EVENT_SELECTOR aligns well with the changes in the event_key function. Good job keeping the imports up-to-date!

crates/torii/core/src/processors/metadata_update.rs (1)

60-61: Ohayo again, sensei! The event processing looks updated.

The changes to extracting the resource and URI data align with the new event structure. Good job adapting to the new format!

To ensure system-wide consistency, let's verify that other components interacting with this event data have been updated accordingly. Run this script to check for potential inconsistencies:

This will help identify any other places in the codebase that might need similar updates to maintain consistency with the new event structure.

crates/dojo-lang/src/event.rs (3)

12-12: Ohayo, sensei! New import added for SYSTEM_EVENT_SELECTOR.

The addition of this import aligns with the PR objectives by introducing the system event selector concept.


79-81: Updated comments clarify the purpose of SYSTEM_EVENT_SELECTOR, sensei!

The comments now explain that the first key of a dojo event will be the SYSTEM_EVENT_SELECTOR, which helps distinguish dojo events from starknet events. This aligns with the PR objectives of enhancing event retrieval granularity.


90-91: SYSTEM_EVENT_SELECTOR now appended to keys array, sensei!

This change implements the core functionality described in the updated comments. It ensures that dojo events are uniquely identifiable, which aligns with the PR objectives of treating event fields as keys and improving event retrieval granularity.

Let's verify if this change is consistently applied across the codebase:

examples/spawn-and-move/manifests/dev/deployment/manifest.json (9)

4-5: Ohayo, sensei! New class hash detected for the world contract.

The class_hash and original_class_hash for the world contract have been updated. This suggests a new version of the world contract has been deployed.

Let's make sure this change is intentional and properly propagated:

Verification successful

Ohayo, sensei! The class hash update is consistent across the codebase.

The new class_hash and original_class_hash are consistently used in multiple manifest files, including both development and release configurations, as well as in test data. This suggests that the update was intentional and has been properly propagated throughout the system.

  • examples/spawn-and-move/manifests/dev/deployment/manifest.json
  • examples/spawn-and-move/manifests/dev/deployment/manifest.toml
  • examples/spawn-and-move/manifests/dev/base/dojo-world.toml
  • examples/spawn-and-move/manifests/release/base/dojo-world.toml
  • crates/dojo-lang/src/manifest_test_data/compiler_cairo/manifests/dev/base/dojo-world.toml
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the new class hash is used consistently
rg -i "0x479648c316ee5f9b6999362aa9e72c5cb881ee12e0017559a29025de04a55b6"

Length of output: 1616


769-774: Ohayo! ContractDeployed event got a makeover, sensei!

Multiple fields in the ContractDeployed event have been changed from "data" to "key", and a new salt field has been added. This could significantly impact how contract deployments are tracked and queried.

Let's ensure this change is reflected in the contract deployment logic:

Also applies to: 779-785

Verification successful

Ohayo, sensei! ContractDeployed event changes are all good!

The changes to the ContractDeployed event, including the addition of the salt field and the marking of fields as keys, are correctly reflected in the contract deployment logic and verified by test cases. No issues found.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for ContractDeployed event usage
rg "ContractDeployed" -A 10 -g "*.cairo"

Length of output: 6912


801-801: Key change for ContractUpgraded event, sensei!

The class_hash field in the ContractUpgraded event has been changed from "data" to "key". This could affect how contract upgrades are indexed and queried.

Let's check if this change is consistently applied:

Verification successful

Ohayo, sensei! The class_hash field change is consistently applied.

The class_hash field in the ContractUpgraded event is marked as a key in the source code, specifically in crates/dojo-core/src/world/world_contract.cairo. This confirms the change is applied where it impacts functionality. The JSON files are representations and do not need to reflect the #[key] attribute. No further inconsistencies found.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for ContractUpgraded event usage
rg "ContractUpgraded" -A 5 -g "*.cairo"

Length of output: 3022


Script:

#!/bin/bash
# Search for other definitions or usages of ContractUpgraded in the codebase
rg "ContractUpgraded" -A 5

Length of output: 23734


1906-1908: More contract upgrades detected, sensei!

Two more contracts have had their address, class_hash, and original_class_hash updated. This appears to be a large-scale upgrade of multiple contracts in the system.

We should ensure all these upgrades are coordinated and properly tested:

Also applies to: 2127-2129


847-847: Ohayo, sensei! Multiple events got the key treatment!

The resource field in MetadataUpdate, namespace in NamespaceRegistered, and name and namespace in ModelRegistered events have been changed from "data" to "key". This could significantly impact event indexing and querying across the system.

Let's ensure these changes are consistently applied and handled in the event processing logic:

Also applies to: 864-864, 881-886

Verification successful

Ohayo, sensei! The key changes are consistently applied and handled. The MetadataUpdate, NamespaceRegistered, and ModelRegistered events have been updated with the #[key] attribute, and their usage in the event processing logic confirms that these changes are correctly integrated. The processors validate the keys, ensuring proper handling of these events.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for affected events
rg -e "MetadataUpdate" -e "NamespaceRegistered" -e "ModelRegistered" -A 10 -g "*.cairo"

Length of output: 13609


Script:

#!/bin/bash
# Search for usage of the affected events in the codebase to verify consistent handling
rg -e "MetadataUpdate" -e "NamespaceRegistered" -e "ModelRegistered" -A 10

Length of output: 90466


757-757: Key change for WorldSpawned event, sensei!

The creator field in the WorldSpawned event has been changed from "data" to "key". This could affect event indexing and querying.

Let's check if this change is consistent across the codebase:

Verification successful

Ohayo, sensei! The key change is consistent in the implementation. The creator field in the WorldSpawned event is marked as a key in the Cairo source file, confirming the review comment. The broader impact on indexing and querying would depend on how these files are used with the Cairo implementation. No inconsistencies were found in the references across the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for WorldSpawned event usage
rg "WorldSpawned" -A 5 -g "*.cairo"

Length of output: 1497


Script:

#!/bin/bash
# Search for all occurrences of WorldSpawned event across the codebase
rg "WorldSpawned" -A 5

Length of output: 21329


1232-1233: New world address and transaction hash, sensei!

The address and transaction_hash for the world contract have been updated. This suggests a new deployment of the world contract.

Let's make sure this change is properly reflected in the deployment scripts and any dependent contracts:


945-950: Massive key changes across multiple events, sensei!

Several fields in StoreSetRecord, StoreUpdateRecord, StoreUpdateMember, StoreDelRecord, WriterUpdated, and OwnerUpdated events have been changed from "data" to "key". This is a significant change that could affect how data is indexed and queried throughout the system.

We need to ensure these changes are properly handled in all event listeners and data processors:

Also applies to: 967-972, 989-999, 1016-1021, 1033-1038, 1055-1060

Verification successful

Ohayo, sensei! The key changes are handled properly.

The changes from "data" to "key" in the events StoreSetRecord, StoreUpdateRecord, StoreUpdateMember, StoreDelRecord, WriterUpdated, and OwnerUpdated are managed by specific event processors in the codebase. These processors validate and process the events, ensuring that the system handles them appropriately. No further action is needed.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for affected events
rg -e "StoreSetRecord" -e "StoreUpdateRecord" -e "StoreUpdateMember" -e "StoreDelRecord" -e "WriterUpdated" -e "OwnerUpdated" -A 10 -g "*.cairo"

Length of output: 13452


Script:

#!/bin/bash
# Search for usage of the affected events in the codebase to check for event listeners or data processors
rg -e "StoreSetRecord" -e "StoreUpdateRecord" -e "StoreUpdateMember" -e "StoreDelRecord" -e "WriterUpdated" -e "OwnerUpdated" -A 10

Length of output: 152882


1253-1255: New contract deployment detected, sensei!

The address, class_hash, and original_class_hash for a contract have been updated. This indicates a new version of the contract has been deployed.

Let's ensure this change is intentional and properly handled in the deployment process:


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

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.

Tip

Early access features: enabled

We are currently testing the following features in early access:

  • Anthropic claude-3-5-sonnet for code reviews: Anthropic claims that the new Claude model has stronger code understanding and code generation capabilities than their previous models. Note: Our default code review model was also updated late last week. Please compare the quality of the reviews between the two models by toggling the early access feature.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues on the discussion post.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Thanks for that! The Torii processors must also be updated to ensure they are parsing the data from the keys array, and not data as currently. 👍

@remybar
Copy link
Contributor Author

remybar commented Aug 11, 2024

Thanks for that! The Torii processors must also be updated to ensure they are parsing the data from the keys array, and not data as currently. 👍

Ok !

I've just reported an issue to Starkware about the pop_log function which does not work where an event has a ByteArray field key: starkware-libs/cairo#6186.

@remybar remybar force-pushed the event_fields_as_key branch 4 times, most recently from 2fde18f to 3ee44ce Compare August 12, 2024 12:33
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: 2

Outside diff range, codebase verification and nitpick comments (1)
crates/dojo-world/src/contracts/abi/world.rs (1)

746-746: Ohayo, sensei! Possible ABI Consistency Issue Detected

The change from "data" to "key" is consistently applied in world.rs, but not in executor.rs or model.rs. This could lead to inconsistencies in ABI generation and contract interactions. Please review these files to ensure consistent application of the "kind": "key" change.

  • world.rs: Consistent application found.
  • executor.rs: No occurrences found.
  • model.rs: No occurrences found.
Analysis chain

Ohayo, sensei! Confirm ABI consistency with key changes.

The transition from "data" to "key" in the abigen! macro suggests these fields are now primary references. Verify that ABI generation and contract interactions are consistent with this change to avoid integration issues.

Also applies to: 763-763, 773-773, 778-778, 790-790, 819-819, 836-836, 853-853, 858-858, 917-917, 922-922, 939-939, 944-944, 961-961, 966-966, 971-971, 988-988, 993-993, 1005-1005, 1010-1010, 1027-1027, 1032-1032

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Confirm ABI consistency with `kind` changes from "data" to "key".

# Test: Search for `abigen!` macro usage to ensure ABI consistency.
rg --type rust 'abigen!\('

Length of output: 469


Script:

#!/bin/bash
# Description: Check the usage of `abigen!` macro in specific files to verify the change from "data" to "key".

# Search for `abigen!` macro usage in `world.rs`.
rg --type rust 'abigen!\(' crates/dojo-world/src/contracts/abi/world.rs -A 10

# Search for `abigen!` macro usage in `executor.rs`.
rg --type rust 'abigen!\(' crates/dojo-world/src/contracts/abi/executor.rs -A 10

# Search for `abigen!` macro usage in `model.rs`.
rg --type rust 'abigen!\(' crates/dojo-world/src/contracts/abi/model.rs -A 10

Length of output: 849


Script:

#!/bin/bash
# Description: Verify if the "kind": "key" change is consistently applied in ABI definitions.

# Search for "kind": "key" in `world.rs`.
rg --type rust '"kind": "key"' crates/dojo-world/src/contracts/abi/world.rs

# Search for "kind": "key" in `executor.rs`.
rg --type rust '"kind": "key"' crates/dojo-world/src/contracts/abi/executor.rs

# Search for "kind": "key" in `model.rs`.
rg --type rust '"kind": "key"' crates/dojo-world/src/contracts/abi/model.rs

Length of output: 720

crates/dojo-world/src/manifest/manifest_test.rs Outdated Show resolved Hide resolved
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

Outside diff range, codebase verification and nitpick comments (1)
examples/spawn-and-move/manifests/release/base/abis/dojo-world.json (1)

813-813: Ohayo, sensei! Inconsistent usage of resource as a key.

The resource field is marked as a "key" in some files but remains as "data" in others. Please ensure consistent usage across the codebase to avoid potential issues with resource identification.

  • Check examples/game-lib/armory/manifests/dev/base/abis/dojo-world.json for "kind": "data".
  • Verify other instances where resource is used as "data" to ensure consistency.
Analysis chain

Ohayo, sensei! Verify the resource field usage.

The change from "data" to "key" for the resource field is approved. Ensure that this field is consistently used as a unique identifier throughout the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `resource` as a key.

# Test: Search for the `resource` field usage. Expect: Consistent use as a key.
rg --type json '"resource"' -A 3

Length of output: 26757

Copy link

codecov bot commented Aug 29, 2024

Codecov Report

Attention: Patch coverage is 72.09302% with 48 lines in your changes missing coverage. Please review.

Project coverage is 67.86%. Comparing base (1d95782) to head (8ee0ab7).

Files with missing lines Patch % Lines
...s/torii/core/src/processors/store_update_member.rs 0.00% 16 Missing ⚠️
crates/torii/core/src/processors/event_message.rs 0.00% 15 Missing ⚠️
...s/torii/core/src/processors/store_update_record.rs 0.00% 12 Missing ⚠️
...rates/torii/core/src/processors/metadata_update.rs 0.00% 4 Missing ⚠️
...ates/torii/core/src/processors/store_set_record.rs 94.11% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2280      +/-   ##
==========================================
- Coverage   67.86%   67.86%   -0.01%     
==========================================
  Files         359      359              
  Lines       46959    47003      +44     
==========================================
+ Hits        31869    31898      +29     
- Misses      15090    15105      +15     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

the event messages are not working anymore.

@Larkooo @lambda-0x as we have the event messages processors being a catch all, it will run on every message as we only check the length of the keys.

But as now, most of events have keys, and they contains ByteArray, the length is not longer a good filter.

We end up with this processor being run on all StoreSetRecord etc...

Some solutions we may have:

  1. Blacklist all the world events, which ensure we only process emit! generated events. But this is too bad for Torii performances.
  2. When using emit!, we already happen the system's address, we may also happen a selector!("SystemEvent") before the address. Like so, the event message processor can directly check the -2 position in the array.
  3. We could wrap the system event into a world's event to make the first key (the event selector) the actual SystemEvent.
  4. Something else?

@lambda-0x
Copy link
Collaborator

was just thinking about this yesterday! since we already have ability to add custom key in the event the current behaviour of trying it for every event is slow in performance.

i think 2 and 3 makes sense to me, preferably 3 if possible so we have to just first key for all types of event.

@Larkooo
Copy link
Collaborator

Larkooo commented Aug 30, 2024

the event messages are not working anymore.

@Larkooo @lambda-0x as we have the event messages processors being a catch all, it will run on every message as we only check the length of the keys.

But as now, most of events have keys, and they contains ByteArray, the length is not longer a good filter.

We end up with this processor being run on all StoreSetRecord etc...

Some solutions we may have:

  1. Blacklist all the world events, which ensure we only process emit! generated events. But this is too bad for Torii performances.
  2. When using emit!, we already happen the system's address, we may also happen a selector!("SystemEvent") before the address. Like so, the event message processor can directly check the -2 position in the array.
  3. We could wrap the system event into a world's event to make the first key (the event selector) the actual SystemEvent.
  4. Something else?

Yeah I think blacklisting is not a sustainable solution, so 2 and 3 make the most sense to me. I think it just depends on if its going to be a breaking change or not. I remember when I was working on the event messages we had to follow the same event structure as a normal event for it to also work for the emit!. We need to take that into consideration and also what happens if we index older event messages (old structure) and newer event messages. Seems like we cannot have both

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

Outside diff range, codebase verification and nitpick comments (9)
examples/spawn-and-move/manifests/release/base/contracts/dojo_examples-actions-40b6994c.toml (1)

2-3: Ohayo, sensei! Missing ABI file and incorrect paths detected.

The ABI file for the contract dojo_examples-actions-40b6994c is missing, and the paths specified in the manifest files are incorrect. This could lead to deployment or integration issues.

  • Ensure the ABI file exists and is correctly tracked in the repository.
  • Verify and update the paths in the manifest files to point to the correct ABI file location.
Analysis chain

Ohayo, sensei! New class hash detected. Let's verify its implications.

The class_hash and original_class_hash have been updated to the same value. This suggests a fresh deployment or significant update to the contract.

To ensure this change doesn't introduce unexpected behavior, please run the following script:

This script will help us confirm that the new class hash is consistently used and that any related deployment scripts or ABIs have been updated accordingly.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new class hash and its usage

# Test 1: Check if the new class hash exists in other files
echo "Checking for occurrences of the new class hash:"
rg --type toml "0x270c8ffb9f92d3711fd67d9842f7519c663ddb17f15ddafd08bfc2aeb7d86d9"

# Test 2: Check for any deployment scripts or logs referencing this contract
echo "Checking for deployment scripts or logs:"
rg --type yaml --type sh "dojo_examples-actions-40b6994c"

# Test 3: Verify if there are any changes to the contract's ABI
echo "Checking for changes in the contract's ABI:"
git diff HEAD~1 manifests/release/base/abis/contracts/dojo_examples-actions-40b6994c.json

Length of output: 1785


Script:

#!/bin/bash
# Description: Further investigate the ABI file and other references

# Test 1: Check if the ABI file exists in the repository
echo "Checking for the existence of the ABI file:"
fd 'dojo_examples-actions-40b6994c.json' manifests/release/base/abis/contracts

# Test 2: Search for any other references to the contract in the repository
echo "Searching for other references to the contract:"
rg 'dojo_examples-actions-40b6994c'

Length of output: 1441

crates/torii/core/src/processors/event_message.rs (4)

24-24: Sugoi change to event_key, sensei!

Returning SYSTEM_EVENT_SELECTOR instead of an empty string is a great improvement. It provides a more meaningful event key representation.

Consider using SYSTEM_EVENT_SELECTOR.into() instead of .to_string() for better performance, as it avoids an unnecessary allocation:

-        SYSTEM_EVENT_SELECTOR.to_string()
+        SYSTEM_EVENT_SELECTOR.into()

29-31: Arigatou for the clear comments, sensei!

The updated comments in the validate function greatly improve the understanding of the expected event key structure. Well done!

Consider adding a brief explanation of what SYSTEM_EVENT_SELECTOR represents for developers who might not be familiar with it:

-        // 1: SYSTEM_EVENT_SELECTOR
+        // 1: SYSTEM_EVENT_SELECTOR (identifies system-level events)

51-58: Subarashii error handling, sensei!

The addition of a warning log when the model is not found is a great improvement. It enhances visibility into potential issues during event processing.

Consider including the event_id in the warning log for easier tracing:

                 warn!(
                     target: LOG_TARGET,
                     model = %event.keys[MODEL_INDEX],
+                    event_id = %event_id,
                     "System event model not found."
                 );

67-71: Kakkoii update to keys_and_unpacked, sensei!

Skipping the first two keys aligns well with the updated event structure expectations. Good job on maintaining consistency!

Consider extracting the index calculations into named constants for better readability:

+        const EVENT_SELECTOR_INDEX: usize = 1;
+        const KEYS_START_INDEX: usize = MODEL_INDEX + 1;
+        const SYSTEM_KEY_INDEX: usize = event.keys.len() - 1;
 
-        let mut keys_and_unpacked =
-            [event.keys[MODEL_INDEX + 1..event.keys.len() - 1].to_vec(), event.data.clone()]
-                .concat();
+        let mut keys_and_unpacked = [
+            event.keys[KEYS_START_INDEX..SYSTEM_KEY_INDEX].to_vec(),
+            event.data.clone()
+        ].concat();

This change would make the code more self-documenting and easier to maintain.

crates/torii/core/src/processors/metadata_update.rs (2)

38-39: Ohayo, sensei! The validation looks tighter now.

The change to require exactly two keys aligns well with the expected structure. Nice work!

Consider updating the error log message to reflect this specific requirement:

- "Invalid event keys."
+ "Invalid event keys. Expected exactly 2 keys (selector and resource)."

This will provide more precise information for debugging.


Line range hint 1-168: Ohayo, sensei! Overall, these changes look solid.

The modifications to the MetadataUpdateProcessor reflect a shift in how event data is structured and processed. The validation is now more precise, and the event data extraction has been adjusted accordingly. These changes seem to be part of a broader effort to standardize event handling across the system.

As we move forward with these changes, consider the following:

  1. Ensure that all other event processors in the system are updated to match this new structure.
  2. Update any documentation or comments in other parts of the codebase that describe the event structure.
  3. If there are any external systems or services that interact with these events, make sure they're aware of the changes in the event structure.

These steps will help maintain consistency and prevent potential issues down the line. Keep up the great work, sensei!

examples/spawn-and-move/manifests/dev/deployment/manifest.json (2)

Line range hint 1-2348: Ohayo, sensei! Let's wrap up this massive upgrade!

This manifest update represents a significant overhaul of the system:

  1. Multiple contract upgrades, including the world contract
  2. Extensive changes to event structures, with many fields changing from "data" to "key"
  3. New deployment addresses and transaction hashes

These changes will likely impact event indexing, querying, and overall system behavior.

Consider the following:

  1. Ensure all event listeners and data processors are updated to handle the new event structures
  2. Update any external systems or UIs that rely on the old event formats
  3. Thoroughly test the system to ensure all upgrades are compatible and functioning as expected
  4. Update documentation to reflect these changes, especially regarding event handling and contract addresses

Great work on this upgrade, sensei! Just make sure everything is properly tested and documented.


1667-1669: Ohayo, sensei! It seems that the contract upgrade involving the class_hash 0x4590a27e4ec7366358ba5f60323777f301435ebbdd113ab02c54b947717530d is not explicitly documented in the manifest files. The entries are present across multiple files, but there are no accompanying comments or documentation explaining the upgrade process. You might want to ensure that this upgrade is documented elsewhere or consider adding some comments for clarity.

Analysis chain

Another contract upgrade, sensei!

The address, class_hash, and original_class_hash for another contract have been updated. This suggests multiple contracts are being upgraded in this deployment.

Let's check if this upgrade is properly documented and handled:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the new class hash
rg "0x4590a27e4ec7366358ba5f60323777f301435ebbdd113ab02c54b947717530d"

Length of output: 1386


Script:

#!/bin/bash
# Search for documentation or comments related to the class hash
rg "0x4590a27e4ec7366358ba5f60323777f301435ebbdd113ab02c54b947717530d" -A 5

Length of output: 3623

@glihm
Copy link
Collaborator

glihm commented Sep 3, 2024

@Larkooo should be ok, will let you make your checks and let's move forward if all good.
In a second phase, we will make the adjustment on the event/model separation.

@@ -1,5 +1,7 @@
use starknet::core::types::Felt;

pub const SYSTEM_EVENT_SELECTOR: &str = "SystemEvent__";
Copy link
Collaborator

Choose a reason for hiding this comment

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

Just curious as to why we have that for the event messages? Can't we just do something similar to StoreSetRecord? Like EventMessage and define a wrapper struct?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Hum, we could do something like:

pub struct EventMessage {
    #[keys]
    pub keys: Span<felt252>,
    pub values: Span<felt252>,
}

The problem with that is in the keys we will have the span length. But using a manual selector, we're not injecting the length of the span into the keys, which may break the indexing and query by keys.

// and dont include last key as its the system key
let mut keys_and_unpacked =
[event.keys[1..event.keys.len() - 1].to_vec(), event.data.clone()].concat();
[event.keys[MODEL_INDEX + 1..event.keys.len() - 1].to_vec(), event.data.clone()]
Copy link
Collaborator

Choose a reason for hiding this comment

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

Maybe we should move the event.keys[] to a variable of its own

warn!(
target: LOG_TARGET,
model = %event.keys[MODEL_INDEX],
"System event model not found."
Copy link
Collaborator

Choose a reason for hiding this comment

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

I feel like it might be confusing referring to event messages as SystemEvents and EventMessages. Should we settle on one unique event name?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Ideally as we mentioned during a call, we will actually only have event messages. Which should remove the confusion.
We could switch to Event message and keep this nomenclature yeah. Then I'll complete this PR by restricting events to only be available in Dojo and not using Starknet event, wdyt?

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.

feat(world): make fields as keys in events where possible
4 participants