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

Torii wasm entities #67

Merged
merged 3 commits into from
Dec 1, 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
17 changes: 9 additions & 8 deletions packages/torii-wasm/crate/Cargo.lock

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

6 changes: 3 additions & 3 deletions packages/torii-wasm/crate/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ tokio = { version = "1.32.0", default-features = false, features = [ "rt" ] }
url = "2.4.0"

# Dojo
dojo-types = { git = "https://github.com/dojoengine/dojo", tag = "v0.3.13" }
torii-client = { git = "https://github.com/dojoengine/dojo", tag = "v0.3.13" }
torii-grpc = { git = "https://github.com/dojoengine/dojo", tag = "v0.3.13" }
dojo-types = { git = "https://github.com/dojoengine/dojo", rev = "9d207ba5b46227e6e2544e0b8a4988abbb263345" }
torii-client = { git = "https://github.com/dojoengine/dojo", rev = "9d207ba5b46227e6e2544e0b8a4988abbb263345" }
torii-grpc = { git = "https://github.com/dojoengine/dojo", rev = "9d207ba5b46227e6e2544e0b8a4988abbb263345" }

# WASM
js-sys = "0.3.64"
Expand Down
36 changes: 34 additions & 2 deletions packages/torii-wasm/crate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use std::str::FromStr;

use torii_grpc::types::KeysClause;
use torii_grpc::types::{KeysClause, Clause, Query};
use futures::StreamExt;
use starknet::core::types::FieldElement;
use starknet::core::utils::cairo_short_string_to_felt;
Expand All @@ -12,7 +12,7 @@ mod types;
mod utils;

use types::{ClientConfig, EntityModel, IEntityModel};
use utils::parse_ty_as_json_str;
use utils::{parse_ty_as_json_str, parse_entities_as_json_str};

type JsFieldElement = JsValue;

Expand All @@ -32,6 +32,38 @@ pub struct Client {

#[wasm_bindgen]
impl Client {
#[wasm_bindgen(js_name = getEntitiesByKeys)]
pub async fn get_entities_by_keys(
&self,
model: &str,
keys: Vec<JsFieldElement>,
limit: u32,
offset: u32
) -> Result<JsValue, JsValue> {
#[cfg(feature = "console-error-panic")]
console_error_panic_hook::set_once();

let keys = keys
.into_iter()
.map(serde_wasm_bindgen::from_value::<FieldElement>)
.collect::<Result<Vec<FieldElement>, _>>()
.map_err(|err| JsValue::from(format!("failed to parse entity keys: {err}")))?;

let results = self.inner.entities(Query {
clause: Clause::Keys(KeysClause {
model: model.to_string(),
keys
}),
limit,
offset
}).await;

match results {
Ok(entities) => Ok(js_sys::JSON::parse(&parse_entities_as_json_str(entities).to_string())?),
Err(err) => Err(JsValue::from(format!("failed to get entities: {err}"))),
}
}

/// Retrieves the model value of an entity. Will fetch from remote if the requested entity is not one of the entities that are being synced.
#[wasm_bindgen(js_name = getModelValue)]
pub async fn get_model_value(
Expand Down
121 changes: 119 additions & 2 deletions packages/torii-wasm/crate/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
use dojo_types::primitive::Primitive;
use dojo_types::schema::Ty;
use torii_grpc::types::Entity;
use serde_json::Value;

pub fn parse_entities_as_json_str(entities: Vec<Entity>) -> Value {
entities
.into_iter()
.map(|entity| {
let entity_key = format!("{:#x}", entity.key);
let models_map = entity
.models
.into_iter()
.map(|model| {
let model_map = model.members
.iter()
.map(|member| (member.name.to_owned(), parse_ty_as_json_str(&member.ty)))
.collect::<serde_json::Map<String, Value>>();

(model.name, model_map.into())
}).collect::<serde_json::Map<String, Value>>();

(entity_key, models_map.into())
}).collect::<serde_json::Map<String, Value>>()
.into()
}

pub fn parse_ty_as_json_str(ty: &Ty) -> Value {
match ty {
Ty::Primitive(primitive) => primitive_value_json(*primitive),
Expand Down Expand Up @@ -45,8 +68,10 @@ fn primitive_value_json(primitive: Primitive) -> Value {

#[cfg(test)]
mod test {
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);

use dojo_types::schema::{Enum, EnumOption, Member, Struct};
use torii_grpc::types::{Entity, Model};
use serde_json::json;
use starknet::macros::felt;
use wasm_bindgen_test::*;
Expand Down Expand Up @@ -125,7 +150,7 @@ mod test {
});

let actual_json = parse_ty_as_json_str(&expected_ty);
assert_eq!(expected_json.to_string(), actual_json)
assert_eq!(expected_json, actual_json)
}

#[wasm_bindgen_test]
Expand Down Expand Up @@ -194,6 +219,98 @@ mod test {
});

let actual_json = parse_ty_as_json_str(&expected_ty);
assert_eq!(expected_json.to_string(), actual_json)
assert_eq!(expected_json, actual_json)
}

#[wasm_bindgen_test]
fn parse_entity_to_value() {

let entity = Entity {
key: felt!("0x123"),
models: vec![
Model {
name: "position".into(),
members: vec![
Member {
name: "kind".into(),
key: false,
ty: Ty::Enum(Enum {
name: "PlayerKind".into(),
option: Some(1),
options: vec![
EnumOption {
name: "Good".into(),
ty: Ty::Tuple(vec![]),
},
EnumOption {
name: "Bad".into(),
ty: Ty::Tuple(vec![]),
},
],
}),
},
Member {
name: "vec".into(),
key: false,
ty: Ty::Struct(Struct {
name: "vec".into(),
children: vec![
Member {
name: "x".into(),
key: false,
ty: Ty::Primitive(Primitive::U128(Some(10))),
},
Member {
name: "y".into(),
key: false,
ty: Ty::Primitive(Primitive::U128(Some(10))),
},
],
}),
},
]
},
Model {
name: "stats".into(),
members: vec![
Member {
name: "health".into(),
key: false,
ty: Ty::Primitive(Primitive::U64(Some(42))),
},
Member {
name: "mana".into(),
key: false,
ty: Ty::Primitive(Primitive::U64(Some(69))),
},
Member {
name: "is_dead".into(),
key: false,
ty: Ty::Primitive(Primitive::Bool(Some(false))),
},
]
}
]
};

let expected_json = json!({
"0x123": {
"position" : {
"kind": "Bad",
"vec": {
"x": "0xa",
"y": "0xa",
}
},
"stats" : {
"health": 42,
"mana": 69,
"is_dead": false,
}
}
});

let actual_json = parse_entities_as_json_str(vec![entity]);
assert_eq!(expected_json, actual_json)
}
}
Loading