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

Animations #213

Merged
merged 75 commits into from
Jan 2, 2025
Merged

Animations #213

merged 75 commits into from
Jan 2, 2025

Conversation

okhaimie-dev
Copy link
Contributor

@okhaimie-dev okhaimie-dev commented Dec 31, 2024

Summary by CodeRabbit

  • Dependencies

    • Updated @cartridge/connector from ^0.5.6 to ^0.5.7
    • Updated @cartridge/controller from ^0.5.6 to ^0.5.7
  • Code Improvements

    • Refined code formatting across multiple components
    • Improved readability and consistency in component structures
    • Enhanced error handling and prop management in various components
    • Simplified props and internal logic in the TopPit component
  • Performance

    • Optimized seed rendering and positioning logic
    • Improved memoization of functions using useCallback
    • Enhanced control flow and error handling in game logic

Copy link

vercel bot commented Dec 31, 2024

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

Name Status Preview Comments Updated (UTC)
mancala ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 2, 2025 6:48pm
mancala-pkco ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 2, 2025 6:48pm

Copy link

coderabbitai bot commented Dec 31, 2024

Walkthrough

This pull request encompasses multiple updates across the client-side codebase, focusing on dependency version upgrades, code formatting improvements, and minor structural refinements. The primary changes include updating @cartridge/connector and @cartridge/controller dependencies to version ^0.5.7, refactoring component implementations like App.tsx and Seed, and standardizing code formatting across various files. The modifications aim to enhance code readability, maintainability, and consistency without introducing significant functional changes.

Changes

File Change Summary
client/package.json Updated @cartridge/connector and @cartridge/controller dependencies from ^0.5.6 to ^0.5.7
client/src/App.tsx Refactored rpc function to useCallback, added voyager explorer, simplified StarknetConfig props
client/src/components/gameplay/game-board.tsx Introduced memoized seeds variable, added getSeed function for seed details, updated rendering logic for player pots
client/src/components/gameplay/game-message.tsx Adjusted formatting of moveMessageOnTimer function parameters for readability
client/src/components/gameplay/game-navigation.tsx Enhanced safety of accessing nested properties for player names with optional chaining
client/src/components/gameplay/player-profile.tsx Removed unnecessary indentation for UserIcon div
client/src/components/header.tsx Consolidated import statements and standardized quote usage
client/src/components/lobby/duels.tsx Reformatted player name logic and color handling for clarity
client/src/components/lobby/leaderboard.tsx Minor formatting change by removing unnecessary space in closing div tag
client/src/components/lobby/live-duels.tsx Reformatted player name logic for improved readability
client/src/components/pits.tsx Simplified TopPit props, adjusted BottomPit rendering logic
client/src/components/profile/game-history.tsx Adjusted JSX formatting for user icons
client/src/components/profile/user-section.tsx Reformatted state initialization and rendering logic for consistency
client/src/components/seed.tsx Extensive restructuring with new required props and dynamic positioning logic
client/src/dojo/createSystemCalls.ts Updated string literals to use double quotes for consistency
client/src/lib/constants.ts Updated ACTION_ADDRESS, modified GraphQL queries, added updatedAt field
client/src/lib/utils.ts Standardized quote usage and improved formatting for clarity
client/src/pages/Lobby.tsx Reformatted useQuery hook and filtering logic for clarity
client/src/pages/Profile.tsx Reformatted useQuery hook for improved readability
client/src/pages/games/Gameplay.tsx Reformatted import statements for better readability
contracts/manifest_sepolia.json Updated class_hash for a contract
contracts/src/components/playable.cairo Updated move function to include new return value and streamlined assertions
contracts/src/utils/board.cairo Updated function signatures and return types for clarity

Suggested reviewers

  • supreme2580

Possibly related PRs


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: 3

🧹 Nitpick comments (14)
client/src/components/gameplay/game-navigation.tsx (1)

43-48: Consider refactoring repetitive code with a helper function to fetch the player name

Your code for finding and formatting player_one_name and player_two_name is nearly identical. This duplication can make the code harder to maintain and more prone to errors if modifications become necessary. A short helper function can improve readability and reduce duplication.

Here is a sample refactor:

-const player_one_name = formatPlayerName(
-  player_names?.mancalaDevProfileModels.edges.find(
-    (item: any) => item.node.address === game_node?.player_one,
-  )?.node.name,
-  game_node?.player_one,
-);
-const player_two_name = formatPlayerName(
-  player_names?.mancalaDevProfileModels.edges.find(
-    (item: any) => item.node.address === game_node?.player_two,
-  )?.node.name,
-  game_node?.player_two,
-);

+function getFormattedPlayerName(
+  address: string | undefined,
+  allProfiles: any,
+) {
+  const foundProfile = allProfiles?.edges
+    ?.find((item: any) => item.node.address === address)
+    ?.node.name;
+  return formatPlayerName(foundProfile, address);
+}

+const player_one_name = getFormattedPlayerName(
+  game_node?.player_one,
+  player_names?.mancalaDevProfileModels,
+);
+const player_two_name = getFormattedPlayerName(
+  game_node?.player_two,
+  player_names?.mancalaDevProfileModels,
+);
client/src/components/lobby/duels.tsx (1)

149-149: Avoid magic number offsets.

The offset + 3 is a magic number, making it unclear why the color index is shifted by three. Consider introducing a named constant (e.g., CHALLENGED_COLOR_OFFSET) to clarify this logic and improve maintainability.

client/src/components/gameplay/game-message.tsx (3)

104-108: Remove or utilize the unused "player" parameter.
This parameter is declared but never used in the function body. Consider removing it for clarity, or adjust the logic if you intended to use it.


126-135: Destructure the “account” object for improved readability.
You can enhance clarity and reduce repetitive property access by destructuring “account.account?.address” at the top of the function or before usage.


200-204: Confirm if the “player” parameter is necessary.
This call site passes game_node?.current_player as the “player” argument to moveMessageOnTimer, but the function does not use it. Consider removing the parameter or handling it if required in future logic.

client/src/components/seed.tsx (4)

23-43: Avoid magic numbers in position maps
Storing raw values like -715, -595, or references to >24, >38 can make maintenance harder. Consider extracting them into named constants for readability.


44-63: Consolidate shared logic
Player and opponent positions share a similar structure with slight variations. Refactoring these into a single helper function (e.g., getPitPositions(isNative, type)) might help reduce duplication.


64-113: Complex nested logic
The grid position code for pit_number === 7 is detailed but somewhat complex. Consider minor refactoring or additional inline comments to highlight the rationale behind each sub-block (main vs. intermediate grids).


175-180: Redundant re-initialization
You set animationDelay on line 175 and reset it again in the effect. If the formula repeats, consider using either just the state initialization or the effect, unless the effect covers a future scenario.

client/src/components/gameplay/game-board.tsx (3)

31-31: Frequent polling
startPolling(1000) might be too frequent if there are many active users. Assess whether you can increase the interval or use on-demand refetch for better performance.


32-51: Efficient deduplication
Sorting and manually deduplicating seeds works, but for large datasets, consider more efficient data structures or a query approach (e.g., sorting in GraphQL) to reduce client overhead.


144-172: Repeated mapping logic
Both top pot (opponent) and bottom pot (player) map over 24 seeds with near-identical logic. Consider refactoring into a shared component or helper function to reduce duplicate code.

Also applies to: 245-273

client/src/pages/Lobby.tsx (2)

115-121: Consider refining the type usage for game.

Using any here can obscure potential type mismatches. Defining an interface for game and using it as a generic type for .filter() or .map() would improve clarity and type safety.


143-159: Optional: Simplify the logic with filter + map.

The reduce usage here is valid, but you could also use chaining with .filter() and then .map(), which can sometimes be clearer. If performance is not critical here, rewriting may improve readability. Otherwise, leaving it as is is acceptable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d279aa2 and 3b516b2.

⛔ Files ignored due to path filters (1)
  • client/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !client/pnpm-lock.yaml and included by client/**
📒 Files selected for processing (20)
  • client/package.json (1 hunks)
  • client/src/App.tsx (2 hunks)
  • client/src/components/gameplay/game-board.tsx (7 hunks)
  • client/src/components/gameplay/game-message.tsx (5 hunks)
  • client/src/components/gameplay/game-navigation.tsx (1 hunks)
  • client/src/components/gameplay/player-profile.tsx (1 hunks)
  • client/src/components/header.tsx (5 hunks)
  • client/src/components/lobby/duels.tsx (2 hunks)
  • client/src/components/lobby/leaderboard.tsx (2 hunks)
  • client/src/components/lobby/live-duels.tsx (1 hunks)
  • client/src/components/pits.tsx (3 hunks)
  • client/src/components/profile/game-history.tsx (3 hunks)
  • client/src/components/profile/user-section.tsx (5 hunks)
  • client/src/components/seed.tsx (1 hunks)
  • client/src/dojo/createSystemCalls.ts (3 hunks)
  • client/src/lib/constants.ts (4 hunks)
  • client/src/lib/utils.ts (4 hunks)
  • client/src/pages/Lobby.tsx (3 hunks)
  • client/src/pages/Profile.tsx (1 hunks)
  • client/src/pages/games/Gameplay.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (9)
  • client/src/pages/games/Gameplay.tsx
  • client/src/components/gameplay/player-profile.tsx
  • client/src/components/profile/game-history.tsx
  • client/src/dojo/createSystemCalls.ts
  • client/src/components/lobby/leaderboard.tsx
  • client/src/components/profile/user-section.tsx
  • client/src/components/lobby/live-duels.tsx
  • client/src/lib/utils.ts
  • client/src/components/header.tsx
🧰 Additional context used
📓 Learnings (1)
client/src/components/gameplay/game-message.tsx (1)
Learnt from: supreme2580
PR: realm-of-ra/mancala#149
File: client/src/pages/games/Gameplay.tsx:0-0
Timestamp: 2024-11-12T06:00:31.919Z
Learning: The `moveMessageOnTimer` function in `client/src/pages/games/Gameplay.tsx` has been updated to use `React.createElement` instead of `dangerouslySetInnerHTML` to avoid XSS attacks.
🔇 Additional comments (18)
client/src/components/gameplay/game-navigation.tsx (1)

37-42: Validate presence of player_names?.mancalaDevProfileModels before accessing subfields

Your usage of optional chaining is good, mitigating potential runtime errors when player_names?.mancalaDevProfileModels or edges is missing. However, consider verifying whether player_names?.mancalaDevProfileModels?.edges actually contains objects. If edges is undefined or empty, find() returns undefined, so ?.node.name becomes undefined. This may impact user experience unless formatPlayerName ensures a meaningful fallback string is displayed.

client/package.json (2)

17-18: Verify dependency compatibility with the project.

The project uses several Dojo Engine packages (v1.0.4-alpha.3.1.2) and Starknet-related dependencies. Let's ensure these updated Cartridge packages are compatible.

Run the following script to check for potential compatibility issues:

✅ Verification successful

Let me try another verification approach to check the dependency compatibility.


The Cartridge package updates appear compatible with the project

The verification shows that:

  • The Cartridge packages (@cartridge/connector and @cartridge/controller) are used in a limited scope, primarily in App.tsx and useControllerData.ts
  • The usage pattern is straightforward, importing the controller connector and types
  • There are no explicit version conflicts with other dependencies in the project
  • The update is a minor version bump (^0.5.7), which should maintain backward compatibility

The project's main dependencies are Dojo Engine (v1.0.4-alpha.3.1.2) and Starknet-related packages, which don't have direct interactions with the Cartridge packages based on the import patterns found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential compatibility issues with other dependencies

# Search for import statements using these packages to understand usage
echo "Checking usage patterns..."
rg -l "@cartridge/(connector|controller)" --type ts --type tsx

# Check for any peer dependency warnings in the project
echo "Checking for peer dependency warnings in package-lock.json..."
if [ -f package-lock.json ]; then
  jq '.packages | .[] | select(.peerDependencies != null) | {name, peerDependencies}' package-lock.json
fi

Length of output: 319


Script:

#!/bin/bash
# Check package.json for related dependencies and their versions
echo "Checking package.json for related dependencies..."
cat client/package.json | jq '.dependencies'

# Search for import statements with a broader pattern
echo -e "\nChecking usage patterns..."
rg "@cartridge" --type js --type ts

# Look for any README or documentation files that might mention compatibility
echo -e "\nChecking documentation..."
fd -e md -e txt | xargs grep -l -i "cartridge\|compatibility" || true

Length of output: 2490


17-18: Verify the dependency updates and their changelog.

The updates to @cartridge/connector and @cartridge/controller from ^0.5.6 to ^0.5.7 are patch-level changes. However, given that this PR is titled "Animations", we should verify if these updates contain the necessary animation-related changes.

Run the following script to check the changelog and verify the updates:

✅ Verification successful

Let me try a different approach to verify these dependencies.


Let me try one more time with corrected syntax:


Dependencies update appears to be related to animation changes

Based on the verification results, I can confirm that these dependency updates are aligned with the PR's animation focus:

  1. The codebase shows extensive animation-related changes across multiple files, particularly in UI components.
  2. The project uses animation-related dependencies like framer-motion and tailwindcss-animate.
  3. The @cartridge/connector and @cartridge/controller packages are used in App.tsx and useControllerData.ts, which are likely being updated to support new animation features.

The patch version updates (0.5.6 to 0.5.7) suggest these are minor compatibility or enhancement changes. The dependencies appear to be properly integrated with other animation-related packages in the project.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the changelog and verify the updates for both dependencies

# Check if the repositories exist and are accessible
for repo in connector controller; do
  echo "Checking @cartridge/$repo changelog..."
  gh api repos/cartridge/$repo/releases/tags/v0.5.7 2>/dev/null || \
  gh api repos/cartridge-gg/$repo/releases/tags/v0.5.7 2>/dev/null || \
  echo "Repository or release not found"
done

# Check for any breaking changes or peer dependency requirements
for repo in connector controller; do
  echo "Checking @cartridge/$repo package.json..."
  curl -s "https://registry.npmjs.org/@cartridge/$repo/0.5.7" | \
  jq -r '.peerDependencies // empty'
done

Length of output: 1648


Script:

#!/bin/bash
# Search for any animation-related changes in the codebase
echo "Searching for animation-related changes..."
rg -l "animation|animate|transition" --type ts --type tsx

# Check package.json for any animation-related dependencies
echo -e "\nChecking package.json for animation dependencies..."
cat client/package.json | jq '.dependencies + .devDependencies' | rg -i "animation|animate|transition"

# Look for imports of these cartridge packages to understand their usage
echo -e "\nChecking imports of cartridge packages..."
rg -A 2 "from ['\"]\@cartridge/(connector|controller)['\"]" --type ts --type tsx

Length of output: 750


Script:

#!/bin/bash
# Search for any animation-related changes in the codebase
echo "Searching for animation-related changes..."
rg -l "animation|animate|transition" 

# Check package.json for any animation-related dependencies
echo -e "\nChecking package.json for animation dependencies..."
cat client/package.json | jq '.dependencies + .devDependencies'

# Look for imports of these cartridge packages to understand their usage
echo -e "\nChecking imports of cartridge packages..."
rg "@cartridge/(connector|controller)" -A 2

Length of output: 6041

client/src/components/lobby/duels.tsx (1)

32-43: Consider extracting "0x0" into a defined constant and verify correct usage of winner name.

You may want to define "0x0" as a constant to avoid potential typos and to improve clarity when comparing addresses. Also, it appears that winner might need to reference data.node.winner_name instead of data.node.winner, if that's intended to display the winner's actual name.

client/src/components/gameplay/game-message.tsx (2)

145-145: Message logic looks good.
No issues spotted in how displayName is rendered. This approach avoids dangerouslySetInnerHTML and mitigates XSS concerns.


156-156: No issues with awaiting the player's move.
The logic is consistent, and the reference to displayName for labeling the next move is clear.

client/src/components/seed.tsx (3)

2-3: Imports look good
The Framer Motion library is useful for the seed animations, and React’s useEffect/useState hooks facilitate dynamic behavior.


7-12: Consider assigning a default value to 'length'
While 'length' is optional in the props, the code frequently uses it. You might want to use a default value to ensure it’s never undefined.


182-209: Animation timings
Increasing durations and damping can enhance user experience, but be mindful of potential performance impacts when many seeds animate simultaneously.

client/src/components/gameplay/game-board.tsx (1)

53-69: Ensure consistent 'isNative' logic
The code uses numeric checks (1–24 vs. 25–48) to determine isNative. Verify that these ranges align with the rules for both players and remain accurate if seed ID generation changes.

client/src/components/pits.tsx (1)

4-6: Simplified 'TopPit'
Removing extra props and logic makes this component cleaner. Ensure that any removed functionality is handled elsewhere (like game-board.tsx).

client/src/App.tsx (2)

52-55: Memoized provider RPC
Using useCallback ensures the RPC object is stable across renders. Good optimization for re-render performance.


61-62: Usage of explorers
explorer={voyager} and autoConnect appear correct. Just confirm the explorer fully supports your chain (sepolia) for relevant transaction and contract lookups.

client/src/lib/constants.ts (2)

604-604: Confirm new ACTION_ADDRESS validity
You’ve updated the ACTION_ADDRESS. Make sure this contract address is correct in the current environment and that you’re referencing the appropriate chain.


688-691: Query readability and data usage
The multi-line formatting for the query is clearer. Verify that updatedAt is indeed necessary for the new logic, given it increases query payload size.

Also applies to: 747-749

client/src/pages/Lobby.tsx (2)

112-113: Looks good!

This small formatting change to the useQuery hook call is purely cosmetic and improves code readability without altering functionality.


458-458: No functional changes, formatting looks good.

client/src/pages/Profile.tsx (1)

12-13: Clean formatting improvement.

Splitting the useQuery hook call across multiple lines makes the code more readable without altering behavior.

@@ -137,7 +51,7 @@ export function BottomPit({
winner === "0x0"
) {
message(undefined);
const res = await system.move(userAccount?.account, game_id, pit);
await system.move(userAccount?.account, game_id, pit);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Handle move errors
handleMove calls an async function but lacks error handling. Consider a try/catch to handle rejections (e.g., network errors or contract call failures). This prevents unhandled promise rejections and improves user feedback.

+ try {
+   await system.move(userAccount?.account, game_id, pit);
+   setTimeRemaining(max_block_between_move);
+ } catch (error) {
+   message("Move failed. Please try again.");
+ }

Also applies to: 74-76

Comment on lines +188 to +205
const gamesWithPlayerNames = data?.mancalaDevMancalaBoardModels?.edges?.map(
(game: any) => {
const player1Profile = playerData?.mancalaDevProfileModels?.edges?.find(
(profile: any) => profile.node.address === game.node.player_one,
);
const player2Profile = playerData?.mancalaDevProfileModels?.edges?.find(
(profile: any) => profile.node.address === game.node.player_two,
);
return {
...game,
node: {
...game.node,
player_one_name: player1Profile?.node?.name,
player_two_name: player2Profile?.node?.name,
},
};
},
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Reuse the dictionary approach for repeated .find() calls.

Similar to the earlier suggestion, building a dictionary for playerData could improve performance and readability in this code block.

Comment on lines +122 to +141
const player1Profile = playerData?.mancalaDevProfileModels?.edges?.find(
(profile: any) => profile.node.address === game.node.player_one,
);
const player2Profile = playerData?.mancalaDevProfileModels?.edges?.find(
(profile: any) => profile.node.address === game.node.player_two,
);

const filteredTransactions =
data?.mancalaDevMancalaBoardModels?.edges?.reduce((acc: any[], game: any) => {
if (
(game?.node?.player_one === account.account?.address ||
game?.node?.player_two === account.account?.address) &&
game?.node?.entity.executedAt
) {
acc.push({
const winner = playerData?.mancalaDevProfileModels?.edges?.find(
(profile: any) => profile.node.address === game.node.winner,
);
return {
...game,
node: {
...game.node,
executedAt: game?.node?.entity.executedAt,
});
}
return acc;
}, []) || [];
player_one_name: player1Profile?.node?.name,
player_two_name: player2Profile?.node?.name,
winner: winner?.node?.name || game.node.winner,
},
};
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize repeated .find() operations with a dictionary/map approach.

Each iteration performs up to three .find() calls on playerData?.mancalaDevProfileModels?.edges. If the arrays are large, repeated searches might impact performance. Instead, consider constructing a dictionary keyed by address once, and then retrieve player data in O(1) time.

  // Example approach:
+  const profilesDict = playerData?.mancalaDevProfileModels?.edges?.reduce(
+    (acc: Record<string, any>, profileEdge: any) => {
+      acc[profileEdge.node.address] = profileEdge.node;
+      return acc;
+    },
+    {}
+  );

  .map((game: any) => {
-    const player1Profile = playerData?.mancalaDevProfileModels?.edges?.find(
-      (profile: any) => profile.node.address === game.node.player_one,
-    );
-    ...
+    const player1Profile = profilesDict?.[game.node.player_one];
+    const player2Profile = profilesDict?.[game.node.player_two];
+    const winnerProfile = profilesDict?.[game.node.winner];

Committable suggestion skipped: line range outside the PR's diff.

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 (2)
contracts/manifest_sepolia.json (1)

1256-1256: Ensure proper documentation of contract upgrade.

Since this is a significant contract upgrade, it's important to:

  1. Document the changes introduced in the new implementation
  2. Update any relevant deployment or integration guides
  3. Consider adding a changelog entry
contracts/src/components/playable.cairo (1)

247-247: Implement or remove the // TODO: Validate last pit is not the opponent's pit.
Currently, the new boolean return value partially addresses this. If you still need additional checks for corner cases (e.g., last pit is the opponent’s store, etc.), finalize the logic or remove the stale TODO to maintain clarity.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3b516b2 and c346e26.

📒 Files selected for processing (3)
  • contracts/manifest_sepolia.json (1 hunks)
  • contracts/src/components/playable.cairo (2 hunks)
  • contracts/src/utils/board.cairo (7 hunks)
🔇 Additional comments (10)
contracts/manifest_sepolia.json (1)

1256-1256: Verify the contract upgrade implementation and class hash.

The class hash update indicates a contract upgrade. Given that this contract handles critical game actions and player interactions, it's essential to verify:

  1. The new implementation maintains the same interface
  2. The upgrade mechanism is properly secured
  3. No breaking changes are introduced

Run the following script to verify the contract implementation:

✅ Verification successful

Let me gather more information about the contract implementation and upgrade mechanism.


Let me check the other manifest files to compare class hashes and understand the upgrade pattern.


Let me try one final verification to check the class hashes and interfaces.


Contract upgrade appears to be properly implemented with standard interfaces

Based on the verification results:

  1. The contract follows the Dojo framework's standard upgrade pattern with IUpgradeableWorld and IUpgradeable interfaces
  2. The contract maintains the required interfaces (IContract) and systems
  3. The upgrade mechanism is secured through proper event emission (ContractUpgraded, Upgraded) and standard upgrade components

The class hash update is part of a controlled upgrade process with appropriate safeguards in place.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify contract implementation and upgrade mechanism

# Check if the new class hash exists in other configuration files
rg "0x48dc9a86cb8adbe69982cdd63a571efe14e61b042be46ef771d5dbb065fec0f"

# Search for upgrade-related code to verify proper implementation
ast-grep --pattern 'function upgrade($$$) {
  $$$
}'

Length of output: 246


Script:

#!/bin/bash
# Check the contract configuration and related files
rg -A 5 -B 5 "mancala_dev-actions" contracts/manifest_sepolia.json

# Look for upgrade-related events or configurations
rg -i "upgrade" contracts/manifest_sepolia.json

# Search for previous class hash to understand the change
fd manifest --exec grep -l "class_hash"

Length of output: 2291


Script:

#!/bin/bash
# Check class hashes in other manifest files
rg -A 2 -B 2 '"tag": "mancala_dev-actions"' contracts/manifest_*.json

# Get the contract interfaces to verify compatibility
rg -A 5 '"interfaces":' contracts/manifest_sepolia.json

Length of output: 851


Script:

#!/bin/bash
# Get the class hashes for the actions contract across different manifests
rg -B 3 -A 1 '"tag": "mancala_dev-actions"' contracts/manifest_*.json | rg "class_hash|tag"

# Check the contract's interface definitions
rg -A 10 '"contracts": \[' contracts/manifest_sepolia.json

Length of output: 729

contracts/src/components/playable.cairo (2)

233-235: Confirm consistency when using the new (last_pit, is_in_current_player_side).
By returning a boolean to indicate whether the last pit lies in the current player's side, you’ve made the subsequent logic for capturing seeds much clearer. Ensure all calling sites (like the move function) consistently handle cases when the last pit might be the store (pit #7).


248-257: Verify capturing logic aligns with Mancala rules.
Wrapping the capture logic within if is_in_current_player_side ensures seeds are only captured when landing on the current player's pit. This is a good match for the standard Mancala rules alongside the checks in capture_seeds(). Consider adding negative test cases in your unit tests to confirm correct handling when the last pit is on the opponent’s side or is the store.

contracts/src/utils/board.cairo (7)

29-33: Trailing comma in add_seed_to_pit signature.
This style is acceptable if it matches your team’s code formatting conventions. Ensure consistency with other functions for a unified style.


Line range hint 46-125: Revised distribute_seeds returning (u8, bool) clarifies pit ownership.

  1. Return Type: The addition of (u8, bool) is well-integrated. It simplifies deciding whether the last pit belongs to the current player.
  2. Player Switching: Toggling is_current_player and resetting current_pit to 1 when current_pit > 7 is a clean approach.
  3. Opposition Pit Indexing: The conversion of the last pit to 7 - last_pit is a succinct solution to track relative pit positions, though be sure your logic across the codebase accounts for it.
  4. verify_seed_counts: Confirming the overall pit and seed integrity after each distribution is a strong safeguard against corrupted states.

Overall, this function is well-structured and clearly communicates the state changes.


129-129: Keep capture_seeds signature in sync with code style.
The trailing comma in the parameters is consistent with the updated style. Ensure all references to this function in your codebase reflect the same signature.


237-237: Pit resetting logic appears unchanged.
The declaration let mut idx = 1; is standard loop initialization for re-initializing pits. No immediate issues.


325-328: Trailing comma and blank line in initialize_player_seeds.
Similarly to other functions, these formatting refinements look consistent. Confirm your team’s preference for trailing commas.


343-344: Improved readability for seed_id calculation.
Breaking the expression across lines clarifies each step. This is beneficial for large numeric computations.


361-361: Closing brace seems aligned with no functional changes.
No concerns here.

@okhaimie-dev okhaimie-dev merged commit eb56037 into develop Jan 2, 2025
3 checks passed
okhaimie-dev added a commit that referenced this pull request Jan 7, 2025
* V1 init (#174)

* feat: contract upgrade w/ minor fe config changes

* fixed contract calls and updated lobby

* Clear store pit of each player on restart (#172)

Co-authored-by: Jonatan Chaverri <[email protected]>

* Fix capture seeds (#173)

Co-authored-by: Jonatan Chaverri <[email protected]>

---------

Co-authored-by: Tony Stark <[email protected]>
Co-authored-by: Jonatan Chaverri <[email protected]>
Co-authored-by: Jonatan Chaverri <[email protected]>

* Fix capture seeds on empty opponent pit (#176)

Co-authored-by: Jonatan Chaverri <[email protected]>

* V1 init (#180)

* feat: contract upgrade w/ minor fe config changes

* fixed contract calls and updated lobby

* fixed leaderboard

* Clear store pit of each player on restart (#172)

Co-authored-by: Jonatan Chaverri <[email protected]>

* Fix capture seeds (#173)

Co-authored-by: Jonatan Chaverri <[email protected]>

* Fix capture seeds on empty opponent pit (#175)

Co-authored-by: Jonatan Chaverri <[email protected]>

* backend updated

* feat: added timeout

* feat: client re-config re:/ mancala board changes

* made backend typescript

* coderabbit suggestions

---------

Co-authored-by: Tony Stark <[email protected]>
Co-authored-by: Jonatan Chaverri <[email protected]>
Co-authored-by: Jonatan Chaverri <[email protected]>

* feat: develop patch 1 (#184)

* feat: patch complete (#185)

* feat: switch back to slot (#186)

* Dojo v1 upgrade (#188)

* feat: contract upgrade checkpoint

* feat: contract upgrade checkpoint

* feat: initial touch, dojo-v1

* feat: initial touch, dojo-v1

* feat: added asset to join game

* tests: wip conversion to dojov1

* test: dojov1 test integrated

* feat: added extra config for slot on client

* fixed creating game loader

---------

Co-authored-by: Supreme2580 <[email protected]>

* Score and Seed UI update (#189)

* player mancala seeds ui update

* opponent score ui fix

* added optionals

* removed use of array from

* added functions for margins

* Sepolia alpha (#192)

* feat: swap to default cartridge controller rpc

* fixed create game bugs (#191)

---------

Co-authored-by: Supreme Labs <[email protected]>

* feat: added movement events (#195)

* fixed gameplay bug (#196)

* fixed gameplay bug

* removed console.logs

* UI upgrade (#200)

* ui upgrade

* ui upgrade

* package.json file

* filter changes fixed

* players skeleton fixed

* ui updates

* leaderboard component

* changed filter cursor to pointer

---------

Co-authored-by: Supreme2580 <[email protected]>

* Profile Page Bug Fixes and UI Optimizations (#203)

* fix profile data display bug

* moved music button on lobby

* prettier

* ui update

* ui update

* Contract movement end game (#204)

* unique seed ids on initialization

* use exisiting seeds do not spawn new seeds

* avoid double counting

* prevent double emissions

* removed unused

* feat: pass

* updated seed id initialization logic

* moved seed id assigner

* update capture remaining seeds

* removed debugging number

---------

Co-authored-by: Tony Stark <[email protected]>

* profile fix (#205)

* fixed winner and loser (#207)

* avoid duplication of seeds (#208)

* Profile sec (#210)

* feat: dojo version bump

* fixed broken test

* feat: modified some client config

* feat: more dojo frontend config

* feat: dojojs update

* feat: fixed distribution logic bug

---------

Co-authored-by: Tony Stark <[email protected]>

* Animations (#213)

Dependencies

Updated @cartridge/connector from ^0.5.6 to ^0.5.7
Updated @cartridge/controller from ^0.5.6 to ^0.5.7
Code Improvements

Refined code formatting across multiple components
Improved readability and consistency in component structures
Enhanced error handling and prop management in various components
Simplified props and internal logic in the TopPit component
Performance

Optimized seed rendering and positioning logic
Improved memoization of functions using useCallback
Enhanced control flow and error handling in game logic

---------

Co-authored-by: Supreme2580 <[email protected]>

* fixed seed distribution logic (#215)

---------

Co-authored-by: Supreme Labs <[email protected]>
Co-authored-by: Jonatan Chaverri <[email protected]>
Co-authored-by: Jonatan Chaverri <[email protected]>
Co-authored-by: Supreme2580 <[email protected]>
Co-authored-by: Eniola Ajiboye <[email protected]>
Co-authored-by: kelvin_joshua <[email protected]>
@okhaimie-dev okhaimie-dev mentioned this pull request Jan 7, 2025
@okhaimie-dev okhaimie-dev deleted the animations branch January 7, 2025 09:00
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.

2 participants