Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load entity values #466

Merged
merged 1 commit into from
Jun 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
39 changes: 33 additions & 6 deletions crates/dojo-world/src/system_test.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,59 @@
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();

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

assert_eq!(position, vec![1_u8.into(), 1_u8.into()]);
}
11 changes: 10 additions & 1 deletion crates/dojo-world/src/world_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use camino::Utf8PathBuf;
use dojo_test_utils::sequencer::TestSequencer;
use starknet::accounts::ConnectedAccount;
use starknet::core::types::{BlockId, BlockTag, FieldElement};
use starknet::core::utils::cairo_short_string_to_felt;

use super::WorldContract;
use crate::manifest::Manifest;
Expand Down Expand Up @@ -63,10 +64,18 @@ pub async fn deploy_world(
declare_output.push(res);
}

let _ = WorldContract::new(world_address, &account)
let world = WorldContract::new(world_address, &account);
let _ = world
.register_systems(&declare_output.iter().map(|o| o.class_hash).collect::<Vec<_>>())
.await
.unwrap();

let block_id = BlockId::Tag(BlockTag::Latest);
let grant_auth_role = world.system("GrantAuthRole", block_id).await.unwrap();
grant_auth_role
.execute(vec![executor_address, cairo_short_string_to_felt("Admin").unwrap()])
.await
.unwrap();

(world_address, executor_address)
}
79 changes: 0 additions & 79 deletions crates/torii/src/processors/component_state_update.rs

This file was deleted.

Loading