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 indexer purchase data #277

Merged
merged 1 commit into from
Oct 7, 2024
Merged

Fix indexer purchase data #277

merged 1 commit into from
Oct 7, 2024

Conversation

starknetdev
Copy link
Member

@starknetdev starknetdev commented Oct 7, 2024

Bug presented where a double G20 upgrade presents a market larger than the one produced from VRF.

To fix, the indexer should always store the xp, greatness and special data when an item is purchased and not solely rely on the UpgradesAvailable market data.

Summary by CodeRabbit

  • New Features
    • Introduced new event types for item management: DISCOVERED_LOOT and EQUIPMENT_CHANGED.
    • Added utility functions for parsing new events.
  • Enhancements
    • Improved item processing logic to handle new events and ensure accurate data structure.
    • Default values for item properties are now set upon creation or updates.
  • Bug Fixes
    • Adjusted handling of the UPGRADES_AVAILABLE case for correct item processing.

Copy link

vercel bot commented Oct 7, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
loot-survivor ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 0:18am

Copy link

coderabbitai bot commented Oct 7, 2024

Walkthrough

The changes primarily affect the indexer/src/items.ts file, where the import statements have been reordered, and new constants and utility functions have been introduced. New event types, DISCOVERED_LOOT and EQUIPMENT_CHANGED, have been added, along with their respective parsing functions. The event handling logic has been updated to set default properties for item entities and to ensure proper processing of these new events. Additionally, the UPGRADES_AVAILABLE case has been modified, and the timestamp property is now consistently set during updates.

Changes

File Change Summary
indexer/src/items.ts Reordered import statements; added constants and utility functions; introduced new event types and parsing functions; updated event handling logic for item properties and timestamp.
./utils/events.ts Added methods: parseDiscoveredLoot and parseEquipmentChanged.

Poem

In the land of code where bunnies play,
New events hop in, brightening the day.
Loot discovered, equipment changed,
With each little tweak, our game is rearranged.
So let’s celebrate with a joyful cheer,
For every new feature brings us near! 🐇✨


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@starknetdev starknetdev merged commit 9a83858 into main Oct 7, 2024
9 checks passed
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: 1

🧹 Outside diff range and nitpick comments (3)
indexer/src/items.ts (3)

Line range hint 168-184: Ensure consistent initialization of item properties across events

In the EQUIPMENT_CHANGED event handler, properties like xp, greatness, special1, special2, and special3 are set to null. In other handlers such as PURCHASED_ITEMS, these properties are initialized to 0 or 1. This inconsistency can lead to issues if downstream processes expect these properties to be of a specific type (e.g., number). Ensure that item properties are initialized consistently across all event handlers.


Line range hint 90-100: Handle potential errors when parsing event data

When parsing event data in each case, errors might occur due to unexpected data formats or missing fields. Consider adding error handling to manage exceptions thrown by parsing functions like parsePurchasedItems or parseEquipmentChanged to prevent the indexer from crashing.

Apply this diff to add try-catch blocks around parsing functions:

-case PURCHASED_ITEMS: {
-  const { value } = parsePurchasedItems(event.data, 0);
+case PURCHASED_ITEMS: {
+  let value;
+  try {
+    ({ value } = parsePurchasedItems(event.data, 0));
+  } catch (error) {
+    console.error("Error parsing PURCHASED_ITEMS event:", error);
+    return [];
+  }

Repeat similar patterns for other event cases as needed.


Event filter is missing some event keys.

Ensure that the following event keys are included in the filter to prevent missing crucial data during event processing:

  • DISCOVERED_HEALTH
  • DISCOVERED_GOLD
  • DISCOVERED_BEAST
  • AMBUSHED_BY_BEAST
  • ATTACKED_BEAST
  • ATTACKED_BY_BEAST
  • ADVENTURER_DIED
  • FLEE_FAILED
  • FLEE_SUCCEEDED
  • NEW_HIGH_SCORE
  • REWARD_DISTRIBUTION
  • RECEIVED_LEVEL_SEED
  • NEW_COLLECTION_TOTAL
  • TRANSFER
  • CLAIMED_FREE_GAME
🔗 Analysis chain

Line range hint 56-68: Confirm inclusion of all relevant events in the filter

The filter object has been updated to include new events like DISCOVERED_LOOT and EQUIPMENT_CHANGED. Ensure that all events relevant to item updates are included in the filter to prevent missing any crucial data during event processing.

Run the following script to list all event keys defined in ./utils/events.ts and compare them with those included in the filter:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: List all event keys and compare with filter inclusion.

# Extract event keys from events.ts
rg --type ts "export const .* = .*;" utils/events.ts | awk '{print $3}' > all_event_keys.txt

# Extract event keys from filter in items.ts
rg --type ts "keys: \[.*\]" indexer/src/items.ts | sed 's/.*keys: \[\(.*\)\].*/\1/' | tr ',' '\n' | sed 's/ //g' > filter_event_keys.txt

# Compare the two lists
echo "Event keys not included in filter:"
comm -23 <(sort all_event_keys.txt) <(sort filter_event_keys.txt)

Length of output: 4728


Script:

#!/bin/bash
# Description: List all event keys and compare with filter inclusion.

# Extract event keys from events.ts
rg --type ts "export const .* = .*;" utils/events.ts | awk '{print $3}' > all_event_keys.txt
if [ $? -ne 0 ]; then
  echo "Failed to extract event keys from utils/events.ts"
  exit 1
fi

# Extract event keys from filter in items.ts
rg --type ts "keys:\s*\[.*\]" indexer/src/items.ts | sed 's/.*keys:\s*\[\(.*\)\].*/\1/' | tr ',' '\n' | sed 's/ //g' > filter_event_keys.txt
if [ $? -ne 0 ]; then
  echo "Failed to extract filter event keys from indexer/src/items.ts"
  exit 1
fi

# Check if comm is available
if command -v comm >/dev/null 2>&1; then
  # Compare the two lists
  echo "Event keys not included in filter:"
  comm -23 <(sort all_event_keys.txt) <(sort filter_event_keys.txt)
else
  # Alternative comparison using grep
  echo "comm command not found. Using grep for comparison."
  sort all_event_keys.txt > sorted_all_event_keys.txt
  sort filter_event_keys.txt > sorted_filter_event_keys.txt
  grep -Fxv -f sorted_filter_event_keys.txt sorted_all_event_keys.txt
fi

Length of output: 536


Script:

#!/bin/bash
# Description: Locate all events.ts files in the repository.

# Search for all files named events.ts
fd --type f --extension ts 'events.ts'

# Alternatively, using rg if fd is not available
if ! command -v fd >/dev/null 2>&1; then
  rg --files -g 'events.ts'
fi

Length of output: 184


Script:

#!/bin/bash
# Description: List all event keys from indexer/src/utils/events.ts and compare with filter inclusion in indexer/src/items.ts.

# Extract event keys from indexer/src/utils/events.ts
rg --type ts "export const .* = .*;" indexer/src/utils/events.ts | awk '{print $3}' > all_event_keys.txt
if [ $? -ne 0 ]; then
  echo "Failed to extract event keys from indexer/src/utils/events.ts"
  exit 1
fi

# Extract event keys from filter in indexer/src/items.ts
rg --type ts "keys:\s*\[.*\]" indexer/src/items.ts | sed 's/.*keys:\s*\[\(.*\)\].*/\1/' | tr ',' '\n' | sed 's/ //g' > filter_event_keys.txt
if [ $? -ne 0 ]; then
  echo "Failed to extract filter event keys from indexer/src/items.ts"
  exit 1
fi

# Compare the two lists using grep to find event keys not included in the filter
echo "Event keys not included in filter:"
grep -Fxv -f filter_event_keys.txt all_event_keys.txt

Length of output: 621

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 925def0 and dd09113.

📒 Files selected for processing (1)
  • indexer/src/items.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
indexer/src/items.ts (2)

Line range hint 320-324: Potential missing updates to item availability in 'ADVENTURER_UPGRADED' event

In the ADVENTURER_UPGRADED event handler, the isAvailable property is set to false for items. However, the items associated with the adventurer might need to update other properties such as xp, greatness, or specials to reflect the upgrade. Verify if additional updates are required to accurately represent the adventurer's upgraded state.

Would you like assistance in determining the necessary updates for the items during an adventurer upgrade?


Line range hint 243-258: Review the use of 'ownerAddress' and 'purchasedTime' in 'UPGRADES_AVAILABLE' event

In the UPGRADES_AVAILABLE event handler, ownerAddress is set to 0, and purchasedTime is set to 0. In other events, when an item is not owned, ownerAddress is often set to null or omitted, and purchasedTime is set to null or the current timestamp. Setting ownerAddress to 0 might not accurately represent the absence of an owner and could cause confusion or errors in data processing.

Run the following script to check how ownerAddress and purchasedTime are set across different event handlers:

Comment on lines +137 to +142
xp: 0,
greatness: 1,
special1: 0,
special2: 0,
special3: 0,
isAvailable: false,
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring repeated item initialization into a helper function

The initialization of item properties like xp, greatness, special1, special2, special3, and isAvailable is repeated across multiple event handlers (PURCHASED_ITEMS, EQUIPMENT_CHANGED, DISCOVERED_LOOT). Refactoring this repeated code into a helper function will improve maintainability and reduce potential errors from inconsistent values.

Apply this diff to create a helper function for item initialization:

+function initializeItemProperties(itemId, adventurerId, ownerAddress, equipped, isAvailable) {
+  return {
+    item: checkExistsInt(itemId),
+    adventurerId: checkExistsInt(parseInt(adventurerId)),
+    owner: true,
+    equipped: equipped,
+    tier: gameData.ITEM_TIERS[itemId],
+    slot: gameData.ITEM_SLOTS[itemId],
+    type: gameData.ITEM_TYPES[itemId],
+    ownerAddress: checkExistsInt(BigInt(ownerAddress).toString(16)),
+    xp: 0,
+    greatness: 1,
+    special1: 0,
+    special2: 0,
+    special3: 0,
+    isAvailable: isAvailable,
+    purchasedTime: isAvailable ? null : new Date().toISOString(),
+    timestamp: new Date().toISOString(),
+  };
+}

Then replace the repeated initialization code in event handlers with calls to this function:

-// Existing initialization code in PURCHASED_ITEMS
-{
-  item: checkExistsInt(item.item.id),
-  adventurerId: checkExistsInt(parseInt(as.adventurerId)),
-  owner: true,
-  equipped: false,
-  tier: gameData.ITEM_TIERS[item.item.id],
-  slot: gameData.ITEM_SLOTS[item.item.id],
-  type: gameData.ITEM_TYPES[item.item.id],
-  ownerAddress: checkExistsInt(BigInt(as.owner).toString(16)),
-  xp: 0,
-  greatness: 1,
-  special1: 0,
-  special2: 0,
-  special3: 0,
-  isAvailable: false,
-  purchasedTime: new Date().toISOString(),
-  timestamp: new Date().toISOString(),
-},
+// Refactored code using the helper function
+initializeItemProperties(
+  item.item.id,
+  as.adventurerId,
+  as.owner,
+  false,
+  false
+),

Committable suggestion was skipped due to low confidence.

@starknetdev starknetdev deleted the fix/purchase-data branch October 7, 2024 16:33
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