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

Adding the model and system tournament blueprint #96

Merged
merged 4 commits into from
Nov 27, 2024

Conversation

Gerson2102
Copy link
Contributor

@Gerson2102 Gerson2102 commented Nov 21, 2024

Closes #93. I just created the model and system blueprint to keep working on it. Any feedback is more then welcome. I still need to figure it out how to do the remaining functions. (register_player, start_tournament and complete_torunament)

And btw, how can I check that the code is working fine, when I run sozo build nothing happens. See this picture:

image

Summary by CodeRabbit

  • New Features

    • Introduced a structured system for managing tournaments, including the ability to create, register players, start, and retrieve tournament details.
    • Added a new enumeration for tournament statuses: Pending, Ongoing, and Completed.
  • Bug Fixes

    • Implemented tests to ensure correct initialization and functionality of the tournament system.
  • Documentation

    • Updated documentation to reflect the new tournament management features and structures.

Copy link

coderabbitai bot commented Nov 21, 2024

Walkthrough

The pull request introduces significant enhancements to the tournament management functionality within the application. It adds a new enumeration, TournamentStatus, which defines three states: Pending, Ongoing, and Completed. A struct named Tournament is also introduced, encapsulating various fields such as tournament_id, name, status, entry_fee, max_participants, current_participants, and prize_pool. This struct is designed for managing tournament data effectively.

Additionally, a new interface ITournamentAction is implemented, which outlines methods for creating, registering players, starting, and retrieving tournaments. The tournament_system module provides concrete implementations of these methods, ensuring proper management of tournament operations. The changes also include the addition of a test module that verifies the correct initialization of a Tournament instance. Overall, these modifications aim to establish a robust framework for handling in-game tournaments dynamically.

Assessment against linked issues

Objective Addressed Explanation
Create a tournament PoC model (93)
Create a tournament with specified attributes (93)
Register a player in the tournament (93)
Start a tournament and validate conditions (93)
Retrieve details of a specific tournament (93)

Possibly related issues


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.

coderabbitai[bot]

This comment was marked as spam.

@coxmars
Copy link
Contributor

coxmars commented Nov 21, 2024

Hi @Gerson2102, if you execute sozo build and you do not receive errors it's ok, but remember to import the new files/code in the lib.cairo file (I think you need to do it). Also if you want to validate in a quickly way that your functions are working just write some unit tests for yourself to verify that (do not upload that in the PR), because the idea is to create a complete set of unit tests in the other issue.

coderabbitai[bot]

This comment was marked as spam.

@Gerson2102
Copy link
Contributor Author

I'm getting this error while trying to test my code:

sozo test -f test_create_tournament
testing test(bytebeasts_unittest) bytebeasts v0.1.0 (/root/ByteBeastsBackend/Scarb.toml)
running 1 test
test bytebeasts::tests::test_tournament::tests::test_create_tournament ... fail (gas usage est.: 10994620)
failures:
   bytebeasts::tests::test_tournament::tests::test_create_tournament - Panicked with ("Model `Tournament`: deserialization failed. Ensure the length of the keys tuple is matching the number of #[key] fields in the model struct.", 0x454e545259504f494e545f4641494c4544 ('ENTRYPOINT_FAILED')).

error: test result: FAILED. 0 passed; 1 failed; 0 ignored

I dont know why is that happening, the Tournament model just has one #[key] argument. It should works.

@danielcdz
Copy link
Contributor

@Gerson2102 can you show me your tests?

@Gerson2102
Copy link
Contributor Author

@danielcdz this is the test:

#[test]
    fn test_create_tournament() {
        let (_, tournament_system) = setup_world();
        let mut players = ArrayTrait::new();

        let player_ash = Player {
            player_id: 1,
            player_name: 'Ash',
            beast_1: 1, // Beast 1 assigned
            beast_2: 0, // No beast assigned
            beast_3: 0, // No beast assigned
            beast_4: 0, // No beast assigned
            potions: 1
        };
        players.append(player_ash);

        tournament_system
            .create_tournament(1, 'tournament', TournamentStatus::Pending, 1, 2, players, 1);
        let tournament = tournament_system.get_tournament(1);
        assert!(tournament.name == 'tournament', "The tournament name is wrong!");
    }

@danielcdz
Copy link
Contributor

@Gerson2102 can you add the test file to this PR to have all the context and try to debug the test?

@Gerson2102
Copy link
Contributor Author

@Gerson2102 can you add the test file to this PR to have all the context and try to debug the test?

This is my dojo version currently: 1.0.0-alpha.5

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

🧹 Outside diff range and nitpick comments (1)
src/tests/test_tournament.cairo (1)

16-19: Simplify import statements

The double curly braces in the imports are unnecessary and can be simplified.

-use bytebeasts::{
-    models::tournament::{{Tournament, tournament}}, models::tournament::TournamentStatus,
-    models::player::{{Player, player}},
-};
+use bytebeasts::{
+    models::tournament::{Tournament, tournament, TournamentStatus},
+    models::player::{Player, player},
+};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 32f38c3 and 3fac51d.

📒 Files selected for processing (1)
  • src/tests/test_tournament.cairo (1 hunks)
🔇 Additional comments (2)
src/tests/test_tournament.cairo (2)

30-32: Previous comment about error handling is still valid


41-60: Previous comment about test coverage and readability is still valid

@ByteBuildersLabs ByteBuildersLabs deleted a comment from coderabbitai bot Nov 26, 2024
@ByteBuildersLabs ByteBuildersLabs deleted a comment from coderabbitai bot Nov 26, 2024
@ByteBuildersLabs ByteBuildersLabs deleted a comment from coderabbitai bot Nov 26, 2024
@ByteBuildersLabs ByteBuildersLabs deleted a comment from coderabbitai bot Nov 26, 2024
@ByteBuildersLabs ByteBuildersLabs deleted a comment from coderabbitai bot Nov 26, 2024
@ByteBuildersLabs ByteBuildersLabs deleted a comment from coderabbitai bot Nov 26, 2024
@danielcdz
Copy link
Contributor

@Gerson2102 I saw your tests and they seem to be good, I faced a similar issue a couple of weeks ago and I think is related to the Dojo version, for now, is ok to delete those system tests as we will be migrating all these repo to Dojo 1.0.0 soon, but please add some tests to the model, something like this:

fn test_battle_initialization() {

@Gerson2102
Copy link
Contributor Author

@Gerson2102 I saw your tests and they seem to be good, I faced a similar issue a couple of weeks ago and I think is related to the Dojo version, for now, is ok to delete those system tests as we will be migrating all these repo to Dojo 1.0.0 soon, but please add some tests to the model, something like this:

fn test_battle_initialization() {

Got it. Changes made now.

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

🧹 Outside diff range and nitpick comments (3)
src/models/tournament.cairo (1)

25-69: Enhance test coverage with edge cases and validation tests.

The current test only covers basic initialization. Consider adding:

  1. Edge cases:

    • Maximum number of participants
    • Zero entry fee tournaments
    • Various prize pool configurations
  2. Validation tests:

    • Invalid prize pool amounts
    • Participant overflow
    • Tournament status transitions
  3. Realistic test data:

    • Prize pool should typically be greater than a single entry fee
    • Test with multiple participants

Example test cases to add:

#[test]
fn test_tournament_validation() {
    // Test maximum participants
    let tournament_max = create_tournament_with_max_participants();
    assert(tournament_max.current_participants.len() <= tournament_max.max_participants);

    // Test prize pool validation
    let tournament_prize = create_tournament_with_prize_pool();
    assert(tournament_prize.prize_pool >= tournament_prize.entry_fee * tournament_prize.max_participants);
}

#[test]
fn test_tournament_with_multiple_participants() {
    let tournament = create_tournament_with_multiple_players();
    assert(tournament.current_participants.len() > 1);
}
src/systems/tournament.cairo (2)

18-18: TODO: Implement complete_tournament method.

The commented-out method suggests incomplete implementation. This aligns with the PR objectives mentioning that complete_tournament needs to be implemented.

Would you like me to help implement the complete_tournament method? I can provide a basic implementation that:

  1. Verifies the tournament is in Ongoing status
  2. Updates the tournament status to Completed
  3. Handles prize distribution to the winning player

1-89: Consider architectural improvements for scalability.

A few architectural suggestions:

  1. Consider implementing events for tournament state changes to facilitate frontend updates
  2. Think about implementing a separate prize pool management system for better modularity
  3. Consider adding tournament types/formats for future extensibility

Example event implementation:

#[event]
fn TournamentCreated(tournament_id: u32, name: felt252) {}

#[event]
fn TournamentStarted(tournament_id: u32) {}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3fac51d and 7a8bae0.

📒 Files selected for processing (3)
  • src/lib.cairo (2 hunks)
  • src/models/tournament.cairo (1 hunks)
  • src/systems/tournament.cairo (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib.cairo
🔇 Additional comments (5)
src/models/tournament.cairo (3)

1-8: LGTM! Well-structured enum implementation.

The TournamentStatus enum is well-designed with appropriate trait derivations and clear status values that properly represent a tournament's lifecycle.


11-22: 🛠️ Refactor suggestion

Add documentation and field constraints.

While the struct implementation matches the requirements, it needs documentation and field constraints:

  1. Add documentation for the struct and each field
  2. Consider adding the following constraints in the tournament system contract:
    • entry_fee: Should be non-negative
    • max_participants: Should have a reasonable upper limit
    • prize_pool: Should be >= total entry fees (entry_fee * max_participants)
 #[derive(Drop, Serde)]
 #[dojo::model]
+/// Represents a tournament in the ByteBeasts game
 pub struct Tournament {
     #[key]
+    /// Unique identifier for the tournament
     pub tournament_id: u32,
+    /// Name of the tournament
     pub name: felt252,
+    /// Current status of the tournament (Pending, Ongoing, or Completed)
     pub status: TournamentStatus,
+    /// Entry fee required to participate (must be non-negative)
     pub entry_fee: u32,
+    /// Maximum number of participants allowed
     pub max_participants: u32,
+    /// Array of currently registered participants
     pub current_participants: Array<Player>,
+    /// Total prize pool (must be >= entry_fee * max_participants)
     pub prize_pool: u32,
 }

11-22: Verify struct design supports upcoming tournament functions.

The current struct design needs to support the pending functions mentioned in the PR objectives (register_player, start_tournament, complete_tournament). Let's verify the implementation:

✅ Verification successful

The initial results show that the functions are being implemented, but we need to verify the complete implementation details and the TournamentStatus enum to ensure the struct design properly supports these functions.


Tournament struct design adequately supports the system implementation

The Tournament struct design properly supports all the implemented and planned tournament functions:

  • register_player: Struct has current_participants array and max_participants for validation
  • start_tournament: Struct has status field to track tournament state transitions
  • complete_tournament (planned): Struct includes status enum with Completed state and prize_pool for rewards

The implementation shows proper usage of all struct fields with appropriate validations in place.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any existing tournament-related function implementations
echo "Searching for tournament-related functions..."
rg -A 5 "fn (register_player|start_tournament|complete_tournament)"

# Check for any existing tournament system implementations
echo "Checking for tournament system implementations..."
fd -e cairo -x grep -l "tournament" {}

Length of output: 1960


Script:

#!/bin/bash
# Let's check the tournament system implementation details
echo "Checking tournament system implementation..."
cat src/systems/tournament.cairo

# Let's also check the tournament status enum
echo "\nChecking tournament status definition..."
rg -A 5 "enum TournamentStatus"

Length of output: 3683

src/systems/tournament.cairo (2)

1-5: LGTM! Imports and interface declaration are well-structured.

The imports and interface declaration follow the dojo patterns correctly.


23-31: LGTM! Contract implementation follows dojo patterns.

The contract structure and interface implementation are correctly defined.

Comment on lines +59 to +62
assert!(
tournament.current_participants.len() < tournament.max_participants.try_into().unwrap(),
"Tournament is full"
);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential integer overflow in length comparison.

The current comparison between len() and max_participants involves unsafe type conversion.

Consider this safer approach:

-        assert!(
-            tournament.current_participants.len() < tournament.max_participants.try_into().unwrap(), 
-            "Tournament is full"
-        );
+        let current_count: u32 = tournament.current_participants.len().try_into().unwrap();
+        assert!(current_count < tournament.max_participants, "Tournament is full");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
assert!(
tournament.current_participants.len() < tournament.max_participants.try_into().unwrap(),
"Tournament is full"
);
let current_count: u32 = tournament.current_participants.len().try_into().unwrap();
assert!(current_count < tournament.max_participants, "Tournament is full");

Comment on lines +54 to +67
fn register_player(ref world: IWorldDispatcher, tournament_id: u32, new_player: Player) {
let mut tournament = get!(world, tournament_id, (Tournament));

assert!(tournament.status == TournamentStatus::Pending, "Tournament not open for registration");

assert!(
tournament.current_participants.len() < tournament.max_participants.try_into().unwrap(),
"Tournament is full"
);

tournament.current_participants.append(new_player);

set!(world, (tournament));
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add player validation and entry fee handling.

The register_player method needs additional validations:

  1. Check for duplicate players
  2. Handle entry fee payment

Consider adding these validations:

     fn register_player(ref world: IWorldDispatcher, tournament_id: u32, new_player: Player) {
         let mut tournament = get!(world, tournament_id, (Tournament));
     
         assert!(tournament.status == TournamentStatus::Pending, "Tournament not open for registration");
     
         assert!(
             tournament.current_participants.len() < tournament.max_participants.try_into().unwrap(), 
             "Tournament is full"
         );

+        // Check for duplicate players
+        let mut i = 0;
+        loop {
+            if i >= tournament.current_participants.len() {
+                break;
+            }
+            assert!(
+                tournament.current_participants[i].player_id != new_player.player_id,
+                "Player already registered"
+            );
+            i += 1;
+        };
+
+        // TODO: Handle entry fee payment
+        // This would require integration with a payment system
+        // assert!(payment_received == tournament.entry_fee, "Entry fee not paid");

         tournament.current_participants.append(new_player);

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

Comment on lines +32 to +52
fn create_tournament(
ref world: IWorldDispatcher,
tournament_id: u32,
name: felt252,
status: TournamentStatus,
entry_fee: u32,
max_participants: u32,
current_participants: Array<Player>,
prize_pool: u32
) {
let tournament = Tournament {
tournament_id: tournament_id,
name: name,
status: status,
entry_fee: entry_fee,
max_participants: max_participants,
current_participants: current_participants,
prize_pool: prize_pool
};
set!(world, (tournament))
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation for tournament ID uniqueness.

The create_tournament method should verify that the tournament_id doesn't already exist to prevent overwriting existing tournaments.

Add this validation before creating the tournament:

         prize_pool: u32
     ) {
+        let existing = get!(world, tournament_id, (Tournament));
+        assert!(existing.tournament_id == 0, "Tournament ID already exists");
         let tournament = Tournament {

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

Comment on lines +84 to +87
fn get_tournament(world: @IWorldDispatcher, tournament_id: u32) -> Tournament {
let tournament_from_world = get!(world, tournament_id, (Tournament));
tournament_from_world
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for non-existent tournament.

The get_tournament method should handle the case when the tournament doesn't exist.

Add error handling:

     fn get_tournament(world: @IWorldDispatcher, tournament_id: u32) -> Tournament {
         let tournament_from_world = get!(world, tournament_id, (Tournament));
+        assert!(tournament_from_world.tournament_id != 0, "Tournament not found");
         tournament_from_world
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn get_tournament(world: @IWorldDispatcher, tournament_id: u32) -> Tournament {
let tournament_from_world = get!(world, tournament_id, (Tournament));
tournament_from_world
}
fn get_tournament(world: @IWorldDispatcher, tournament_id: u32) -> Tournament {
let tournament_from_world = get!(world, tournament_id, (Tournament));
assert!(tournament_from_world.tournament_id != 0, "Tournament not found");
tournament_from_world
}

@danielcdz
Copy link
Contributor

@Gerson2102 are sozo build and sozo test working?

@Gerson2102
Copy link
Contributor Author

@danielcdz yes

image
image

@Gerson2102
Copy link
Contributor Author

The CI is failing for a weird reason. Seems like is running out of memory, I remember to have faced that kind of issues locally with other projects. But I'm not sure if it is that.

@danielcdz danielcdz added enhancement New feature or request M actual: 2 labels Nov 27, 2024
Copy link
Contributor

@danielcdz danielcdz left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Contributor

@coxmars coxmars left a comment

Choose a reason for hiding this comment

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

LGTM

@coxmars coxmars merged commit 7d47281 into ByteBuildersLabs:main Nov 27, 2024
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Create a tournament PoC model
3 participants