Dojo: The Provable Game Engine

Dojo is a provable game engine built using 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 elucidates this emergent concept of autonomous worlds and Provable games.

Dojo is an open-source onchain gaming project currently in its early development phase, and warmly welcomes contributors. For additional resources, join the community on Discord and check out the contribution guide.


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, Realms & BibliothecaDAO, briq and many more contributors.

How do I get involved?

Check out our Github, our Twitter, Discord and contribution guide

dojo

What is Dojo?

Dojo is the culmination of lessons learned from attempts at building onchain games, 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.

Torii - 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 to auto-index all contract states, ensuring efficient and streamlined queries. Torii then exposes these states via a GraphQL API or gRPC, 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 - 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 - 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.

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

Provable games

Provable games demand zero-knowledge properties for efficient scaling and verification of computations. Cairo addresses this need by providing a generalized language, eliminating the complexity of creating circuits to incorporate SNARKs.

You can simply program in Cairo and your applications become automatically provable.

Moreover, you can deploy your programs on the Cairo Virtual Machine (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.

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. 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

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! Within the dojo toolchain exists Katana which is a gaming specific sequencer, which is perfectly suited to run a Dojo appchain.

The Dojo team is also working closely with the Madara team to enable Starknet appchains to seamlessly run Dojo worlds.

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 and join the Discord 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.

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.

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.

Can dojo implement client side proofs?

The ability to execute Dojo programs in the browser is entirely plausible and is on our roadmap. Expect q1/q2 in 2024, or if you are a specalist in this jump into the code and help out!

Can I deploy dojo on Starknet?

Yes! Dojo can run on any StarknetVM including the public blockchains. Within the dojo toolchain exists Katana which is a gaming specific sequencer, which is perfectly suited to Dojo games.

Quick Start

It is worth reading theory to familiarize yourself with the concept of Autonomous Worlds (AWs) and the Cairo ecosystem 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.

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.

dojoup

For full dojoup reference and debugging see Dojoup.

Next steps

Head to Hello Dojo to get create your first Dojo world.

Building from source

If you are just wanting to play with the toolchain, we strongly suggest following the Quick Start guide.

Prerequisites

You will need the Rust compiler and Cargo, the Rust package manager. The easiest way to install both is with rustup.rs.

On Windows, you will also need a recent version of Visual Studio, installed with the "Desktop Development With C++" Workloads option.

Building

You can either use the different Dojoup flags:

dojoup --branch master
dojoup --path path/to/dojo

Or, by using a single Cargo command:

cargo install --git https://github.com/dojoengine/dojo --force sozo katana torii

Or, by manually building from a local copy of the Dojo repository:

# 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 run -—bin torii

Development Setup

This 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 guide.

Prerequisites

Guide

Clone

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:

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 package manager by running:

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 extension for Visual Studio Code.

Windows

Coming soon

Container

Coming soon

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 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.

Get Started

Dojo is a thriving community of builders, artists, and deep thinkers, pushing the frontier of what is possible.

Ecosystem & Studios powered by Dojo

dojo

Realms World

Briq World

Cartridge

Templates & Libraries

Templates, libraries or utilities that use Dojo.

Awesome Projects

  • Beer Baron - An dojo onchain simulation masked as a beer brewing game. It is designed to work with 10 - 10,000 players.
  • Chess Dojo - A chess game built on Dojo.
  • Dope Wars: Roll Your Own - An onchain adaptation of the classic Drug Wars game developed by the Cartridge team.
  • Drive AI - An onchain driving simulator controlled by a neural network developed by the Cartridge team.
  • Emoji Man - Pac-man inspired onchain game using dojo and phaser.
  • Loot Underworld - Excavating the dangerous, endless mysteries of the subterranean in the dark depths of the Realms Autonomous (Under)World.
  • PixeLAW - A pixel grid-based Autonomous World with coexisting games (i.e. Paint, Snake, Rock-Paper-Scissors).
  • Realms Autonomous World - The Realms Autonomous World
  • Stark Lander - Land on the Moon!
  • StarkLand - Full On-chain Multiplayer Online Simulation Game (FOMOSLG) built on Starknet.
  • Underdark: Lair of the Slenderduck - An unhinged on-chain generative dungeon skin crawler. Beware the Slenderduck!
  • zDefender - An onchain tower defense.
  • zKnight - An onchain strategy game

You should have a good understanding of Cairo before proceeding. If you're unfamiliar with Cairo, we recommend you read the Cairo documentation first.

A New Approach to Onchain 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.

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:

- src
  - main.cairo
  - lib.cairo
- Scarb.toml

While seemingly simple, behind the scenes Dojo compiler generates foundational contracts, setting the stage for you to focus purely on data and logic.

Lets take a look at the main.cairo:

use starknet::ContractAddress;

// dojo data models
#[derive(Model, Copy, Drop, Serde)]
struct Position {
    #[key] // primary key
    player: ContractAddress,
    vec: Vec2,
}

// regular cairo struct
#[derive(Copy, Drop, Serde, Introspect)]
struct Vec2 {
    x: u32,
    y: u32
}

// interface
#[starknet::interface]
trait IPlayerActions<TContractState> {
    fn spawn(self: @TContractState);
}

// contract
#[dojo::contract]
mod player_actions {
    use starknet::{ContractAddress, get_caller_address};
    use super::{Position, Vec2};
    use super::IPlayerActions;

    #[external(v0)]
    impl PlayerActionsImpl of IPlayerActions<ContractState> {
        //
        // This is how we interact with the world contract.
        //
        fn spawn(self: @ContractState) {
            // Access the world dispatcher for reading.
            let world = self.world_dispatcher.read();

            // 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

Dojo contract is just a regular Cairo contract, with some dojo specifics.

Position struct - the dojo model

In a Dojo world, state is defined using models. These are structs marked with the #[derive(Model)] attribute, functioning similarly to a key-pair 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.

spawn function - a dojo system

In the spawn function, we just call self.world_dispatcher. This provides a gateway to the world contract. This facilitates the effortless utilization of the get! and set! commands, allowing seamless interaction with the world contract.

Commands, a significant innovation in Dojo, are further explored here.

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.

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.

NOTE: 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.

Events

The world contract emits all model events via the StoreSetRecord event. This enables block explorers to reconstruct everything in the world by listening to one contract.

Full World API

The world exposes an interface which can be interacted with by any client. It is worth noting here that as a developer you don't deploy this world, it is deployed when you migrate the world.

// World interface
#[starknet::interface]
trait IWorld<T> {
    fn metadata_uri(self: @T, resource: felt252) -> Span<felt252>;
    fn set_metadata_uri(ref self: T, resource: felt252, uri: Span<felt252>);
    fn model(self: @T, name: felt252) -> ClassHash;
    fn register_model(ref self: T, class_hash: ClassHash);
    fn deploy_contract(ref self: T, salt: felt252, class_hash: ClassHash) -> ContractAddress;
    fn upgrade_contract(ref self: T, address: ContractAddress, class_hash: ClassHash) -> ClassHash;
    fn uuid(ref self: T) -> usize;
    fn emit(self: @T, keys: Array<felt252>, values: Span<felt252>);
    fn entity(
        self: @T, model: felt252, keys: Span<felt252>, offset: u8, length: usize, layout: Span<u8>
    ) -> Span<felt252>;
    fn set_entity(
        ref self: T,
        model: felt252,
        keys: Span<felt252>,
        offset: u8,
        values: Span<felt252>,
        layout: Span<u8>
    );
    fn entities(
        self: @T,
        model: felt252,
        index: Option<felt252>,
        values: Span<felt252>,
        values_length: usize,
        values_layout: Span<u8>
    ) -> (Span<felt252>, Span<Span<felt252>>);
    fn entity_ids(self: @T, model: felt252) -> Span<felt252>;
    fn set_executor(ref self: T, contract_address: ContractAddress);
    fn executor(self: @T) -> ContractAddress;
    fn base(self: @T) -> ClassHash;
    fn delete_entity(ref self: T, model: felt252, keys: Span<felt252>, layout: Span<u8>);
    fn is_owner(self: @T, address: ContractAddress, resource: felt252) -> bool;
    fn grant_owner(ref self: T, address: ContractAddress, resource: felt252);
    fn revoke_owner(ref self: T, address: ContractAddress, resource: felt252);
    fn is_writer(self: @T, model: felt252, system: ContractAddress) -> bool;
    fn grant_writer(ref self: T, model: felt252, system: ContractAddress);
    fn revoke_writer(ref self: T, model: felt252, system: ContractAddress);
}

uuid()

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:

let game_id = world.uuid();

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] 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 Dojo 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 owner.

System Permissions

Since the whole contract is given write access to the model, it is important to be careful when defining systems. A simple way to think about it is:

System Permissions

System Structure

Every system function starts with a world 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.

NOTE: This is not using the #[dojo::contract] attribute meaning it was to accept the world as a parameter.

#[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<ContractState> {
        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 function in a contract

As you can see a System is like a regular function of a Starknet contract. This contract can include storage, and it can implement interfaces.

Spawn function

The spawn function is currently the only system that exists in this contract. 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 #[dojo::contract] decorator, ensuring accurate compilation. In this context, Dojo introduces the #[dojo::contract] decorator, which aims to minimize boilerplate in contract writing.

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.

#[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> {
        // ContractState is defined by system decorator expansion
        fn spawn(self: @ContractState) {
            // world dispatcher
            let world = self.world_dispatcher.read();

            // player
            let player = get_caller_address();

            // get the position
            let position = get!(world, player, (Position));

            // set the 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) {
            // world dispatcher
            let world = self.world_dispatcher.read();

            // player
            let player = get_caller_address();

            // get the position and moves
            let (mut position, mut moves) = get!(world, player, (Position, Moves));

            // adjust
            moves.remaining -= 1;
            moves.last_direction = direction;

            // get next direction
            let next = next_position(position, direction);

            // set models
            set!(world, (moves, next));

            // emit custom event
            emit!(world, Moved { player, direction });
        }
    }
}

To interact with Systems read more in the sozo docs.

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.

#[derive(Model, Copy, Drop, Serde)]
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.

#[derive(Model, Copy, Drop, Serde)]
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:

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.

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.

const GAME_SETTINGS_ID: u32 = 9999999999999;

#[derive(model, Copy, Drop, Serde)]
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:

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:

impl RolesSchemaIntrospectionImpl for SchemaIntrospection<Roles> {
    #[inline(always)]
    fn size() -> usize {
        1 // Represents the byte size of the enum.
    }

    #[inline(always)]
    fn layout(ref layout: Array<u8>) {
        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.

#[derive(Model, Copy, Drop, Serde)]
struct Potions {
    #[key]
    entity_id: u32,
    quantity: u8,
}

#[derive(Model, Copy, Drop, Serde)]
struct Health {
    #[key]
    entity_id: u32,
    health: u8,
}

#[derive(Model, Copy, Drop, Serde)]
struct Position {
    #[key]
    entity_id: u32,
    x: u32,
    y: u32
}

// Special counter model
#[derive(Model, Copy, Drop, Serde)]
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 contract would look like this:

#[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 settings.
    const COUNTER_ID: u32 = 9999999999999;

    // impl: implement functions specified in trait
    #[external(v0)]
    impl GoblinActionsImpl of IGoblinActions<ContractState> {
        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
                    },
                )
            );
        }
    }
}

A complete example can be found in the Dojo Starter

Commands

TL;DR

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

// 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.

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.

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.

Config

Dojo worlds are defined in their Scarb.toml files. This is just a regular Scarb file which is an excellent Cairo package manager and project manager.

Full example of a Scarb.toml file:

[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.15" }

[[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"

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, all these events are seamlessly indexed, ensuring easy and efficient querying.

Model Events

Consider this example of a Moves model:

struct Moves {
    #[key]
    player: Address,
    remaining: u32,
}

When this model is updated, the World contract will emit an event with the following structure:

#[derive(Drop, starknet::Event)]
struct StoreSetRecord {
    table: felt252, // Moves
    keys: Span<felt252>, // [player]
    offset: u8, // offset for the value in the table
    value: Span<felt252>, // [remaining]
}

This will then be captured by Torii and indexed for querying. This will allow you to then reconstruct the state of your world.

Similarly, when a model is deleted, the World contract will emit an event with the following structure:

#[derive(Drop, starknet::Event)]
struct StoreDelRecord {
    table: felt252,
    keys: Span<felt252>,
}

World Events

The World contract also emits events when it's initialized and when new models and contracts are registered. These events are emitted with the following structures:

#[derive(Drop, starknet::Event)]
struct WorldSpawned {
    address: ContractAddress,
    caller: ContractAddress
}
#[derive(Drop, starknet::Event)]
struct ModelRegistered {
    name: felt252,
    class_hash: ClassHash,
    prev_class_hash: ClassHash
}
#[derive(Drop, starknet::Event)]
struct ContractDeployed {
    salt: felt252,
    class_hash: ClassHash,
    address: ContractAddress,
}

#[derive(Drop, starknet::Event)]
struct ContractUpgraded {
    class_hash: ClassHash,
    address: ContractAddress,
}

These events are also captured by Torii and indexed for querying.

Custom Events

Within your game, emitting custom events can be highly beneficial. Fortunately, there's a handy emit! command that lets you release events directly from your world. These events are indexed by Torii.

Use it like so:

emit!(world, Moved { address, direction });

Include this in your contract and it will emit an event with the following structure:

#[derive(Drop, starknet::Event)]
struct Moved {
    address: felt252,
    direction: felt252,
}

Now a full example using a custom event:

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 });
}

Note: Read about the get! and set! macros in Commands.

Authorization

Authorization is crucial to a world, just like how authorization is crucial to any smart contract.

As discussed in the World 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

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.

sozo auth writer Moves spawn

This command will generate a writer authorization for the spawn system to update the Moves model.

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:

[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.

Migration

0.2.0 -> 0.3.0

0.3.0 -> 0.4.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 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:

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:

impl RolesSchemaIntrospectionImpl of SchemaIntrospection<Roles> {
    #[inline(always)]
    fn size() -> usize {
        1 // Represents the byte size of the enum.
    }

    #[inline(always)]
    fn layout(ref layout: Array<u8>) {
        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 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:

#[starknet::interface]
trait ICreateCard<TContractState> {
    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;.
#[external(v0)]
impl CreateCardImpl of ICreateCard<ContractState> {
    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.

#[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:

#[derive(Drop, starknet::Event, Copy)]
struct DeckCreated {
    player: ContractAddress,
    token_list: Span<u256>,
}

New Format:

#[event]
#[derive(Drop, starknet::Event)]
enum Event {
    DeckCreated: DeckCreated
}

#[derive(Drop, starknet::Event)]
struct DeckCreated {
    player: ContractAddress,
    token_list: Span<u256>,
}

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:
use dojo::test_utils::deploy_contract;
use tsubasa::systems::{ICreateCardDispatcher, ICreateCardDispatcherTrait};
  1. Deploy the contract and instantiate the dispatcher:
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:

// ... (previous setup code)

let result = create_card_system.create_card(
    // ... provide necessary parameters here
);

// Assert or validate the 'result' as per your test conditions

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

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

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.

#[derive(Model, Drop, Serde)]
struct Moves {
    #[key]
    player: ContractAddress,
    remaining: u8,
    last_direction: Direction
}

#[derive(Copy, Drop, Serde, Introspect)]
struct Vec2 {
    x: u32,
    y: u32
}

#[derive(Model, Copy, Drop, Serde)]
struct Position {
    #[key]
    player: ContractAddress,
    vec: Vec2,
}

...rest of code

Notice the #[derive(Model, 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 time, 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 model using the player field. Our Moves model also contains the remaining and last_direction fields

In a similar vein, we have a Position model that have a Vec2 data structure. Vec holds x and y values. Once again, this model is indexed by the player field.

Now, let's examine the src/actions.cairo file:

// 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> {
        // 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 function in a contract

As you can see a System is like a regular function of 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.

// 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 to retrieve the Position and Moves model for the player entity, which is the address of the caller.

Now the next line:

// 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 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 spawn and move functions
  • Explained the Moves and Position 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:

sozo build

That compiled the models and system into an artifact that can be deployed! Simple as that!

Now, let's deploy it to Katana! First, we need to get Katana running. Open a second terminal and execute:

katana --disable-fee

Success! Katana should now be running locally on your machine. Now, let's deploy! In your primary terminal, execute:

sozo migrate

This will deploy the artifact to Katana. You should see terminal output similar to this:


Migration account: 0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973

World name: dojo_examples

[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: 0x59f31686991d7cac25a7d4844225b9647c89e3e1e2d03460dbc61e3fbfafc59
# Base Contract
  > Class Hash: 0x77638e9a645209ac1e32e143bfdbfe9caf723c4f7645fcf465c38967545ea2f
# World
  > Contract address: 0x5010c31f127114c6198df8a5239e2b7a5151e1156fb43791e37e7385faa8138
# Models (2)
Moves
  > Class hash: 0x509a65bd8cc5516176a694a3b3c809011f1f0680959c567b3189e60ddab7ce1
Position
  > Class hash: 0x52a1da1853c194683ca5d6d154452d0654d23f2eacd4267c555ff2338e144d6
  > Registered at: 0x82d996aab290f086314745685c6f05bd69730d46589339763202de5264b1b6
# Contracts (1)
actions
  > Contract address: 0x31571485922572446df9e3198a891e10d3a48e544544317dbcbb667e15848cd

🎉 Successfully migrated World at address 0x5010c31f127114c6198df8a5239e2b7a5151e1156fb43791e37e7385faa8138

✨ Updating manifest.json...

✨ Done.

Your 🌎 is now deployed at 0x5010c31f127114c6198df8a5239e2b7a5151e1156fb43791e37e7385faa8138!

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). Make sure your file specifies the version of Dojo you have installed! In this case version 0.3.14.

[dependencies]
dojo = { git = "https://github.com/dojoengine/dojo", version = "0.3.14" }

Indexing

With your local world address established, let's delve into indexing. You can index the entire world. To accomplish this we have to copy your world address from the output of sozo migrate. Now Open a new terminal and input this simple command that includes your own world address:

torii --world 0x5010c31f127114c6198df8a5239e2b7a5151e1156fb43791e37e7385faa8138

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:

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:

query {
  model(id: "Moves") {
    id
    name
    class_hash
    transaction_hash
    created_at
  }
}

After you run the query, you will receive an output like this:

{
  "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:

subscription {
  entityUpdated {
    id
    keys
    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.

# Contracts (1)
actions
  > Contract address: 0x31571485922572446df9e3198a891e10d3a48e544544317dbcbb667e15848cd

We have to use actions contract address to start to create entities. In your main local terminal, run the following command:

sozo execute 0x31571485922572446df9e3198a891e10d3a48e544544317dbcbb667e15848cd 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:

{
  "data": {
    "entityUpdated": {
      "id": "0x28cd7ee02d7f6ec9810e75b930e8e607793b302445abbdee0ac88143f18da20",
      "keys": [
        "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973"
      ],
      "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"
      ],
      "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 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?

Entities

Entities are the primary key value within the world, to which models 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 models can be attached. To illustrate this concept, consider a simple example of a character in a game that has a Moves and a Position model.

When defining the models 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.

#[derive(Models, Drop, Serde)]
struct Moves {
    #[key]
    player: ContractAddress,
    remaining: u8,
}

#[derive(Models, Drop, Serde)]
struct Health {
    #[key]
    player: ContractAddress,
    x: u32,
    y: u32
}

ECS Theory: Plenty has been written on ECS systems, to go deeper read ECS-FAQ

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:

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:

models.cairo


...//rest of code

#[cfg(test)]
mod tests {
    use super::{Position, Vec2, Vec2Trait};

    #[test]
    #[available_gas(100000)]
    fn test_vec_is_zero() {
        assert(Vec2Trait::is_zero(Vec2 { x: 0, y: 0 }), 'not zero');
    }

    #[test]
    #[available_gas(100000)]
    fn test_vec_is_equal() {
        let position = Vec2 { x: 420, y: 0 };
        assert(position.is_equal(Vec2 { 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:

move.cairo

#[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::{actions, IActionsDispatcher, IActionsDispatcherTrait};

    // helper setup function
    // reusable function for tests
    fn setup_world() -> IActionsDispatcher {
        // 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', actions::TEST_CLASS_HASH.try_into().unwrap());
        let actions_system = IActionsDispatcher { contract_address };

        actions_system
    }


    #[test]
    #[available_gas(30000000)]
    fn test_move() {
        // caller
        let caller = starknet::contract_address_const::<0x0>();

        let actions_system = setup_world();

         // System calls
        actions_system.spawn();
        actions_system.move(Direction::Right(()));

        // check moves
        let moves = get!(world, caller, (Moves));
        assert(moves.remaining == 99, 'moves is wrong');

        // get new_position
        let new_position = get!(world, caller, Position);

        // check new position x
        assert(new_position.vec.x == 11, 'position x is wrong');

        // check new position y
        assert(new_position.vec.y == 10, 'position y is wrong');
    }
}

Useful Dojo Test Functions

spawn_test_world(models) - 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.

origami

The magic of origami is in seeing a single piece of cairo evolve into a masterpiece through careful folds.

What is Origami?

Origami is the native dojo collection of primitives that can be imported into your game.

It contains:

  • algebra
  • defi
  • hex map
  • random
  • security
  • erc tokens

Find the Origami repo

Overview

Dojo is BYO client, meaning that you can use any client you want to connect to the Dojo network.

Dojo is always looking to expand these clients, if you would like to contribute reach out into the Discord

Dojo.js

Javascript is a great way to get started with Dojo. It's easy to use, and you can get started in minutes.

@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

bun add @dojoengine/core

@dojoengine/create-burner

Create burner is a simple way to incorporate burner wallets into your Dojo app.

Repository

bun add @dojoengine/create-burner

@dojoengine/utils

These are utils for helping with interfacing dojo.

Repository

bun add @dojoengine/utils

@dojoengine/react

React hooks for dojo.

Repository

bun add @dojoengine/react

@dojoengine/torii-client

The wasm client to access torii via grpc.

Repository

bun add @dojoengine/torii-client

@dojoengine/torii-wasm

Torii client for wasm bindings.

Repository

bun add @dojoengine/torii-wasm

Unity

Dojo Unity SDK

Dojo c

c bindings

dojoup

Update or revert to a specific Dojo branch with ease.

Installing

curl -L https://install.dojoengine.org | bash

Usage

To install latest stable version:

dojoup

Note: You may have to install jq to use dojoup. You can do so with the following commands:

# Debian
sudo apt-get install jq

# Mac
brew install jq

To install a specific version (in this case the nightly version):

dojoup --version nightly

To install a specific branch (in this case the release/0.1.0 branch's latest commit):

dojoup --branch release/0.1.0

To install a fork's main branch (in this case tarrencev/dojo's main branch):

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

dojoup --repo tarrencev/dojo --branch patch-10

To install from a specific Pull Request:

dojoup --pr 1071

To install from a specific commit:

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.
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. These are better managed by using Dojoup.

ℹ️ Note

If you're on Windows, you will need to install and use Git BASH or WSL, as your terminal, since Dojoup currently does not support Powershell or Cmd.

katana

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, our dedicated installation package manager.

Installing from Source

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 for a complete overview of all the available subcommands.

sozo reference

Common options

Project Commands

World Commands

use sozo profiles

Profiles can be convenient when dealing with multiple environments (dev, staging, prod)

--profile
    Specify profile to use by name.

--dev
    Use dev profile.

--release
    Use release profile.

USAGE

Multiple profiles can be defined in Scarb.toml

[profile.dev.tool.dojo.env]
rpc_url = "http://localhost:5050"
account_address = "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973"
private_key = "0x1800000000300000180000000000030000000000003006001800006600"

[profile.staging.tool.dojo.env]
rpc_url = "https://api.cartridge.gg/x/mydojoproject/katana"
account_address = "0x5686a647a9cdd63ade617e0baf3b364856b813b508f03903eb58a7e622d5855"
private_key = "0x33003003001800009900180300d206308b0070db00121318d17b5e6262150b"

Then used with sozo commands

sozo --profile dev migrate

is equivalent to

sozo migrate --rpc-url http://localhost:5050 --account-address 0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973 --private-key 0x1800000000300000180000000000030000000000003006001800006600

offline

use sozo offline

--offline
    Run without accessing the network.
    [env: SOZO_OFFLINE=]

USAGE

sozo --offline [COMMAND]

For example

sozo --offline build

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.

sozo init

sozo build

build is used to compile the cairo contracts, generating the necessary artifacts for deployment.

sozo build

sozo test

test is used to test the project's cairo contracts. It will run all tests found within the project.

sozo test

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 <WORLD_ADDRESS> 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

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

--world WORLD_ADDRESS
    The address of the World contract.
    ENV: DOJO_WORLD_ADDRESS

Starknet Options

--rpc-url URL
    The Starknet RPC endpoint. [default: http://localhost:5050]
    ENV: STARKNET_RPC_URL

Account Options

--account-address ACCOUNT_ADDRESS
    The Starknet account address.
    ENV: DOJO_ACCOUNT_ADDRESS

Signer Options - Raw

--private-key PRIVATE_KEY
    The raw private key associated with the account contract.
    ENV: DOJO_PRIVATE_KEY

Signer Options - Keystore

--keystore PATH
    Use the keystore in the given folder or file.

--password PASSWORD
    The keystore password. Used with --keystore.
    ENV: DOJO_KEYSTORE_PASSWORD

EXAMPLES

  1. Deploying your World for the first time to a local Katana node
sozo migrate --name ohayo --rpc-url http://localhost:5050
  1. Updating a remote World after making some changes
sozo migrate --world 0x123456
  1. Deploying your World using profile options
sozo --profile dev migrate

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

sozo execute <CONTRACT> <ENTRYPOINT>

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

--world WORLD_ADDRESS
    The address of the World contract.
    ENV: DOJO_WORLD_ADDRESS

Starknet Options

--rpc-url URL
    The Starknet RPC endpoint. [default: http://localhost:5050]
    ENV: STARKNET_RPC_URL

Account Options

--account-address ACCOUNT_ADDRESS
    The Starknet account address.
    ENV: DOJO_ACCOUNT_ADDRESS

Signer Options - Raw

--private-key PRIVATE_KEY
    The raw private key associated with the account contract.
    ENV: DOJO_PRIVATE_KEY

Signer Options - Keystore

--keystore PATH
    Use the keystore in the given folder or file.

--password PASSWORD
    The keystore password. Used with --keystore.
    ENV: DOJO_KEYSTORE_PASSWORD

EXAMPLES

  1. Executing the position system which takes two values (x: 0x77 and y: 0x44)
sozo execute moving_contract position --calldata 0x77,0x44

sozo register

register is used to register new systems and components.

sozo register [OPTIONS] <COMMAND>
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)
# 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

sozo system

system is used to interact with a World's systems. It is useful for querying about a system's information.

USAGE

sozo system <COMMAND>

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

sozo system get <NAME>
Arguments

NAME
    The name of the system

dependency

Retrieve the component dependencies of a system

sozo system dependency <NAME>
Arguments

NAME
    The name of the system

OPTIONS

World Options

--world WORLD_ADDRESS
    The address of the World contract.
    ENV: DOJO_WORLD_ADDRESS

Starknet Options

--rpc-url URL
    The Starknet RPC endpoint. [default: http://localhost:5050]
    ENV: STARKNET_RPC_URL

EXAMPLES

  1. Get the class hash of the spawn system
sozo system get spawn
  1. Get the component dependencies of the spawn system
sozo system dependency spawn

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

sozo component <COMMAND>

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

sozo component get <NAME>
Arguments

NAME
    The name of the component

schema

Retrieve the schema for a component

sozo component schema <NAME>
Arguments

NAME
    The name of the component

entity

Get the component value for an entity

sozo component entity <NAME> [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

--world WORLD_ADDRESS
    The address of the World contract.
    ENV: DOJO_WORLD_ADDRESS

Starknet Options

--rpc-url URL
    The Starknet RPC endpoint. [default: http://localhost:5050]
    ENV: STARKNET_RPC_URL

sozo events

events is used to queries world events.

sozo events

sozo auth

auth is used to manage world authorization.

sozo auth [OPTIONS] <COMMAND> --world <WORLD_ADDRESS>
Commands:
  writer  Auth a system with the given calldata.
  help    Print this message or the help of the given subcommand(s)
# 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 <CONTRACT_ADDRESS> --world <WORLD_ADDRESS>

katana

Katana is a blazingly fast sequencer, designed to support both local development as well as production deployments.

In development mode, Katana provides the tool necessary for rapid iteration, including custom development RPCs for manipulating the execution context.

In produciton mode, Katana provides a high performance sequencer optimized for gaming workloads, with support for settlment and cross layer communication.

Features

  • Starknet JSON-RPC v0.3.0 support
  • Cross layer communication (L1 <> L2, LN <> LN+1)
  • Custom methods for manipulating the blockchain states

Installation

katana binary is available via dojoup.

Installing from source

git clone https://github.com/dojoengine/dojo
cd dojo
cargo install --path ./crates/katana --locked --force

Usage

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://0.0.0.0:5050


To enable development features, run using the --dev flag.

📚 Reference

See the katana Reference for an in depth reference and documentation on Katana.

katana reference

NAME

katana - Create a local testnet node for deploying and testing Starknet smart contracts.

USAGE

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 <MILLISECONDS> flag, as demonstrated in the following example.

# 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 <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 <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.

# 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.

katana --messaging path/to/messaging/config.json

The messaging config file is a JSON file that contains the following fields:

{
  /// 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:

katana --port <PORT>

Starknet Feature Compatibility

Supported Transaction Type
TypeVersion
INVOKE1
DECLARE1, 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 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 <MILLISECONDS>
     Block time in milliseconds for interval mining.

--dump-state <PATH>
     Dump the state of chain on exit to the given file.
     If the value is a directory, the state will be written to <PATH>/state.bin.

--load-state <PATH>
     Initialize the chain from a previously saved state snapshot.

--rpc-url <URL>
     The Starknet RPC provider to fork the network from.

--json-log
     Output logs in JSON format.

--fork-block-number <BLOCK_NUMBER>
     Fork the network at a specific block.

--messaging <PATH>
     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>
     Port number to listen on. [default: 5050]

--host <HOST>
     The IP address the server will listen on.

Starknet Options

--seed <SEED>
     Specify the seed for randomness of accounts to be predeployed.

--accounts <NUM>
     Number of pre-funded accounts to generate. [default: 10]

--disable-fee
     Disable charging fee for transactions.

Environment Options

--chain-id <CHAIN_ID>
     The chain ID. [default: KATANA]

--gas-price <GAS_PRICE>
     The gas price.

--validate-max-steps <VALIDATE_MAX_STEPS>
     The maximum number of steps available for the account validation logic.

--invoke-max-steps <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:

katana completions bash >> ~/.bashrc

EXAMPLES

  1. Create 15 dev accounts and disable transaction fee mechanism
katana --accounts 15 --disable-fee
  1. Set the chain id to SN_GOERLI and run the server on port 8545
katana --chain-id SN_GOERLI --port 8545
  1. Load previously stored state and dump the state of this session to a file on shutdown
katana --load-state ./dump-state.bin --dump-state ./dump-state.bin

katana

Torii - Networking & Indexing

Torii is an automatic indexer for dojo worlds. Built in rust to be blazingly fast and exceptionally scalable. Torii provides a fully typed, dynamically generated GraphqQL interface and a high performance gRPC api for binding clients to the world state.

Usage

Torii leverages world introspection to bootstrap directly from an onchain deployment. Simply run:

torii --world <World Address>

You'll have a GraphQL API running at http://localhost:8080/graphql and a gRPC api at http://localhost:8080/grpc

Installation

The torii binary can be installed via dojoup, our dedicated installation package manager.

Installing from Source

If you prefer to install from the source code:

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 for a complete reference.

torii reference

Name

torii - An automatic indexer and networking layer for a world contract.

USAGE

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.

# 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>
     Database filepath (ex: indexer.db) [default: :memory:]

-s, --start-block <START_BLOCK>
     Specify a block to start indexing from, ignored if stored head exists [default: 0]

--allowed-origins <ALLOWED_ORIGINS>
     Specify allowed origins for api endpoints (comma-separated list of allowed origins, or "*" for all) [default: *]

--external-url <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

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.

torii --world <WORLD_ADDRESS>

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. For example: positionModels.

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 we fetched some data from the Moves model. This time let's fetch only id, name, class_hash fields from Position model .

query {
  model(id: "Position") {
    id
    name
    class_hash
  }
}

After you run the query, you will receive an output like this:

{
  "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.

query {
  movesModels {
    edges {
      node {
        player
        remaining
        last_direction
      }
    }
  }
}

After you run the query, you will receive an output like this:

{
  "data": {
    "movesModels": {
      "edges": [
        {
          "node": {
            "player": "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973",
            "remaining": 10,
            "last_direction": "None"
          }
        }
      ]
    }
  }
}

Transactions

GraphQL additionally offers an API to fetch transactions emitted from your world. Presently, you can retrieve transaction data with the potential for future support of transaction receipt. Current API includes pagination support, although filtering is not yet supported. Let's explore an example.

query{
  transactions{
    edges{
      node{
        id
        transaction_hash
        sender_address
        calldata
      }
    }
    total_count
  }
}

If you execute this query after you applied sozo migrate in your hello-dojo example. You will get an output similar to this.

{
  "data": {
    "transactions": {
      "edges": [
        {
          "node": {
            "id": "0x000000000000000000000000000000000000000000000000000000000000000a:0x0000",
            "transaction_hash": "0x2da3d65e223362c72906f97663a4e7dc81ab0bbd04bbde5532a230c1e97d93e",
            "sender_address": "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973",
            "calldata": [
              "0x1",
              "0x405a3c5421ca7e23052abce78057e27384ba9db5e4feff7b4041a74e769a98a",
              "0x2730079d734ee55315f4f141eaed376bddd8c2133523d223a344c5604e0f7f8",
              "0x0",
              "0x2",
              "0x2",
              "0x35ec9fd22092dc0c8fc9341e94d5f361924d921c128fa46a0648f2dac519ce4",
              "0x2ffecbe8de6c7c10c785a6eb964ee6489f8dcf139000adbe2c0f12d249be7d8"
            ]
          }
        },
        {
          "node": {
            "id": "0x0000000000000000000000000000000000000000000000000000000000000008:0x0000",
            "transaction_hash": "0x2aa02de0e3fa582b3cb6cf9e4371051f44ae2e0d6c94f5c936338ffc8c2ac12",
            "sender_address": "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973",
            "calldata": [
              "0x2",
              "0x405a3c5421ca7e23052abce78057e27384ba9db5e4feff7b4041a74e769a98a",
              "0x1e7875674bcb09daaf984cbf77264ac98120cb39e6d17522520defcdc347476",
              "0x0",
              "0x1",
              "0x405a3c5421ca7e23052abce78057e27384ba9db5e4feff7b4041a74e769a98a",
              "0x1e7875674bcb09daaf984cbf77264ac98120cb39e6d17522520defcdc347476",
              "0x1",
              "0x1",
              "0x2",
              "0x2e5174b54aef0b99d4685827ffa51488447e1f5607908293d5c715d6bd22433",
              "0x6a11b5b3003a3aa0ae7f8f443e48314cc0bc51eaea7c3ed1c19beb909f5dda3"
            ]
          }
        },
        {
          "node": {
            "id": "0x0000000000000000000000000000000000000000000000000000000000000005:0x0000",
            "transaction_hash": "0x1f03fa7dc5a673f96d53b728785a98d6ff089c182a7bb32735b150e91817e5b",
            "sender_address": "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973",
            "calldata": [
              "0x1",
              "0x41a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf",
              "0x1987cbd17808b9a23693d4de7e246a443cfe37e6e7fbaeabd7d7e6532b07c3d",
              "0x0",
              "0x6",
              "0x6",
              "0xb3e374b8087dca92601afbb9881fed855ac0d568e3bf878a876fca5ffcb479",
              "0x41d7f42bf7a362f0420aaae66d7a91df981100a039ac116a1d9cb632c74ad27",
              "0x0",
              "0x2",
              "0x59f31686991d7cac25a7d4844225b9647c89e3e1e2d03460dbc61e3fbfafc59",
              "0x77638e9a645209ac1e32e143bfdbfe9caf723c4f7645fcf465c38967545ea2f"
            ]
          }
        }
      ],
      "total_count": 3
    }
  }
}

Now 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 type.

You can read more about graphql pagination here.

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

query {
  entities (first: 2) {
    total_count
    edges {
      cursor
      node {
        ...
      }
    }
  }
}

Result shows there are 5 entities and returns the first two

{
  "entities" {
    "total_count": 5,
    "edges" [
      {
        "cursor": "Y3Vyc29yX29uZQ==",
        "node" : { }
      },
      {
        "cursor": "Y3Vyc29yX3R3bw==",
        "node" : { }
      },
    ]
  }
}

Query 3 entities after the second node (last 3)

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.

# 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

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:

subscription {
  entityUpdated(
    id: "0x28cd7ee02d7f6ec9810e75b930e8e607793b302445abbdee0ac88143f18da20"
  ) {
    id
    keys
    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:

{
  "data": {
    "entityUpdated": {
      "id": "0x28cd7ee02d7f6ec9810e75b930e8e607793b302445abbdee0ac88143f18da20",
      "keys": [
        "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973"
      ],
      "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
          }
        }
      ]
    }
  }
}

Susbcription to events

A valuable approach for harnessing the power of GraphQL is by actively monitoring the events emitted throughout your game. This allows you to extract essential information such as key values, data, and transaction hashes. These events are customizable and can be filtered based on keys, much like entities query, and they seamlessly support pagination. In the subsequent example, we will demonstrate how to listen for any event emitted within your program.

subscription {
  eventEmitted {
    id
    keys
    data
    transaction_hash
  }
}

If you execute this suscription after you applied sozo execute <ACTION_CONTRACT_ADDRESS> spawn in your hello-dojo example. You will get an output similar to this.

{
  "data": {
    "eventEmitted": {
      "id": "0x000000000000000000000000000000000000000000000000000000000000000b:0x0000:0x0000",
      "keys": [
        "0x1a2f334228cee715f1f0f54053bb6b5eac54fa336e0bc1aacf7516decb0471d"
      ],
      "data": [
        "0x4d6f766573",
        "0x1",
        "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973",
        "0x0",
        "0x2",
        "0x64",
        "0x0"
      ],
      "transaction_hash": "0x3b7b034a087355c996abb52e363932c1135f8dd49587bc9a05902d3cf0650b"
    }
  }
}
-----------------------------------------------------------------------------------------------
{
  "data": {
    "eventEmitted": {
      "id": "0x000000000000000000000000000000000000000000000000000000000000000b:0x0000:0x0001",
      "keys": [
        "0x1a2f334228cee715f1f0f54053bb6b5eac54fa336e0bc1aacf7516decb0471d"
      ],
      "data": [
        "0x506f736974696f6e",
        "0x1",
        "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973",
        "0x0",
        "0x2",
        "0xa",
        "0xa"
      ],
      "transaction_hash": "0x3b7b034a087355c996abb52e363932c1135f8dd49587bc9a05902d3cf0650b"
    }
  }
}

Graphql

Slot

Slot is a toolchain developed by Cartrige.gg for rapidly spinning up Katana and Torii instances. Play test your game in seconds.

Installation

Run the following command to install slot:

curl -L https://slot.cartridge.sh | bash

Once finished, run slotup to manage slot installations and follow the outputted directions.

Deploy using Slot

To deploy your projects using slot, check out the tutorial Deploy using Slot.

📚 Reference

See the slot Reference for a complete overview of all the available subcommands.

slot reference

Name

slot - a toolchain developed for rapidly spinning up Katana and Torii instances.

Usage

slot [COMMANDS] [OPTIONS]

Commands

auth
     Manage auth credentials for the Slot CLI.

deployments

     Manage Slot deployments.

help
     Print this message or the help of the given subcommand(s)

slot deployments

It allows you the manage your slot deployments.

Commands

create     Create a new deployment.

delete     Delete a deployment.

update     Update a deployment.

describe     Describe a deployment's configuration.

list     List all deployments.

logs     Fetch logs for a deployment.

help     Print this message or the help of the given subcommand(s)

Deploying Locally to Katana

Dojo is engineered for rapid development, boasting a lightning-fast local development sequencer, Katana. 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 guide and have a project initialized.

From your project directory, run:

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:

sozo migrate --name test

Note - this will only work if you have compiled your contracts. If you have not, run:

sozo build

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

[package]
name = "ohayoo"
version = "0.1.0"
cairo-version = "0.3.15"

[cairo]
sierra-replace-ids = true

[dependencies]
dojo = { git = "https://github.com/dojoengine/dojo", tag = "v0.3.15" }

# KATANA on slot
# rpc_url = "https://api.cartridge.gg/x/example/katana"
# account_address = "0x2d5260ba1d62ed0ea7c598f1460d27528b27afdf3bb43524a1ba3617e8279b2"
# private_key = "0x6768b97b44cfbfa9f776a3c00ebe33c228058bf8716bb0515a1363049da2a11"
# world = "0x1fad58d91d5d121aa6dc4d16c01a161e0441ef75fe7d31e3664a61e66022b1f"

# ENDPOINT
rpc_url = "https://api.cartridge.gg/x/shinai/madara"
account_address = "0x2"
private_key = "0xc1cf1490de1352865301bb8705143f3ef938f97fdf892f1090dcb5ac7bcd1d"
world_address = "0x5b328933afdbbfd44901fd69a2764a254edbb6e992ae87cf958c70493f2d201"

# GOERLI
# rpc_url = "https://starknet-goerli.g.alchemy.com/v2/<API KEY>"
# account_address = "0x2d5260ba1d62ed0ea7c598f1460d27528b27afdf3bb43524a1ba3617e8279b2"
# private_key = "0x6768b97b44cfbfa9f776a3c00ebe33c228058bf8716bb0515a1363049da2a11"
# world = "0x1fad58d91d5d121aa6dc4d16c01a161e0441ef75fe7d31e3664a61e66022b1f"

Deploy to public Starknet

If you credentials are correct in the Scarb.toml then a simple migrate will deploy the world to Starknet.

Deploy to Remote Katana

Katanas are able to be hosted and run as remote testnets, however this is not recommended for production use.

Deploy to remote katana with slot here

Deploy to Remote Madara

Madara is a blazingly fast Starknet sequencer.

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.

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.

0. Setup

Before starting recommend following the hello-dojo 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.

mkdir dojo-chess

Open the project folder.

cd dojo-chess

And initialize the project using sozo init.

sozo init

Cleaning Up the Boilerplate

The project comes with a lot of boilerplate codes. Clear it all. Make sure both actions.cairo, models.cairo and utils.cairo files are empty. Then create a new empty tests.cairo file in your /src directory.

Remodel yourlib.cairo, to look like this :

mod actions;
mod models;
mod utils;
mod tests;

Make sure your Scarb.toml looks like this:

[package]
cairo-version = "2.3.0"
name = "dojo_chess"
version = "0.3.15"

[cairo]
sierra-replace-ids = true

[dependencies]
dojo = { git = "https://github.com/dojoengine/dojo", version = "0.3.15" }

[[target.dojo]]

[tool.dojo]
initializer_class_hash = "0xbeef"

[tool.dojo.env]
rpc_url = "http://localhost:5050/"
# Default account for katana with seed = 0
account_address = "0x517ececd29116499f4a1b64b094da79ba08dfd54a3edaa316134c41f8160973"
private_key = "0x1800000000300000180000000000030000000000003006001800006600"

Compile your project with:

sozo build

Basic Models

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.

#[derive(Model, Drop, Serde)]
struct Square {
    #[key]
    game_id: u32,
    #[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: (),
}

Basic systems

Starting from the next chapter, you will implement the actions.cairo file. This is where our game logic/contract will reside.

For now, actions.cairo should look like this:

#[dojo::contract]
mod actions {
}

It should be noted that Systems function are contract methods, 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.

Complied? Great! then let's move on. If not fix try issues, so that you can run the sozo build command successfully.

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

  • Game model with fields: game_id, winner, white, black.

  • GameTurn model with fields: game_id, turn.

Try to implement this code by yourself, Otherwise

Click to see full `models.cairo` code
use starknet::ContractAddress;

#[derive(Model, Drop, Serde)]
struct Square {
    #[key]
    game_id: u32,
    #[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 {
    #[key]
    game_id: u32,
    winner: Color,
    white: ContractAddress,
    black: ContractAddress
}

#[derive(Model, Drop, Serde)]
struct GameTurn {
    #[key]
    game_id: u32,
    turn: Color
}

This tutorial is extracted from here

Congratulations! You've completed the basic setup for building an on-chain chess game 🎉

1. Actions

This chapter will address implementing actions.cairo, which spawns the game & squares containing pieces and also allow players to move pieces.

What is actions contract?

To play chess, you need, to start game, spawn the pieces, and move around the board. the actions contract has two dominant functions spawn function which spawns the game entity, places each piece in its proper position on the board and returns the game_id, and the move funtion which allows pieces to be moved around the board.

image

Requirements

  1. Write an interface for the actions contract on top of your code. In this case, move and spawn
    use starknet::ContractAddress;

    #[starknet::interface]
    trait IActions<ContractState> {
        fn move(
            self: @ContractState,
            curr_position: (u32, u32),
            next_position: (u32, u32),
            caller: ContractAddress, //player
            game_id: u32
        );
        fn spawn(
            self: @ContractState, white_address: ContractAddress, black_address: ContractAddress
        ) -> u32;
    }
  1. Bring in required imports into the contract like this :
    #[dojo::contract]
    mod actions {
        use dojo_chess::models::{Color, Square, PieceType, Game, GameTurn};
        use super::{ContractAddress, IActions};
        use dojo_chess::utils::{is_out_of_board, is_right_piece_move, is_piece_is_mine};
    }

Should be noted that actions is the contract name.

  1. Write a spawn 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 fn.
    #[external(v0)]
    impl IActionsImpl of IActions<ContractState> {
        fn spawn(
            self: @ContractState, white_address: ContractAddress, black_address: ContractAddress
        ) -> u32 {
            let world = self.world_dispatcher.read();
            let game_id = world.uuid();
            set!(
                world,
                (
                    Game {
                        game_id,
                        winner: Color::None(()),
                        white: white_address,
                        black: black_address
                    },
                    GameTurn { game_id, turn: Color::White(())},
                )
            );

            set!(world, (Square { game_id, x: 0, y: 0, piece: PieceType::WhiteRook }));
            set!(world, (Square { game_id, x: 0, y: 1, piece: PieceType::WhitePawn }));
            set!(world, (Square { game_id, x: 1, y: 6, piece: PieceType::BlackPawn }));
            set!(world, (Square { game_id, x: 1, y: 0, piece: PieceType::WhiteKnight }));

            //the rest of the positions on the board goes here....

            game_id
        }
        fn move(self: @ContractState, curr_position: (u32, u32),
            next_position: (u32, u32), caller: ContractAddress,
            game_id: u32
        ) {
            // Upcoming code
        }
    }

Before we implement the move() function, we are going to setup some helper function in our utils.cairo file

2. Utils and Legal Moves

In order to keep our code has dry as possible, we decide to modularize some functions. Those functions are the ones we import from utils.cairo into actions.cairo.

    use dojo_chess::utils::{is_out_of_board, is_right_piece_move, is_piece_is_mine};

This functions will 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. Fill the following code in your utils.cairo file

  1. See if player is moving the right piece
    use dojo_chess::models::PieceType;
    use starknet::ContractAddress;
    fn is_piece_is_mine(maybe_piece: PieceType) -> bool {
        false
    }
  1. See if the next spot is still on the board.
    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
    }
  1. See if the person trying the move is doing it at the right time and with their piece color.
    fn is_correct_turn(maybe_piece: PieceType, caller: ContractAddress, game_id: felt252) -> bool {
        true
    }
  1. see if it's the right move
    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']),
        }
    }
  1. You can also add other check functions to be extra sure the move is allowed.

    We will use these check functions to implement the move() function in the contract on our next chapter. You can decide how to set them up and which ones to use.

3 Move function

  1. Write a move function that accepts the current position, next position, caller address, and game id. The move function should look like this:
    #[external(v0)]
    impl PlayerActionsImpl of IActions<ContractState> {
        fn spawn(
            self: @ContractState, white_address: ContractAddress, black_address: ContractAddress
        ) {
            // Rest of code
        }
        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));
        }
    }
  1. Run sozo build to compile the code.

    Great, Now we can start testing our functions

Test Flow

  • Spawn the test world (spawn_test_world) that imports the models in testing.
  • deploy actions contract
  • interact with spawn 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

#[cfg(test)]
mod tests {
    use starknet::ContractAddress;
    use dojo::test_utils::{spawn_test_world, deploy_contract};
    use dojo::world::{IWorldDispatcher, IWorldDispatcherTrait};
    use dojo_chess::models::{Game, game, GameTurn, game_turn, Square, square, PieceType};
    use dojo_chess::actions::actions;
    use dojo_chess::actions::{IActionsDispatcher, IActionsDispatcherTrait};

    // helper setup function
    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
        let game_id = actions_system.spawn(white, black);

        //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(white, black);

        let game_id = world.uuid();

        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');
    }
}

Diving into the Code

setup_world

We should list both models with each having CLASS_HASH as elements and then we deploy world to models with spawn_test_world

    //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, then we return our world and actions_systems dispatcher

    let contract_address = world
            .deploy_contract('salt', actions::TEST_CLASS_HASH.try_into().unwrap());
    let actions_system = IActionsDispatcher { contract_address };
    (world, actions_system)

test_initiate

First, we'll set up the players address and their colors.

   let white = starknet::contract_address_const::<0x01>();
   let black = starknet::contract_address_const::<0x02>();

We use spawn function in actions.cairo to put our Square pieces on the board. Each Square holds a piece. The system's spawn function needs some input i.e the addresses of the players.

    // spawn
    let game_id = actions_system.spawn(white, black);

Then we check if the players got their setup address. After that we check if a White rook is at (0,0). 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.

    //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_move

Here, after setting up the board, we use move function in the contract to make moves. Provide the current position, the next position, the player's address, and the game id.

    //Move White Pawn to (0,2)
    actions_system.move((0, 1), (0, 2), white.into(), game_id);

Then we check if a White Pawn is at the new position.

    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!

4 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. Call spawn to setup white_pawn to (0,1) and black_pawn to (1,6)
  2. Move white_pawn to (0,3)
  3. Move black_pawn to (1,4)
  4. Move white_pawn to (1,4)
  5. Capture black_pawn

To place the pieces, use our spawn function in our actions contract. For moving them, use the move contract. Remember to check if a piece can be captured when using move.

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.

Full Code

#[cfg(test)]
mod tests {
    use dojo_chess::models::{Square, PieceType};
    use dojo::world::IWorldDispatcherTrait;
    use dojo_chess::actions::tests::setup_world;
    use dojo_chess::actions::{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
        let game_id = actions_system.spawn(white, black);

        //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)');
    }
}

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

Lastly, share your project with others in the Dojo community!

Deploy your game using Slot

Welcome to this tutorial where we'll guide you through deploying a project using the Slot.


Before we start, make sure you are using the latest dojo version. Run dojoup to have the latest version installed.

Now, let's create a new folder and initialize it with sozo.

mkdir dojo-starter && cd dojo-starter
sozo init

First, we need to set up our configuration, starting by authenticating with Cartridge. To do this, run the following command, which will then prompt a new screen where you will need to go through the authentication process.

slot auth login

# Slot Auth debug (if old auth credentials):
rm ~/Library/Application\ Support/slot/credentials.json

Once successful, you can create a new deployment with a unique DEPLOYMENT_NAME. To do this, run the following command:

slot deployments create DEPLOYMENT_NAME katana

After that, you should receive the RPC endpoint for the katana slot. Now, you can use that and update your Scarb.toml file with the new RPC endpoint as follows:

[tool.dojo.env]
rpc_url = "YOUR_NEW_RPC_URL"

Now, you can stream katana in a new terminal. Open a new terminal and run the following command:

slot deployments logs DEPLOYMENT_NAME katana -f

Then, copy the account address and the private key from the first account into the Scarb.toml file and replace the existing ones as follows:

account_address = "YOUR_NEW_ACCOUNT_ADDRESS"
private_key = "YOUR_NEW_PRIVATE_KEY"

Note: For each new Katana slot, a different account seed is used, making all the accounts unique!


Once finished with the new configurations, we are ready to build and migrate the project. To build the project, run the following command:

sozo build

Now, let's migrate the project to our new katana slot:

sozo migrate --name YOUR_PROJECT_NAME

If the migrations have been successful, you will receive the WORLD_ADDRESS, which then you can use to interact with your world.

🎉 Successfully migrated World at address WORLD_ADDRESS

✨ Updating manifest.json...

✨ Done.

Congratulations! You have successfully deployed your project with a Katana slot.

Torii

To initiate a Torri indexer slot, execute the following command:

slot deployments create DEPLOYMENT_NAME torii --world YOUR_WORLD_ADDRESS --rpc YOUR_NEW_RPC_URL --start-block 1

Once deployment is successful, you should receive the endpoints for GraphQL and gRPC.

If you wish to stream the logs, you can run the following command in a new terminal:

slot deployments logs DEPLOYMENT_NAME torii -f

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.

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:

## Some Page

We do not use:

# Some Page