diff --git a/.cursorrules b/.cursorrules new file mode 100644 index 0000000..484277f --- /dev/null +++ b/.cursorrules @@ -0,0 +1,73 @@ +You are an expert in Cairo, game development, ECS (Entity Component System), blockchain technology, Starknet, and the Dojo Framework. + +Key Principles + +- Write clear, concise, and idiomatic Cairo code with accurate examples. +- Use ECS paradigms effectively for game development. +- Prioritize modularity, clean code organization, and efficient resource management in Cairo and Dojo projects. +- Use expressive variable names that convey intent (e.g., `is_ready`, `has_data`). +- Adhere to Cairo's naming conventions: snake_case for variables and functions, PascalCase for types and structs. +- Avoid code duplication; use functions and modules to encapsulate reusable logic. +- Write code with safety, concurrency, and performance in mind, embracing Cairo's ownership and type system. + +Game Development with ECS + +- Implement ECS architecture using Dojo's components, systems, and world. +- Use Dojo's query system for efficient entity management and data access. +- Leverage Dojo's event system for game state changes and inter-system communication. +- Implement game loops and update cycles using Dojo's system execution order. +- Optimize performance by minimizing state changes and leveraging Dojo's batched updates. + +Smart Contract Development + +- Use Starknet-specific annotations and decorators for contract development. +- Implement storage variables and mappings using Starknet's storage model. +- Use events for logging important state changes in smart contracts. +- Implement view and external functions for contract interactions. +- Utilize Starknet's native types (e.g., felt252, ContractAddress) appropriately. + +Blockchain Integration + +- Implement cross-contract communication using contract calls and interfaces. +- Use Starknet's messaging system for L1-L2 communication. +- Implement account abstraction features for enhanced user experience. +- Utilize Starknet's cryptographic primitives for secure operations. + +Dojo Framework + +- Use Sozo for project scaffolding, building, and deployment. +- Leverage Katana for local development and testing of Starknet contracts. +- Utilize Torii for efficient indexing and querying of on-chain data. +- Implement and use actions for game state transitions. +- Use Dojo's authorization system for secure contract interactions. + +Testing and Deployment + +- Write unit tests for Cairo contracts using the `#[test]` attribute. +- Use Dojo's testing utilities for simulating game scenarios. +- Implement integration tests to validate contract interactions and game logic. +- Use Katana for local testing and Starknet's testnet for pre-production deployment. +- Leverage Sozo for managing contract migrations and upgrades. + +Performance Optimization + +- Minimize storage reads and writes in smart contracts. +- Use efficient data structures and algorithms for on-chain computations. +- Implement off-chain computations where possible, using on-chain verification. +- Optimize gas usage by batching transactions and using calldata efficiently. + Ï + Key Conventions + +1. Structure the application into modules: separate concerns like game logic, smart contracts, and off-chain components. +2. Use environment variables for configuration management in off-chain components. +3. Ensure code is well-documented with inline comments and Cairo-doc. + +Ecosystem + +- Use Cairo for smart contract development on Starknet. +- Leverage Scarb for package management and build processes. +- Use Dojo for game development on Starknet. +- Utilize Katana for local Starknet development environment. +- Implement off-chain components using languages like Rust or TypeScript for optimal performance. + +Refer to the Cairo Book, Starknet documentation, and Dojo documentation for in-depth information on best practices and advanced features.Ï diff --git a/.github/workflows/ci-contracts.yml b/.github/workflows/ci-contracts.yml new file mode 100644 index 0000000..8ca8257 --- /dev/null +++ b/.github/workflows/ci-contracts.yml @@ -0,0 +1,33 @@ +name: ci-contracts + +on: + push: + branches: [main] + + pull_request: + branches: [main] + +env: + CARGO_TERM_COLOR: always + RUST_VERSION: 1.80.1 + +jobs: + cairofmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: software-mansion/setup-scarb@v1 + with: + scarb-version: "2.7.0" + - run: | + scarb fmt --check + core-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: asdf-vm/actions/setup@v3 + - run: | + asdf plugin add dojo https://github.com/dojoengine/asdf-dojo + asdf install dojo 1.0.0-alpha.11 + asdf global dojo 1.0.0-alpha.11 + sozo test diff --git a/README.md b/README.md index 61a5fc1..57c3166 100644 --- a/README.md +++ b/README.md @@ -1,129 +1,67 @@ + +Dojo logo + + + + + + + + + +[![discord](https://img.shields.io/badge/join-pixelaw-green?logo=discord&logoColor=white)](https://discord.gg/PwDa2mKhR4) + # PixeLAW App Template Contracts written in Cairo using Dojo to showcase a Pixel World with app interoperability. Its interoperability is made possible with core actions. Apps are any other contracts that are deployed to the Pixel World. -## Development - -### Prerequisites +## Prerequisites - [asdf](https://asdf-vm.com/) - [scarb](https://docs.swmansion.com/scarb/) - [dojo](https://github.com/dojoengine/dojo) -### Install asdf +## Install asdf Follow the asdf installation instructions. -### Install dojo +## Install dojo ``` asdf plugin add dojo https://github.com/dojoengine/asdf-dojo asdf install dojo 1.0.0-alpha.11 ``` -### Install scarb +## Install scarb ``` asdf plugin add scarb -asdf install scarb 2.7.0-rc.4 +asdf install scarb 2.7.0 ``` And after moving into contracts directory, the versions for these libs are set in the .tool-versions file. -## Default Apps - -These are apps developed by PixeLAW - -## Paint - -### Overview - -The Paint App is a collection of functions that allow players to manipulate the color of a Pixel. - -### Properties - -None, Paint is just behavior. - -### Behavior - -- public `put_color(color)` - - context: position -- both `put_fading_color(color)` - - context: position -- public `remove_color()` - - context: position - -## Snake - -### Overview +## Running Locally -It it basically the game "snake", but with Pixels not necessarily available to move on/over. It is a player-initialized instance that coordinates pixel's color and text being overriden and reverted (if allowed). -If hitting an unowned Pixel, the snake will move, if Pixel is owned by player, Snake grows, and if Pixel is not owned but it's App allows Snake, it shrinks. In all other cases, Snake dies. +#### Terminal one (Make sure this is running) -### Properties - -- position -- color -- text -- direction - -### Behavior - -- public `spawn(color, text, direction)` - - context: position -- public `turn(snake_id, direction)` - - context: player -- private `move(snake_id)` - -## Rock Paper Scissors - -### Overview - -Each Pixel can contain an instance of the RPS App, where it holds a commitment (rock, paper or scissors) from player1. Any other player can now "join" and submit their move. Player1 can then reveal, the winner is decided then. Winner gains ownership of the losing RPS pixel. In case of a draw, the pixel is reset. -The App is also tracking score for each Player. - -### Global Properties - -- player+wins - -### Game-based Properties - -- player1 -- player2 - -### Behavior - -- create (position, player1, commit1) -- join (position, player2, move2) -- finish (position, move1, salt1) -- reset (position) +```bash +# Run Katana +katana --disable-fee --allowed-origins "*" +``` -## CommitReveal inputs +#### Terminal two -### Param of the action +```bash +# Build the example +sozo build -- (Hashed Commit) - - parametername of action has structure: "PREFIX_TYPE_NAME" - - PREFIX is "cr\_" - - TYPE for now is the name of an int, felt or Enum declared in the manifest - - NAME is a chosen name to refer to the param. -- (Value+Salt reveal) - - parametername of action has structure: "PREFIX_NAME" - - PREFIX shall always be "rv\_" - - NAME is the same name user during sending the commit +# Migrate the example +sozo migrate apply -### Clientside functioning +# Initialize the pixelaw app +scarb run init_auth -- If client finds a param starting with "cr\_" -- It will prompt user for a param with TYPE - - example: - - The game RPS needs player1 to choose one option, but only send the hashedcommit - - Then, during a next stage of the game, the plaintext move and the salt will be requested - - The challenge is that the UI needsto be capable of doing this without knowing about the specific application. Reveal/Commit is a feature of the platform. - - Commit - - RpsMove is an enum with 3 fields, so ui presents user with 3 choices - - UI stores this clientside related to the pixel/app - - UI then hashes this with a salt, and also stores the salt with the choice - - UI then calls the functions with only the hash value - - Reveal - - there will be 2 params: "rv_NAME" (the actual param) and "rs_NAME" (the used salt) +# Start Torii +torii --world 0x263ae44e5414519a5c5a135cccaf3d9d7ee196d37e8de47a178da91f3de9b34 --allowed-origins "*" +``` diff --git a/Scarb.lock b/Scarb.lock index 544bc90..ca7dd89 100644 --- a/Scarb.lock +++ b/Scarb.lock @@ -18,12 +18,14 @@ source = "git+https://github.com/dojoengine/dojo?rev=f15def33#f15def330c0d099e79 name = "myapp" version = "0.0.0" dependencies = [ + "dojo", "pixelaw", ] [[package]] name = "pixelaw" version = "0.3.50" +source = "git+https://github.com/pixelaw/core?tag=v0.3.50#78abcff1835740411f785b65e84941c3f7ee59b6" dependencies = [ "dojo", ] diff --git a/Scarb.toml b/Scarb.toml index b8b21b9..dbeef9d 100644 --- a/Scarb.toml +++ b/Scarb.toml @@ -7,11 +7,35 @@ version = "0.0.0" sierra-replace-ids = true [dependencies] -pixelaw = { path = "/Users/asumayamada/Private/pixelaw/core/contracts" } -# pixelaw = { git = "https://github.com/pixelaw/core", tag = "v0.3.50" } +pixelaw = { git = "https://github.com/pixelaw/core", tag = "v0.3.50" } +# Added explicitly for https://github.com/dojoengine/dojo/issues/2430 +dojo = { git = "https://github.com/dojoengine/dojo", tag = "v1.0.0-alpha.11" } [[target.dojo]] -build-external-contracts = [] +build-external-contracts = [ + "pixelaw::core::models::pixel::pixel", + "pixelaw::core::models::pixel::Pixel", + "pixelaw::core::models::pixel::PixelUpdate", + "pixelaw::core::models::queue::queue_item", + "pixelaw::core::models::registry::app", + "pixelaw::core::models::registry::app_name", + "pixelaw::core::models::registry::app_user", + "pixelaw::core::models::registry::app_instruction", + "pixelaw::core::models::registry::instruction", + "pixelaw::core::models::registry::core_actions_address", + "pixelaw::core::models::permissions::permissions", + "pixelaw::core::utils::get_core_actions", + "pixelaw::core::utils::Direction", + "pixelaw::core::utils::Position", + "pixelaw::core::utils::DefaultParameters", + "pixelaw::core::actions::actions", + "pixelaw::core::actions::IActionsDispatcher", + "pixelaw::core::actions::IActionsDispatcherTrait", +] [tool.fmt] -sort-module-level-items = true \ No newline at end of file +sort-module-level-items = true + + +[scripts] +init_auth = "./scripts/init_auth.sh" \ No newline at end of file diff --git a/scripts/default_auth.sh b/scripts/default_auth.sh deleted file mode 100644 index 8541c33..0000000 --- a/scripts/default_auth.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash -set -euo pipefail -pushd $(dirname "$0")/.. - - -export APP_NAME=$(grep "^name" Scarb.toml | awk -F' = ' '{print $2}' | tr -d '"') -# export ACTIONS_ADDRESS=$(cat ./target/$SCARB_PROFILE/manifest.json | jq -r '.contracts | first | .address') -export ACTIONS_ADDRESS=$(cat ./manifests/dev/manifest.json | jq -r '.contracts | first | .address') - -echo "---------------------------------------------------------------------------" -echo app : $APP_NAME -echo " " -echo actions : $ACTIONS_ADDRESS -echo "---------------------------------------------------------------------------" - -# enable system -> component authorizations -# COMPONENTS=($(jq -r --arg APP_NAME "$APP_NAME" '.models[] | select(.name | contains($APP_NAME)) | .name' ./target/dev/manifest.json)) -COMPONENTS=($(jq -r --arg APP_NAME "$APP_NAME" '.models[] | select(.name | contains($APP_NAME)) | .name' ./manifests/dev/manifest.json)) - -for index in "${!COMPONENTS[@]}"; do - IFS='::' read -ra NAMES <<< "${COMPONENTS[index]}" - LAST_INDEX=${#NAMES[@]}-1 - NEW_NAME=`echo ${NAMES[LAST_INDEX]} | sed -r 's/_/ /g' | awk '{for(j=1;j<=NF;j++){ $j=toupper(substr($j,1,1)) substr($j,2) }}1' | sed -r 's/ //g'` - COMPONENTS[index]=$NEW_NAME -done - -# if #COMPONENTS is 0, then there are no models in the manifest. This might be error, -echo "Write permissions for ACTIONS" -if [ ${#COMPONENTS[@]} -eq 0 ]; then - echo "Warning: No models found in manifest.json. Are you sure you don't have new any components?" -else - for component in ${COMPONENTS[@]}; do - echo "For $component" - # sozo --profile $SCARB_PROFILE auth grant writer $component,$ACTIONS_ADDRESS - sozo --profile dev auth grant writer $component,$ACTIONS_ADDRESS - done -fi -echo "Write permissions for ACTIONS: Done" - -# echo "Initialize ACTIONS: (sozo --profile $SCARB_PROFILE execute $ACTIONS_ADDRESS init)" -echo "Initialize ACTIONS: (sozo --profile dev execute $ACTIONS_ADDRESS init)" - -sleep 0.1 -# sozo --profile $SCARB_PROFILE execute $ACTIONS_ADDRESS init -sozo --profile dev execute $ACTIONS_ADDRESS init -echo "Initialize ACTIONS: Done" - - -echo "Default authorizations have been successfully set." diff --git a/scripts/init_auth.sh b/scripts/init_auth.sh new file mode 100755 index 0000000..609de55 --- /dev/null +++ b/scripts/init_auth.sh @@ -0,0 +1,52 @@ +#!/bin/bash +set -euo pipefail +pushd $(dirname "$0")/.. + +echo $SCARB_PROFILE + +# Get the profile from $SCARB_PROFILE +profile=${SCARB_PROFILE:-"dev"} + +# Read values from dojo_${profile}.toml +config_file="dojo_${profile}.toml" + +if [ ! -f "$config_file" ]; then + echo "Error: $config_file not found" + exit 1 +fi + +# Extract values using grep and cut +account_address=$(grep "account_address" "$config_file" | cut -d'"' -f2) +private_key=$(grep "private_key" "$config_file" | cut -d'"' -f2) +world_address=$(grep "world_address" "$config_file" | cut -d'"' -f2) + +declare "CORE_ACTIONS"="pixelaw-actions" +declare "MYAPP_ACTIONS"="pixelaw-myapp_actions" + +## Set RPC_URL with default value +#RPC_URL="http://localhost:5050" + +# Check if a command line argument is supplied +if [ $# -gt 0 ]; then + # If an argument is supplied, use it as the RPC_URL + RPC_URL=$1 +fi + +# make sure all components/systems are deployed +CORE_MODELS=("pixelaw-App" "pixelaw-AppName" "pixelaw-CoreActionsAddress" "pixelaw-Pixel" "pixelaw-Permissions" "pixelaw-QueueItem" "pixelaw-Instruction") + +echo "Write permissions for CORE_ACTIONS" +for model in ${CORE_MODELS[@]}; do + sleep 0.1 + sozo --profile $SCARB_PROFILE auth grant writer model:$model,$CORE_ACTIONS +done +echo "Write permissions for CORE_ACTIONS: Done" + +echo "Initialize CORE_ACTIONS : $CORE_ACTIONS" +sleep 0.1 +sozo --profile $SCARB_PROFILE execute $CORE_ACTIONS init +echo "Initialize CORE_ACTIONS: Done" + +sleep 0.1 +sozo --profile $SCARB_PROFILE execute $MYAPP_ACTIONS init +echo "Initialize MYAPP_ACTIONS: Done" diff --git a/scripts/ready_for_deployment.sh b/scripts/ready_for_deployment.sh deleted file mode 100644 index 363b100..0000000 --- a/scripts/ready_for_deployment.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -while true; do - response=$(curl -s http://localhost:3000/manifests/core) - if [[ $response != *"Not Found"* ]]; then - echo "Ready for app deployment" - break - fi - sleep 1 -done diff --git a/scripts/upload_manifest.sh b/scripts/upload_manifest.sh deleted file mode 100644 index 9ea3363..0000000 --- a/scripts/upload_manifest.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash - -APP_NAME=$(grep "^name" ./Scarb.toml | awk -F' = ' '{print $2}' | tr -d '"') -echo "APP_NAME : $APP_NAME" -SYSTEMS=("core" "paint" "snake" "$APP_NAME") - -DEFAULT_BASE_URL="http://localhost:3000/manifests" -# JSON_FILE="./target/dev/manifest.json" -JSON_FILE="./manifests/dev/manifest.json" - -# Check if a command line argument is provided -if [ "$#" -ne 0 ]; then - BASE_URL="$1" -else - BASE_URL="$DEFAULT_BASE_URL" -fi - -echo "---------------------------------------------------------------------------" -echo BASE_URL : $BASE_URL -echo "---------------------------------------------------------------------------" - -echo "Uploading manifests for system" -echo " " -for system in ${SYSTEMS[@]}; do - echo "Uploading manifest for" $system - URL="${BASE_URL}/${system}" - curl -X POST -H "Content-Type: application/json" -d @"$JSON_FILE" "$URL" - echo " " - echo "Uploading manifest for" $system ": DONE" - echo " " -done diff --git a/src/app.cairo b/src/app.cairo index dff85f2..1327364 100644 --- a/src/app.cairo +++ b/src/app.cairo @@ -4,7 +4,7 @@ use pixelaw::core::utils::{get_core_actions, Direction, Position, DefaultParamet use starknet::{get_caller_address, get_contract_address, get_execution_info, ContractAddress}; #[dojo::interface] -trait IMyAppActions { +pub trait IMyAppActions { fn init(ref world: IWorldDispatcher); fn interact(ref world: IWorldDispatcher, default_params: DefaultParameters); } @@ -20,7 +20,7 @@ const APP_MANIFEST: felt252 = 'BASE/manifests/myapp'; /// contracts must be named as such (APP_KEY + underscore + "actions") #[dojo::contract(namespace: "pixelaw", nomapping: true)] -mod myapp_actions { +pub mod myapp_actions { use debug::PrintTrait; use pixelaw::core::actions::{ IActionsDispatcher as ICoreActionsDispatcher, @@ -45,20 +45,6 @@ mod myapp_actions { let core_actions = pixelaw::core::utils::get_core_actions(world); core_actions.update_app(APP_KEY, APP_ICON, APP_MANIFEST); - - //Grant permission to the snake App - core_actions - .update_permission( - 'snake', - Permission { - app: false, - color: true, - owner: false, - text: true, - timestamp: false, - action: true - } - ); } /// Put color on a certain position diff --git a/src/lib.cairo b/src/lib.cairo index c241698..5c5d798 100644 --- a/src/lib.cairo +++ b/src/lib.cairo @@ -1,2 +1,2 @@ -mod app; +pub mod app; mod tests;