diff --git a/0.3.0/book.toml b/0.3.0/book.toml deleted file mode 100644 index 6c0e2c8b..00000000 --- a/0.3.0/book.toml +++ /dev/null @@ -1,21 +0,0 @@ -[book] -authors = ["Tarrence van As", "Loaf", "Sylve Chevet"] -language = "en" -multilingual = false -src = "src" -title = "Dojo: The Provable Game Engine" - -[build] -extra-watch-dirs = ["po"] - -[preprocessor.gettext] -after = ["links"] - -[output.html] -git-repository-url = "https://github.com/dojoengine/book" -edit-url-template = "https://github.com/dojoengine/book/edit/main/{path}" -no-section-label = true - -[output.html.fold] -enable = true -level = 0 diff --git a/0.3.0/src/README.md b/0.3.0/src/README.md deleted file mode 100644 index f59454e2..00000000 --- a/0.3.0/src/README.md +++ /dev/null @@ -1,35 +0,0 @@ -![Dojo](images/dojo-mark-full-dark.svg) - -> Dojo is an open-source project, currently in its early development phase, and warmly welcomes contributors. For additional resources, join the community on [Discord](https://discord.gg/vUN4Xq9Qv6) and check out the [contribution guide](./misc/contributors.md). - ---- - -## Dojo: The Provable Game Engine - -Dojo is a provable game engine built using [Cairo](https://github.com/starkware-libs/cairo). It establishes a standard for game development via smart contracts, blending best practices with streamlined development and deployment tools. With Dojo by your side, you can evolve from initial concept to a fully realized game in days, not weeks. - -This book is dedicated to familiarizing you with the Dojo engine and the potential of Provable games. A special section on the [Theory](./theory/autonomous-worlds.md) elucidates this emergent concept of autonomous worlds and Provable games. - -- [Quickstart](./getting-started/quick-start.md) -- [What is Dojo? ](./theory/what-is-dojo.md) -- [Explore the Architecture](./cairo/hello-dojo.md) - - -### Explainer - -Here's a video of [Cartridge](https://cartridge.gg/)'s [Tarrence](https://twitter.com/tarrenceva) explaining how Dojo works at the 2023 [Autonomous Anonymous Summit](https://twitter.com/pet3rpan_/status/1666764726427353091): - - - - - - -### Organizational Structure -Dojo is an open-source initiative, licensed under Apache 2.0, dedicated to promoting and advancing the concept of Autonomous Worlds (AWs). It is spearheaded by [Cartridge](https://cartridge.gg/), [Realms & BibliothecaDAO](https://bibliothecadao.xyz/), [briq](https://briq.construction/) and many more [contributors](https://github.com/orgs/dojoengine/people). - -### How do I get involved? - -Check out our [Github](https://github.com/dojoengine), our [Twitter](https://twitter.com/dojostarknet), [Discord](https://discord.gg/vUN4Xq9Qv6) and [contribution guide](https://book.dojoengine.org/misc/contributors.html) diff --git a/0.3.0/src/SUMMARY.md b/0.3.0/src/SUMMARY.md deleted file mode 100644 index 375e425f..00000000 --- a/0.3.0/src/SUMMARY.md +++ /dev/null @@ -1,88 +0,0 @@ -# Summary - -- [Foreword](./README.md) - - [What is Dojo?](./theory/what-is-dojo.md) - - [AW Theory](./theory/autonomous-worlds.md) - - [Cairo Ecosystem](./theory/cairo.md) - - [FAQs](./theory/faqs.md) - -# Getting Started - -- [Quick Start](./getting-started/quick-start.md) - - [Manual Install](./getting-started/from-source.md) - - [Development Setup](./getting-started/setup.md) - - [Contributing](./getting-started/contributing.md) - -# Community - -- [Get Started](./community/get-started.md) - -# Architecture - -- [Overview](./cairo/overview.md) - - [World](./cairo/world.md) - - [Systems](./cairo/systems.md) - - [Models](./cairo/models.md) - - [Commands](./cairo/commands.md) - - [Config](./cairo/config.md) - - [Events](./cairo/events.md) - - [Authorization](./cairo/authorization.md) - - [Metadata](./cairo/metadata.md) -- [Migration](./cairo/migration.md) - - [0.2.0 -> 0.3.0](./cairo/migration/0.3.0.md) -- [ECS in 15 minutes](./cairo/hello-dojo.md) - - - [Entities](./cairo/entities.md) - - [Testing](./cairo/testing.md) - -- [Modules](./cairo/modules.md) - - [ERC20](./cairo/modules/erc20.md) - - [ERC721]() - - [ERC1155]() - - [DeFi]() - -# Client SDKs - -- [Overview](./client/overview.md) -- [JS](./client/npm.md) - - [Core](./client/npm/core.md) -- [torii](./client/torii.md) - -# Toolchain - -- [Dojoup](./toolchain/dojoup.md) -- [Sozo](./toolchain/sozo/overview.md) - - [Reference](./toolchain/sozo/reference.md) - - [init](./toolchain/sozo/project-commands/init.md) - - [build](./toolchain/sozo/project-commands/build.md) - - [test](./toolchain/sozo/project-commands/test.md) - - [migrate](./toolchain/sozo/project-commands/migrate.md) - - [execute](./toolchain/sozo/world-commands/execute.md) - - [register](./toolchain/sozo/world-commands/register.md) - - [system](./toolchain/sozo/world-commands/system.md) - - [component](./toolchain/sozo/world-commands/component.md) - - [events](./toolchain/sozo/world-commands/events.md) - - [auth](./toolchain/sozo/world-commands/auth.md) -- [Katana](./toolchain/katana/overview.md) - - [Reference](./toolchain/katana/reference.md) -- [Torii](./toolchain/torii/overview.md) - - [Reference](./toolchain/torii/reference.md) - - [Graphql](./toolchain/torii/graphql.md) - -# Deploying - -- [Locally](./deployment/locally.md) -- [Remote](./deployment/remote.md) - -# Tutorial - -- [Onchain Chess](./tutorial/onchain-chess/README.md) - - [0. Setup](./tutorial/onchain-chess/0-setup.md) - - [1. Initiate](./tutorial/onchain-chess/1-action.md) - - [2. Move](./tutorial/onchain-chess/2-legal.md) - - [3. Check Legal Move](./tutorial/onchain-chess/3-test.md) - - [4. Test Chess](./tutorial/onchain-chess/4-utils.md) - ---- - -[Contributors](misc/contributors.md) diff --git a/0.3.0/src/cairo/authorization.md b/0.3.0/src/cairo/authorization.md deleted file mode 100644 index e7bfbac0..00000000 --- a/0.3.0/src/cairo/authorization.md +++ /dev/null @@ -1,23 +0,0 @@ -## Authorization - -> Authorization is crucial to a world, just like how authorization is crucial to any smart contract. - -As discussed in the [World](./world.md) chapter, Autonomous Worlds (AWs) function as sovereign chains nested within a public blockchain. These Worlds are also open to the public. This structure allows anyone to enhance a World by deploying models or systems. However, this openness also introduces security considerations. Similar to Ethereum, interacting with a model's state within a System requires the appropriate authorization from the model owner. - -### Auth Architecture - -Every time a `set!` is called in a `System`, the world checks if the `System` has authorization to update the model state. Only when the `System` possesses the necessary authorization, the `set!` is executed. The following diagram illustrates the authorization architecture. - -![Authorization Architecture](../images/dojo-auth.png) - -### Providing Authorization - -> The deployer of the model is its initial owner. A model owner is able to grant the `owner` and `writer` roles. Only owners can grant a System the `writer` role which allows it to update the model. - -`sozo` offers a convenient tool to authorize systems. - -```shell -sozo auth writer Moves spawn -``` - -This command will generate a `writer` authorization for the `spawn` system to update the `Moves` model. \ No newline at end of file diff --git a/0.3.0/src/cairo/commands.md b/0.3.0/src/cairo/commands.md deleted file mode 100644 index 461239b2..00000000 --- a/0.3.0/src/cairo/commands.md +++ /dev/null @@ -1,60 +0,0 @@ -## Commands - -_tldr_ -- Commands are shorthand ways to write function calls -- Commands abstract complex queries into shorthands -- Commands are similar to rust macros - -Understanding commands is key to understanding Dojo. You will leverage them heavily within the systems you design. - -Commands in Dojo are generalized functions that are expanded at compile time to facilitate system execution. They provide a convenient way for systems to interact with the world state by abstracting common operations, such as retrieving or updating models, and generating unique IDs. By leveraging these commands, developers can streamline their system implementations and improve code readability. - - -### Using commands - -Commands are used within systems to interact with the world state. They are called using the following syntax: - -### The `get!` command - -The `get!` command is used to retrieve models from the world state: - -```rust,ignore -// world = calling world -// caller = key of the entity that called the system -// (Position, Moves) = tuple of models to retrieve -let (position, moves) = get!(world, caller, (Position, Moves)); -``` - -Here we are retrieving the `Position` and `Moves` models from the world state. We are also using the `caller` to retrieve the models for the current entity. - -You can then use `position` and `moves` as you would as any other Cairo struct. - -### The `set!` command - -The `set!` command is used to update models state. - -```rust,ignore -set !(world, ( - Moves { - player: caller, remaining: 10 - }, - Position { - player: caller, x: position.x + 10, y: position.y + 10 - }, -)); - -// If the structs are already defined it can also be written as: -set!(world, (moves, position)); -``` - -Here we are updating the `Moves` and `Position` models in the world state using the `caller` as the entity id. - -### The `emit!` command - -The `emit!` command is used to emit custom events. These events are indexed by [torii](../toolchain/torii/overview.md) - -```rust,ignore -emit!(world, Moved { address: caller, direction }); -``` - -This will emit these values which could be captured by a client or you could query these via [torii](../toolchain/torii/overview.md) diff --git a/0.3.0/src/cairo/config.md b/0.3.0/src/cairo/config.md deleted file mode 100644 index 934ec2f4..00000000 --- a/0.3.0/src/cairo/config.md +++ /dev/null @@ -1,37 +0,0 @@ -# Config - -Dojo worlds are defined in their Scarb.toml files. This is just a regular [Scarb](https://docs.swmansion.com/scarb/) file which is an excellent Cairo package manager and project manager. - -Full example of a Scarb.toml file: - -```toml -[package] -cairo-version = "2.3.0" -name = "dojo_examples" -version = "0.1.0" - -[cairo] -sierra-replace-ids = true - -[dependencies] -# IMPORTANT: Dojo should be pinned to a specific version or else your world might not compile -dojo = { git = "https://github.com/dojoengine/dojo", rev="v0.3.0" } - -[[target.dojo]] - -[tool.dojo] -initializer_class_hash = "0xbeef" - -[tool.dojo.env] -# local katana devnet -rpc_url = "http://localhost:5050/" - -# account address of world deployer -account_address = "0x33c627a3e5213790e246a917770ce23d7e562baa5b4d2917c23b1be6d91961c" - -# private key of world deployer -private_key = "0x333803103001800039980190300d206608b0070db0012135bd1fb5f6282170b" - -# world contract address -world_address = "0x789c94ef39aeebc7f8c4c4633030faefb8bee454e358ae53d06ced36136d7d6" -``` \ No newline at end of file diff --git a/0.3.0/src/cairo/entities.md b/0.3.0/src/cairo/entities.md deleted file mode 100644 index 348ab0fc..00000000 --- a/0.3.0/src/cairo/entities.md +++ /dev/null @@ -1,58 +0,0 @@ -## Entities - -> Entities are the primary key value within the world, to which components can be attached. - -Different ECS systems handle entities in various ways. In Dojo, entities are treated as a primary key value within the world, to which components can be attached. To illustrate this concept, consider a simple example of a character in a game that has a `Moves` and a `Position` component. - -When defining the components for this entity, it is important to note that we do not reference the entity directly. Instead, we simply provide two structs that the entity will contain. - -```rust,ignore -#[derive(Component, Copy, Drop, Serde, SerdeLen)] -struct Moves { - #[key] - player: ContractAddress, - remaining: u8, -} - -#[derive(Component, Copy, Drop, Serde, SerdeLen)] -struct Health { - #[key] - player: ContractAddress, - x: u32, - y: u32 -} -``` - -Now, let's create a `Spawn` for the character. It is important to note that we have not explicitly defined an Entity anywhere. Instead, we use the `ctx.origin` to reference the current entity. - -In this example we are using the `ctx.origin` to reference the current entity. - -```rust,ignore -#[system] -mod spawn { - use array::ArrayTrait; - use box::BoxTrait; - use traits::Into; - use dojo::world::Context; - - use dojo_examples::components::Position; - use dojo_examples::components::Moves; - - fn execute(ctx: Context) { - let position = get!(ctx.world, ctx.origin, (Position)); - set!( - ctx.world, - ( - Moves { - player: ctx.origin, remaining: 10 - }, Position { - player: ctx.origin, x: position.x + 10, y: position.y + 10 - }, - ) - ); - return (); - } -} -``` - -> ECS Theory: Plenty has been written on ECS systems, to go deeper read [ECS-FAQ](https://github.com/SanderMertens/ecs-faq) \ No newline at end of file diff --git a/0.3.0/src/cairo/events.md b/0.3.0/src/cairo/events.md deleted file mode 100644 index 3ef7db4b..00000000 --- a/0.3.0/src/cairo/events.md +++ /dev/null @@ -1,108 +0,0 @@ -## Events - -Events play a pivotal role in decoding the dynamics of a Dojo world. Every time there's an update to a `Model`, the `World` contract emits these events. What's even more exciting is that you can craft your own custom events to fit specific needs! Moreover, thanks to [Torii](../toolchain/torii/overview.md), all these events are seamlessly indexed, ensuring easy and efficient querying. - - -### Component Events - -Consider this example of a `Moves` model: - -```rust,ignore -struct Moves { - #[key] - player: Address, - remaining: u32, -} -``` - -When this component is updated, the `World` contract will emit an event with the following structure: - -```rust,ignore -#[derive(Drop, starknet::Event)] -struct StoreSetRecord { - table: felt252, // Moves - keys: Span, // [player] - offset: u8, // offset for the value in the table - value: Span, // [remaining] -} -``` - -This will then be captured by [Torii](../toolchain/torii/overview.md) and indexed for querying. This will allow you to then reconstruct the state of your world. - -Similarly, when a component is deleted, the `World` contract will emit an event with the following structure: - -```rust,ignore -#[derive(Drop, starknet::Event)] -struct StoreDelRecord { - table: felt252, - keys: Span, -} -``` - -### World Events - -The `World` contract also emits events when it's initialized and when new components and systems are registered. These events are emitted with the following structures: - -```rust,ignore -#[derive(Drop, starknet::Event)] -struct WorldSpawned { - address: ContractAddress, - caller: ContractAddress -} -``` - -```rust,ignore -#[derive(Drop, starknet::Event)] -struct ComponentRegistered { - name: felt252, - class_hash: ClassHash -} -``` - -```rust,ignore -#[derive(Drop, starknet::Event)] -struct SystemRegistered { - name: felt252, - class_hash: ClassHash -} -``` - -These events are also captured by [Torii](../toolchain/torii/overview.md) and indexed for querying. - - -### Custom Events - -Within your systems, emitting custom events can be highly beneficial. Fortunately, there's a handy `emit!` macro that lets you release events directly from your world. These events are indexed by [torii](../toolchain/torii/overview.md) - -Use it like so: - -```rust,ignore -emit!(world, Moved { address, direction }); -``` - -Include this in your system and it will emit an event with the following structure: - -```rust,ignore -#[derive(Drop, starknet::Event)] -struct Moved { - address: felt252, - direction: felt252, -} -``` - -Now a full example using a custom event: - -```rust,ignore -fn move(ctx: Context, direction: Direction) { - let (mut position, mut moves) = get !(world, caller, (Position, Moves)); - moves.remaining -= 1; - - let next = next_position(position, direction); - - set !(world, (moves, next)); - emit !(world, Moved { address: caller, direction }); - return (); -} -``` - -> Note: Read about the `get!` and `set!` macros in [Commands](./commands.md). \ No newline at end of file diff --git a/0.3.0/src/cairo/hello-dojo.md b/0.3.0/src/cairo/hello-dojo.md deleted file mode 100644 index 190196b7..00000000 --- a/0.3.0/src/cairo/hello-dojo.md +++ /dev/null @@ -1,410 +0,0 @@ -# Hello Dojo - -> This section assumes that you have already installed the Dojo toolchain and are familiar with Cairo. If not, please refer to the [Getting Started](../getting-started/quick-start.md) section. - -## Dojo as an ECS in 15 Minutes - -Although Dojo isn't exclusively an Entity Component System (ECS) framework, we recommend adopting this robust design pattern. In this context, systems shape the environment's logic, while components ([models](./models.md)) mirror the state of the world. By taking this route, you'll benefit from a structured and modular framework that promises both flexibility and scalability in a continuously evolving world. If this seems a bit intricate at first, hang tight; we'll delve into the details shortly. - -To start, let's set up a project to run locally on your machine. From an empty directory, execute: - -```console -sozo init -``` - -Congratulations! You now have a local Dojo project. This command creates a `dojo-starter` project in your current directory. It's the ideal starting point for a new project and equips you with everything you need to begin. - -#### Anatomy of a Dojo Project - -Inspect the contents of the `dojo-starter` project, and you'll notice the following structure (excluding the non-Cairo files): - -```bash -src - - actions.cairo - - lib.cairo - - models.cairo - - utils.cairo -Scarb.toml -``` - -Dojo projects bear a strong resemblance to typical Cairo projects. The primary difference is the inclusion of a special attribute tag used to define your data models. In this context, we'll refer to these models as components. - -As we're crafting an ECS, we'll adhere to the specific terminology associated with Entity Component Systems. - -Open the `src/models.cairo` file to continue. - -```rust,ignore -#[derive(Model, Copy, Drop, Serde)] -struct Moves { - #[key] - player: ContractAddress, - remaining: u8, - last_direction: Direction -} - -#[derive(Copy, Drop, Serde, Print, Introspect)] -struct Vec2 { - x: u32, - y: u32 -} - -#[derive(Model, Copy, Drop, Print, Serde)] -struct Position { - #[key] - player: ContractAddress, - vec: Vec2, -} - -...rest of code -``` - -Notice the `#[derive(Model, Copy, Drop, Serde)]` attributes. For a model to be recognized, we _must_ include `Model`. This signals to the Dojo compiler that this struct should be treated as a model. - -Our `Moves` model houses a `player` field. At the same tine, we have the `#[key]` attribute, it informs Dojo that this model is indexed by the `player` field. If this is unfamiliar to you, we'll clarify its importance later in the chapter. Essentially, it implies that you can query this component using the `player` field. Our `Moves` model also contains the `remaining` and `last_direction` fields - -In a similar vein, we have a `Position` component that have a Vec2 data structure. Vec holds `x` and `y` values. Once again, this component is indexed by the `player` field. - -Now, let's examine the `src/actions.cairo` file: - -```rust,ignore -// dojo decorator -#[dojo::contract] -mod actions { - use starknet::{ContractAddress, get_caller_address}; - use dojo_examples::models::{Position, Moves, Direction, Vec2}; - use dojo_examples::utils::next_position; - use super::IActions; - - // declaring custom event struct - #[event] - #[derive(Drop, starknet::Event)] - enum Event { - Moved: Moved, - } - - // declaring custom event struct - #[derive(Drop, starknet::Event)] - struct Moved { - player: ContractAddress, - direction: Direction - } - - // impl: implement functions specified in trait - #[external(v0)] - impl ActionsImpl of IActions { - // ContractState is defined by system decorator expansion - fn spawn(self: @ContractState) { - // Access the world dispatcher for reading. - let world = self.world_dispatcher.read(); - - // Get the address of the current caller, possibly the player's address. - let player = get_caller_address(); - - // Retrieve the player's current position from the world. - let position = get!(world, player, (Position)); - - // Retrieve the player's move data, e.g., how many moves they have left. - let moves = get!(world, player, (Moves)); - - // Update the world state with the new data. - // 1. Increase the player's remaining moves by 10. - // 2. Move the player's position 10 units in both the x and y direction. - set!( - world, - ( - Moves { - player, remaining: moves.remaining + 10, last_direction: Direction::None(()) - }, - Position { - player, vec: Vec2 { x: position.vec.x + 10, y: position.vec.y + 10 } - }, - ) - ); - } - - // Implementation of the move function for the ContractState struct. - fn move(self: @ContractState, direction: Direction) { - // Access the world dispatcher for reading. - let world = self.world_dispatcher.read(); - - // Get the address of the current caller, possibly the player's address. - let player = get_caller_address(); - - // Retrieve the player's current position and moves data from the world. - let (mut position, mut moves) = get!(world, player, (Position, Moves)); - - // Deduct one from the player's remaining moves. - moves.remaining -= 1; - - // Update the last direction the player moved in. - moves.last_direction = direction; - - // Calculate the player's next position based on the provided direction. - let next = next_position(position, direction); - - // Update the world state with the new moves data and position. - set!(world, (moves, next)); - - // Emit an event to the world to notify about the player's move. - emit!(world, Moved { player, direction }); - } - } -} -``` - -### Breaking it down - -#### System is a contract - -As you can see a `System` is like a dojo(starknet) contract. It imports the Models we defined earlier and exposes two functions `spawn` and `move`. These functions are called when a player spawns into the world and when they move respectively. - -```rust,ignore -// Retrieve the player's current position from the world. -let position = get!(world, player, (Position)); - -// Retrieve the player's move data, e.g., how many moves they have left. -let moves = get!(world, player, (Moves)); -``` - -Here we use `get!` [command](./commands.md) to retrieve the `Position` and `Moves` model for the `player` entity, which is the address of the caller. - -Now the next line: - -```rust,ignore -// Update the world state with the new data. -// 1. Increase the player's remaining moves by 10. -// 2. Move the player's position 10 units in both the x and y direction. -set!( - world, - ( - Moves { - player, remaining: moves.remaining + 10, last_direction: Direction::None(()) - }, - Position { - player, vec: Vec2 { x: position.vec.x + 10, y: position.vec.y + 10} - }, - ) -); -``` - -Here we use the `set!` [command](./commands.md) to set the `Moves` and `Position` models for the `player` entity. - -We covered a lot here in a short time. Let's recap: - -- Explained the anatomy of a Dojo project -- Explained the importance of the `#[derive(Model)]`attribute -- Explained the `execute` function -- Explained the `Context` struct -- Touched on the `get!` and `set!` commands - -### Run it locally! - -Now that we've covered some theory, let's build the Dojo project! In your primary terminal: - -```bash -sozo build -``` - -That compiled the components and system into an artifact that can be deployed! Simple as that! - -Now, let's deploy it to [Katana](../toolchain/katana/overview.md)! First, we need to get Katana running. Open a second terminal and execute: - -```bash -katana --disable-fee -``` - -Success! [Katana](../toolchain/katana/overview.md) should now be running locally on your machine. Now, let's deploy! In your primary terminal, execute: - -```bash -sozo migrate --name test -``` - -This will deploy the artifact to [Katana](../toolchain/katana/overview.md). You should see terminal output similar to this: - -```bash -Migration account: 0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973 - -World name: test - -[1] 🌎 Building World state.... - > No remote World found -[2] 🧰 Evaluating Worlds diff.... - > Total diffs found: 5 -[3] πŸ“¦ Preparing for migration.... - > Total items to be migrated (5): New 5 Update 0 - -# Executor - > Contract address: 0x5c3494b21bc92d40abdc40cdc54af66f22fb92bf876665d982c765a2cc0e06a -# Base Contract - > Class Hash: 0x7aec2b7d7064c1294a339cd90060331ff704ab573e4ee9a1b699be2215c11c9 -# World - > Contract address: 0x1af130f7b9027f3748c1e3b10ca4a82ac836a30ac4f2f84025e83a99a922a0c -# Models (2) -Moves - > Class hash: 0xb37482a660983dfbf65968caa26eab260d3e1077986454b52ac06e58ae20c4 -Position - > Class hash: 0x6ffc643cbc4b2fb9c424242b18175a5e142269b45f4463d1cd4dddb7a2e5095 - > Registered at: 0x3e74b09d320ceb5d4401842bec805489019c04202bc23bc67a385f6e537dce0 -# Contracts (1) -actions - > Contract address: 0x69a474a39b11d05c07bb9090fd1961b8e1c87aa5643e7b97087cb0c7620356a - -πŸŽ‰ Successfully migrated World at address 0x1af130f7b9027f3748c1e3b10ca4a82ac836a30ac4f2f84025e83a99a922a0c - -✨ Updating manifest.json... - -✨ Done. - -``` - -Your 🌎 is now deployed at `0x1af130f7b9027f3748c1e3b10ca4a82ac836a30ac4f2f84025e83a99a922a0c`! - -This establishes the world address for your project. - -Let's discuss the `Scarb.toml` file in the project. This file contains environment variables that make running CLI commands in your project a breeze. (Read more about it [here](./config.md)). Make sure your file specifies the version of Dojo you have installed!. In this case version `v0.3.0` - -```toml -[dependencies] -dojo = { git = "https://github.com/dojoengine/dojo", rev = "v0.3.0" } -``` - -### Indexing - -With your local world address established, let's delve into indexing. You can index the entire world. Open a new terminal and input this simple command: - -```bash -torii --world 0x1af130f7b9027f3748c1e3b10ca4a82ac836a30ac4f2f84025e83a99a922a0c -``` - -Running the command mentioned above starts a Torii server on your local machine. This server uses SQLite as its database and is accessible at http://0.0.0.0:8080/graphql. Torii will automatically organize your data into tables, making it easy for you to perform queries using GraphQL. When you run the command, you'll see terminal output that looks something like this: - -```bash -2023-10-18T06:49:48.184233Z INFO torii::server: πŸš€ Torii listening at http://0.0.0.0:8080 -2023-10-18T06:49:48.184244Z INFO torii::server: Graphql playground: http://0.0.0.0:8080/graphql - -2023-10-18T06:49:48.185648Z INFO torii_core::engine: processed block: 0 -2023-10-18T06:49:48.186129Z INFO torii_core::engine: processed block: 1 -2023-10-18T06:49:48.186720Z INFO torii_core::engine: processed block: 2 -2023-10-18T06:49:48.187202Z INFO torii_core::engine: processed block: 3 -2023-10-18T06:49:48.187674Z INFO torii_core::engine: processed block: 4 -2023-10-18T06:49:48.188215Z INFO torii_core::engine: processed block: 5 -2023-10-18T06:49:48.188611Z INFO torii_core::engine: processed block: 6 -2023-10-18T06:49:48.188985Z INFO torii_core::engine: processed block: 7 -2023-10-18T06:49:48.199592Z INFO torii_core::processors::register_model: Registered model: Moves -2023-10-18T06:49:48.210032Z INFO torii_core::processors::register_model: Registered model: Position -2023-10-18T06:49:48.210571Z INFO torii_core::engine: processed block: 8 -2023-10-18T06:49:48.211678Z INFO torii_core::engine: processed block: 9 -2023-10-18T06:49:48.212335Z INFO torii_core::engine: processed block: 10 - -``` - -You can observe that our `Moves` and `Position` models have been successfully registered. -Next, let's use the GraphiQL IDE to retrieve data from the `Moves` model. In your web browser, navigate to `http://0.0.0.0:8080/graphql`, and enter the following query: - -```graphql -query { - model(id: "Moves") { - id - name - class_hash - transaction_hash - created_at - } -} -``` - -After you run the query, you will receive an output like this: - -```json -{ - "data": { - "model": { - "id": "Moves", - "name": "Moves", - "class_hash": "0xb37482a660983dfbf65968caa26eab260d3e1077986454b52ac06e58ae20c4", - "transaction_hash": "", - "created_at": "2023-10-18 06:49:48" - } - } -} -``` - -Awesome, now let's work with subscriptions to get real-time updates. Let's clean up your workspace on the GraphiQL IDE and input the following subscription: - -```graphql -subscription { - entityUpdated { - id - keys - model_names - event_id - created_at - updated_at - } -} -``` - -Once you execute the subscription, you will receive notifications whenever new entities are updated or created. For now, don't make any changes to it and proceed to create a new entity. - -To accomplish this, we have to go back to our primary terminal and check the contracts section. - -```bash -# Contracts (1) -actions - > Contract address: 0x69a474a39b11d05c07bb9090fd1961b8e1c87aa5643e7b97087cb0c7620356a -``` - -We have to use `actions` contract address to start to create entities. In your main local terminal, run the following command: - -```bash -sozo execute 0x69a474a39b11d05c07bb9090fd1961b8e1c87aa5643e7b97087cb0c7620356a spawn -``` - -By running this command, you've activated the spawn system, resulting in the creation of a new entity. This action establishes a local world that you can interact with. - -Now, go back to your GraphiQL IDE, and you will notice that you have received the subscription's results, which should look something like this: - -```json -{ - "data": { - "entityUpdated": { - "id": "0x28cd7ee02d7f6ec9810e75b930e8e607793b302445abbdee0ac88143f18da20", - "keys": [ - "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973" - ], - "model_names": "Moves", - "event_id": "0x000000000000000000000000000000000000000000000000000000000000000b:0x0000:0x0000", - "created_at": "2023-10-18 06:53:12", - "updated_at": "2023-10-18 06:53:12" - } - } -} --------------------------------------------------------------------------------------------------------- -{ - "data": { - "entityUpdated": { - "id": "0x28cd7ee02d7f6ec9810e75b930e8e607793b302445abbdee0ac88143f18da20", - "keys": [ - "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973" - ], - "model_names": "Moves,Position", - "event_id": "0x000000000000000000000000000000000000000000000000000000000000000b:0x0000:0x0001", - "created_at": "2023-10-18 06:53:12", - "updated_at": "2023-10-18 06:53:12" - } - } -} -``` - -In the GraphiQL IDE, by clicking the `DOCS`-button on the right, you can open the API documentation. This documentation is auto-generated based on our schema definition and displays all API operations and data types of our schema.. In order to know more about query and subscription, you can jump to [GraphQL](../toolchain/torii/graphql.md) section. -We've covered quite a bit! Here's a recap: - -- Built a Dojo world -- Deployed the project to Katana -- Indexed the world with Torii -- Ran the spawn system locally -- Interacted with GraphQL - -### Next Steps - -This overview provides a rapid end-to-end glimpse into Dojo. However, the potential of these worlds is vast! Designed to manage hundreds of systems and components, Dojo is equipped for expansive creativity. So, what will you craft next? diff --git a/0.3.0/src/cairo/metadata.md b/0.3.0/src/cairo/metadata.md deleted file mode 100644 index 18ba9519..00000000 --- a/0.3.0/src/cairo/metadata.md +++ /dev/null @@ -1,28 +0,0 @@ -## Metadata - -Dojo supports associating offchain metadata with the world contract and other deployed contracts. This can provide additional context about the world, such as it's name, description, social links and other media. Enabling external services to easily index and distribute worlds and experiences built on them. - - -### World Metadata - -During migration, `sozo` will automatically manage the worlds metadata for you, uploading it to ipfs and setting it in the world contract. It does so by parsing the metadata defined in the projects `Scarb.toml`. - -To set a worlds metadata, create the following section in your `Scarb.toml`: - -```toml -[tool.dojo.world] -name = "example" -description = "example world" -icon_uri = "file://assets/icon.png" -cover_uri = "file://assets/cover.png" -website = "https://dojoengine.org" -socials.x = "https://twitter.com/dojostarknet" -``` - -The toolchain supports the `name`, `description`, `icon_uri`, `cover_uri`, `website` and `socials` attributes by default. `_uri` attributes can point to a asset in the repo using the `file://` schema or to remote resouces using either `ipfs://` or `https://`. Arbitrary social links can be set by setting a key value on the `socials` attribute. For example, we could add a `socials.github = "..."`. - -During migration, `sozo` will upload any local assets to ipfs, replace the corresponding uris, upload the metadata json to ipfs, and set the `metadata_uri` for the world (resource `0`). - -### Contract Metadata - -It is possible for contract owners to set a `metadata_uri` for any contract. However, this specification has not yet been defined and it is not supported by the toolchain at this time. \ No newline at end of file diff --git a/0.3.0/src/cairo/migration.md b/0.3.0/src/cairo/migration.md deleted file mode 100644 index 1d57d9ff..00000000 --- a/0.3.0/src/cairo/migration.md +++ /dev/null @@ -1,3 +0,0 @@ -## Migration - -[0.2.0 -> 0.3.0](./migration/0.3.0.md) \ No newline at end of file diff --git a/0.3.0/src/cairo/migration/0.3.0.md b/0.3.0/src/cairo/migration/0.3.0.md deleted file mode 100644 index d4d70b56..00000000 --- a/0.3.0/src/cairo/migration/0.3.0.md +++ /dev/null @@ -1,216 +0,0 @@ -## Migration Guide to 0.3.0 - -0.3.0 introduced some breaking changes to Systems and Models which requires reworking of your worlds. - -- [Components](#components-to-models) -- [Systems](#systems-update) -- [Events](#events) -- [Npm](#npm) - -### Components to Models - -In version 0.3.0, "components" have been renamed to "models". This has been done due to Cairo introducing the concept of Components natively. - -You must: - -- Replace `#[component]` with `#[model]`. -- Update `#[derive(Component)]` to `#[derive(Model)]` throughout your code. - -**Note**: Ensure all related files and imports are updated accordingly. - -### Changes in Model Implementation - -The trait `SerdeLen` is no longer implemented for models. If you relied on this previously, you should now use `SchemaIntrospection`. - -### Schema Introduction - -For models containing complex types, it's crucial to implement the `SchemaIntrospection` trait. - -Consider the model below: - -```rust,ignore -struct Card { - - #[key] - token_id: u256, - /// The card's designated role. - role: Roles, -} -``` - -For complex types, like `Roles` in the above example, you need to implement `SchemaIntrospection`. Here's how: - -```rust,ignore -impl RolesSchemaIntrospectionImpl for SchemaIntrospection { - #[inline(always)] - fn size() -> usize { - 1 // Represents the byte size of the enum. - } - - #[inline(always)] - fn layout(ref layout: Array) { - layout.append(8); // Specifies the layout byte size; - } - - #[inline(always)] - fn ty() -> Ty { - Ty::Enum( - Enum { - name: 'Roles', - attrs: array![].span(), - children: array![ - ('Goalkeeper', serialize_member_type(@Ty::Tuple(array![].span()))), - ('Defender', serialize_member_type(@Ty::Tuple(array![].span()))), - ('Midfielder', serialize_member_type(@Ty::Tuple(array![].span()))), - ('Attacker', serialize_member_type(@Ty::Tuple(array![].span()))), - ] - .span() - } - ) - } -} -``` - -**Key Takeaways from custom types**: - -- **size**: Defines the byte size of the type. -- **layout**: Outlines the byte structure/layout for the type. Validate and adjust as necessary. -- **ty**: Details the specific type, attributes, and subcomponents. For enums, like `Roles`, you need to specify each member and its type. - -### Systems Update - -Systems in 0.3.0 are very similar now to Cairo Contracts. You can write your systems just like regular contracts, and each dojo contract can contain mulitple systems. - -Important high level changes: -- Systems are now starknet contracts -- Define [Interfaces](#interface-creation) for each system contract -- New optional `#[dojo::contract]` decorator defining systems -- Multiple systems per dojo contract, rather than singular -- `execute` is no longer required system selector name - - -#### Interface Creation - -System management has been revamped. Start by defining an interface for each system, which specifies its implementation: - -```rust,ignore -#[starknet::interface] -trait ICreateCard { - fn create_card( - self: @TContractState, - world: IWorldDispatcher, - token_id: u256, - dribble: u8, - defense: u8, - cost: u8, - role: Roles, - is_captain: bool - ); -} -``` - -Ensure the trait is typed with `TContractState`. - -**Note**: Earlier versions required functions within the system to be named `execute`. This is no longer the case. - -#### Interface Implementation - -To implement the interface: - -1. Add `#[external(v0)]` before each method. -2. Ensure to reference the created interface in the module with `use super::ICreateCard;`. - -```rust,ignore -#[external(v0)] -impl CreateCardImpl for ICreateCard { - fn create_card( - self: @ContractState, - world: IWorldDispatcher, - token_id: u256, - dribble: u8, - defense: u8, - cost: u8, - role: Roles, - is_captain: bool - ) { - // your logic here - } -} -``` - -This then allows the `create_card` to be called just like a regular starknet function. - -#### `#[dojo::contract]` decorator - -0.3.0 introduces a new optional decorator `#[dojo::contract]` which indicates to the compiler to inject imports and the world dispatcher. This allows for minimal boilerplate. - -```rust,ignore -#[dojo::contract] -mod move { -....code TODO -} -``` - -### Events - -Events should now reside within the models. Here's an example of how to migrate your events: - -**Previous Format**: -```rust,ignore -#[derive(Drop, starknet::Event, Copy)] -struct DeckCreated { - player: ContractAddress, - token_list: Span, -} -``` - -**New Format**: -```rust,ignore -#[event] -#[derive(Copy, Drop, starknet::Event)] -enum Event { - DeckCreated(DeckCreated) -} - -#[derive(Copy, Drop, starknet::Event)] -struct DeckCreated { - player: ContractAddress, - token_list: Span, -} -``` - -### Testing Changes - -#### Setup - -Testing has seen significant changes with the change to systems as Contracts. Instead of using `world.execute`, use the dispatcher. - -1. Import necessary modules and traits: - -```rust,ignore -use dojo::test_utils::deploy_contract; -use tsubasa::systems::{ICreateCardDispatcher, ICreateCardDispatcherTrait}; -``` - -2. Deploy the contract and instantiate the dispatcher: - -```rust,ignore -let contract_create_card = deploy_contract( - create_card_system::TEST_CLASS_HASH, array![].span() -); -let create_card_system = ICreateCardDispatcher { contract_address: contract_create_card }; -``` - -#### Function Testing - -With the contract deployed and the dispatcher instantiated, proceed to test your functions: - -```rust,ignore -// ... (previous setup code) - -let result = create_card_system.create_card( - // ... provide necessary parameters here -); - -// Assert or validate the 'result' as per your test conditions -``` diff --git a/0.3.0/src/cairo/models.md b/0.3.0/src/cairo/models.md deleted file mode 100644 index 10f77394..00000000 --- a/0.3.0/src/cairo/models.md +++ /dev/null @@ -1,275 +0,0 @@ -## Models - -> Models = Data - - -**_TL;DR_** -- Models store structured data in your world. -- Models are Cairo structs with additional features. -- Models can implement traits. -- Use the `#[derive(Model)]` decorator to define them. -- Custom enums and types are supported. -- Define the primary key using the `#[key]` attribute. - -### Models are Structs - -Models are structs annotated with the `#[derive(Model)]` attribute. Consider these models as a key-value store, where the `#[key]` attribute is utilized to define the primary key. While models can contain any number of fields, adhering to best practices in Entity-Component-System (ECS) design involves maintaining small, isolated models. This approach fosters modularity and composability, enabling you to reuse models across various entity types. - -```rust,ignore -#[derive(Model, Copy, Drop, Serde, SerdeLen)] -struct Moves { - #[key] - player: ContractAddress, - remaining: u8, -} -``` - -#### The #[key] attribute - -The `#[key]` attribute indicates to Dojo that this model is indexed by the `player` field. You need to define a key for each model, as this is how you query the model. However, you can create composite keys by defining multiple fields as keys. - -```rust,ignore -#[derive(Model, Copy, Drop, Serde, SerdeLen)] -struct Resource { - #[key] - player: ContractAddress, - #[key] - location: ContractAddress, - balance: u8, -} -``` - -In this case you then would set the model with both the player and location fields: - -```rust,ignore -set!( - world, - ( - Resource { - player: caller, - location: 12, - balance: 10 - }, - ) -); -``` - -#### Implementing Traits - -Models can implement traits. This is useful for defining common functionality across models. For example, you may want to define a `Position` model that implements a `PositionTrait` trait. This trait could define functions such as `is_zero` and `is_equal` which could be used when accessing the model. - -```rust,ignore -trait PositionTrait { - fn is_zero(self: Position) -> bool; - fn is_equal(self: Position, b: Position) -> bool; -} - -impl PositionImpl of PositionTrait { - fn is_zero(self: Position) -> bool { - if self.x - self.y == 0 { - return true; - } - false - } - - fn is_equal(self: Position, b: Position) -> bool { - self.x == b.x && self.y == b.y - } -} -``` - -#### Custom Setting models - -Suppose we need a place to keep a global value with the flexibility to modify it in the future. Take, for instance, a global `combat_cool_down` parameter that defines the duration required for an entity to be primed for another attack. To achieve this, we can craft a model dedicated to storing this value, while also allowing for its modification via a decentralized governance model. - -To establish these models, you'd follow the usual creation method. However, when initializing them, employ a constant identifier, such as GAME_SETTINGS_ID. - -```rust,ignore -const GAME_SETTINGS_ID: u32 = 9999999999999; - -#[derive(model, Copy, Drop, Serde, SerdeLen)] -struct GameSettings { - #[key] - game_settings_id: u32, - combat_cool_down: u32, -} -``` - -#### Types - -Support model types: - -- `u8` -- `u16` -- `u32` -- `u64` -- `u128` -- `u256` -- `ContractAddress` -- Enums -- Custom Types - -It is currently not possible to use Arrays. - -#### Custom Types + Enums -For models containing complex types, it's crucial to implement the `SchemaIntrospection` trait. - -Consider the model below: - -```rust,ignore -struct Card { - #[key] - token_id: u256, - /// The card's designated role. - role: Roles, -} -``` - -For complex types, like `Roles` in the above example, you need to implement `SchemaIntrospection`. Here's how: - -```rust,ignore -impl RolesSchemaIntrospectionImpl for SchemaIntrospection { - #[inline(always)] - fn size() -> usize { - 1 // Represents the byte size of the enum. - } - - #[inline(always)] - fn layout(ref layout: Array) { - layout.append(8); // Specifies the layout byte size; - } - - #[inline(always)] - fn ty() -> Ty { - Ty::Enum( - Enum { - name: 'Roles', - attrs: array![].span(), - children: array![ - ('Goalkeeper', serialize_member_type(@Ty::Tuple(array![].span()))), - ('Defender', serialize_member_type(@Ty::Tuple(array![].span()))), - ('Midfielder', serialize_member_type(@Ty::Tuple(array![].span()))), - ('Attacker', serialize_member_type(@Ty::Tuple(array![].span()))), - ] - .span() - } - ) - } -} -``` - -### In practice with modularity in mind - -Consider a tangible analogy: Humans and Goblins. While they possess intrinsic differences, they share common traits, such as having a position and health. However, humans possess an additional model. Furthermore, we introduce a Counter model, a distinct feature that tallies the numbers of humans and goblins. - -```rust,ignore -#[derive(Model, Copy, Drop, Serde, SerdeLen)] -struct Potions { - #[key] - entity_id: u32, - quantity: u8, -} - -#[derive(Model, Copy, Drop, Serde, SerdeLen)] -struct Health { - #[key] - entity_id: u32, - health: u8, -} - -#[derive(Model, Copy, Drop, Serde, SerdeLen)] -struct Position { - #[key] - entity_id: u32, - x: u32, - y: u32 -} - -// Special counter model -#[derive(Model, Copy, Drop, Serde, SerdeLen)] -struct Counter { - #[key] - counter: u32, - goblin_count: u32, - human_count: u32, -} -``` - -So the Human will have a `Potions`, `Health` and `Position` model, and the Goblin will have a `Health` and `Position` model. By doing we save having to create Health and Position models for each entity type. - -So then a system would look like this: - -```rust,ignore -#[dojo::contract] -mod spawnHuman { - use array::ArrayTrait; - use box::BoxTrait; - use traits::Into; - use dojo::world::Context; - - use dojo_examples::models::Position; - use dojo_examples::models::Health; - use dojo_examples::models::Potions; - use dojo_examples::models::Counter; - - // we can set the counter value as a const, then query it easily! This pattern is useful for settins. - const COUNTER_ID: u32 = 9999999999999; - - // impl: implement functions specified in trait - #[external(v0)] - impl GoblinActionsImpl of IGoblinActions { - fn goblin_actions(self: @ContractState, entity_id: u32) { - let world = self.world_dispatcher.read(); - - let counter = get!(world, COUNTER_ID, (Counter)); - - let human_count = counter.human_count + 1; - let goblin_count = counter.goblin_count + 1; - - // spawn a human - set!( - world, - ( - Health { - entity_id: human_count, health: 100 - }, - Position { - entity_id: human_count, x: position.x + 10, y: position.y + 10, - }, - Potions { - entity_id: human_count, quantity: 10 - - }, - ) - ); - - // spawn a goblin - set!( - world, - ( - Health { - entity_id: goblin_count, health: 100 - }, - Position { - entity_id: goblin_count, x: position.x + 10, y: position.y + 10, - }, - ) - ); - - // increment the counter - set!( - world, - ( - Counter { - counter: COUNTER_ID, human_count: human_count, goblin_count: goblin_count - }, - ) - ); - - return (); - } - } -} -``` - -> A complete example can be found in the [Dojo Starter](https://github.com/dojoengine/dojo-starter) \ No newline at end of file diff --git a/0.3.0/src/cairo/modules.md b/0.3.0/src/cairo/modules.md deleted file mode 100644 index 7bb59dee..00000000 --- a/0.3.0/src/cairo/modules.md +++ /dev/null @@ -1,8 +0,0 @@ -## Dojo Modules - -With standardization of Systems and Components we can create a module architecture for Dojo. This allows us to create reusable modules that can be used in any Dojo world. - -### Module Architecture - -Think of modules as ERCs for Dojo. They are a standard way to create and share functionality. Modules are a collection of Systems and Components that can be imported into a Dojo world. Dojo is following the ERC patterns and has modules already defined for ERC20, ERC721, and ERC1155. - diff --git a/0.3.0/src/cairo/modules/defi.md b/0.3.0/src/cairo/modules/defi.md deleted file mode 100644 index 44d074d6..00000000 --- a/0.3.0/src/cairo/modules/defi.md +++ /dev/null @@ -1 +0,0 @@ -# Defi diff --git a/0.3.0/src/cairo/modules/erc1155.md b/0.3.0/src/cairo/modules/erc1155.md deleted file mode 100644 index c1d50d17..00000000 --- a/0.3.0/src/cairo/modules/erc1155.md +++ /dev/null @@ -1 +0,0 @@ -# ERC1155 diff --git a/0.3.0/src/cairo/modules/erc20.md b/0.3.0/src/cairo/modules/erc20.md deleted file mode 100644 index ca9773c9..00000000 --- a/0.3.0/src/cairo/modules/erc20.md +++ /dev/null @@ -1,7 +0,0 @@ -## ERC20 - -Dojo's ERC20 module is a standard implementation of the ERC20 token standard, but it utilizes Dojo Systems and Components. This allows us to leverage the excellent properties of the ERC20 standard and use it natively within the Dojo environment. - -### Integration into Your World - -To integrate the ERC20 module into your world, you must first deploy the ERC20 Dojo contract. Subsequently, install the systems and components into your world. \ No newline at end of file diff --git a/0.3.0/src/cairo/modules/erc721.md b/0.3.0/src/cairo/modules/erc721.md deleted file mode 100644 index f5c9f638..00000000 --- a/0.3.0/src/cairo/modules/erc721.md +++ /dev/null @@ -1,3 +0,0 @@ -# ERC721 - -__todo__ \ No newline at end of file diff --git a/0.3.0/src/cairo/overview.md b/0.3.0/src/cairo/overview.md deleted file mode 100644 index 672d2138..00000000 --- a/0.3.0/src/cairo/overview.md +++ /dev/null @@ -1,105 +0,0 @@ -> You should have a good understanding of Cairo before proceeding. If you're unfamiliar with Cairo, we recommend you read the [Cairo documentation](https://book.cairo-lang.org/title-page.html) first. - -## A New Approach to Game Development - -Dojo provides an advanced abstraction layer over Cairo, mirroring React's relationship with JavaScript. Its specialized architecture simplifies game design and development. By leveraging Dojo, developers can use succinct commands that transform into comprehensive queries at compile time. This chapter delves deeper into Dojo's unique architecture. - -#### Delving into the Architecture - -Dojo efficiently encapsulates boilerplate contracts within the compiler, letting developers concentrate on the distinct aspects of their game or app. - -Consider this as the most basic Dojo world setup: - -```rust,ignore -- src - - main.cairo - - lib.cairo -- Scarb.toml -``` - -While seemingly simple, behind the scenes Dojo generates foundational contracts, setting the stage for you to focus purely on data and logic. - -Lets take a look at the `main.cairo`: - -```rust,ignore -use dojo::world::{IWorldDispatcher, IWorldDispatcherTrait}; -use starknet::ContractAddress; - -// dojo data models -#[derive(Model, Copy, Drop, Print, Serde)] -struct Position { - #[key] // primary key - player: ContractAddress, - vec: Vec2, -} - -// regular cairo struct -#[derive(Copy, Drop, Serde, Print, Introspect)] -struct Vec2 { - x: u32, - y: u32 -} - -// interface -#[starknet::interface] -trait IPlayerActions { - fn spawn(self: @TContractState, world: IWorldDispatcher); -} - -// contract -#[starknet::contract] -mod player_actions { - use starknet::{ContractAddress, get_caller_address}; - use dojo::world::{IWorldDispatcher, IWorldDispatcherTrait}; - use super::{Position, Vec2}; - use super::IPlayerActions; - - // note the is no storage here - it's in the world contract - #[storage] - struct Storage {} - - #[external(v0)] - impl PlayerActionsImpl of IPlayerActions { - // - // NOTICE: we pass the world dispatcher as an argument to every function. - // This is how we interact with the world contract. - // - fn spawn(self: @ContractState, world: IWorldDispatcher) { - // get player address - let player = get_caller_address(); - - // dojo command - get player position - let position = get!(world, player, (Position)); - - // dojo command - set player position - set!(world, (Position { player, vec: Vec2 { x: 10, y: 10 } })); - } - } -} -``` - -### Breakdown - -This just a regular Cairo contract, with some specifics. - -#### `Position` struct - -In a Dojo world, state is defined using models. These are structs marked with the `#[derive(Model)]` attribute, functioning similarly to a keypair store. The primary key for a model is indicated using the `#[key]` attribute; for instance, the `player` field serves as the primary key in this context. - -Read more about models [here](./models.md). - -#### `spawn` function - a dojo system - -In the `spawn` function, take note of the second parameter: the `IWorldDispatcher` interface. This provides a gateway to the world contract. By integrating it into the function, it enables the `get!` and `set!` macros to interface directly with the world contract. - -Commands, a significant innovation in Dojo, are further explored [here](./commands.md). - -#### `#[storage]` attribute - -You will notice there is no storage in the contract. This is because the storage is in the world contract. You can however use this attribute to store data in the System contract itself, but we suggest you use the world contract for storage. - -### High level transaction flow of a world - -To call a Dojo world you invoke a system, which then calls the [world](./world.md) and does the necessary state changes. - -![Dojo World](../images/world_flow.png) diff --git a/0.3.0/src/cairo/systems.md b/0.3.0/src/cairo/systems.md deleted file mode 100644 index 40b335b6..00000000 --- a/0.3.0/src/cairo/systems.md +++ /dev/null @@ -1,135 +0,0 @@ -## Systems - -> **IMPORTANT:** Before defining your systems, prioritize permissions. Plan carefully to ensure proper access and security. - -**_TL;DR_** -- Systems function as contract methods. -- Contracts containing Systems gain permissions to write to models. -- Systems pass a `world` address as their first parameter unless utilizing the [`#[dojo::contract]`](#the-dojocontract-decorator) decorator. -- Systems engage the world contract to alter models' state. -- The world contract is invoked through systems. -- Systems ought to be concise and specific. -- In most scenarios, systems are stateless. - -### What are Systems? - -Within dojo we define systems as functions within a Contract that act on the world. - -Systems play a pivotal role in your world's logic, directly mutating its component states. It's important to understand that to enact these mutations, a system needs explicit permission from the [`models`](./models.md) owner. - -### System Permissions - -Since the whole contract is giving write access to the model, it is important to be careful when defining systems. A simple way to think about it is: - -![System Permissions](../images/permissions.png) - -### System Structure - -Every system function starts with a [`world`](./world.md) address as its initial parameter. This design permits these functions to alter the world's state. Notably, this structure also makes systems adaptable and reusable across multiple worlds! - -Let's look at the simplest possible system which mutates the state of the `Moves` component. - -```rust,ignore -#[starknet::contract] -mod player_actions { - use starknet::{ContractAddress, get_caller_address}; - use dojo::world::{IWorldDispatcher, IWorldDispatcherTrait}; - use dojo_examples::components::{Position, Moves, Direction, Vec2}; - use dojo_examples::utils::next_position; - use super::IPlayerActions; - - // no storage - #[storage] - struct Storage {} - - // implementation of the PlayerActions interface - #[external(v0)] - impl PlayerActionsImpl of IPlayerActions { - fn spawn(self: @ContractState, world: IWorldDispatcher) { - let player = get_caller_address(); - let position = get!(world, player, (Position)); - set!( - world, - ( - Moves { - player, - remaining: 10, - last_direction: Direction::None(()) - } - ) - ); - } - } -} -``` - -## Breaking it down - -#### System is a contract - -As you can see a System is like a regular Starknet contract. It can include storage, and it can implement interfaces. - -#### `Spawn` function - -The spawn function is currently the only function that exists in this system. It is called when a player spawns into the world. It is responsible for setting up the player's initial state. - -### The `#[dojo::contract]` Decorator - -All StarkNet contracts are defined using the `#[starknet::contract]` decorator, ensuring accurate compilation. In this context, Dojo introduces the `#[dojo::contract]` decorator, which aims to minimize boilerplate in contract writing. It’s imperative to acknowledge that utilizing this decorator is entirely optional. - -The `#[dojo::contract]` decorator allows developers to omit including `world: IWorldDispatcher` as a parameter. Behind the scenes, it injects the world into the contract and eliminates some imports, thereby streamlining the development process. - -```rust,ignore -#[dojo::contract] -mod player_actions { - use starknet::{ContractAddress, get_caller_address}; - use dojo_examples::models::{Position, Moves, Direction, Vec2}; - use dojo_examples::utils::next_position; - use super::IPlayerActions; - - #[event] - #[derive(Drop, starknet::Event)] - enum Event { - Moved: Moved, - } - - #[derive(Drop, starknet::Event)] - struct Moved { - player: ContractAddress, - direction: Direction - } - - // impl: implement functions specified in trait - #[external(v0)] - impl PlayerActionsImpl of IPlayerActions { - // ContractState is defined by system decorator expansion - fn spawn(self: @ContractState) { - let world = self.world_dispatcher.read(); - let player = get_caller_address(); - let position = get!(world, player, (Position)); - set!( - world, - ( - Moves { player, remaining: 10, last_direction: Direction::None(()) }, - Position { player, vec: Vec2 { x: 10, y: 10 } }, - ) - ); - } - - fn move(self: @ContractState, direction: Direction) { - let world = self.world_dispatcher.read(); - let player = get_caller_address(); - let (mut position, mut moves) = get!(world, player, (Position, Moves)); - moves.remaining -= 1; - moves.last_direction = direction; - let next = next_position(position, direction); - set!(world, (moves, next)); - emit!(world, Moved { player, direction }); - return (); - } - } -} -``` - - -> To interact with Systems read more in the [sozo](../toolchain/sozo/overview.md) docs. \ No newline at end of file diff --git a/0.3.0/src/cairo/testing.md b/0.3.0/src/cairo/testing.md deleted file mode 100644 index 67f2fb29..00000000 --- a/0.3.0/src/cairo/testing.md +++ /dev/null @@ -1,123 +0,0 @@ -## Testing - -Testing is a crucial part of any software development process. Dojo provides a testing framework that allows you to write tests for your smart contracts. Since Dojo uses a custom compiler, you need to use `sozo` to test your contracts. - -From your project directory, simply: - -```shell -sozo test -``` - -This will search for all tests within your project and run them. - - -### Writing Unit Tests - -It is best practise to include unit tests in the same file as the model/System you are writing. - -Lets show a `model` test example from the [dojo-starter](https://github.com/dojoengine/dojo-starter): - -`models.cairo` -```rust,ignore - -...rest of code - -#[cfg(test)] -mod tests { - use debug::PrintTrait; - use super::{Position, PositionTrait}; - - #[test] - #[available_gas(100000)] - fn test_position_is_zero() { - let player = starknet::contract_address_const::<0x0>(); - assert(PositionTrait::is_zero(Position { player, x: 0, y: 0 }), 'not zero'); - } - - #[test] - #[available_gas(100000)] - fn test_position_is_equal() { - let player = starknet::contract_address_const::<0x0>(); - let position = Position { player, x: 420, y: 0 }; - position.print(); - assert(PositionTrait::is_equal(position, Position { player, x: 420, y: 0 }), 'not equal'); - } -} - -``` - -In this test we are testing the `is_zero` and `is_equal` functions of the `Position` model. It is good practise to test all functions of your models. - - -### Writing Integration Tests - -Integration tests are e2e tests that test the entire system. You can write integration tests for your world by creating a `tests` directory in your project root. Then create a file for each integration test you want to write. - -This is the example from the [dojo-starter](https://github.com/dojoengine/dojo-starter): - -`move.cairo` -```rust,ignore -#[cfg(test)] -mod tests { - use dojo::world::{IWorldDispatcherTrait, IWorldDispatcher}; - use dojo::test_utils::{spawn_test_world, deploy_contract}; - use dojo_examples::models::{position, moves}; - use dojo_examples::models::{Position, Moves, Direction}; - - use super::{ - IPlayerActionsDispatcher, IPlayerActionsDispatcherTrait, - player_actions_external as player_actions - }; - - //OFFSET is defined in constants.cairo - use dojo_examples::constants::OFFSET; - - //{Event and Moved are defined in events.cairo} - #[event] - use dojo_examples::events::{Event, Moved}; - - // helper setup function - // reusable function for tests - fn setup_world() -> IPlayerActionsDispatcher { - // components - let mut models = array![position::TEST_CLASS_HASH, moves::TEST_CLASS_HASH]; - - // deploy world with models - let world = spawn_test_world(models); - - // deploy systems contract - let contract_address = world - .deploy_contract('salt', player_actions::TEST_CLASS_HASH.try_into().unwrap()); - let player_actions_system = IPlayerActionsDispatcher { contract_address }; - - player_actions_system - } - - - #[test] - #[available_gas(30000000)] - fn test_move() { - // caller - let caller = starknet::contract_address_const::<0x0>(); - - let player_actions_system = setup_world(); - - // System calls - player_actions_system.spawn(); - player_actions_system.move(Direction::Right(())); - - // check moves - let moves = get!(world, caller, (Moves)); - assert(moves.remaining == 99, 'moves is wrong'); - - // check position - let new_position = get!(world, caller, (Position)); - assert(new_position.x == (OFFSET + 1).try_into().unwrap(), 'position x is wrong'); - assert(new_position.y == OFFSET.try_into().unwrap(), 'position y is wrong'); - } -} -``` - -#### Useful Dojo Test Functions - -`spawn_test_world(models, systems)` - This function will create a test world with the models and systems you pass in. It will also deploy the world and register the models and systems. diff --git a/0.3.0/src/cairo/world.md b/0.3.0/src/cairo/world.md deleted file mode 100644 index d41a3cbe..00000000 --- a/0.3.0/src/cairo/world.md +++ /dev/null @@ -1,58 +0,0 @@ -> **To think about:** Consider Autonomous Worlds as sovereign blockchains residing within another blockchain - a nested blockchain, so to speak. Just as you can deploy contracts onto Ethereum to enhance its functionality, you can similarly introduce systems into the World contract to enrich its features. While anyone can contribute to the World, akin to Ethereum, authorization is required to interact with model state. There is a dedicated topic to [Authorisation](./authorization.md). - -## The World Contract - -The world contract functions as a central store for the world models and systems. Every contract that interacts with the world, must use the world contract address as the first parameter. This is how the world contract is able to manage the state of the world. - -Although we suggest strongly to structure your world around an ECS pattern you are not required to do so. You can simply use the dojo-models as a keypair store along with the supporting infrastructure. - -> Dojo core abstracts the world contract away, you do not write it and it is not meant to be altered when building a world. However, it's important to understand how it works and how it interacts with the rest of the system. - -### The `uuid()` command - -It is often useful to generate unique IDs for entities. The `uuid()` fn can be used to generate a unique ID. - -Use it like this: - -```rust,ignore -let game_id = world.uuid(); -``` - - -### Full World API - -The world exposes an interface which can be interacted with by any client. - -```rust,ignore -// World interface -#[starknet::interface] -trait IWorld { - fn component(self: @T, name: felt252) -> ClassHash; - fn register_component(ref self: T, class_hash: ClassHash); - fn system(self: @T, name: felt252) -> ClassHash; - fn register_system(ref self: T, class_hash: ClassHash); - fn uuid(ref self: T) -> usize; - fn emit(self: @T, keys: Array, values: Span); - fn entity( - self: @T, component: felt252, keys: Span, offset: u8, length: usize - ) -> Span; - fn set_entity( - ref self: T, component: felt252, keys: Span, offset: u8, value: Span - ); - fn entities( - self: @T, component: felt252, index: felt252, length: usize - ) -> (Span, Span>); - fn set_executor(ref self: T, contract_address: ContractAddress); - fn executor(self: @T) -> ContractAddress; - fn delete_entity(ref self: T, component: felt252, keys: Span); - fn origin(self: @T) -> ContractAddress; - - fn is_owner(self: @T, account: ContractAddress, target: felt252) -> bool; - fn grant_owner(ref self: T, account: ContractAddress, target: felt252); - fn revoke_owner(ref self: T, account: ContractAddress, target: felt252); - - fn is_writer(self: @T, component: felt252, system: felt252) -> bool; - fn grant_writer(ref self: T, component: felt252, system: felt252); - fn revoke_writer(ref self: T, component: felt252, system: felt252); -} -``` \ No newline at end of file diff --git a/0.3.0/src/client/npm.md b/0.3.0/src/client/npm.md deleted file mode 100644 index dce79e82..00000000 --- a/0.3.0/src/client/npm.md +++ /dev/null @@ -1,38 +0,0 @@ -# Javascript Libraries - -> Javascript is a great way to get started with Dojo. It's easy to use, and you can get started in minutes. - -### Examples using these: - -- [Dojo-create-react-app](https://github.com/dojoengine/dojo-starter-react-app) -- [Dojo-starter-phaser](https://github.com/dojoengine/dojo-starter-phaser) - -### @dojoengine/core - -This is the lowest level library, and is used by all other downstream libraries. It contains the core functionality of Dojo and exposes the contract interfaces. Use it if you want to build your own library on top of Dojo. - -[Repository](https://github.com/dojoengine/packages/tree/main/packages/core) - -```console -bun add @dojoengine/core -``` - -### @dojoengine/create-burner - -Create burner is a simple way to incorporate burner wallets into your Dojo app. - -[Repository](https://github.com/dojoengine/packages/tree/main/packages/create-burner) - -```console -bun add @dojoengine/create-burner -``` - -### @dojoengine/utils - -These are utils for helping with interfacing dojo. - -[Reopsitory](https://github.com/dojoengine/packages/tree/main/packages/utils) - -```console -bun add @dojoengine/utils -``` diff --git a/0.3.0/src/client/overview.md b/0.3.0/src/client/overview.md deleted file mode 100644 index 5349cdaf..00000000 --- a/0.3.0/src/client/overview.md +++ /dev/null @@ -1,8 +0,0 @@ -# Overview - -Dojo is BYO client, meaning that you can use any client you want to connect to the Dojo network. - -- [npm](./npm.md) -- [torii](torii.md) - -> Dojo is always looking to expand these clients, if you would like to contribute reach out into the [Discord](https://discord.gg/KG9w9BmDrV) \ No newline at end of file diff --git a/0.3.0/src/client/torii.md b/0.3.0/src/client/torii.md deleted file mode 100644 index 4cd1a2de..00000000 --- a/0.3.0/src/client/torii.md +++ /dev/null @@ -1,9 +0,0 @@ -## Torii Client - -Torii client is a rust client for interacting with Dojo worlds. It can be compiled to wasm to be used in JS clients, or can used directly in Rust clients or other lower level languages with bindings. - -### Usage in Rust projects - -__@kairy__ - -### Usage in JS Clients \ No newline at end of file diff --git a/0.3.0/src/community/get-started.md b/0.3.0/src/community/get-started.md deleted file mode 100644 index 25ba3c07..00000000 --- a/0.3.0/src/community/get-started.md +++ /dev/null @@ -1,6 +0,0 @@ -## Get Started - -- [Community Hub](https://dojoengine.notion.site/Dojo-Engine-Community-Hub-d316194b998941c48ddf771a4dd5ff08#bcd6a32db1b2406cb6c325f3b700d45a) -- [Discord](https://discord.gg/KG9w9BmDrV) -- [Twitter](https://twitter.com/dojostarknet) -- [Awesome Dojo](https://github.com/dojoengine/awesome-dojo) diff --git a/0.3.0/src/deployment/locally.md b/0.3.0/src/deployment/locally.md deleted file mode 100644 index e0a932ae..00000000 --- a/0.3.0/src/deployment/locally.md +++ /dev/null @@ -1,31 +0,0 @@ -## Deploying Locally - -Dojo is engineered for rapid development, boasting a lightning-fast local development environment named [Katana](./toolchain/katana/overview.md). Katana serves as an on-device Starknet blockchain, allowing you to rigorously test your smart contracts before transitioning them to the remote testnet. - -### Katana Deployments - -Deploying to Katana could not be easier. - -> This assumes you have followed the [Quick Start](./getting-started/quick-start.md) guide and have a project initialized. - -From your project directory, run: - -```bash -katana --disable-fee -``` - -This has started a local Katana which you can now deploy on! - -### Deploying to Katana - -To deploy your project to Katana, run: - -```bash -sozo migrate --name test -``` - -Note - this will only work if you have compiled your contracts. If you have not, run: - -```bash -sozo build -``` diff --git a/0.3.0/src/deployment/remote.md b/0.3.0/src/deployment/remote.md deleted file mode 100644 index f7b34a32..00000000 --- a/0.3.0/src/deployment/remote.md +++ /dev/null @@ -1,61 +0,0 @@ -## Deployment to Remote Network - -> *IMPORTANT: Dojo is unaudited. Use at your own risk.* - -Dojo makes it easy to deploy to remote networks, you just need to have a valid account and network endpoint. - -Scarb.toml - -```toml -[package] -name = "ohayoo" -version = "0.1.0" -cairo-version = "2.1.1" - -[cairo] -sierra-replace-ids = true - -[dependencies] -dojo = { git = "https://github.com/dojoengine/dojo.git" } - -# # Katana -# rpc_url = "http://localhost:5050" -# account_address = "0x03ee9e18edc71a6df30ac3aca2e0b02a198fbce19b7480a63a0d71cbd76652e0" -# private_key = "0x0300001800000000300000180000000000030000000000003006001800006600" - -#Madara -rpc_url = "https://api.cartridge.gg/x/shinai/madara" -account_address = "0x2" -private_key = "0xc1cf1490de1352865301bb8705143f3ef938f97fdf892f1090dcb5ac7bcd1d" -#world_address = "0x5b328933afdbbfd44901fd69a2764a254edbb6e992ae87cf958c70493f2d201" -``` - -### Remote Katana - -Katanas are able to be hosted and run as remote testnets, however this is not recommended for production use. - -__todo__: add instructions for deploying to remote katana - - -### Madara - -[Madara](https://github.com/keep-starknet-strange/madara) is a blazingly fast Starknet sequencer. Built on the robust Substrate framework and fast, thanks to Rust πŸ¦€, Madara delivers unmatched performance and scalability to power your Starknet-based Validity Rollup chain. - -A public Madara testnet is available for deployment: - -**Testnet RPC:** https://api.cartridge.gg/x/shinai/madara - -You can use the following account to deploy: - -```toml -# ...rest of Scarb.toml - -rpc_url = "https://api.cartridge.gg/x/shinai/madara" -account_address = "0x2" -private_key = "0xc1cf1490de1352865301bb8705143f3ef938f97fdf892f1090dcb5ac7bcd1d" -``` - - -### Starknet - -__todo__: add instructions for deploying to remote Starknet diff --git a/0.3.0/src/getting-started/contributing.md b/0.3.0/src/getting-started/contributing.md deleted file mode 100644 index a1de86d8..00000000 --- a/0.3.0/src/getting-started/contributing.md +++ /dev/null @@ -1,7 +0,0 @@ -# Contributing to the Core - -Dojo is an open-source project, currently in its early development phase, and warmly welcomes contributors. - -## How to Contribute - -Head to the [Github](https://github.com/dojoengine/dojo/issues) for open issues, if you see an issue that is unassigned, please request in the comments to be assigned to it. If you have an idea for a new feature, please create an issue with the `enhancement` tag. \ No newline at end of file diff --git a/0.3.0/src/getting-started/from-source.md b/0.3.0/src/getting-started/from-source.md deleted file mode 100644 index f91e0323..00000000 --- a/0.3.0/src/getting-started/from-source.md +++ /dev/null @@ -1,40 +0,0 @@ -## Building from source - -> If you are just wanting to play with the toolchain, we strongly suggest following the [Quick Start](./quick-start.md) guide. - -#### Prerequisites - -You will need the [Rust](https://rust-lang.org) compiler and Cargo, the Rust package manager. -The easiest way to install both is with [`rustup.rs`](https://rustup.rs/). - -On Windows, you will also need a recent version of [Visual Studio](https://visualstudio.microsoft.com/downloads/), -installed with the "Desktop Development With C++" Workloads option. - -#### Building - -You can either use the different [Dojoup](#using-dojoup) flags: - -```sh -dojoup --branch master -dojoup --path path/to/dojo -``` - -Or, by using a single Cargo command: - -```sh -cargo install --git https://github.com/dojoengine/dojo --force sozo katana torii -``` - -Or, by manually building from a local copy of the [Dojo repository](https://github.com/dojoengine/dojo): - -```sh -# clone the repository -git clone https://github.com/dojoengine/dojo.git -cd dojo -# install Sozo -cargo install --path ./crates/sozo --force -# install Katana -cargo install --path ./crates/katana --force -# install Torii -cargo install --path ./crates/torii --force -``` diff --git a/0.3.0/src/getting-started/quick-start.md b/0.3.0/src/getting-started/quick-start.md deleted file mode 100644 index c8c26220..00000000 --- a/0.3.0/src/getting-started/quick-start.md +++ /dev/null @@ -1,26 +0,0 @@ -## Quick Start - -> It is worth reading [theory](../theory/autonomous-worlds.md) to familiarize yourself with the concept of Autonomous Worlds (AWs) and the [Cairo ecosystem](../theory/cairo.md) before diving into the code. - - -### Install Dojoup - -Dojo is built around a set of development tools - Katana, Torii and Sozo. Install them all easily with Dojoup. You can find detailed information about Dojoup [here](https://github.com/dojoengine/dojo/blob/master/dojoup/README.md). - -```sh -curl -L https://install.dojoengine.org | bash -``` - -This will install Dojoup, then simply follow the instructions on-screen, -which will make the `dojoup` command available in your CLI. - -```sh -dojoup -``` - -For full `dojoup` reference and debugging see [Dojoup](../toolchain/dojoup.md). - -### Next steps - -> Head to [Hello Dojo](../cairo/hello-dojo.md) to get create your first Dojo world. - diff --git a/0.3.0/src/getting-started/setup.md b/0.3.0/src/getting-started/setup.md deleted file mode 100644 index a4bbf90b..00000000 --- a/0.3.0/src/getting-started/setup.md +++ /dev/null @@ -1,51 +0,0 @@ -# Development Setup - -> This article is a guide to setting up a development environment for Dojo. It is not suggested to follow this guide if you are just wanting to play with the toolchain. We strongly suggest following the [Quick Start](../getting-started/quick-start.md) guide. - -### Prerequisites - -- Rust -- Cairo - - - -## Guide - -### Clone - -```sh -git clone https://github.com/dojoengine/dojo.git -``` - -### Linux & Mac - -#### 1. Install Rust and Dependencies - -Start by installing Rust and running the test suite to confirm your setup: - -```sh -rustup override set stable && rustup update && cargo test -``` - -> Note: Depending on your Linux distribution, you may need to install additional dependencies. Make sure to install any suggested or missing dependencies that arise during the setup process. - -#### 2. Install Scarb Package Manager - -Next, install the [Scarb](https://docs.swmansion.com/scarb) package manager by running: - -```sh -curl --proto '=https' --tlsv1.2 -sSf https://docs.swmansion.com/scarb/install.sh | sh -``` - -#### 3. Add the Cairo 1.0 VSCode Extension - -Install the [Cairo 1.0](https://marketplace.visualstudio.com/items?itemName=starkware.cairo1) extension for Visual Studio Code. - - -### Windows - -_Coming soon_ - -### Container - -_Coming soon_ diff --git a/0.3.0/src/images/ECS.png b/0.3.0/src/images/ECS.png deleted file mode 100644 index 638e86c0..00000000 Binary files a/0.3.0/src/images/ECS.png and /dev/null differ diff --git a/0.3.0/src/images/board.png b/0.3.0/src/images/board.png deleted file mode 100644 index ce3ab4c8..00000000 Binary files a/0.3.0/src/images/board.png and /dev/null differ diff --git a/0.3.0/src/images/dojo-auth.png b/0.3.0/src/images/dojo-auth.png deleted file mode 100644 index 46cf7ec5..00000000 Binary files a/0.3.0/src/images/dojo-auth.png and /dev/null differ diff --git a/0.3.0/src/images/dojo-mark-full-dark.svg b/0.3.0/src/images/dojo-mark-full-dark.svg deleted file mode 100644 index 5bc5b839..00000000 --- a/0.3.0/src/images/dojo-mark-full-dark.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/0.3.0/src/images/dojo-sozo-workflow.jpg b/0.3.0/src/images/dojo-sozo-workflow.jpg deleted file mode 100644 index 7a6ecb5e..00000000 Binary files a/0.3.0/src/images/dojo-sozo-workflow.jpg and /dev/null differ diff --git a/0.3.0/src/images/permissions.png b/0.3.0/src/images/permissions.png deleted file mode 100644 index 1fca70d8..00000000 Binary files a/0.3.0/src/images/permissions.png and /dev/null differ diff --git a/0.3.0/src/images/world_flow.png b/0.3.0/src/images/world_flow.png deleted file mode 100644 index 6812f3e8..00000000 Binary files a/0.3.0/src/images/world_flow.png and /dev/null differ diff --git a/0.3.0/src/misc/contributors.md b/0.3.0/src/misc/contributors.md deleted file mode 100644 index a91e8dd2..00000000 --- a/0.3.0/src/misc/contributors.md +++ /dev/null @@ -1,51 +0,0 @@ -## Contributing to Dojo Book - -As the Dojo engine progresses and develops, it is essential for the Dojo book to keep pace with these advancements. Updating and refining the book ensures that it remains a relevant and valuable resource for those interested in understanding and utilizing the latest Dojo engine features and capabilities. All help is welcome! - -### The purpose of the book - -The Dojo book is designed to be a comprehensive resource that caters to users at various levels of experience. It aims to serve as both an introductory guide for those new to Dojo and its ancillary packages, as well as a reference for more experienced users seeking to deepen their understanding of the engine's features and capabilities. - -The book is split into some major chapters: - -- Framework Theory -- Getting Started -- Building a World - -### Code of Conduct - -The book follows the [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct). - -### Ways to contribute - -#### Issues - -If you think that some content is missing or out-of-date, feel free to open an issue. If you find multiple pieces of content lacking, please open up a separate issue for each. - -The issues will then be labeled so other contributors can find chunks of work they are interested in more easily. - -The issue should contain what is missing, or what could be improved, in as much detail as you deem necessary. - -#### Pull requests - -Feel free to contribute changes to the book by opening a pull request - anything is welcome, from reformulating a sentence, fixing a typo, to adding new sections or chapters. - -When your pull request is open, other contributors will take a look and may request changes. Do not be discouraged! - -### Writing style - -This section documents a few standards for writing used throughout the book. - -#### Chapters start with a second level heading - -We use: - -```md -## Some Page -``` - -We do not use: - -```md -# Some Page -``` \ No newline at end of file diff --git a/0.3.0/src/theory/autonomous-worlds.md b/0.3.0/src/theory/autonomous-worlds.md deleted file mode 100644 index 2c03e467..00000000 --- a/0.3.0/src/theory/autonomous-worlds.md +++ /dev/null @@ -1,23 +0,0 @@ -## Autonomous Worlds - -> "Autonomous worlds represent persistent, permissionless, and decentralized open environments that users can freely interact with and contribute to." - -The precise definition of Autonomous Worlds (AWs) remains somewhat elusive, as it is more of an abstract concept that has yet to be fully crystallized. Lattice first [introduced](https://0xparc.org/blog/autonomous-worlds) the terminology in 2022, but the notion of open worlds operating on the blockchain has been around for a while. The abstraction introduced by MUD served as a catalyst for the market to recognize the potential of these worlds. - -Autonomous Worlds share notable similarities with blockchains in their fundamental nature. Once established, they persist, maintaining their state throughout the lifespan of the chain. Players can join or leave, and developers can expand these worlds by deploying features in a permissionless manner, much like how contracts are added to a chain. While there is no universally accepted definition for an Autonomous World, we believe that a game must possess at least the following two essential features to be considered as such: - -1. Decentralized data availability layer: While the state execution may reside on a centralized layer, it is crucial that the state can be reconstructed if the execution layer ceases to exist. Rollups offer a solution, providing increased capacity execution layers while ensuring data is permanently settled on Ethereum. This guarantees the world's perpetual persistence. - -2. Permissionless entry point for expanding the world: The World contract must be capable of accepting new systems and components without requiring permission. While this doesn't imply that every component and system will be utilized, they must adhere to this pattern, ensuring open and unrestricted access for potential enhancements. - -We're firm believers in the potential for Autonomous Worlds to catalyze the exploration of novel forms in the medium provided by zk proofs and blockchain technology. This is not only about games, but also about new forms of artwork, coordination, fun, emerging from tinkering and radical innovation, eventually questioning the very notion of "play" in this brave new decentralized and trustless world. - -### Homework -- [Wired - Autonomous Worlds Primer](https://www.wired.com/story/autonomous-worlds-aim-to-free-online-games-from-corporate-control/) -- [0xParc - Autonomous Worlds (Part 1)](https://0xparc.org/blog/autonomous-worlds) -- [Gubsheep - The Strongest Crypto Gaming Thesis](https://gubsheep.substack.com/p/the-strongest-crypto-gaming-thesis) -- [Lattice - MUD: An engine for Autonomous Worlds](https://lattice.xyz/blog/mud-an-engine-for-autonomous-worlds) -- [Guiltygyoza - Game 2.0](https://www.guiltygyoza.xyz/2022/07/game2) -- [Guiltygyoza - Composable Engineering](https://www.guiltygyoza.xyz/2023/05/composable-engineering) -- [Jay Springett - Wind-up Worlds](https://www.thejaymo.net/2022/05/06/wind-up-worlds/) -- [Are.na collection on Autonomous Worlds](https://www.are.na/sylve-chevet/on-chain-realities-and-autonomous-worlds) diff --git a/0.3.0/src/theory/cairo.md b/0.3.0/src/theory/cairo.md deleted file mode 100644 index c6beae80..00000000 --- a/0.3.0/src/theory/cairo.md +++ /dev/null @@ -1,34 +0,0 @@ -# Provable games - -Provable games demand [zero-knowledge](https://ethereum.org/en/zero-knowledge-proofs/) properties for efficient scaling and verification of computations. [Cairo](https://book.starknet.io/chapter_1/what_is_cairo.html) addresses this need by providing a generalized language, eliminating the complexity of creating circuits to incorporate [SNARKs](https://consensys.net/blog/developers/introduction-to-zk-snarks/). - -**You can simply program in Cairo and your applications become automatically provable**. - -Moreover, you can deploy your programs on the [Cairo Virtual Machine](https://medium.com/starkware/cairo-welcome-on-board-1cf3487554f) (CVM), which is compatible with Starknet's Layer 2, Starknet appchains, and even in-browser through WebAssembly (WASM)! Dojo aims to supply straightforward ZK primitives to fuel your game development. - -For more information about Starknet, Cairo and its tech stack, check out the [Starknet & Cairo book](https://book.starknet.io/). - -## Cairo - -Cairo is an open-source, Turing-complete smart contract language developed by Starkware, designed to power the Validity Rollup Starknet. The language enables highly expressive and verifiable computation, making it well-suited for building scalable and secure applications, including decentralized finance (DeFi) projects. - -Dojo builds on Cairo to create a robust framework for developing Autonomous Worlds (AWs). By leveraging the capabilities of Cairo, Dojo aims to streamline the development process, improve maintainability, and enhance the performance of AWs. - -A key feature of the Dojo framework is its use of [commands](../cairo/commands.md). Commands are a design pattern that helps to reduce boilerplate code, resulting in cleaner and more maintainable applications. They achieve this by encapsulating specific actions or operations within self-contained, reusable units. - -Developers can write commands freely within Systems, and the Cairo compiler takes care of inlining the appropriate functions. - -#### Essential Reading -- [Cairo book](https://cairo-book.github.io/) -- [Awesome Cairo](https://github.com/auditless/awesome-cairo) -- [Starknet Book](https://book.starknet.io/) - -### Starknet as an L2 - -Starknet is a Validity Rollup Layer 2 (L2) solution designed to scale Ethereum. It operates by offering high transaction throughput and low gas costs while maintaining the same level of security as Ethereum Layer 1 (L1). The strategy it uses is akin to solving a sudoku puzzle: verifying a solution is easier than finding the solution from scratch. Similarly, Starknet replaces heavy and costly L1 computation with cheaper L1 verification through the use of STARK proofs computed off-chain. - -In more technical terms, Starknet is a permissionless Validity-Rollup (also known as a "ZK-Rollup") that supports general computation and currently runs as an L2 network over Ethereum. The network's L1 security is guaranteed by its utilization of the STARK cryptographic proof system, which is considered one of the safest and most scalable. - -### Starknet as an Appchain - -Cairo is an isomorphic, general-purpose language, optimized for Zero-Knowledge (ZK) proofs. It's the driving force behind Starknet, Starkex, and appchains. Remarkably, you can also run it in WebAssembly (WASM) to generate proofs on the client-side! The Dojo team is working closely with the [Madara](https://github.com/keep-starknet-strange/madara) team to enable Starknet appchains to seamlessly run Dojo worlds. diff --git a/0.3.0/src/theory/faqs.md b/0.3.0/src/theory/faqs.md deleted file mode 100644 index 6dc62a74..00000000 --- a/0.3.0/src/theory/faqs.md +++ /dev/null @@ -1,31 +0,0 @@ -# FAQs - -#### Who owns Dojo? - -Dojo is strictly open-source and uses the Apache 2.0 license. Anyone can use Dojo for free, and anyone can contribute to the project. - -#### Why Dojo? - -Dojo was created to solve problems the founders faced when building onchain games. It standardizes the process of building such games and provides a suite of tools to make it easier. - -#### What is the Dojo roadmap? - -Dojo is rapidly evolving. You can find open issues on the [Dojo Github](https://github.com/dojoengine/dojo/issues) and join the [Discord](https://discord.gg/vUN4Xq9Qv6) to get involved. If you have ideas for the project, please open an issue. - -#### What is an onchain game? - -Onchain games are games that exist entirely on a public blockchain network; all states and logic are onchain. Clients (like web browsers) do not exist on the chain but exist purely to interact with and interpret the onchain state. - -#### What is an autonomous world? - -An autonomous world is one that exists entirely onchain. It's not controlled by any single entity but is instead governed by the rules set within that world. Dive deeper into the topic here: [Autonomous Worlds](../theory/autonomous-worlds.md). - -#### What is Cairo? - -Cairo is an opensource programming language invented by Starkware. It's a Turing-complete language meant for general-purpose computation. It's a low-level language designed to compile to the Cairo Virtual Machine. Learn more about it here: [Cairo](../theory/cairo.md). - -#### What is a provable game? - -Thanks to the magic of zero-knowledge proofs, we can ensure a game is fair by verifying a zk proof created off-chain. But what does that entail? Consider a game of chess. We aim for an experience where players trust each other's moves. In a straightforward approach β€” and given the simple rules of chess β€” if this were in a blockchain environment, every move would be a transaction on the blockchain. This is costly. We just want to know the winner, not every move. - -With zk proofs and client communications, players can establish a state channel, sharing moves off-chain and ensuring their validity. At the end, a zk proof can be submitted to the blockchain to confirm the game's fairness. This constitutes a provable game. \ No newline at end of file diff --git a/0.3.0/src/theory/what-is-dojo.md b/0.3.0/src/theory/what-is-dojo.md deleted file mode 100644 index 7affe807..00000000 --- a/0.3.0/src/theory/what-is-dojo.md +++ /dev/null @@ -1,45 +0,0 @@ -# What is Dojo? - -Dojo is the culmination of lessons learned from attempts at building [onchain games](https://naavik.co/digest/primer-fully-on-chain-gaming), an emerging sector in the gaming industry. Any developer who has endeavored to build an on-chain game recognizes the inherent engineering hurdles - a realization that drove us to create Dojo. Just as you wouldn't recreate Unity every time you develop a new game, the same principle applies here. Dojo is designed to handle the complex infrastructure, allowing developers to focus on the unique aspects of their games. - -Dojo aspires to be the go-to tool for building provable games. It is radically open-source, and all contributions are welcome. - ---- - -## Stop building infrastructure; start building games - -Dojo's suite of tools takes the infrastructure complexity out of building on-chain games. It includes: - -### Entity Component System (ECS) - -Dojo offers a standardized approach to building games on smart contracts. Recognizing the intricacies of game design, Dojo simplifies the development process, allowing creators to focus on gameplay logic. This standardization paves the way for an interconnected network of worlds, streamlining developer expertise and promoting game integration. - -Utilizing the ECS (Entity Component System) as its core architecture, Dojo effectively manages the state and behavior of Autonomous Worlds (AWs). This model revolves around systems acting on entities, which are collections of pure data components. Systems efficiently determine which entities to process based on persistent queries over these components. - -Read detailed information about the [Dojo ECS](../cairo/overview.md). - -### [Torii](/crates/torii/README.md) - Starknet Indexer - -Building on-chain games often involves grappling with the challenge of indexing on-chain state. However, Dojo standardizes contract states to mirror traditional relational databases. This setup enables the [Torii Indexer](../toolchain/torii/overview.md) to auto-index all contract states, ensuring efficient and streamlined queries. Torii then exposes these states via a GraphQL API or gRPC (coming soon), allowing developers to easily query and retrieve data. - -Using Torii drastically reduces the time and effort required to build on-chain games. It also eliminates the need to manually create indexers, which can be a tedious and error-prone process. - -### [Katana](/crates/katana/README.md) - Blazingly fast development network - -Katana is a customizable StarkNet development network. It is blazingly fast and allows you to iterate on your game logic swiftly. - -### [Sozo CLI](/crates/sozo/README.md) - CLI Management Tool - -Dojo worlds are poised to become some of the largest contracts. Sozo is a CLI tool that assists you in managing your worlds. It enables you to create, build, test, and deploy your worlds. Additionally, you can craft new components and systems and register them with your world. - -### What Dojo doesn't give you - -1. Visual graphics - While Dojo provides networking and contracts, it doesn't offer graphical engines. You can bring your graphics of choice! Integrate your Dojo world with Unreal, Godot, or Unity. - -## Understanding the Dojo Workflow: A Visual Guide - -To help you understand how `Sozo` works, we've created a visual guide that outlines the flow of execution using the powerful sozo tool and the katana development network. - -This visual representation will help you grasp the fundamental steps of working with Dojo, guiding you through the process of creating and managing your on-chain games. - -![Dojo Sozo Workflow](../images/dojo-sozo-workflow.jpg) diff --git a/0.3.0/src/toolchain/dojoup.md b/0.3.0/src/toolchain/dojoup.md deleted file mode 100644 index 72babc4f..00000000 --- a/0.3.0/src/toolchain/dojoup.md +++ /dev/null @@ -1,87 +0,0 @@ -# `dojoup` - -Update or revert to a specific Dojo branch with ease. - -## Installing - -```sh -curl -L https://install.dojoengine.org | bash -``` - -## Usage - -To install latest **stable** version: - -```sh -dojoup -``` -> Note: You may have to install `jq` to use `dojoup`. You can do so with the following commands: - -```sh -# Debian -sudo apt-get install jq - -# Mac -brew install jq -``` - -To install a specific **version** (in this case the `nightly` version): - -```sh -dojoup --version nightly -``` - -To install a specific **branch** (in this case the `release/0.1.0` branch's latest commit): - -```sh -dojoup --branch release/0.1.0 -``` - -To install a **fork's main branch** (in this case `tarrencev/dojo`'s main branch): - -```sh -dojoup --repo tarrencev/dojo -``` - -To install a **specific branch in a fork** (in this case the `patch-10` branch's latest commit in `tarrencev/dojo`): - -```sh -dojoup --repo tarrencev/dojo --branch patch-10 -``` - -To install from a **specific Pull Request**: - -```sh -dojoup --pr 1071 -``` - -To install from a **specific commit**: - -```sh -dojoup -C 94bfdb2 -``` - -To install a local directory or repository (e.g. one located at `~/git/dojo`, assuming you're in the home directory) - -##### Note: --branch, --repo, and --version flags are ignored during local installations. - -```sh -dojoup --path ./git/dojo -``` - ---- - -**Tip**: All flags have a single character shorthand equivalent! You can use `-v` instead of `--version`, etc. - ---- - -### Precompiled binaries - -Precompiled binaries are available from the [GitHub releases page](https://github.com/dojoengine/dojo/releases). -These are better managed by using [Dojoup](#using-dojoup). - - -> ℹ️ **Note** -> -> If you're on Windows, you will need to install and use [Git BASH](https://gitforwindows.org/) or [WSL](https://learn.microsoft.com/en-us/windows/wsl/install), -> as your terminal, since Dojoup currently does not support Powershell or Cmd. \ No newline at end of file diff --git a/0.3.0/src/toolchain/katana/development.md b/0.3.0/src/toolchain/katana/development.md deleted file mode 100644 index 459110d3..00000000 --- a/0.3.0/src/toolchain/katana/development.md +++ /dev/null @@ -1 +0,0 @@ -# Development diff --git a/0.3.0/src/toolchain/katana/overview.md b/0.3.0/src/toolchain/katana/overview.md deleted file mode 100644 index 6ab121bb..00000000 --- a/0.3.0/src/toolchain/katana/overview.md +++ /dev/null @@ -1,62 +0,0 @@ -## Katana - -`katana` is a _blazingly fast_ local Starknet node, designed to support local development with Dojo. - -### Features - -- [Starknet JSON-RPC v0.3.0](https://github.com/starkware-libs/starknet-specs/tree/v0.3.0) support -- Custom methods for manipulating the blockchain states - -## Installation - -`katana` binary is available via [`dojoup`](../../getting-started/quick-start.md). - -### Installing from source - -```sh -git clone https://github.com/dojoengine/dojo -cd dojo -cargo install --path ./crates/katana --locked --force -``` - -### Usage - -```console -$ katana - - - -β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— -β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— -β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ -β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘ -β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ -β•šβ•β• β•šβ•β•β•šβ•β• β•šβ•β• β•šβ•β• β•šβ•β• β•šβ•β•β•šβ•β• β•šβ•β•β•β•β•šβ•β• β•šβ•β• - - - -PREFUNDED ACCOUNTS -================== - -| Account address | 0x3ee9e18edc71a6df30ac3aca2e0b02a198fbce19b7480a63a0d71cbd76652e0 -| Private key | 0x300001800000000300000180000000000030000000000003006001800006600 -| Public key | 0x1b7b37a580d91bc3ad4f9933ed61f3a395e0e51c9dd5553323b8ca3942bb44e - -| Account address | 0x33c627a3e5213790e246a917770ce23d7e562baa5b4d2917c23b1be6d91961c -| Private key | 0x333803103001800039980190300d206608b0070db0012135bd1fb5f6282170b -| Public key | 0x4486e2308ef3513531042acb8ead377b887af16bd4cdd8149812dfef1ba924d - - -ACCOUNTS SEED -============= -0 - - -πŸš€ JSON-RPC server started: http://127.0.0.1:5050 - - -``` - -> πŸ“š **Reference** -> -> See the [`katana` Reference](./reference.md) for an in depth reference and documentation on Katana. diff --git a/0.3.0/src/toolchain/katana/reference.md b/0.3.0/src/toolchain/katana/reference.md deleted file mode 100644 index f92a10dd..00000000 --- a/0.3.0/src/toolchain/katana/reference.md +++ /dev/null @@ -1,263 +0,0 @@ -## katana reference - -### NAME - -katana - Create a local testnet node for deploying and testing Starknet smart contracts. - -### USAGE - -```sh -katana [OPTIONS] -``` - -### DESCRIPTION - -Create a local testnet node for deploying and testing Starknet smart contracts. Katana supports deployment and execution of the **new** as well as the **legacy** (Cairo 0) Cairo contracts. - -This section covers an extensive list of information about Mining Modes, Supported RPC Methods, Katana flags and their usages. You can run multiple flags at the same time. - -#### Mining Modes - -In Katana, mining modes determine how frequent blocks are mined. By default, a new block is automatically mined as soon as a transaction is submitted. - -You can switch from the default mining behaviour to interval mining, where a new block is created at a fixed time interval selected by the user. To enable this mode of mining, use the `--block-time ` flag, as demonstrated in the following example. - -```sh -# Produces a new block every 10 seconds -katana --block-time 10000 -``` - -#### Forking - -Katana supports forking from a Starknet RPC provider. You can configure your node to enable the forking feature by providing a valid RPC provider using the `--rpc-url ` flag., which would initiate Katana to fork the latest block of the provided network. If you would like to fork from a specific block, you can do so using `--fork-block-number `. - -NOTE: This does not allow fetching of historical blocks but only blocks that are mined by Katana. However, support for fetching historical blocks will be added in the future. - -```sh -# Forks the network at block 1200 -katana --rpc-url http://your-rpc-provider.com --fork-block-number 1200 -``` - -#### Messaging - -Katana also allows users to perform L1 <-> L2 integration using the messaging feature. There are two types of messaging service supported by Katana: - -1. _Ethereum_ -2. _Starknet_ (**experimental**) - -If configured to _Ethereum_ messaging, Katana will listen/send messages on an Ethereum chain. This type of messaging behaves similar to the canonical Starknet sequencer with the exception that messages from L2 -> L1 will be sent directly to the settlement chain for consumption, instead of having to wait for the corresponding blocks of the messages to be proven on the settlement chain (which in reality would be a very time consuming process). - -The _Starknet_ messaging, however, is an experimental feature that allows Katana to listen/send messages on a Starknet chain. It attempts to replicate the behaviour of Ethereum messaging but with a Starknet chain as the settlement layer. This is achieved by having Katana listen to the Starknet chain for new blocks and then sending the messages to the settlement chain for consumption. This is an experimental and opinionated feature, and is not recommended for production use. - -```sh -katana --messaging path/to/messaging/config.json -``` - -The messaging config file is a JSON file that contains the following fields: - -```json -{ - /// The type of messaging service to use. Can be either "ethereum" or "starknet". - "chain": "ethereum", - /// The RPC-URL of the settlement chain. - "rpc_url": "http://127.0.0.1:8545", - /// The messaging-contract address on the settlement chain. - "contract_address": "0x5FbDB2315678afecb367f032d93F642f64180aa3", - /// The address to use for settling messages. It should be a valid address that - /// can be used to send a transaction on the settlement chain. - "sender_address": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - /// The private key associated to `sender_address`. - "private_key": "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80", - /// The interval, in seconds, at which the messaging service will fetch and settle messages - /// from/to the settlement chain. - "interval": 2, - /// The block on settlement chain from where Katana will start fetching messages. - "from_block": 0 -} -``` - -#### Supported Transport Layers - -Only HTTP connection is supported at the moment. The server listens on port 5050 by default, but it can be changed by running the following command: - -```sh -katana --port -``` - -#### Starknet Feature Compatibility - -##### Supported Transaction Type - -| Type | Version | -| -------------- | ------- | -| INVOKE | 1 | -| DECLARE | 1, 2 | -| DEPLOY_ACCOUNT | | - -#### Supported RPC Methods - -##### Starknet Methods - -Katana supports version **v0.3.0** of the Starknet JSON-RPC specifications. The standard methods are based on [this](https://github.com/starkware-libs/starknet-specs/tree/v0.3.0) reference. - -- `starknet_blockNumber` -- `starknet_blockHashAndNumber` -- `starknet_getBlockWithTxs` -- `starknet_getBlockWithTxHashes` -- `starknet_getBlockTransactionCount` -- `starknet_getTransactionByHash` -- `starknet_getTransactionByBlockIdAndIndex` -- `starknet_getTransactionReceipt` -- `starknet_pendingTransactions` -- `starknet_getStateUpdate` - -- `starknet_call` -- `starknet_estimateFee` - -- `starknet_chainId` - -- `starknet_getNonce` -- `starknet_getEvents` -- `starknet_getStorageAt` -- `starknet_getClassHashAt` -- `starknet_getClass` -- **`starknet_getClassAt`** - -- `starknet_addInvokeTransaction` -- `starknet_addDeclareTransaction` -- `starknet_addDeployAccountTransaction` - -##### Custom Methods - -Katana provides a convenient set of custom RPC methods to quickly and easily configure the node to suit your testing environment. - -`katana_generateBlock` -Mine a new block which includes all currently pending transactions. - -`katana_nextBlockTimestamp` -Get the time for the next block. - -`katana_increaseNextBlockTimestamp` -Increase the time for the block by a given amount of time, in seconds. - -`katana_setNextBlockTimestamp` -Similar to `katana_increaseNextBlockTimestamp` but takes the exact timestamp that you want in the next block. - -`katana_predeployedAccounts` -Get the info for all of the predeployed accounts. - -`katana_setStorageAt` -Set an exact value of a contract's storage slot. - -### OPTIONS - -#### General Options - -`--silent` -     Don't print anything on startup. - -`--no-mining` -     Disable auto and interval mining, and mine on demand instead. - -`-b, --block-time ` -     Block time in milliseconds for interval mining. - -`--dump-state ` -     Dump the state of chain on exit to the given file. -     If the value is a directory, the state will be written to `/state.bin`. - -`--load-state ` -     Initialize the chain from a previously saved state snapshot. - -`--rpc-url ` -     The Starknet RPC provider to fork the network from. - -`--json-log` -     Output logs in JSON format. - -`--fork-block-number ` -     Fork the network at a specific block. - -`--messaging ` -     Configure the messaging service to allow Katana to listen/send messages on a settlement chain that can be either Ethereum or another Starknet sequencer (experimental). - -`-h, --help` -     Print help (see a summary with '-h'). - -`-V, --version` -     Print version information. - -#### Server Options - -`-p, --port ` -     Port number to listen on. [default: 5050] - -`--host ` -     The IP address the server will listen on. - -#### Starknet Options - -`--seed ` -     Specify the seed for randomness of accounts to be predeployed. - -`--accounts ` -     Number of pre-funded accounts to generate. [default: 10] - -`--disable-fee` -     Disable charging fee for transactions. - -#### Environment Options - -`--chain-id ` -     The chain ID. [default: KATANA] - -`--gas-price ` -     The gas price. - -`--validate-max-steps ` -     The maximum number of steps available for the account validation logic. - -`--invoke-max-steps ` -     The maximum number of steps available for the account execution logic. - -### Shell Completions - -`katana` completions shell - -Generates a shell completions script for the given shell. - -Supported shells are: - -- bash -- elvish -- fish -- powershell -- zsh - -#### EXAMPLES - -Generate shell completions script for `bash` and appends it to a `.bashrc` file: - -```bash -katana completions bash >> ~/.bashrc -``` - -### EXAMPLES - -1. Create 15 dev accounts and disable transaction fee mechanism - -```sh -katana --accounts 15 --disable-fee -``` - -2. Set the chain id to `SN_GOERLI` and run the server on port 8545 - -```sh -katana --chain-id SN_GOERLI --port 8545 -``` - -3. Load previously stored state and dump the state of this session to a file on shutdown - -```sh -katana --load-state ./dump-state.bin --dump-state ./dump-state.bin -``` diff --git a/0.3.0/src/toolchain/sozo/common/account-options.md b/0.3.0/src/toolchain/sozo/common/account-options.md deleted file mode 100644 index 7e48da08..00000000 --- a/0.3.0/src/toolchain/sozo/common/account-options.md +++ /dev/null @@ -1,3 +0,0 @@ -`--account-address` _ACCOUNT_ADDRESS_ -    The Starknet account address. -    ENV: `DOJO_ACCOUNT_ADDRESS` diff --git a/0.3.0/src/toolchain/sozo/common/signer-options-keystore.md b/0.3.0/src/toolchain/sozo/common/signer-options-keystore.md deleted file mode 100644 index f58cca5f..00000000 --- a/0.3.0/src/toolchain/sozo/common/signer-options-keystore.md +++ /dev/null @@ -1,6 +0,0 @@ -`--keystore` _PATH_ -    Use the keystore in the given folder or file. - -`--password` _PASSWORD_ -    The keystore password. Used with --keystore. -    ENV: `DOJO_KEYSTORE_PASSWORD` diff --git a/0.3.0/src/toolchain/sozo/common/signer-options-raw.md b/0.3.0/src/toolchain/sozo/common/signer-options-raw.md deleted file mode 100644 index 21f6eeb2..00000000 --- a/0.3.0/src/toolchain/sozo/common/signer-options-raw.md +++ /dev/null @@ -1,3 +0,0 @@ -`--private-key` _PRIVATE_KEY_ -    The raw private key associated with the account contract. -    ENV: `DOJO_PRIVATE_KEY` diff --git a/0.3.0/src/toolchain/sozo/common/starknet-options.md b/0.3.0/src/toolchain/sozo/common/starknet-options.md deleted file mode 100644 index acc58704..00000000 --- a/0.3.0/src/toolchain/sozo/common/starknet-options.md +++ /dev/null @@ -1,3 +0,0 @@ -`--rpc-url` _URL_ -    The Starknet RPC endpoint. [default: http://localhost:5050] -    ENV: `STARKNET_RPC_URL` diff --git a/0.3.0/src/toolchain/sozo/common/world-options.md b/0.3.0/src/toolchain/sozo/common/world-options.md deleted file mode 100644 index 358e0e18..00000000 --- a/0.3.0/src/toolchain/sozo/common/world-options.md +++ /dev/null @@ -1,3 +0,0 @@ -`--world` _WORLD_ADDRESS_ -    The address of the World contract. -    ENV: `DOJO_WORLD_ADDRESS` diff --git a/0.3.0/src/toolchain/sozo/development.md b/0.3.0/src/toolchain/sozo/development.md deleted file mode 100644 index 459110d3..00000000 --- a/0.3.0/src/toolchain/sozo/development.md +++ /dev/null @@ -1 +0,0 @@ -# Development diff --git a/0.3.0/src/toolchain/sozo/overview.md b/0.3.0/src/toolchain/sozo/overview.md deleted file mode 100644 index 3bb86a24..00000000 --- a/0.3.0/src/toolchain/sozo/overview.md +++ /dev/null @@ -1,25 +0,0 @@ -## Sozo - -`sozo` is a powerful all-in-one tool for managing your Dojo projects. It helps with everything from scaffolding a new project, all the way to deploying and interacting with your Dojo Worlds. It includes a migration planning tool, designed to streamline the updating and deployment of AWs. It provides a robust command-line interface (CLI) that simplifies World management tasks, enabling you to focus on the creative aspects of World-building. In the future, it may include a GUI. - -## Features - -- **Binary CLI**: Sozo provides an intuitive binary CLI, ensuring easy management of your Worlds, whether you're updating existing ones or deploying new ones. - -## Installation - -`sozo` binary can be installed via [`dojoup`](../../getting-started/quick-start.md), our dedicated installation package manager. - -### Installing from Source - -```sh -git clone https://github.com/dojoengine/dojo -cd dojo -cargo install --path ./crates/sozo --locked --force -``` - -This will install Sozo and the required dependencies on your local system. - -> πŸ“š **Reference** -> -> See the [`sozo` Reference](./reference.md) for a complete overview of all the available subcommands. diff --git a/0.3.0/src/toolchain/sozo/project-commands/build.md b/0.3.0/src/toolchain/sozo/project-commands/build.md deleted file mode 100644 index 06dfdd64..00000000 --- a/0.3.0/src/toolchain/sozo/project-commands/build.md +++ /dev/null @@ -1,7 +0,0 @@ -## sozo build - -`build` is used to compile the cairo contracts, generating the necessary artifacts for deployment. - -```sh -sozo build -``` \ No newline at end of file diff --git a/0.3.0/src/toolchain/sozo/project-commands/init.md b/0.3.0/src/toolchain/sozo/project-commands/init.md deleted file mode 100644 index fd2870b9..00000000 --- a/0.3.0/src/toolchain/sozo/project-commands/init.md +++ /dev/null @@ -1,7 +0,0 @@ -## sozo init - -`init` is used to initialize a new project. It will initialize a new project in the current directory by cloning the [dojo-starter](https://github.com/dojoengine/dojo-starter). - -```sh -sozo init -``` \ No newline at end of file diff --git a/0.3.0/src/toolchain/sozo/project-commands/migrate.md b/0.3.0/src/toolchain/sozo/project-commands/migrate.md deleted file mode 100644 index 53943f77..00000000 --- a/0.3.0/src/toolchain/sozo/project-commands/migrate.md +++ /dev/null @@ -1,52 +0,0 @@ -## sozo migrate - -`migrate` is used to perform the migration (deployment) process, declaring and deploying contracts as necessary to deploy or update the World. - -Changes made to the local World after the initial deployment, can easily be pushed to the remote counterpart by running `sozo migrate --world ` with `WORLD_ADDRESS` being the address of the remote World. In the background, `migrate` will compute the diffs of the local and remote World, then, start constructing a migration strategy to determine, if any, which part of the local World needs to be pushed upstream. - -### USAGE - -```sh -sozo migrate [OPTIONS] -``` - -### OPTIONS - -#### General Options - -`--name` _NAME_ -    Name of the World. At the moment, the only usage for this option is to be used as a salt when deploying the World contract to avoid address conflicts. This option is **required** when performing the initial migration of the World. - -#### World Options - -{{#include ../common/world-options.md}} - -#### Starknet Options - -{{#include ../common/starknet-options.md}} - -#### Account Options - -{{#include ../common/account-options.md}} - -#### Signer Options - Raw - -{{#include ../common/signer-options-raw.md}} - -#### Signer Options - Keystore - -{{#include ../common/signer-options-keystore.md}} - -### EXAMPLES - -1. Deploying your World for the first time to a local Katana node - -```sh -sozo migrate --name ohayo --rpc-url http://localhost:5050 -``` - -2. Updating a remote World after making some changes - -```sh -sozo migrate --world 0x123456 -``` diff --git a/0.3.0/src/toolchain/sozo/project-commands/test.md b/0.3.0/src/toolchain/sozo/project-commands/test.md deleted file mode 100644 index 6ec74dd9..00000000 --- a/0.3.0/src/toolchain/sozo/project-commands/test.md +++ /dev/null @@ -1,7 +0,0 @@ -## sozo test - -`test` is used to test the project's cairo contracts. It will run all tests found within the project. - -```sh -sozo test -``` \ No newline at end of file diff --git a/0.3.0/src/toolchain/sozo/reference.md b/0.3.0/src/toolchain/sozo/reference.md deleted file mode 100644 index ce23c182..00000000 --- a/0.3.0/src/toolchain/sozo/reference.md +++ /dev/null @@ -1,17 +0,0 @@ -## sozo reference - -### Project Commands - -- [init](./project-commands/init.md) -- [build](./project-commands/build.md) -- [test](./project-commands/test.md) -- [migrate](./project-commands/migrate.md) - -### World Commands - -- [execute](./world-commands/execute.md) -- [register](./world-commands/register.md) -- [system](./world-commands/system.md) -- [component](./world-commands/component.md) -- [events](./world-commands/events.md) -- [auth](./world-commands/auth.md) diff --git a/0.3.0/src/toolchain/sozo/world-commands/auth.md b/0.3.0/src/toolchain/sozo/world-commands/auth.md deleted file mode 100644 index ef78aee1..00000000 --- a/0.3.0/src/toolchain/sozo/world-commands/auth.md +++ /dev/null @@ -1,19 +0,0 @@ -## sozo auth - -`auth` is used to manage world authorization. - -```sh -sozo auth [OPTIONS] --world -``` - -```sh -Commands: - writer Auth a system with the given calldata. - help Print this message or the help of the given subcommand(s) -``` - -```sh -# example: writer - auth a system with the given calldata -# This will auth the spawn system with the writer role for Position component -sozo auth writer Moves --world -``` \ No newline at end of file diff --git a/0.3.0/src/toolchain/sozo/world-commands/component.md b/0.3.0/src/toolchain/sozo/world-commands/component.md deleted file mode 100644 index cae26d30..00000000 --- a/0.3.0/src/toolchain/sozo/world-commands/component.md +++ /dev/null @@ -1,69 +0,0 @@ -## sozo component - -`component` is used to interact with a World's components. It is useful for querying about a component's information, or a component value of an entity. - -### USAGE - -```sh -sozo component - -Commands: - get Get the class hash of a component - schema Retrieve the schema for a component - entity Get the component value for an entity -``` - -### SUBCOMMANDS - -#### `get` - -Get the class hash of a component - -```sh -sozo component get -``` - -##### Arguments - -_`NAME`_ -    The name of the component - -#### `schema` - -Retrieve the schema for a component - -```sh -sozo component schema -``` - -##### Arguments - -_`NAME`_ -    The name of the component - -#### `entity` - -Get the component value for an entity - -```sh -sozo component entity [KEYS]... -``` - -##### Arguments - -_`NAME`_ -     The name of the component - -_`KEYS`_ -     The keys of the entity that you want to query. -     Comma separated values e.g., 0x12345,0x69420,... - -### OPTIONS - -#### World Options - -{{#include ../common/world-options.md}} - -#### Starknet Options - -{{#include ../common/starknet-options.md}} diff --git a/0.3.0/src/toolchain/sozo/world-commands/events.md b/0.3.0/src/toolchain/sozo/world-commands/events.md deleted file mode 100644 index 8b0862fc..00000000 --- a/0.3.0/src/toolchain/sozo/world-commands/events.md +++ /dev/null @@ -1,7 +0,0 @@ -## sozo events - -`events` is used to queries world events. - -```sh -sozo events -``` \ No newline at end of file diff --git a/0.3.0/src/toolchain/sozo/world-commands/execute.md b/0.3.0/src/toolchain/sozo/world-commands/execute.md deleted file mode 100644 index 3e9984b5..00000000 --- a/0.3.0/src/toolchain/sozo/world-commands/execute.md +++ /dev/null @@ -1,47 +0,0 @@ -## sozo execute - -`execute` is used to execute a World's system. - -Performing a system execution requires sending a transaction, therefore, `execute` expects an account address as well as its respective private key in order to sign the transaction before sending it. - -### USAGE - -```sh -sozo execute [OPTIONS] -``` - -### OPTIONS - -#### General Options - -`--calldata` _CALLDATA_ -    The calldata to be passed to the system that you want to execute. -    Comma separated values e.g., 0x12345,0x69420. - -#### World Options - -{{#include ../common/world-options.md}} - -#### Starknet Options - -{{#include ../common/starknet-options.md}} - -#### Account Options - -{{#include ../common/account-options.md}} - -#### Signer Options - Raw - -{{#include ../common/signer-options-raw.md}} - -#### Signer Options - Keystore - -{{#include ../common/signer-options-keystore.md}} - -### EXAMPLES - -1. Executing the _position_ system which takes two values (_x_: 0x77 and _y_: 0x44) - -```sh -sozo execute position --calldata 0x77,0x44 -``` diff --git a/0.3.0/src/toolchain/sozo/world-commands/register.md b/0.3.0/src/toolchain/sozo/world-commands/register.md deleted file mode 100644 index 9db98e71..00000000 --- a/0.3.0/src/toolchain/sozo/world-commands/register.md +++ /dev/null @@ -1,24 +0,0 @@ -## sozo register - -`register` is used to register new systems and components. - -```sh -sozo register [OPTIONS] -``` - -```sh -Commands: - component Register a component to a world. - system Register a system to a world. - help Print this message or the help of the given subcommand(s) -``` - -```sh -# example: component - register a component to a world -# this will register the Moves component to the world -sozo register component Moves - -# example: system - register a system to a world -# this will register the spawn system to the world -sozo register system spawn -``` \ No newline at end of file diff --git a/0.3.0/src/toolchain/sozo/world-commands/system.md b/0.3.0/src/toolchain/sozo/world-commands/system.md deleted file mode 100644 index 160f4321..00000000 --- a/0.3.0/src/toolchain/sozo/world-commands/system.md +++ /dev/null @@ -1,65 +0,0 @@ -## sozo system - -`system` is used to interact with a World's systems. It is useful for querying about a system's information. - -### USAGE - -```sh -sozo system - -Commands: - get Get the class hash of a system. - dependency Retrieve the component dependencies of a system. -``` - -### SUBCOMMANDS - -#### `get` - -Get the class hash of a system - -```sh -sozo system get -``` - -##### Arguments - -_`NAME`_ -    The name of the system - -#### `dependency` - -Retrieve the component dependencies of a system - -```sh -sozo system dependency -``` - -##### Arguments - -_`NAME`_ -    The name of the system - -### OPTIONS - -#### World Options - -{{#include ../common/world-options.md}} - -#### Starknet Options - -{{#include ../common/starknet-options.md}} - -### EXAMPLES - -1. Get the class hash of the _spawn_ system - -```sh -sozo system get spawn -``` - -2. Get the component dependencies of the _spawn_ system - -```sh -sozo system dependency spawn -``` diff --git a/0.3.0/src/toolchain/torii/graphql.md b/0.3.0/src/toolchain/torii/graphql.md deleted file mode 100644 index 8fd22439..00000000 --- a/0.3.0/src/toolchain/torii/graphql.md +++ /dev/null @@ -1,256 +0,0 @@ -## Torii - GraphQL - -### Name - -In Dojo, you have access to custom queries and subscriptions that are specifically designed to work with the `caller` for client applications. GraphQL is the technology that makes this possible. - -GraphQL is the rising star of backend technologies. It replaces REST as an API design paradigm and is becoming the new standard for exposing the data and functionality of a web server. It allows you to specify exactly what data you want to retrieve, and it delivers that data in a structured JSON format. This flexibility in data retrieval ensures that you get the information you need efficiently and in a format that's easy to work with. - -#### GraphQL Playground - -GraphQL Playground is a `GraphQL IDE`` that allows you to interactively explore the functionality of a GraphQL API by sending queries and mutations to it. It’s somewhat similar to Postman which offers comparable functionality for REST APIs. - -### USAGE - -#### Pre-requisites - -Make sure torii is running in your local terminal. - -```sh -torii --world -``` - -It starts GraphQL server at `http://0.0.0.0:8080/graphql` - -After the torii server starts on your local machine, you're ready to make query and subscription operations. - -### Schema and query defintions - -Torii generates both the schema and queries at runtime specific to your world. There are mainly two groups of queries, predefined queries and dynamically generated custom queries. - -Predefined queries like `entities` provide a generic entry point to the entities data of the world. Custom queries on the other hand are built according to the models of the world. Each model has a correpsonding `{name}Models` query and retrieves the associated model data. - -The benefit of custom queries becomes apparent when filtering and sorting is needed. They allow much more finer control of the returned dataset. - -### Query operation - -In [`hello-dojo`](../../cairo/hello-dojo.md#next-steps) we fetched some data from the `Moves` model. This time let's fetch only `id`, `name`, `class_hash` fields from `Position` model . - -```graphql -query { - model(id: "Position") { - id - name - class_hash - } -} -``` - -After you run the query, you will receive an output like this: - -```json -{ - "data": { - "model": { - "id": "Position", - "name": "Position", - "class_hash": "0x6ffc643cbc4b2fb9c424242b18175a5e142269b45f4463d1cd4dddb7a2e5095" - } - } -} -``` - -Great! If you're wondering about the number of fields a `Model` has or the details of a `Entities`, you can find all the information about the schema definition in the `Documentation Explorer` section of the GraphQL IDE. It's your go-to place for exploring the rest of the documentation. - -Now lets retrieve more data from `Moves` model. - -```graphql -query { - movesModels { - edges { - node { - player - remaining - last_direction - } - } - } -} -``` - -After you run the query, you will receive an output like this: - -```json -{ - "data": { - "movesModels": { - "edges": [ - { - "node": { - "player": "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973", - "remaining": 10, - "last_direction": "None" - } - } - ] - } - } -} -``` - -Feel free to play around with the query by removing any fields from the selection set and observe the responses sent by the server. It is your turn to create any kind of query for entities and models! - -#### Pagination - -As the entities in your world grows, fetching all of that data at once can become inefficient and slow. - -Torii provides two methods to address this - cursor or offset/limit based pagination. To keep the return type consistent, both methods will return a [`Connection`](https://relay.dev/graphql/connections.htm#sec-Connection-Types) type. - -You can read more about graphql pagination [here](https://graphql.org/learn/pagination). - -##### Cursor - -Cursor based pagination is the most efficient, allowing us to query a subset or slice of the entire set of data. Both forward and backward pagination are supported using a combination of `first, last, before, after` input arguments. - -Forward pagination uses `first`/`after` and backward pagination uses `last`/`before`. `first`/`last` are integers representing the number of items to return. `after`/`before` are the cursors to paginate from. - -Query for first page of 2 entities - -```graphql -query { - entities (first: 2) { - total_count - edges { - cursor - node { - ... - } - } - } -} -``` - -Result shows there are 5 entities and returns the first two - -```json -{ - "entities" { - "total_count": 5, - "edges" [ - { - "cursor": "Y3Vyc29yX29uZQ==", - "node" : { } - }, - { - "cursor": "Y3Vyc29yX3R3bw==", - "node" : { } - }, - ] - } -} -``` - -Query 3 entities after the second node (last 3) - -```graphql -query { - entities (first: 3, after: "Y3Vyc29yX3R3bw==") { - ... - } -} -``` - -##### Offset/limit - -Offset/limit based pagination can be more intuitive and easier to use. However, for very, very large datasets they can be inefficient. - -```graphql -# essentially the same as the last query in cursor example -query { - entities (offset: 2, limit 3) { - ... - } -} -``` - -### Subscription operations - -Subscriptions are a GraphQL feature that allows a server to send data to its clients when a specific event happens. Subscriptions are usually implemented with WebSockets. In that setup, the server maintains a steady connection to its subscribed client. This also breaks the β€œRequest-Response-Cycle” that is used for with REST APIs. - -Instead, the client initially opens up a long-lived connection to the server by sending a subscription query that specifies which event it is interested in. Every time this particular event happens, the server uses the connection to push the event data to the subscribed client(s). - -In this example, you can listen when an `Model` is registered by executing this subscription - -```graphql -subscription modelRegistered { - modelRegistered { - id - name - } -} -``` - -Graphql also supports subscription to a targeted entity or model, for this we have to pass its id as an argument - -In this example, our server provides a `entityUpdated` subscription, which should notify clients whenever an entity with id `0x28cd7ee02d7f6ec9810e75b930e8e607793b302445abbdee0ac88143f18da20` is updated. On the same subscription we can get the model(components) values of the updated entity . A client can execute a subscription that looks like this: - -```graphql -subscription { - entityUpdated( - id: "0x28cd7ee02d7f6ec9810e75b930e8e607793b302445abbdee0ac88143f18da20" - ) { - id - keys - model_names - event_id - created_at - updated_at - models { - __typename - ... on Moves { - remaining - player - } - ... on Position { - vec { - x - y - } - } - } - } -} -``` - -According to your input, you will receive an output like this: - -```json -{ - "data": { - "entityUpdated": { - "id": "0x28cd7ee02d7f6ec9810e75b930e8e607793b302445abbdee0ac88143f18da20", - "keys": [ - "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973" - ], - "model_names": "Moves,Position", - "event_id": "0x0000000000000000000000000000000000000000000000000000000000000013:0x0000:0x0000", - "created_at": "2023-10-17 11:39:42", - "updated_at": "2023-10-17 11:52:48", - "models": [ - { - "__typename": "Moves", - "remaining": 10, - "player": "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973" - }, - { - "__typename": "Position", - "vec": { - "x": 10, - "y": 10 - } - } - ] - } - } -} -``` diff --git a/0.3.0/src/toolchain/torii/overview.md b/0.3.0/src/toolchain/torii/overview.md deleted file mode 100644 index e88a367c..00000000 --- a/0.3.0/src/toolchain/torii/overview.md +++ /dev/null @@ -1,30 +0,0 @@ -## Torii - Networking & Indexing - -Torii is an automatic indexer for dojo worlds. Built in rust to be blazingly fast and exceptionally scalable. - -### Dojo indexer - -Torii indexes your dojo worlds and exposes a GraphQL API to query them. Simply run: - -```sh -torii -``` -and you'll have a GraphQL API running on `http://localhost:8080`! - -## Installation - -The `torii` binary can be installed via [`dojoup`](../../getting-started/quick-start.md), our dedicated installation package manager. - -### Installing from Source - -If you prefer to install from the source code: - -```sh -cargo install --path ./crates/torii --profile local --force -``` - -This will install Torii and the required dependencies on your local system. - -> πŸ“š **Reference** -> -> See the [`torii` Reference](./reference.md) for a complete reference. \ No newline at end of file diff --git a/0.3.0/src/toolchain/torii/reference.md b/0.3.0/src/toolchain/torii/reference.md deleted file mode 100644 index 2ec50f41..00000000 --- a/0.3.0/src/toolchain/torii/reference.md +++ /dev/null @@ -1,59 +0,0 @@ -## torii reference - -### Name - -torii - An automatic indexer and networking layer for a world contract. - -### USAGE - -```sh -torii [OPTIONS] -``` - -### DESCRIPTION - -`torii` starts the indexer and exposes GraphQL/gRPC API endpoints. The indexer queries the specified Starknet RPC endpoint for transaction blocks and listens for transactions related to the world contract. These transactions can include component/system registrations, entity state updates, system calls, and events. The parsed data is then stored in a local SQLite database. - -The GraphQL and gRPC API endpoints run in tandem with the indexer, providing custom queries specific to the world contract for client applications. - -#### Database URL - -`torii` uses a sqlite database to store indexed data. The database can be stored either in-memory or persistently on the filesystem. - -- The in-memory database is ephemeral and only lasts as long as the indexer is running. This is a fast and simple option to start the indexer for development/testing. -- Persistent storage should be used in production. It relies on the local filesystem for storage. - -Note: If using in-memory db, the memory will be garbage collected after a period of inactivity, causing queries to result in errors. Workaround is to use a persistent database. - -```sh -# Persistent database storage using file indexer.db -torii --database indexer.db -``` - -### OPTIONS - -#### General Options - -`-w, --world` -     Address of the world contract to index - -`--rpc` -     Starknet RPC endpoint to use [default: http//localhost:5050] - -`-d, --database ` -     Database filepath (ex: indexer.db) [default: :memory:] - -`-s, --start-block ` -     Specify a block to start indexing from, ignored if stored head exists [default: 0] - -`--allowed-origins ` -     Specify allowed origins for api endpoints (comma-separated list of allowed origins, or "\*" for all) [default: *] - -`--external-url ` -     The external url of the server, used for configuring the GraphQL Playground in a hosted environment - -`-h, --help` -     Print help - -`-V, --version` -     Print version diff --git a/0.3.0/src/tutorial/onchain-chess/0-setup.md b/0.3.0/src/tutorial/onchain-chess/0-setup.md deleted file mode 100644 index d11a9c91..00000000 --- a/0.3.0/src/tutorial/onchain-chess/0-setup.md +++ /dev/null @@ -1,331 +0,0 @@ -# 0. Setup - -_Before starting recommend following the [`hello-dojo`](../../cairo/hello-dojo.md) chapter to gain a basic understanding of the Dojo game._ - -## Initializing the Project - -Create a new Dojo project folder. You can name your project what you want. - -```sh -mkdir dojo-chess -``` - -Open the project folder. - -```sh -cd dojo-chess -``` - -And initialize the project using sozo init. - -```sh -sozo init -``` - -## Cleaning Up the Boilerplate - -The project comes with a lot of boilerplate codes. Clear it all. Make sure both `models.cairo` and `systems.cairo` files are empty. In this tutorial, we won't be creating a `systems.cairo` nor the `src/systems` folder, you can delete both (highly optional, folder structure is entirely up to you). instead, we'll be creating a file named `actions_contract.cairo`, this is where our game logic/contract will reside. - -Remodel your`lib.cairo`, to look like this : - -```rust,ignore -mod models; -mod actions_contract; -mod tests; -``` - -Compile your project with: - -```sh -sozo build -``` - -## Basic components - -While there are many ways to design a chess game using the ECS model, we'll follow this approach: - -> Every square of the chess board (e.g., A1) will be treated as an entity. If a piece exists on a square, the square entity will hold that piece. - -First, add this basic model to `models.cairo` file. If you are not familar with model syntax in Dojo engine, go back to this [chapter](../../cairo/models.md). - -```rust,ignore -#[derive(Model)] -struct Square { - #[key] - game_id: felt252, - #[key] - x: u32, - #[key] - y: u32, - piece: PieceType, -} - -enum PieceType { - WhitePawn : (), - WhiteKnight: (), - WhiteBishop: (), - WhiteRook: (), - WhiteQueen: (), - WhiteKing: (), - BlackPawn: (), - BlackKnight: (), - BlackBishop: (), - BlackRook: (), - BlackQueen: (), - BlackKing: (), - None: () -} -``` - -## Basic systems - -Starting from the next chapter, you will implement the `actions_contract.cairo` logic. - -Create `actions_contract.cairo` inside the src folder. the file should contain a basic contract. - -For example, `actions_contract.cairo` should look like this: - -```rust,ignore -#[starknet::contract] -mod actions { - - #[storage] - struct Storage {} -} -``` -It should be noted that systems are cairo contracts, by implication, rather than implementing the game logic in systems, we are implementing it in a contract. - -## Compile your project - -Now try `sozo build` to build. Faced some errors? - -```sh -error: Trait has no implementation in context: -``` - -You would probably faced some trait implementation errors, which you can implement as a derive like: - -```rust,ignore - -#[derive(Model, Drop, Serde)] -struct Square { - #[key] - game_id: felt252, - #[key] - x: u32, - #[key] - y: u32, - piece: PieceType, -} - -#[derive(Serde, Drop, Copy, PartialEq, Introspect)] -enum PieceType { - WhitePawn: (), - WhiteKnight: (), - WhiteBishop: (), - WhiteRook: (), - WhiteQueen: (), - WhiteKing: (), - BlackPawn: (), - BlackKnight: (), - BlackBishop: (), - BlackRook: (), - BlackQueen: (), - BlackKing: (), - None: (), -} -``` - -Complied? Great! then let's move on. If not fix other issues as above, so that you can run the `sozo build` command successfully. - -## Run test - -Before proceeding to the next chapter, remember that `sozo build` and `sozo test` are important steps to ensure your code is correct. - -Run sozo test. Did you face any errors? - -```sh -error: Trait has no implementation in context: -``` - -```sh -error: Variable not dropped. Trait has no implementation in context: -``` - -For the no implementation error, implement the PrintTrait to run `sozo test` successfully. For the not dropped error, add the Drop trait. Address other errors by adding derives or implementing them on a case-by-case basis. - -## Add more models - -Before you move on, add more models so we can use them in the next chapter when creating the action contract. - -### Requirements - -- `Color` enum with values White,Black & None -```rust,ignore - White: (), - Black: (), - None: (), -``` - -- `Game` model: -```rust,ignore - game_id: felt252, - winner: Color, - white: ContractAddress, - black: ContractAddress -``` - -- `GameTurn` model: -```rust,ignore - game_id: felt252, - turn: Color -``` - -- Run `sozo build` to see if your code compiles, we'll handle `test` implementiation in the subsequent chapters. - -This tutorial is extracted from [here](https://github.com/Akinbola247/chess-dojo/tree/tutorialv3) - -
-Click to see full `models.cairo` code - -```rust,ignore -use array::ArrayTrait; -use debug::PrintTrait; -use starknet::ContractAddress; -use dojo::database::schema::{SchemaIntrospection, Ty, Enum, serialize_member_type}; - - -#[derive(Model, Drop, Serde)] -struct Square { - #[key] - game_id: felt252, - #[key] - x: u32, - #[key] - y: u32, - piece: PieceType, -} - -#[derive(Serde, Drop, Copy, PartialEq, Introspect)] -enum PieceType { - WhitePawn: (), - WhiteKnight: (), - WhiteBishop: (), - WhiteRook: (), - WhiteQueen: (), - WhiteKing: (), - BlackPawn: (), - BlackKnight: (), - BlackBishop: (), - BlackRook: (), - BlackQueen: (), - BlackKing: (), - None: (), -} - -#[derive(Serde, Drop, Copy, PartialEq, Introspect)] -enum Color { - White: (), - Black: (), - None: (), -} - -#[derive(Model, Drop, Serde)] -struct Game { - /// game id, computed as follows pedersen_hash(player1_address, player2_address) - #[key] - game_id: felt252, - winner: Color, - white: ContractAddress, - black: ContractAddress -} - -#[derive(Model, Drop, Serde)] -struct GameTurn { - #[key] - game_id: felt252, - turn: Color -} - - -//printing trait for debug -impl ColorPrintTrait of PrintTrait { - #[inline(always)] - fn print(self: Color) { - match self { - Color::White(_) => { - 'White'.print(); - }, - Color::Black(_) => { - 'Black'.print(); - }, - Color::None(_) => { - 'None'.print(); - }, - } - } -} - - -impl BoardPrintTrait of PrintTrait<(u32, u32)> { - #[inline(always)] - fn print(self: (u32, u32)) { - let (x, y): (u32, u32) = self; - x.print(); - y.print(); - } -} - - -impl PieceTypePrintTrait of PrintTrait { - #[inline(always)] - fn print(self: PieceType) { - match self { - PieceType::WhitePawn(_) => { - 'WhitePawn'.print(); - }, - PieceType::WhiteKnight(_) => { - 'WhiteKnight'.print(); - }, - PieceType::WhiteBishop(_) => { - 'WhiteBishop'.print(); - }, - PieceType::WhiteRook(_) => { - 'WhiteRook'.print(); - }, - PieceType::WhiteQueen(_) => { - 'WhiteQueen'.print(); - }, - PieceType::WhiteKing(_) => { - 'WhiteKing'.print(); - }, - PieceType::BlackPawn(_) => { - 'BlackPawn'.print(); - }, - PieceType::BlackKnight(_) => { - 'BlackKnight'.print(); - }, - PieceType::BlackBishop(_) => { - 'BlackBishop'.print(); - }, - PieceType::BlackRook(_) => { - 'BlackRook'.print(); - }, - PieceType::BlackQueen(_) => { - 'BlackQueen'.print(); - }, - PieceType::BlackKing(_) => { - 'BlackKing'.print(); - }, - PieceType::None(_) => { - 'None'.print(); - }, - } - } -} - -``` - -
- -Congratulations! You've completed the basic setup for building an on-chain chess game πŸŽ‰ diff --git a/0.3.0/src/tutorial/onchain-chess/1-action.md b/0.3.0/src/tutorial/onchain-chess/1-action.md deleted file mode 100644 index 28c211aa..00000000 --- a/0.3.0/src/tutorial/onchain-chess/1-action.md +++ /dev/null @@ -1,246 +0,0 @@ -# 1. Action_Contract - -This chapter will address implementing `action_contract.cairo`, which spawns the game & squares containing pieces and also allow players to move pieces. - -## What is `action_contract`? - -To play chess, you need, to start game, spawn the pieces, and move around the board. the `action_contract` has two dominant functions `spawn_game` function which spawns the game entity and places each -piece in its proper position on the board and the `move` funtion which allows pieces to be moved around the board. - -

-image - -## Requirements - -_Copy the unit tests below and paste them at the bottom of your `action_contract.cairo` file._ - -1. Write an interface for the `initiate_system` contract and define your functions. In this case, `move` and `spawn_game` -```shell - #[starknet::interface] - trait IActions { - fn move( - self: @ContractState, - curr_position: (u32, u32), - next_position: (u32, u32), - caller: ContractAddress, //player - game_id: felt252 - ); - fn spawn_game( - self: @ContractState, white_address: ContractAddress, black_address: ContractAddress, - ); - } -``` -2. Bring in required imports into the contract and initialize storage with the `world_dispatcher` in it like this : -```shell - #[starknet::contract] - mod actions { - use dojo::world::{IWorldDispatcher, IWorldDispatcherTrait}; - use debug::PrintTrait; - use starknet::ContractAddress; - use dojo_chess::models::{Color, Square, PieceType, Game, GameTurn}; - use super::IActions; - - #[storage] - struct Storage { - world_dispatcher: IWorldDispatcher, - } - } -``` -should be noted that `actions` is the contract name. - -3. Write a `spawn_game` function that accepts the `white address`, and `black address` as input and set necessary states using `set!(...)`.Implement the game entity, comprised of the `Game` model and `GameTurn` model we created in the `models.cairo` and Implement the square entities from a1 to h8 containing the correct `PieceType` in the `spawn_game` fn. -```shell - #[external(v0)] - impl PlayerActionsImpl of IActions { - fn spawn_game( - self: @ContractState, white_address: ContractAddress, black_address: ContractAddress - ) { - let world = self.world_dispatcher.read(); - let game_id = pedersen::pedersen(white_address.into(), black_address.into()); - set!( - world, - ( - Game { - game_id: game_id, - winner: Color::None(()), - white: white_address, - black: black_address, - }, GameTurn { - game_id: game_id, turn: Color::White(()), - }, - ) - ); - - set!(world, (Square { game_id: game_id, x: 0, y: 0, piece: PieceType::WhiteRook })); - - set!(world, (Square { game_id: game_id, x: 0, y: 1, piece: PieceType::WhitePawn })); - - set!(world, (Square { game_id: game_id, x: 1, y: 6, piece: PieceType::BlackPawn })); - - set!(world, (Square { game_id: game_id, x: 1, y: 0, piece: PieceType::WhiteKnight })); - - //the rest of the positions on the board goes here.... - } -``` -4. Write a `move` function that accepts the `current position`, `next position`, `caller address`, and `game id`. The `move` function should look like this: -```shell - fn move( - self: @ContractState, - curr_position: (u32, u32), - next_position: (u32, u32), - caller: ContractAddress, //player - game_id: felt252 - ) { - let world = self.world_dispatcher.read(); - - let (current_x, current_y) = curr_position; - let (next_x, next_y) = next_position; - current_x.print(); - current_y.print(); - - next_x.print(); - next_y.print(); - - let mut current_square = get!(world, (game_id, current_x, current_y), (Square)); - - // check if next_position is out of board or not - assert(is_out_of_board(next_position), 'Should be inside board'); - - // check if this is the right piece type move - assert( - is_right_piece_move(current_square.piece, curr_position, next_position), - 'Should be right piece move' - ); - let target_piece = current_square.piece; - // make current_square piece none and move piece to next_square - current_square.piece = PieceType::None(()); - let mut next_square = get!(world, (game_id, next_x, next_y), (Square)); - - // check the piece already in next_suqare - let maybe_next_square_piece = next_square.piece; - - if maybe_next_square_piece == PieceType::None(()) { - next_square.piece = target_piece; - } else { - if is_piece_is_mine(maybe_next_square_piece) { - panic(array!['Already same color piece exist']) - } else { - next_square.piece = target_piece; - } - } - - set!(world, (next_square)); - set!(world, (current_square)); - } - //helper functions within the fn move. don't worry, we'll address logic content in the next chapter - fn is_piece_is_mine(maybe_piece: PieceType) -> bool { - //the rest of the code .... - } - fn is_correct_turn(maybe_piece: PieceType, caller: ContractAddress, game_id: felt252) -> bool { - //the rest of the code .... - } - fn is_out_of_board(next_position: (u32, u32)) -> bool { - //the rest of the code .... - } - fn is_right_piece_move(maybe_piece: PieceType, curr_position: (u32, u32), next_position: (u32, u32)) -> bool { - //the rest of the code .... - } - } -``` -7. Run `sozo test` and pass all the tests. - -## Test Flow - -- Spawn the test world (`spawn_test_world`) that imports the models in testing. -- deploy actions contract -- interact with `spawn_game` function in the `actions` contract by providing white and black player's wallet addresses as inputs. -- Retrieve the game entity and piece entity created in `actions` contract. -- Ensure the game has been correctly created. -- Verify that each `Piece` is located in the correct `Square`. - -## Unit Tests - -```rust,ignore -#[cfg(test)] -mod tests { - use starknet::ContractAddress; - use dojo::test_utils::{spawn_test_world, deploy_contract}; - use dojo_chess::models::{Game, game, GameTurn, game_turn, Square, square, PieceType}; - - use dojo_chess::actions_contract::actions; - use starknet::class_hash::Felt252TryIntoClassHash; - use dojo::world::IWorldDispatcherTrait; - use dojo::world::IWorldDispatcher; - use core::array::SpanTrait; - use super::{IActionsDispatcher, IActionsDispatcherTrait}; - - // helper setup function - // reusable function for tests - fn setup_world() -> (IWorldDispatcher, IActionsDispatcher) { - // models - let mut models = array![ - game::TEST_CLASS_HASH, game_turn::TEST_CLASS_HASH, square::TEST_CLASS_HASH - ]; - // deploy world with models - let world = spawn_test_world(models); - - // deploy systems contract - let contract_address = world - .deploy_contract('salt', actions::TEST_CLASS_HASH.try_into().unwrap()); - let actions_system = IActionsDispatcher { contract_address }; - - (world, actions_system) - } - - #[test] - #[available_gas(3000000000000000)] - fn test_initiate() { - let white = starknet::contract_address_const::<0x01>(); - let black = starknet::contract_address_const::<0x02>(); - - let (world, actions_system) = setup_world(); - - //system calls - actions_system.spawn_game(white, black); - let game_id = pedersen::pedersen(white.into(), black.into()); - - //get game - let game = get!(world, game_id, (Game)); - assert(game.white == white, 'white address is incorrect'); - assert(game.black == black, 'black address is incorrect'); - - //get a1 square - let a1 = get!(world, (game_id, 0, 0), (Square)); - assert(a1.piece == PieceType::WhiteRook, 'should be White Rook'); - assert(a1.piece != PieceType::None, 'should have piece'); - } - - - #[test] - #[available_gas(3000000000000000)] - fn test_move() { - let white = starknet::contract_address_const::<0x01>(); - let black = starknet::contract_address_const::<0x02>(); - - let (world, actions_system) = setup_world(); - actions_system.spawn_game(white, black); - - let game_id = pedersen::pedersen(white.into(), black.into()); - - let a2 = get!(world, (game_id, 0, 1), (Square)); - assert(a2.piece == PieceType::WhitePawn, 'should be White Pawn'); - assert(a2.piece != PieceType::None, 'should have piece'); - - actions_system.move((0, 1), (0, 2), white.into(), game_id); - - let c3 = get!(world, (game_id, 0, 2), (Square)); - assert(c3.piece == PieceType::WhitePawn, 'should be White Pawn'); - assert(c3.piece != PieceType::None, 'should have piece'); - } -``` - -## Need help? - -If you're stuck, don't hesitate to ask questions at the [Dojo community](https://discord.gg/akd2yfuRS3)! - -You can find the [answer](https://github.com/rkdud007/chess-dojo/blob/tutorialv3/src/actions_contract.cairo) for chapter 1 here. diff --git a/0.3.0/src/tutorial/onchain-chess/2-legal.md b/0.3.0/src/tutorial/onchain-chess/2-legal.md deleted file mode 100644 index 0c61b3ce..00000000 --- a/0.3.0/src/tutorial/onchain-chess/2-legal.md +++ /dev/null @@ -1,166 +0,0 @@ -# 2. Check Legal Move - -In this chapter, we'll make functions to check: - -- If the next move goes outside the board. -- If there's a piece that can be captured. -- If the next move is allowed for the type of piece. -- If the user can allow to make a action (based on the piece's color). -- ... You can also add other custom check functions. - -## Make Check Functions - -We need to add some check functions in `actions` contract. These will help make sure the next move is allowed. - -1. See if player is moving the right piece - -```rust,ignore - fn is_piece_is_mine(maybe_piece: PieceType) -> bool { - false - } -``` - -2. See if the next spot is still on the board. - -```rust,ignore - fn is_out_of_board(next_position: (u32, u32)) -> bool { - let (n_x, n_y) = next_position; - if n_x > 7 || n_x < 0 { - return false; - } - if n_y > 7 || n_y < 0 { - return false; - } - true - } -``` - -3. See if the person trying the move is doing it at the right time and with their piece color. - -```rust,ignore - fn is_correct_turn(maybe_piece: PieceType, caller: ContractAddress, game_id: felt252) -> bool { - true - } -``` - -4. see if it's the right move -```rust,ignore - fn is_right_piece_move( - maybe_piece: PieceType, curr_position: (u32, u32), next_position: (u32, u32) - ) -> bool { - let (c_x, c_y) = curr_position; - let (n_x, n_y) = next_position; - match maybe_piece { - PieceType::WhitePawn => { - true - }, - PieceType::WhiteKnight => { - if n_x == c_x + 2 && n_y == c_x + 1 { - return true; - } - - panic(array!['Knight illegal move']) - }, - PieceType::WhiteBishop => { - true - }, - PieceType::WhiteRook => { - true - }, - PieceType::WhiteQueen => { - true - }, - PieceType::WhiteKing => { - true - }, - PieceType::BlackPawn => { - true - }, - PieceType::BlackKnight => { - true - }, - PieceType::BlackBishop => { - true - }, - PieceType::BlackRook => { - true - }, - PieceType::BlackQueen => { - true - }, - PieceType::BlackKing => { - true - }, - PieceType::None(_) => panic(array!['Should not move empty square']), - } - } -``` -5. You can also add other check functions to be extra sure the move is allowed. - -Once you've made these check functions, you can use them in the `move` function in the contract as illustrated in the previous chapter [here](1-action.md). You can decide how to set them up and which ones to use. We'll give an example to help: - -## Testing Each Function - -Since we have different check functions, we need to test each one. To make this easier, let's use parts that are the same for many tests. - -First, make a helper function called `setup_world`. This will give back an `IWorldDispatcher` and `IActionsDispatcher` that we can use many times in the tests. - -```rust,ignore - #[test] - #[available_gas(3000000000000000)] - fn setup_world() -> (IWorldDispatcher, IActionsDispatcher) { - // models - let mut models = array![ - game::TEST_CLASS_HASH, game_turn::TEST_CLASS_HASH, square::TEST_CLASS_HASH - ]; - // deploy world with models - let world = spawn_test_world(models); - - // deploy systems contract - let contract_address = world - .deploy_contract('salt', actions::TEST_CLASS_HASH.try_into().unwrap()); - let actions_system = IActionsDispatcher { contract_address }; - - (world, actions_system) - } -``` - -Then, our main `test_move` function will be simpler. - -```rust,ignore - #[test] - #[available_gas(3000000000000000)] - fn test_move() { - let white = starknet::contract_address_const::<0x01>(); - let black = starknet::contract_address_const::<0x02>(); - let (move_system, initate_system) = setup_world(); - let game_id = pedersen(white.into(), black.into()); - // other codes are same - } -``` - -Now we can make tests that show errors if we try moves that aren't allowed. Let's make a `test_piecetype_illegal` function. This will check if the `is_right_piece_move` function, that you implemented in the move system, works right. - -```rust,ignore - #[test] - #[should_panic] - fn test_piecetype_ilegal() { - let white = starknet::contract_address_const::<0x01>(); - let black = starknet::contract_address_const::<0x02>(); - let (world, actions_system) = setup_world(); - let game_id = pedersen::pedersen(white.into(), black.into()); - - let b1 = get!(world, (game_id, 1, 0), (Square)); - assert(b1.piece == PieceType::WhiteKnight, 'should be White Knight'); - - // Knight cannot move to that square - actions_system.move((1,0),(2,3),white.into(), game_id); - } -``` - -Finish by making your tests. These should find wrong moves and give back errors. - -## Need help? - -If you're stuck, don't hesitate to ask questions at the [Dojo community](https://discord.gg/akd2yfuRS3)! - diff --git a/0.3.0/src/tutorial/onchain-chess/3-test.md b/0.3.0/src/tutorial/onchain-chess/3-test.md deleted file mode 100644 index e4d8aacc..00000000 --- a/0.3.0/src/tutorial/onchain-chess/3-test.md +++ /dev/null @@ -1,145 +0,0 @@ - # 3 Test Contract - -In this chapter, we'll use everything we've learned to run a full chess game scenario. - -Here's what we'll do in our test: - -1. Spawn `white_pawn_1` to (0,1) -2. Move `white_pawn_1` to (0,3) -3. Move `black_pawn_2` to (1,6) -4. Move `white_pawn_1` to (0,4) -5. Move `black_pawn_2` to (1,4) -6. Move `white_pawn_1` to (1,4) -7. Capture `black_pawn_2` - -To place the pieces, use our `spawn_game` function in our `actions` contract. For moving them, use the `move_system` contract. Remember to check if a piece can be captured when using `move_system`. - -Before we get to the code, set up your integration test like this: - -- Copy the test below and add it to your `src/tests.cairo` file. -- Make a `test.cairo` in your src and update `lib.cairo` by adding the `mod tests;` line. - -## Full Code - -```rust,ignore -#[cfg(test)] -mod tests { - use starknet::ContractAddress; - use dojo::test_utils::spawn_test_world; - use dojo_chess::models::{Game, game, GameTurn, game_turn, Square, square, PieceType}; - - use dojo_chess::actions_contract::actions; - use array::ArrayTrait; - use core::traits::Into; - use dojo::world::IWorldDispatcherTrait; - use core::array::SpanTrait; - use dojo_chess::actions_contract::tests::setup_world; - use dojo_chess::actions_contract::{IActionsDispatcher, IActionsDispatcherTrait}; - - - #[test] - #[available_gas(3000000000000000)] - fn integration() { - let white = starknet::contract_address_const::<0x01>(); - let black = starknet::contract_address_const::<0x02>(); - - let (world, actions_system) = setup_world(); - - //system calls - actions_system.spawn_game(white, black); - let game_id = pedersen::pedersen(white.into(), black.into()); - - //White pawn is now in (0,1) - let a2 = get!(world, (game_id, 0, 1), (Square)); - assert(a2.piece == PieceType::WhitePawn, 'should be White Pawn in (0,1)'); - assert(a2.piece != PieceType::None, 'should have piece in (0,1)'); - - //Black pawn is now in (1,6) - let b7 = get!(world, (game_id, 1, 6), (Square)); - assert(b7.piece == PieceType::BlackPawn, 'should be Black Pawn in (1,6)'); - assert(b7.piece != PieceType::None, 'should have piece in (1,6)'); - - //Move White Pawn to (0,3) - actions_system.move((0, 1), (0, 3), white.into(), game_id); - - //White pawn is now in (0,3) - let a4 = get!(world, (game_id, 0, 3), (Square)); - assert(a4.piece == PieceType::WhitePawn, 'should be White Pawn in (0,3)'); - assert(a4.piece != PieceType::None, 'should have piece in (0,3)'); - - //Move black Pawn to (1,4) - actions_system.move((1, 6), (1, 4), white.into(), game_id); - - //Black pawn is now in (1,4) - let b5 = get!(world, (game_id, 1, 4), (Square)); - assert(b5.piece == PieceType::BlackPawn, 'should be Black Pawn in (1,4)'); - assert(b5.piece != PieceType::None, 'should have piece in (1,4)'); - - // Move White Pawn to (1,4) - // Capture black pawn - actions_system.move((0, 3), (1, 4), white.into(), game_id); - - let b5 = get!(world, (game_id, 1, 4), (Square)); - assert(b5.piece == PieceType::WhitePawn, 'should be White Pawn in (1,4)'); - assert(b5.piece != PieceType::None, 'should have piece in (1,4)'); - } -} - -``` - -## Diving into the Code -First, we'll set up the players and their colors. - -```rust,ignore - let white = starknet::contract_address_const::<0x01>(); - let black = starknet::contract_address_const::<0x02>(); -``` - -We should list both models with each having CLASS_HASH as elements and then we deploy world to models with `spawn_test_world` - -```rust,ignore -//models - let mut models = array![game::TEST_CLASS_HASH, game_turn::TEST_CLASS_HASH, square::TEST_CLASS_HASH]; - let world = spawn_test_world(models); -``` -We then deploy our system contracts in our helper function in `action_contract` file. we only imported it in our test file. -```rust,ignore - let contract_address = world - .deploy_contract('salt', actions::TEST_CLASS_HASH.try_into().unwrap()); - let actions_system = IActionsDispatcher { contract_address }; -``` - -We use `spawn_game` function in `actions_contract.cairo` to put our Square pieces on the board. Each Square holds a piece. The system's `spawn_game` function needs some input i.e the addresses of the players. - -```rust,ignore - // spawn - actions_system.spawn_game(white, black); -``` - -Let's check if a White pawn is at (0,1). Remember, to get a piece that exists on the square, you need to use the keys of the `Square` model, which are `game_id`, `x`, and `y`. Do the same check for the Black Pawn. - -```rust,ignore - //White pawn is now in (0,1) - let a2 = get!(world, (game_id, 0, 1), (Square)); - assert(a2.piece == PieceType::WhitePawn, 'should be White Pawn in (0,1)'); - assert(a2.piece != PieceType::None, 'should have piece in (0,1)'); -``` - -After setting up the board, use `move` function in the contract to make moves. Provide the current position, the next position, the player's address, and the game id. - -```rust,ignore - //Move White Pawn to (0,3) - actions_system.move((0, 1), (0, 3), white.into(), game_id); -``` - -Keep moving pieces and checking if they're in the right places. - -## Congratulations! - -You've made the basic contracts for a chess game using the Dojo engine! This tutorial was just the beginning. There are many ways to make the game better, like optimizing parts, adding checks, or considering special cases. If you want to do more with this chess game, try these challenges: - -- Add a checkmate feature. Our game doesn't end now, so decide when it should! -- Include special moves like castling, En Passant Capture, or Pawn Promotion. -- Make your own chess rules! You could even create your own version of the [immortal game](https://immortal.game/) - -Lastly, share your project with others in the [Dojo community](https://discord.gg/akd2yfuRS3)! diff --git a/0.3.0/src/tutorial/onchain-chess/4-utils.md b/0.3.0/src/tutorial/onchain-chess/4-utils.md deleted file mode 100644 index 2469b4d2..00000000 --- a/0.3.0/src/tutorial/onchain-chess/4-utils.md +++ /dev/null @@ -1,30 +0,0 @@ -# 4. Modularize functions -In order to keep our code has dry as possible, you can modularize your functions. To do this, we'll create an `utils.cairo` file and add the below: -```rust,ignore -use dojo_chess::models::PieceType; -use starknet::ContractAddress; - -fn is_piece_is_mine(maybe_piece: PieceType) -> bool { - //rest of the code here -} - -fn is_correct_turn(maybe_piece: PieceType, caller: ContractAddress, game_id: felt252) -> bool { - //rest of the code here -} - -fn is_out_of_board(next_position: (u32, u32)) -> bool { - //rest of the code here -} - -fn is_right_piece_move( - maybe_piece: PieceType, curr_position: (u32, u32), next_position: (u32, u32) -) -> bool { - //rest of the code here - -} -``` -In your, `action_contracts`, these functions can be imported for use as follows -```rust,ignore - use dojo_chess::utils::{is_out_of_board, is_right_piece_move, is_piece_is_mine}; -``` -That's right! you have successfully modularized your functions. diff --git a/0.3.0/src/tutorial/onchain-chess/README.md b/0.3.0/src/tutorial/onchain-chess/README.md deleted file mode 100644 index 6e5921e6..00000000 --- a/0.3.0/src/tutorial/onchain-chess/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# Building a Chess Game - -_"I just finished reading The Dojo Book. What should I do next?"_ - -The answers to this question are always "Make something!", sometimes followed by a list of cool projects. This is a great answer for some people, but others might be looking for a little more direction. - -This guide is intended to fill the gap between heavily directed beginner tutorials and working on your projects. The primary goal here is to get you to write code. The secondary goal is to get you reading documentation. - -If you haven't read the Dojo Book yet, it is highly encouraged for you to do so before starting this project. - -## What are we building? - -We're building an on-chain chess game contract that lets you start a new game and play chess. This guide does not cover every rules of the chess game. You will build step by step as follows: - -1. A system contract to spawn all the chess pieces -2. A system contract to make pieces move -3. Add some functions to check a legal move -4. Play chess β™Ÿβ™™ - integration test! - -The full code of tutorial is based on [this repo](https://github.com/dojoengine/dojo-examples/tree/main/examples/dojo-chess). - -If this seems too hard, don't worry! This guide is for beginners. If you know some basics about Cairo and Dojo, you're good. We won't make a full chess game with all the rules. We're keeping it simple. - -## What after this guide? - -We're making another guide to help design the frontend. This will make our chess game complete. - -After you finish all the four chapters, we can move on to the frontend guide. diff --git a/0.3.0/po/es.po b/po/es.po similarity index 100% rename from 0.3.0/po/es.po rename to po/es.po diff --git a/0.3.0/po/messages.pot b/po/messages.pot similarity index 100% rename from 0.3.0/po/messages.pot rename to po/messages.pot