Skip to content

Commit

Permalink
Load entity values
Browse files Browse the repository at this point in the history
  • Loading branch information
tarrencev committed Jun 11, 2023
1 parent 9f0e409 commit 0b491ab
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 29 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 21 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,19 @@

resolver = "2"

members = [ "crates/bevy-dojo", "crates/dojo-lang", "crates/dojo-language-server", "crates/dojo-world", "crates/dojo-test-utils", "crates/dojo-signers", "crates/katana", "crates/katana-core", "crates/katana-rpc", "crates/sozo", "crates/torii" ]
members = [
"crates/bevy-dojo",
"crates/dojo-lang",
"crates/dojo-language-server",
"crates/dojo-world",
"crates/dojo-test-utils",
"crates/dojo-signers",
"crates/katana",
"crates/katana-core",
"crates/katana-rpc",
"crates/sozo",
"crates/torii",
]

[workspace.package]
version = "0.1.0"
Expand All @@ -27,7 +39,7 @@ cairo-lang-lowering = "1.1.0"
cairo-lang-parser = "1.1.0"
cairo-lang-plugins = "1.1.0"
cairo-lang-project = "1.1.0"
cairo-lang-semantic = { version = "1.1.0", features = [ "testing" ] }
cairo-lang-semantic = { version = "1.1.0", features = ["testing"] }
cairo-lang-sierra-generator = "1.1.0"
cairo-lang-sierra = "1.1.0"
cairo-lang-sierra-to-casm = "1.1.0"
Expand All @@ -36,9 +48,9 @@ cairo-lang-syntax = "1.1.0"
cairo-lang-test-utils = "1.1.0"
cairo-lang-test-runner = "1.1.0"
cairo-lang-utils = "1.1.0"
camino = { version = "1.1.2", features = [ "serde1" ] }
chrono = { version = "0.4.24", features = [ "serde" ] }
clap = { version = "4.2", features = [ "derive" ] }
camino = { version = "1.1.2", features = ["serde1"] }
chrono = { version = "0.4.24", features = ["serde"] }
clap = { version = "4.2", features = ["derive"] }
colored = "2"
env_logger = "0.10.0"
indoc = "1.0.7"
Expand All @@ -50,15 +62,16 @@ rayon = "0.9.0"
salsa = "0.16.1"
scarb = { git = "/~https://github.com/software-mansion/scarb", rev = "0aa0f97b89a2e6f38f3b005cad2817dcaee7bf51" }
semver = "1.0.5"
serde = { version = "1.0.156", features = [ "derive" ] }
serde = { version = "1.0.156", features = ["derive"] }
serde_json = "1.0"
serde_with = "2.3.1"
smol_str = { version = "0.2.0", features = [ "serde" ] }
smol_str = { version = "0.2.0", features = ["serde"] }
starknet = { git = "/~https://github.com/xJonathanLEI/starknet-rs", branch = "dev/jsonrpc_0_3_0" }
starknet-crypto = { git = "/~https://github.com/xJonathanLEI/starknet-rs", branch = "dev/jsonrpc_0_3_0" }
starknet_api = { git = "/~https://github.com/starkware-libs/starknet-api" }
test-log = "0.2.11"
thiserror = "1.0.32"
tokio = { version = "1.16", features = [ "full" ] }
tokio = { version = "1.16", features = ["full"] }
toml = "0.7.4"
tracing = "0.1"
tracing-subscriber = "0.3.16"
Expand Down
2 changes: 1 addition & 1 deletion crates/dojo-core/src/storage/kv.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ mod KeyValueStore {
use dojo_core::{integer::u250, serde::SpanSerde};

fn address(table: u250, key: u250) -> starknet::StorageBaseAddress {
starknet::storage_base_address_from_felt252(hash::LegacyHash::hash(0x420, (table, key)))
starknet::storage_base_address_from_felt252(hash::LegacyHash::hash(table.into(), key))
}

#[view]
Expand Down
3 changes: 1 addition & 2 deletions crates/dojo-core/src/storage/query.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,11 @@ impl QueryImpl of QueryTrait {

fn hash(self: @Query) -> u250 {
let keys = *self.keys;
if keys.len() == 1 & *self.partition == 0.into() {
if keys.len() == 1 {
return *keys.at(0);
}

let mut serialized = ArrayTrait::new();
self.partition.serialize(ref serialized);
self.keys.serialize(ref serialized);
poseidon_hash_span(serialized.span()).into()
}
Expand Down
1 change: 1 addition & 0 deletions crates/dojo-world/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ serde_json.workspace = true
serde_with.workspace = true
smol_str.workspace = true
starknet.workspace = true
starknet-crypto.workspace = true
thiserror.workspace = true
tracing.workspace = true
url = "2.2.2"
Expand Down
45 changes: 40 additions & 5 deletions crates/dojo-world/src/component.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
use std::vec;

use starknet::core::crypto::pedersen_hash;
use starknet::core::types::{BlockId, FieldElement, FunctionCall};
use starknet::core::utils::{
cairo_short_string_to_felt, get_selector_from_name, parse_cairo_short_string,
CairoShortStringToFeltError, ParseCairoShortStringError,
};
use starknet::providers::{Provider, ProviderError};
use starknet_crypto::{poseidon_hash, poseidon_hash_many};

use crate::manifest::Member;
use crate::world::{ContractReaderError, WorldContractReader};
Expand Down Expand Up @@ -31,6 +35,7 @@ pub enum ComponentError<P> {
pub struct ComponentReader<'a, P: Provider + Sync> {
world: &'a WorldContractReader<'a, P>,
class_hash: FieldElement,
name: FieldElement,
}

impl<'a, P: Provider + Sync> ComponentReader<'a, P> {
Expand All @@ -39,23 +44,22 @@ impl<'a, P: Provider + Sync> ComponentReader<'a, P> {
name: String,
block_id: BlockId,
) -> Result<ComponentReader<'a, P>, ComponentError<P::Error>> {
let name = cairo_short_string_to_felt(&name)
.map_err(ComponentError::CairoShortStringToFeltError)?;
let res = world
.provider
.call(
FunctionCall {
contract_address: world.address,
calldata: vec![
cairo_short_string_to_felt(&name)
.map_err(ComponentError::CairoShortStringToFeltError)?,
],
calldata: vec![name],
entry_point_selector: get_selector_from_name("component").unwrap(),
},
block_id,
)
.await
.map_err(ComponentError::ProviderError)?;

Ok(Self { world, class_hash: res[0] })
Ok(Self { world, class_hash: res[0], name })
}

pub fn class_hash(&self) -> FieldElement {
Expand Down Expand Up @@ -93,4 +97,35 @@ impl<'a, P: Provider + Sync> ComponentReader<'a, P> {

Ok(members)
}

pub async fn entity(
&self,
partition_id: FieldElement,
keys: Vec<FieldElement>,
block_id: BlockId,
) -> Result<Vec<FieldElement>, ComponentError<P::Error>> {
let members = self.schema(block_id).await?;

let table = if partition_id == FieldElement::ZERO {
self.name
} else {
poseidon_hash(self.name, partition_id)
};
let keys_hash = if keys.len() == 1 { keys[0] } else { poseidon_hash_many(&keys) };
let key = pedersen_hash(&table, &keys_hash);

let mut values = vec![];
for member in members {
let value = self
.world
.provider
.get_storage_at(self.world.address, key + member.slot.into(), block_id)
.await
.map_err(ComponentError::ProviderError)?;

values.push(value);
}

Ok(values)
}
}
32 changes: 26 additions & 6 deletions crates/dojo-world/src/system_test.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,52 @@
use camino::Utf8PathBuf;
use dojo_test_utils::sequencer::TestSequencer;
use starknet::accounts::ConnectedAccount;
use starknet::accounts::Account;
use starknet::core::types::{BlockId, BlockTag};
use starknet_crypto::FieldElement;

use crate::manifest::Dependency;
use crate::world::test::deploy_world;
use crate::world::WorldContractReader;
use crate::world::WorldContract;

#[tokio::test]
async fn test_system() {
let sequencer = TestSequencer::start().await;
let account = sequencer.account();
let provider = account.provider();
let (world_address, _) = deploy_world(
&sequencer,
Utf8PathBuf::from_path_buf("../../examples/ecs/target/dev".into()).unwrap(),
)
.await;

let block_id: BlockId = BlockId::Tag(BlockTag::Latest);
let world = WorldContractReader::new(world_address, provider);
let system = world.system("Spawn", block_id).await.unwrap();
let dependencies = system.dependencies(block_id).await.unwrap();
let world = WorldContract::new(world_address, &account);
let spawn = world.system("Spawn", block_id).await.unwrap();
let dependencies = spawn.dependencies(block_id).await.unwrap();
assert_eq!(
dependencies,
vec![
Dependency { name: "Moves".into(), read: false, write: true },
Dependency { name: "Position".into(), read: false, write: true }
]
);

let _ = spawn.execute(vec![]).await.unwrap();

let component = world.component("Moves", block_id).await.unwrap();
let moves =
component.entity(FieldElement::ZERO, vec![account.address()], block_id).await.unwrap();

assert_eq!(moves, vec![10_u8.into()]);

// let move_system = world.system("Move", block_id).await.unwrap();

// let _ = move_system.execute(vec![FieldElement::ONE]).await.unwrap();
// let _ = move_system.execute(vec![FieldElement::THREE]).await.unwrap();

// let moves =
// component.entity(FieldElement::ZERO, vec![account.address()], block_id).await.unwrap();

// assert_eq!(moves, vec![8_u8.into()]);

// let position_component = world.component("Position", block_id).await.unwrap();
}
12 changes: 5 additions & 7 deletions examples/ecs/src/systems.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ mod Spawn {
use dojo_examples::components::Position;
use dojo_examples::components::Moves;

fn execute() {
let caller = starknet::get_caller_address();
fn execute(ctx: Context) {
let player = commands::set_entity(
caller.into(), (Moves { remaining: 10 }, Position { x: 0, y: 0 }, )
ctx.caller_account.into(), (Moves { remaining: 10 }, Position { x: 0, y: 0 }, )
);
return ();
}
Expand Down Expand Up @@ -42,12 +41,11 @@ mod Move {
}
}

fn execute(direction: Direction) {
let caller = starknet::get_caller_address();
let (position, moves) = commands::<Position, Moves>::entity(caller.into());
fn execute(ctx: Context, direction: Direction) {
let (position, moves) = commands::<Position, Moves>::entity(ctx.caller_account.into());
let next = next_position(position, direction);
let uh = commands::set_entity(
caller.into(),
ctx.caller_account.into(),
(Moves { remaining: moves.remaining - 1 }, Position { x: next.x, y: next.y }, )
);
return ();
Expand Down

0 comments on commit 0b491ab

Please sign in to comment.