Skip to content

Commit

Permalink
Remove partitions
Browse files Browse the repository at this point in the history
  • Loading branch information
tarrencev committed Aug 5, 2023
1 parent 991e5b3 commit 66c9851
Show file tree
Hide file tree
Showing 25 changed files with 134 additions and 195 deletions.
38 changes: 11 additions & 27 deletions crates/dojo-client/src/contract/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,29 +80,27 @@ impl<'a, P: Provider + Sync> ComponentReader<'a, P> {
.map_err(ComponentError::ContractReaderError)?;

let mut members = vec![];
for chunk in res[3..].chunks(4) {
if chunk.len() != 4 {
for chunk in res[3..].chunks(3) {
if chunk.len() != 3 {
return Err(ComponentError::InvalidSchemaLength);
}

let is_key: u8 = chunk[2].try_into().map_err(|_| ComponentError::ConvertingFelt)?;

members.push(Member {
name: parse_cairo_short_string(&chunk[0])
.map_err(ComponentError::ParseCairoShortStringError)?,
ty: parse_cairo_short_string(&chunk[1])
.map_err(ComponentError::ParseCairoShortStringError)?,
slot: chunk[2].try_into().map_err(|_| ComponentError::ConvertingFelt)?,
offset: chunk[3].try_into().map_err(|_| ComponentError::ConvertingFelt)?,
key: is_key == 1,
});
}

Ok(members)
}

pub async fn length(
&self,
block_id: BlockId,
) -> Result<FieldElement, ComponentError<P::Error>> {
let entrypoint = get_selector_from_name("length").unwrap();
pub async fn size(&self, block_id: BlockId) -> Result<FieldElement, ComponentError<P::Error>> {
let entrypoint = get_selector_from_name("size").unwrap();

let res = self
.world
Expand All @@ -119,30 +117,16 @@ impl<'a, P: Provider + Sync> ComponentReader<'a, P> {

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

let table = if partition_id == FieldElement::ZERO {
self.name
} else {
poseidon_hash_many(&[self.name, partition_id])
};

let id = if keys.len() == 1 {
keys[0]
} else {
let mut keys = keys;
keys.insert(0, keys.len().into());
poseidon_hash_many(&keys)
};
let size: u8 = self.size(block_id).await?.try_into().unwrap();

let key = poseidon_hash_many(&[short_string!("dojo_storage"), table, id]);
let key = poseidon_hash_many(&keys);
let key = poseidon_hash_many(&[short_string!("dojo_storage"), self.name, key]);

let mut values = vec![];
for slot in 0..length {
for slot in 0..size {
let value = self
.world
.provider
Expand Down
7 changes: 4 additions & 3 deletions crates/dojo-client/src/contract/component_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async fn test_component() {
assert_eq!(
component.class_hash(),
FieldElement::from_hex_be(
"0x02da8fb6056624dd6fa7070497350a13914a21e2a53f171271f72721c5448912"
"0x04caa1806451739b6fb470652b8066a11f80e847d49003b43cca75a2fd7647b6"
)
.unwrap()
);
Expand All @@ -38,8 +38,9 @@ async fn test_component() {
assert_eq!(
members,
vec![
Member { name: "x".into(), ty: "u32".into(), slot: 0, offset: 0 },
Member { name: "y".into(), ty: "u32".into(), slot: 1, offset: 0 }
Member { name: "player".into(), ty: "ContractAddress".into(), key: true },
Member { name: "x".into(), ty: "u32".into(), key: false },
Member { name: "y".into(), ty: "u32".into(), key: false }
]
)
}
13 changes: 4 additions & 9 deletions crates/dojo-client/src/contract/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,6 @@ impl<'a, A: ConnectedAccount + Sync> System<'a, A> {
self.reader.call(calldata, block_id).await.map_err(SystemError::ReaderError)
}

pub async fn dependencies(
&self,
block_id: BlockId,
) -> Result<Vec<Dependency>, SystemError<A::SignError, <A::Provider as Provider>::Error>> {
self.reader.dependencies(block_id).await.map_err(SystemError::ReaderError)
}

pub async fn execute(
&self,
calldata: Vec<FieldElement>,
Expand Down Expand Up @@ -115,8 +108,10 @@ impl<'a, P: Provider + Sync> SystemReader<'a, P> {
.call(
FunctionCall {
contract_address: world.address,
calldata: vec![cairo_short_string_to_felt(&name)
.map_err(SystemReaderError::CairoShortStringToFeltError)?],
calldata: vec![
cairo_short_string_to_felt(&name)
.map_err(SystemReaderError::CairoShortStringToFeltError)?,
],
entry_point_selector: get_selector_from_name("system").unwrap(),
},
block_id,
Expand Down
20 changes: 3 additions & 17 deletions crates/dojo-client/src/contract/system_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use camino::Utf8PathBuf;
use dojo_test_utils::sequencer::{
get_default_test_starknet_config, SequencerConfig, TestSequencer,
};
use dojo_types::system::Dependency;
use starknet::accounts::Account;
use starknet::core::types::{BlockId, BlockTag};
use starknet_crypto::FieldElement;
Expand All @@ -24,20 +23,11 @@ async fn test_system() {
let block_id: BlockId = BlockId::Tag(BlockTag::Latest);
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();
let moves = component.entity(vec![account.address()], block_id).await.unwrap();

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

Expand All @@ -46,17 +36,13 @@ async fn test_system() {
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();
let moves = component.entity(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();
let position = position_component.entity(vec![account.address()], block_id).await.unwrap();

assert_eq!(position, vec![1_u8.into(), 1_u8.into()]);
}
41 changes: 35 additions & 6 deletions crates/dojo-lang/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@ pub fn handle_component_struct(
.members(db)
.elements(db)
.iter()
.enumerate()
.map(|(slot, member)| {
(member.name(db).text(db), member.type_clause(db).ty(db), slot as u64, 0)
.map(|member| {
(member.name(db).text(db), member.type_clause(db).ty(db), member.has_attr(db, "key"))
})
.collect::<_>();

Expand Down Expand Up @@ -104,16 +103,38 @@ pub fn handle_component_struct(
})
.collect::<_>();

let schema = elements
.iter()
.map(|member| {
RewriteNode::interpolate_patched(
"array::ArrayTrait::append(ref arr, ('$name$', '$typ$', $is_key$));",
UnorderedHashMap::from([
(
"name".to_string(),
RewriteNode::new_trimmed(member.name(db).as_syntax_node()),
),
(
"typ".to_string(),
RewriteNode::new_trimmed(member.type_clause(db).ty(db).as_syntax_node()),
),
(
"is_key".to_string(),
RewriteNode::Text(member.has_attr(db, "key").to_string()),
),
]),
)
})
.collect::<_>();

let name = struct_ast.name(db).text(db);
aux_data.components.push(Component {
name: name.to_string(),
members: members
.iter()
.map(|(name, ty, slot, offset)| Member {
.map(|(name, ty, key)| Member {
name: name.to_string(),
ty: ty.as_syntax_node().get_text(db).trim().to_string(),
slot: *slot,
offset: *offset,
key: *key,
})
.collect(),
});
Expand Down Expand Up @@ -167,6 +188,13 @@ pub fn handle_component_struct(
fn size(self: @ContractState) -> usize {
dojo::SerdeLen::<$type_name$>::len()
}
#[external(v0)]
fn schema(self: @ContractState) -> Array<(felt252, felt252, bool)> {
let mut arr = array::ArrayTrait::new();
$schema$
arr
}
}
",
UnorderedHashMap::from([
Expand All @@ -190,6 +218,7 @@ pub fn handle_component_struct(
"component_serialized_values".to_string(),
RewriteNode::new_modified(component_serialized_values),
),
("schema".to_string(), RewriteNode::new_modified(schema)),
]),
),
diagnostics,
Expand Down
25 changes: 25 additions & 0 deletions crates/dojo-lang/src/plugin_test_data/component
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,15 @@ mod position {
fn size(self: @ContractState) -> usize {
dojo::SerdeLen::<Position>::len()
}

#[external(v0)]
fn schema(self: @ContractState) -> Array<(felt252, felt252, bool)> {
let mut arr = array::ArrayTrait::new();
array::ArrayTrait::append(ref arr, ('id', 'felt252', true));
array::ArrayTrait::append(ref arr, ('x', 'felt252', false));
array::ArrayTrait::append(ref arr, ('y', 'felt252', false));
arr
}
}

impl SerdeLenPosition of dojo::SerdeLen<Position> {
Expand Down Expand Up @@ -187,6 +196,13 @@ mod roles {
fn size(self: @ContractState) -> usize {
dojo::SerdeLen::<Roles>::len()
}

#[external(v0)]
fn schema(self: @ContractState) -> Array<(felt252, felt252, bool)> {
let mut arr = array::ArrayTrait::new();
array::ArrayTrait::append(ref arr, ('role_ids', 'Array<u8>', false));
arr
}
}


Expand Down Expand Up @@ -254,6 +270,15 @@ mod player {
fn size(self: @ContractState) -> usize {
dojo::SerdeLen::<Player>::len()
}

#[external(v0)]
fn schema(self: @ContractState) -> Array<(felt252, felt252, bool)> {
let mut arr = array::ArrayTrait::new();
array::ArrayTrait::append(ref arr, ('game', 'felt252', true));
array::ArrayTrait::append(ref arr, ('player', 'ContractAddress', true));
array::ArrayTrait::append(ref arr, ('name', 'felt252', false));
arr
}
}

impl SerdeLenPlayer of dojo::SerdeLen<Player> {
Expand Down
3 changes: 1 addition & 2 deletions crates/dojo-types/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,5 @@ pub struct Member {
/// Type of the member.
#[serde(rename = "type")]
pub ty: String,
pub slot: u64,
pub offset: u8,
pub key: bool,
}
1 change: 0 additions & 1 deletion crates/dojo-types/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ use starknet::core::types::FieldElement;
#[derive(Clone, Debug)]
pub struct Query {
pub address_domain: u32,
pub partition: FieldElement,
pub keys: Vec<FieldElement>,
}
4 changes: 0 additions & 4 deletions crates/sozo/src/commands/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,6 @@ pub enum ComponentCommands {
#[arg(help = "Comma seperated values e.g., 0x12345,0x69420,...")]
keys: Vec<FieldElement>,

#[arg(long = "partition_id", default_value = "0x0")]
#[arg(help = "Entity query partition id.")]
partition_id: FieldElement,

#[command(flatten)]
world: WorldOptions,

Expand Down
5 changes: 2 additions & 3 deletions crates/sozo/src/ops/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,14 @@ pub async fn execute(command: ComponentCommands, env_metadata: Option<Value>) ->
}
}

ComponentCommands::Entity { name, partition_id, keys, starknet, world, .. } => {
ComponentCommands::Entity { name, keys, starknet, world, .. } => {
let world_address = world.address(env_metadata.as_ref())?;
let provider = starknet.provider(env_metadata.as_ref())?;

let world = WorldContractReader::new(world_address, &provider);
let component = world.component(&name, BlockId::Tag(BlockTag::Pending)).await?;

let entity =
component.entity(partition_id, keys, BlockId::Tag(BlockTag::Pending)).await?;
let entity = component.entity(keys, BlockId::Tag(BlockTag::Pending)).await?;

println!(
"{}",
Expand Down
12 changes: 2 additions & 10 deletions crates/sozo/src/ops/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,15 @@ pub async fn execute(command: SystemCommands, env_metadata: Option<Value>) -> Re
.iter()
.enumerate()
.filter_map(|(i, d)| {
if d.read {
Some(format!("{}.{}", i + 1, d.name.clone()))
} else {
None
}
if d.read { Some(format!("{}.{}", i + 1, d.name.clone())) } else { None }
})
.collect::<Vec<_>>();

let write = deps
.iter()
.enumerate()
.filter_map(|(i, d)| {
if d.write {
Some(format!("{}. {}", i + 1, d.name.clone()))
} else {
None
}
if d.write { Some(format!("{}. {}", i + 1, d.name.clone())) } else { None }
})
.collect::<Vec<_>>();

Expand Down
5 changes: 1 addition & 4 deletions crates/torii/migrations/20230316154230_setup.sql
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ CREATE TABLE component_members(
component_id TEXT NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL,
slot INTEGER NOT NULL,
offset INTEGER NOT NULL,
key BOOLEAN NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (component_id, name),
FOREIGN KEY (component_id) REFERENCES components(id)
Expand Down Expand Up @@ -57,14 +56,12 @@ CREATE INDEX idx_systems_created_at ON systems (created_at);

CREATE TABLE entities (
id TEXT NOT NULL PRIMARY KEY,
partition TEXT NOT NULL,
keys TEXT,
component_names TEXT,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_entities_partition ON entities (partition);
CREATE INDEX idx_entities_keys ON entities (keys);
CREATE INDEX idx_entities_keys_create_on ON entities (keys, created_at);

Expand Down
Loading

0 comments on commit 66c9851

Please sign in to comment.