### Install and Build Game Components with Scarb Source: https://github.com/provable-games/game-components/blob/main/README.md This snippet demonstrates the command-line steps to clone the game components repository, navigate into the directory, build the entire workspace using Scarb, and run tests with coverage using StarkNet Foundry. ```bash # Clone the repository git clone cd game-components # Build the entire workspace scarb build # Run tests with coverage cd packages/test_starknet && snforge test --coverage ``` -------------------------------- ### Install Starknet Foundry Source: https://github.com/provable-games/game-components/blob/main/packages/test_starknet/README.md Specifies the required version of Starknet Foundry for the project. Ensure this version is installed and active. ```text starknet-foundry 0.31.0 ``` -------------------------------- ### Advanced Token Contract with Selected Features (Cairo) Source: https://github.com/provable-games/game-components/blob/main/packages/token/README.md This example demonstrates building an advanced Starknet token contract by enabling specific features like Minter, MultiGame, and Objectives. It includes the necessary component definitions and `OptionalImpl` for the enabled features, while using `NoOp` for disabled ones. ```cairo // In your config.cairo pub const MINTER_ENABLED: bool = true; pub const MULTI_GAME_ENABLED: bool = true; pub const OBJECTIVES_ENABLED: bool = true; pub const CONTEXT_ENABLED: bool = false; pub const SOULBOUND_ENABLED: bool = false; pub const RENDERER_ENABLED: bool = false; // In your contract #[starknet::contract] mod MyAdvancedToken { use game_components_token_optimized::core::CoreTokenComponent; use game_components_token_optimized::features::{ MinterComponent, MultiGameComponent, ObjectivesComponent }; component!(path: CoreTokenComponent, storage: core_token, event: CoreTokenEvent); component!(path: MinterComponent, storage: minter, event: MinterEvent); component!(path: MultiGameComponent, storage: multi_game, event: MultiGameEvent); component!(path: ObjectivesComponent, storage: objectives, event: ObjectivesEvent); // Enable selected features impl MinterOptionalImpl = MinterComponent::MinterOptionalImpl; impl MultiGameOptionalImpl = MultiGameComponent::MultiGameOptionalImpl; impl ObjectivesOptionalImpl = ObjectivesComponent::ObjectivesOptionalImpl; // Disable unused features impl ContextImpl = NoOpContext; impl SoulboundImpl = NoOpSoulbound; impl RendererImpl = NoOpRenderer; } ``` -------------------------------- ### Basic Token Contract with Minimal Features (Cairo) Source: https://github.com/provable-games/game-components/blob/main/packages/token/README.md This example shows how to define a basic Starknet contract using the `CoreTokenComponent`. By setting all feature flags in `config.cairo` to `false`, only the essential core logic is included, resulting in a minimal contract size. It utilizes `NoOp` implementations for disabled features. ```cairo // In your config.cairo pub const MINTER_ENABLED: bool = false; pub const MULTI_GAME_ENABLED: bool = false; pub const OBJECTIVES_ENABLED: bool = false; pub const CONTEXT_ENABLED: bool = false; pub const SOULBOUND_ENABLED: bool = false; pub const RENDERER_ENABLED: bool = false; // In your contract #[starknet::contract] mod MyToken { use game_components_token_optimized::core::CoreTokenComponent; use game_components_token_optimized::core::traits::*; component!(path: CoreTokenComponent, storage: core_token, event: CoreTokenEvent); #[abi(embed_v0)] impl CoreTokenImpl = CoreTokenComponent::CoreTokenImpl; impl CoreTokenInternalImpl = CoreTokenComponent::InternalImpl; // Use NoOp implementations for disabled features impl MinterImpl = NoOpMinter; impl MultiGameImpl = NoOpMultiGame; impl ObjectivesImpl = NoOpObjectives; impl ContextImpl = NoOpContext; impl SoulboundImpl = NoOpSoulbound; impl RendererImpl = NoOpRenderer; } ``` -------------------------------- ### Cairo Test Helper Functions Source: https://github.com/provable-games/game-components/blob/main/test_plan.md A list of essential helper functions for testing Cairo smart contracts. These functions cover contract setup, token minting, time manipulation, event verification, and fuzzing utilities. ```cairo // Helper functions needed: 1. setup_contracts() - Deploy all contracts 2. create_test_token() - Mint with defaults 3. advance_time() - Cheat code wrapper 4. assert_event_emitted() - Event verification 5. generate_random_lifecycle() - Fuzz helper 6. batch_mint() - Concurrent testing ``` -------------------------------- ### Custom Minter Trait Implementation (Cairo) Source: https://github.com/provable-games/game-components/blob/main/packages/token/README.md This example shows how to override specific behaviors by implementing a custom trait, such as `OptionalMinter`, for the `ContractState`. This allows for tailored logic within the game components. ```cairo // Override specific behaviors impl CustomMinter of OptionalMinter { fn on_mint_with_minter(ref self: ContractState, minter: ContractAddress) -> u64 { // Custom minter logic 42 } } ``` -------------------------------- ### Manage Token Renderers for Game NFTs (Cairo) Source: https://context7.com/provable-games/game-components/llms.txt This code illustrates how to manage custom rendering for game token metadata using the IMinigameTokenRenderer interface. It shows how to get the renderer contract for a specific token, check if a custom renderer is in use, and reset a token to use the default renderer. ```cairo use game_components_token::extensions::renderer::interface::{ IMinigameTokenRendererDispatcher, IMinigameTokenRendererDispatcherTrait }; use starknet::ContractAddress; fn manage_renderer(token_contract: ContractAddress, token_id: u64) { let renderer = IMinigameTokenRendererDispatcher { contract_address: token_contract }; // Get renderer contract for token let renderer_addr: ContractAddress = renderer.get_renderer(token_id); // Check if token has custom renderer (vs default game renderer) let has_custom: bool = renderer.has_custom_renderer(token_id); // Reset token to use default renderer renderer.reset_token_renderer(token_id); } ``` -------------------------------- ### Build and Test Commands for Cairo/StarkNet Projects Source: https://github.com/provable-games/game-components/blob/main/AGENTS.md This section provides essential command-line instructions for building, testing, and formatting Cairo projects on StarkNet using Scarb and StarkNet Foundry. It covers building the entire workspace, running all tests, executing specific tests, enabling test coverage, generating coverage reports, and formatting the code. ```bash # Build entire workspace scarb build # Run all tests cd packages/test_starknet && snforge test # Run specific test cd packages/test_starknet && snforge test test_mint_basic # Run tests with coverage cd packages/test_starknet && snforge test --coverage # Generate coverage report cairo-coverage # Format code scarb fmt -w ``` -------------------------------- ### ContextComponent API Source: https://github.com/provable-games/game-components/blob/main/packages/metagame/test_plan.md Handles the initialization and registration of the Context component's interfaces. ```APIDOC ## POST initializer ### Description Initializes the Context component. This function registers the component's SRC5 interface. It can only be called once. ### Method POST ### Endpoint /context/initializer ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **message** (string) - Initialization successful. #### Response Example ```json { "message": "Context component initialized successfully." } ``` ``` -------------------------------- ### Deployment and Script Execution Source: https://github.com/provable-games/game-components/blob/main/README.md Lists common shell scripts used for deploying smart contracts and setting up game components on StarkNet. These scripts cover deploying mock contracts, optimized token contracts, and creating game settings and objectives. ```bash # Deploy mock contracts for testing ./scripts/deploy_mocks.sh # Deploy optimized token contract ./scripts/deploy_optimized_token.sh # Create game settings ./scripts/create_settings.sh # Create objectives ./scripts/create_objectives.sh # Mint game tokens ./scripts/mint_games.sh ``` -------------------------------- ### MinigameToken Lifecycle Helper Functions - Cairo Source: https://github.com/provable-games/game-components/blob/main/packages/token/test_plan.md This snippet details the lifecycle helper functions for the MinigameToken Cairo smart contract. These functions are used to determine the state of a game token based on time, such as checking if it has expired, can be started, or is currently playable. They are read-only operations. ```cairo fn has_expired(self: @Lifecycle, current_time: u64) -> bool fn can_start(self: @Lifecycle, current_time: u64) -> bool fn is_playable(self: @Lifecycle, current_time: u64) -> bool ``` -------------------------------- ### Run StarkNet Foundry Tests with Coverage (Bash) Source: https://github.com/provable-games/game-components/blob/main/packages/token/test_plan.md Commands to build all packages using Scarb and then run StarkNet Foundry tests with coverage enabled. It specifies the required coverage thresholds for lines, branches, and events. ```bash # Build all packages scarb build # Run StarkNet Foundry tests with coverage cd packages/test_starknet snforge test --coverage # Coverage threshold: 100% line coverage required # Coverage target: 100% branch coverage required # Coverage target: 100% event coverage required ``` -------------------------------- ### Build and Test Commands for Scarb Source: https://github.com/provable-games/game-components/blob/main/README.md Provides essential commands for building, formatting, and testing StarkNet projects using Scarb and Snforge. Includes commands for building the entire workspace or specific packages, formatting code, running tests, and checking test coverage. ```bash # Build entire workspace scarb build # Build specific packages cd packages/test_starknet && scarb build # Format code scarb fmt -w # Run StarkNet Foundry tests cd packages/test_starknet && snforge test # Run with coverage (required 90%+) snforge test --coverage cairo-coverage # Run specific test snforge test test_mint_basic ``` -------------------------------- ### Run Starknet Foundry Tests with Coverage Source: https://github.com/provable-games/game-components/blob/main/packages/metagame/test_plan.md This command executes all tests within the Starknet Foundry framework and generates coverage data. It's essential for verifying test coverage against the required thresholds. ```bash snforge test --coverage ``` -------------------------------- ### Checking Extension Availability in Cairo Source: https://github.com/provable-games/game-components/blob/main/README.md Demonstrates how to check for and utilize extension functionalities within a Cairo smart contract. It shows the pattern for discovering if a contract supports a specific interface (e.g., IMinigameSettings) and then dispatching calls to that extension. ```cairo // Check for extension availability if src5_component.supports_interface(IMINIGAME_SETTINGS_ID) { let settings = IMinigameSettingsDispatcher { contract_address: settings_address }; // Use extension functionality } ``` -------------------------------- ### Bash Commands for Starknet Testing and Coverage Source: https://github.com/provable-games/game-components/blob/main/test_plan.md Shell commands for running Starknet tests and generating code coverage reports using snforge and cairo-coverage. This includes running all tests, enabling coverage, and filtering coverage by package. ```bash # Run all tests cd packages/test_starknet && snforge test ``` ```bash # Run with coverage snforge test --coverage ``` ```bash # Generate detailed report cairo-coverage ``` ```bash # Check specific package coverage cairo-coverage --package game_components_token ``` -------------------------------- ### Run StarkNet Tests and Generate Coverage Reports Source: https://github.com/provable-games/game-components/blob/main/README.md This bash snippet shows how to execute tests within the `test_starknet` package using `snforge` and generate detailed coverage reports using `cairo-coverage`. This is crucial for maintaining code quality. ```bash cd packages/test_starknet snforge test --coverage cairo-coverage # Generate detailed coverage reports ``` -------------------------------- ### Mock Implementations for Testing Source: https://github.com/provable-games/game-components/blob/main/test_plan.md This section lists the required mock implementations for testing the game components. These mocks simulate external dependencies and contracts, allowing for isolated testing of individual components and scenarios. ```cairo // Mock implementations needed: 1. MockMinigameContract - Implements IMinigameTokenData 2. MockGameRegistry - Multi-game registry 3. MockEventRelayer - Event aggregation 4. MockContext - IMetagameContext provider 5. MockSettings - IMinigameSettings provider 6. MockObjectives - IMinigameObjectives provider 7. MockRenderer - IMinigameTokenRenderer provider 8. MockMinter - IMinigameTokenMinter provider ``` -------------------------------- ### Create Game Settings via Token Contract (Cairo) Source: https://context7.com/provable-games/game-components/llms.txt This function shows how to create game settings presets by calling the 'create_settings' function on a token contract. It defines settings like difficulty, time limit, and lives. Dependencies include the 'game_components_token' crate. ```cairo // Creating settings through token contract use game_components_token::interface::{ IMinigameTokenMixinDispatcher, IMinigameTokenMixinDispatcherTrait }; fn create_game_settings(token_contract: ContractAddress, game_contract: ContractAddress) { let token = IMinigameTokenMixinDispatcher { contract_address: token_contract }; let settings_data = array![ GameSetting { name: "difficulty", value: "hard" }, GameSetting { name: "time_limit", value: "300" }, GameSetting { name: "lives", value: "3" }, ].span(); token.create_settings( game_contract, 1, // settings_id "Hard Mode", // name "Maximum difficulty with time pressure", // description settings_data, ); } ``` -------------------------------- ### Project Dependencies (TOML) Source: https://github.com/provable-games/game-components/blob/main/packages/token/README.md Lists the project's dependencies, including Starknet, other game component crates, and OpenZeppelin contracts. This TOML snippet is crucial for setting up the development environment and understanding project integrations. ```toml [dependencies] starknet = "2.8.2" game_components_minigame = { path = "../minigame" } game_components_metagame = { path = "../metagame" } game_components_utils = { path = "../utils" } [dependencies.openzeppelin] git = "https://github.com/OpenZeppelin/cairo-contracts.git" tag = "v0.18.0" ``` -------------------------------- ### Basic Game Token Deployment with Core Component Source: https://github.com/provable-games/game-components/blob/main/README.md This Cairo code snippet shows how to deploy a basic game token contract using the `CoreTokenComponent` from the `game_components_token` library. It illustrates the component-based architecture in StarkNet contracts. ```cairo // Deploy a simple game token use game_components_token::core::CoreTokenComponent; use game_components_minigame::interface::{IMinigame, IMinigameTokenData}; #[starknet::contract] mod MyGameToken { use super::CoreTokenComponent; component!(path: CoreTokenComponent, storage: core_token, event: CoreTokenEvent); #[abi(embed_v0)] impl CoreTokenImpl = CoreTokenComponent::CoreTokenImpl; } ``` -------------------------------- ### Deploy and Interact with LeaderboardPreset Contract (Cairo) Source: https://github.com/provable-games/game-components/blob/main/packages/presets/README.md Demonstrates deploying a LeaderboardPreset contract and performing common operations like submitting scores, retrieving top entries, and checking qualifications. This preset requires owner, tournament ID, max entries, sorting order, and game contract address as constructor parameters. ```cairo use game_components_presets::leaderboard::ILeaderboardDispatcher; // Deploy the leaderboard let leaderboard = ILeaderboardDispatcher { contract_address: deploy_leaderboard( owner: admin_address, tournament_id: 1, max_entries: 10, ascending: false, // Higher scores rank better game_address: game_contract_address ) }; // Submit a score leaderboard.submit_score(token_id: 123, score: 1500, position: 1); // Get top 5 entries let top_entries = leaderboard.get_top_entries(5); // Check if a score qualifies let qualifies = leaderboard.qualifies(score: 1200); ``` -------------------------------- ### Build Game Components Test Package Source: https://github.com/provable-games/game-components/blob/main/packages/test_starknet/README.md Command to build the Starknet game components test package. This command is typically run from the package's directory. ```bash cd packages/test_starknet scarb build ``` -------------------------------- ### Run Starknet Foundry Tests Source: https://github.com/provable-games/game-components/blob/main/packages/test_starknet/README.md Command to execute unit tests using Starknet Foundry. This command should be run from the project's root directory or the test package directory. ```bash snforge test ``` -------------------------------- ### Scarb.toml Test Dependencies and Configuration Source: https://github.com/provable-games/game-components/blob/main/packages/metagame/test_plan.md This TOML snippet configures the Scarb.toml file for testing purposes. It includes necessary dev-dependencies like snforge_std and local paths for game components, along with Starknet contract build configurations and profile settings for enhanced debugging information. ```toml # Scarb.toml test dependencies [dev-dependencies] snforge_std = "0.45.0" game_components_token = { path = "../token" } [[target.starknet-contract]] sierra = true casm = true [profile.dev.cairo] unstable-add-statements-code-locations = true unstable-add-statements-functions-debug-info = true ``` -------------------------------- ### Generate Starknet Foundry Coverage Report Source: https://github.com/provable-games/game-components/blob/main/packages/metagame/test_plan.md After running tests with coverage enabled, this command generates a human-readable report detailing the test coverage. This report is crucial for identifying areas that may require additional test cases. ```bash snforge coverage-report ``` -------------------------------- ### ContextComponent Function Signatures (Scarb) Source: https://github.com/provable-games/game-components/blob/main/packages/metagame/test_plan.md This snippet shows the internal function signatures for the ContextComponent in Scarb. It includes functions for initialization and registering the context interface. ```Scarb fn initializer(ref self: ComponentState) fn register_context_interface(ref self: ComponentState) ``` -------------------------------- ### Configure Token Features with Macros (Cairo) Source: https://github.com/provable-games/game-components/blob/main/packages/token/README.md This snippet demonstrates how to use the `configure_token_features!` macro to automatically set up token features based on enabled components. It's a key part of the compile-time optimization strategy. ```cairo use game_components_token_optimized::integration::macros::*; // Automatically configure based on enabled components configure_token_features!(ContractState); ``` -------------------------------- ### Initialize MinigameComponent in Cairo Source: https://context7.com/provable-games/game-components/llms.txt This Cairo code snippet demonstrates the initialization of the MinigameComponent within a StarkNet contract. It sets up game metadata, including name, description, developer, publisher, genre, image URL, color, client URL, and addresses for settings, objectives, and the token contract. It also implements the IMinigameTokenData trait for score and game over status retrieval. ```cairo use game_components_minigame::minigame::MinigameComponent; use game_components_minigame::interface::{IMinigame, IMinigameTokenData}; use openzeppelin_introspection::src5::SRC5Component; use starknet::ContractAddress; #[starknet::contract] mod PuzzleGame { use super::*; component!(path: SRC5Component, storage: src5, event: SRC5Event); component!(path: MinigameComponent, storage: minigame, event: MinigameEvent); #[storage] struct Storage { #[substorage(v0)] src5: SRC5Component::Storage, #[substorage(v0)] minigame: MinigameComponent::Storage, scores: starknet::storage::Map, game_over_states: starknet::storage::Map, } #[event] #[derive(Drop, starknet::Event)] enum Event { #[flat] SRC5Event: SRC5Component::Event, #[flat] MinigameEvent: MinigameComponent::Event, } // Implement required IMinigameTokenData trait impl GameTokenDataImpl of IMinigameTokenData { fn score(self: @ContractState, token_id: u64) -> u32 { self.scores.read(token_id) } fn game_over(self: @ContractState, token_id: u64) -> bool { self.game_over_states.read(token_id) } } #[abi(embed_v0)] impl MinigameImpl = MinigameComponent::MinigameImpl; impl MinigameInternalImpl = MinigameComponent::InternalImpl; #[constructor] fn constructor( ref self: ContractState, creator_address: ContractAddress, token_address: ContractAddress, settings_address: Option, objectives_address: Option, ) { self.minigame.initializer( creator_address, "Puzzle Game", // name "A challenging puzzle game", // description "GameStudio", // developer "GamePublisher", // publisher "Puzzle", // genre "https://example.com/image.png", // image Option::Some("#3498db"), // color Option::Some("https://game.example.com"), // client_url Option::None, // renderer_address settings_address, objectives_address, token_address, ); } } ``` -------------------------------- ### Manage Game Settings Presets with IMinigameSettings (Cairo) Source: https://context7.com/provable-games/game-components/llms.txt This function illustrates how to interact with the IMinigameSettings contract to manage game settings presets. It covers checking for preset existence and retrieving detailed settings. Dependencies include the 'game_components_minigame' crate. ```cairo use game_components_minigame::extensions::settings::interface::{ IMinigameSettingsDispatcher, IMinigameSettingsDispatcherTrait }; use game_components_minigame::extensions::settings::structs::{GameSettingDetails, GameSetting}; use starknet::ContractAddress; fn manage_settings(settings_contract: ContractAddress, game_contract: ContractAddress) { let settings_dispatcher = IMinigameSettingsDispatcher { contract_address: settings_contract }; // Check if settings preset exists let exists: bool = settings_dispatcher.settings_exist(1); // Get settings details let details: GameSettingDetails = IMinigameSettingsDetailsDispatcher { contract_address: settings_contract }.settings_details(1); // details.name - Settings preset name // details.description - Settings description // details.settings - Span of GameSetting structs } ``` -------------------------------- ### MetagameComponent API Source: https://github.com/provable-games/game-components/blob/main/packages/metagame/test_plan.md Provides functions for interacting with the Metagame component, including retrieving contract addresses, initialization, and minting game tokens. ```APIDOC ## GET minigame_token_address ### Description Returns the stored minigame token contract address. This is a read-only operation and the value does not change after initialization. ### Method GET ### Endpoint /metagame/minigame_token_address ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **minigame_token_address** (ContractAddress) - The address of the minigame token contract. #### Response Example ```json { "minigame_token_address": "0x1234567890abcdef1234567890abcdef1234567890" } ``` ``` ```APIDOC ## GET context_address ### Description Returns the stored context contract address. This is a read-only operation and the value does not change after initialization. The address can be zero. ### Method GET ### Endpoint /metagame/context_address ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **context_address** (ContractAddress) - The address of the context contract. #### Response Example ```json { "context_address": "0xabcdef1234567890abcdef1234567890abcdef1234" } ``` ``` ```APIDOC ## POST initializer ### Description Initializes the Metagame component. This function can only be called once and sets the minigame token address and an optional context contract address. It also registers the SRC5 interface. ### Method POST ### Endpoint /metagame/initializer ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **context_address** (Option) - Optional address of the context contract. - **minigame_token_address** (ContractAddress) - Required address of the minigame token contract. ### Request Example ```json { "context_address": "0xabcdef1234567890abcdef1234567890abcdef1234", "minigame_token_address": "0x1234567890abcdef1234567890abcdef1234567890" } ``` ### Response #### Success Response (200) - **message** (string) - Initialization successful. #### Response Example ```json { "message": "Metagame component initialized successfully." } ``` ``` ```APIDOC ## POST mint ### Description Delegates the minting of a game token. It first validates context requirements and then calls the mint function on the associated token contract. This function can revert if context validation fails. ### Method POST ### Endpoint /metagame/mint ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **game_address** (Option) - The address of the game. - **player_name** (Option) - The name of the player. - **settings_id** (Option) - The ID of the game settings. - **start** (Option) - The start timestamp for the game. - **end** (Option) - The end timestamp for the game. - **objective_ids** (Option>) - A list of objective IDs. - **context** (Option) - Details about the game context. - **client_url** (Option) - The URL of the game client. - **renderer_address** (Option) - The address of the renderer. - **to** (ContractAddress) - The address to mint the token to. - **soulbound** (bool) - Whether the token should be soulbound. ### Request Example ```json { "game_address": "0xgameaddress123", "player_name": "PlayerOne", "settings_id": 1, "start": 1678886400, "end": 1678972800, "objective_ids": [101, 102], "context": { "key": "value" }, "client_url": "http://example.com/game", "renderer_address": "0xrenderer456", "to": "0xtoaddress789", "soulbound": false } ``` ### Response #### Success Response (200) - **token_id** (u64) - The ID of the minted token. #### Response Example ```json { "token_id": 1234567890 } ``` ``` -------------------------------- ### Library Functions Source: https://github.com/provable-games/game-components/blob/main/packages/metagame/test_plan.md Provides utility functions that can be called externally or delegated to from components. ```APIDOC ## GET libs::assert_game_registered ### Description Verifies if a game is registered with the minigame token contract. This is a library function and can be called directly or delegated. ### Method GET ### Endpoint /libs/assert_game_registered ### Parameters #### Path Parameters None #### Query Parameters - **minigame_token_address** (ContractAddress) - Required - The address of the minigame token contract. - **game_address** (ContractAddress) - Required - The address of the game to check. ### Request Example None ### Response #### Success Response (200) - **status** (string) - Indicates if the game is registered. #### Response Example ```json { "status": "Game is registered." } ``` #### Error Response (400) - **error** (string) - "Game is not registered" #### Error Response Example ```json { "error": "Game is not registered" } ``` ``` ```APIDOC ## POST libs::mint ### Description Directly delegates the minting of a game token to the specified token contract. This function mirrors the MetagameComponent::mint function's parameters and behavior. ### Method POST ### Endpoint /libs/mint ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **minigame_token_address** (ContractAddress) - The address of the minigame token contract. - **game_address** (Option) - The address of the game. - **player_name** (Option) - The name of the player. - **settings_id** (Option) - The ID of the game settings. - **start** (Option) - The start timestamp for the game. - **end** (Option) - The end timestamp for the game. - **objective_ids** (Option>) - A list of objective IDs. - **context** (Option) - Details about the game context. - **client_url** (Option) - The URL of the game client. - **renderer_address** (Option) - The address of the renderer. - **to** (ContractAddress) - The address to mint the token to. - **soulbound** (bool) - Whether the token should be soulbound. ### Request Example ```json { "minigame_token_address": "0x1234567890abcdef1234567890abcdef1234567890", "game_address": "0xgameaddress123", "player_name": "PlayerTwo", "settings_id": 2, "start": 1678886400, "end": 1678972800, "objective_ids": [201, 202], "context": { "key": "value" }, "client_url": "http://example.com/game", "renderer_address": "0xrenderer456", "to": "0xtoaddress789", "soulbound": true } ``` ### Response #### Success Response (200) - **token_id** (u64) - The ID of the minted token. #### Response Example ```json { "token_id": 9876543210 } ``` ``` -------------------------------- ### Library Function Signatures (Scarb) Source: https://github.com/provable-games/game-components/blob/main/packages/metagame/test_plan.md This snippet presents the signatures for library functions related to game registration and minting, written in Scarb. These functions are designed to be called from other contracts. ```Scarb fn assert_game_registered(minigame_token_address: ContractAddress, game_address: ContractAddress) fn mint(minigame_token_address: ContractAddress, game_address: Option, player_name: Option, settings_id: Option, start: Option, end: Option, objective_ids: Option>, context: Option, client_url: Option, renderer_address: Option, to: ContractAddress, soulbound: bool) -> u64 ``` -------------------------------- ### MinigameComponent Initialization in Cairo Source: https://github.com/provable-games/game-components/blob/main/test_plan.md Initializes the Minigame contract, setting the addresses for the token, settings, and objectives components. This is an internal function that modifies the contract's state. ```cairo fn initializer(ref self, token_address: ContractAddress, settings_address: ContractAddress, objectives_address: ContractAddress) ``` -------------------------------- ### MetagameComponent Initialization in Cairo Source: https://github.com/provable-games/game-components/blob/main/test_plan.md Initializes the Metagame contract, setting the addresses for the minigame token and context components. This function is internal and mutates the contract's state. ```cairo fn initializer(ref self, minigame_token_address: ContractAddress, context_address: ContractAddress) ``` -------------------------------- ### Initialize Game Component Contract (Rust) Source: https://context7.com/provable-games/game-components/llms.txt Initializes the core components of a game contract, including ERC721, ERC2981 royalties, and optional extensions. It sets up the contract for a single game scenario. ```rust #[constructor] fn constructor( ref self: ContractState, name: ByteArray, symbol: ByteArray, base_uri: ByteArray, royalty_receiver: ContractAddress, royalty_fraction: u128, game_address: ContractAddress, creator_address: ContractAddress, event_relayer_address: Option, ) { // Initialize ERC721 with name, symbol, and base URI self.erc721.initializer(name, symbol, base_uri); // Initialize ERC2981 royalties (e.g., 5% = 500 basis points) self.erc2981.initializer(royalty_receiver, royalty_fraction); // Initialize core token with single game setup self.core_token.initializer( Option::Some(game_address), // Direct game address Option::Some(creator_address), // Creator receives token 0 Option::None, // No registry for single-game event_relayer_address, ); // Initialize optional extensions self.minter.initializer(); self.objectives.initializer(); self.settings.initializer(); self.context.initializer(); self.renderer.initializer(); } } ``` -------------------------------- ### CoreTokenComponent Initialization in Cairo Source: https://github.com/provable-games/game-components/blob/main/test_plan.md Initializes the CoreToken component, setting addresses for the game, game registry, and event relayer. This internal function mutates state and emits events. ```cairo fn initializer(ref self, game_address: ContractAddress, game_registry_address: ContractAddress, event_relayer_address: ContractAddress) ``` -------------------------------- ### Use MetagameComponent Functions with Cairo Source: https://context7.com/provable-games/game-components/llms.txt Illustrates how to interact with the MetagameComponent for game management, including querying configuration and understanding its role in minting processes. This snippet also shows how to integrate MetagameComponent within a StarkNet contract using the component pattern. ```cairo use game_components_metagame::metagame::MetagameComponent; use game_components_metagame::interface::{IMetagameDispatcher, IMetagameDispatcherTrait}; use game_components_metagame::extensions::context::interface::{ IMetagameContextDispatcher, IMetagameContextDispatcherTrait }; use game_components_metagame::extensions::context::structs::{GameContextDetails, GameContext}; use starknet::ContractAddress; fn use_metagame( metagame_contract: ContractAddress, game_contract: ContractAddress, player: ContractAddress, ) { let metagame = IMetagameDispatcher { contract_address: metagame_contract }; // Query metagame configuration let token_addr: ContractAddress = metagame.default_token_address(); let context_addr: ContractAddress = metagame.context_address(); // Mint through metagame (internal function usage in component) // The metagame component delegates minting to the token contract } // Metagame component integration in a tournament contract #[starknet::contract] mod TournamentContract { use game_components_metagame::metagame::MetagameComponent; use openzeppelin_introspection::src5::SRC5Component; use starknet::ContractAddress; component!(path: SRC5Component, storage: src5, event: SRC5Event); component!(path: MetagameComponent, storage: metagame, event: MetagameEvent); #[storage] struct Storage { #[substorage(v0)] src5: SRC5Component::Storage, #[substorage(v0)] metagame: MetagameComponent::Storage, } #[event] #[derive(Drop, starknet::Event)] enum Event { #[flat] SRC5Event: SRC5Component::Event, #[flat] MetagameEvent: MetagameComponent::Event, } #[abi(embed_v0)] impl MetagameImpl = MetagameComponent::MetagameImpl; impl MetagameInternalImpl = MetagameComponent::InternalImpl; #[constructor] fn constructor( ref self: ContractState, token_address: ContractAddress, context_address: Option, ) { self.metagame.initializer(context_address, token_address); } } ``` -------------------------------- ### Token Contract Feature Flags (Cairo) Source: https://github.com/provable-games/game-components/blob/main/AGENTS.md Demonstrates the use of compile-time feature flags in Cairo for optimizing token contract size. These flags allow for the elimination of unused code at compile time to stay under StarkNet's contract size limits. ```cairo pub const MINTER_ENABLED: bool = true; pub const MULTI_GAME_ENABLED: bool = false; pub const OBJECTIVES_ENABLED: bool = true; // ... etc ``` -------------------------------- ### Conditional Feature Execution Based on Configuration (Cairo) Source: https://github.com/provable-games/game-components/blob/main/packages/token/README.md This code illustrates compile-time optimization and runtime sophistication. It shows how to conditionally execute logic, like checking for a minter component, only if the `MINTER_ENABLED` flag is true. This ensures that the code for disabled features is not included in the final contract. ```cairo // Compile-time optimization let minted_by = if config::MINTER_ENABLED { // Runtime sophistication - only compiled if enabled if src5_component.supports_interface(IMINIGAME_TOKEN_MINTER_ID) { let minter_component = get_dep_component!(ref self, Minter); minter_component.on_mint_with_minter(caller) } else { 0 } } else { 0 }; ``` -------------------------------- ### IMinigameSettings Functions Source: https://context7.com/provable-games/game-components/llms.txt Create and manage game settings presets that define difficulty levels, game modes, and custom parameters. ```APIDOC ## IMinigameSettings Functions ### Description Create and manage game settings presets that define difficulty levels, game modes, and custom parameters. ### Method (Not specified, likely internal or part of a larger contract) ### Endpoint (Not specified) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (Code example provided in source, not a direct API request) ### Response #### Success Response (200) (Not specified) #### Response Example (Not specified) **Key Functions:** - `settings_exist(settings_id)`: Checks if a settings preset exists. - `settings_details(settings_id)`: Retrieves the details of a specific settings preset. - `create_settings(game_contract, settings_id, name, description, settings_data)`: Creates a new game settings preset via the token contract. ``` -------------------------------- ### Mock Extension Contracts (Cairo) Source: https://github.com/provable-games/game-components/blob/main/packages/token/test_plan.md Placeholder modules for mocking optional game extensions. These include mocks for settings (IMinigameSettings), objectives (IMinigameObjectives), and custom renderers. ```cairo # Mocks for optional extensions mod MockSettings; // IMinigameSettings implementation mod MockObjectives; // IMinigameObjectives implementation mod MockRenderer; // Custom renderer implementation ``` -------------------------------- ### Manage Leaderboard Operations with Cairo Source: https://context7.com/provable-games/game-components/llms.txt Demonstrates how to configure, submit scores to, query, and manage a multi-tournament leaderboard using Cairo. It covers admin functions like clearing and ownership transfer, and user-facing functions for score submission and retrieval. Dependencies include the game_components_leaderboard library. ```cairo use game_components_leaderboard::interface::{ ILeaderboardDispatcher, ILeaderboardDispatcherTrait, ILeaderboardAdminDispatcher, ILeaderboardAdminDispatcherTrait }; use game_components_leaderboard::leaderboard::leaderboard::{LeaderboardEntry, LeaderboardResult}; use game_components_leaderboard::leaderboard_store::LeaderboardStoreConfig; use starknet::ContractAddress; fn manage_leaderboard( leaderboard_contract: ContractAddress, game_contract: ContractAddress, tournament_id: u64, ) { let leaderboard = ILeaderboardDispatcher { contract_address: leaderboard_contract }; let admin = ILeaderboardAdminDispatcher { contract_address: leaderboard_contract }; // Configure tournament leaderboard (admin only) admin.configure_tournament( tournament_id, 10, // max_entries - top 10 leaderboard false, // ascending - false means higher scores are better game_contract, ); // Submit a score let result: LeaderboardResult = leaderboard.submit_score( tournament_id, 1, // token_id 1500, // score 1, // position hint (optimization) ); // Query leaderboard let entries: Array = leaderboard.get_entries(tournament_id); let top_5: Array = leaderboard.get_top_entries(tournament_id, 5); // Get position of specific token let position: Option = leaderboard.get_position(tournament_id, 1); // Check if score qualifies for leaderboard let qualifies: bool = leaderboard.qualifies(tournament_id, 1200); // Check leaderboard state let is_full: bool = leaderboard.is_full(tournament_id); let length: u32 = leaderboard.get_leaderboard_length(tournament_id); // Get tournament config let config: LeaderboardStoreConfig = leaderboard.get_tournament_config(tournament_id); // Admin operations admin.clear_leaderboard(tournament_id); admin.transfer_ownership(new_owner); } ``` -------------------------------- ### MetagameComponent Function Signatures (Scarb) Source: https://github.com/provable-games/game-components/blob/main/packages/metagame/test_plan.md This snippet displays the external and internal function signatures for the MetagameComponent, as defined in the Scarb contract language. It includes functions for retrieving contract addresses, initialization, registering interfaces, asserting game registration, and minting tokens. ```Scarb fn minigame_token_address(self: @ComponentState) -> ContractAddress fn context_address(self: @ComponentState) -> ContractAddress fn initializer(ref self: ComponentState, context_address: Option, minigame_token_address: ContractAddress) fn register_src5_interfaces(ref self: ComponentState) fn assert_game_registered(ref self: ComponentState, game_address: ContractAddress) fn mint(ref self: ComponentState, game_address: Option, player_name: Option, settings_id: Option, start: Option, end: Option, objective_ids: Option>, context: Option, client_url: Option, renderer_address: Option, to: ContractAddress, soulbound: bool) -> u64 ``` -------------------------------- ### Register New Game with Minigame Registry (Cairo) Source: https://context7.com/provable-games/game-components/llms.txt Registers a new game with the IMinigameRegistry contract. This function requires the registry's address and the creator's address, and it returns the newly assigned game ID. It assumes the caller is a contract implementing IMinigame. ```cairo use game_components_token::examples::minigame_registry_contract:: IMinigameRegistryDispatcher; use starknet::ContractAddress; fn register_new_game( registry_address: ContractAddress, creator: ContractAddress, ) -> u64 { let registry = IMinigameRegistryDispatcher { contract_address: registry_address }; // Register game (must be called from a contract implementing IMinigame) let game_id = registry.register_game( creator, "Space Invaders", // name "Classic arcade shooter", // description "RetroGames Studio", // developer "Arcade Publisher", // publisher "Arcade", // genre "https://cdn.example.com/space.png", // image Option::Some("#00ff00"), // color Option::Some("https://play.example.com/space"), // client_url Option::None, // renderer_address ); game_id // Returns assigned game ID } ```