Skip to content

Commit

Permalink
Initialize torii server from remote
Browse files Browse the repository at this point in the history
  • Loading branch information
tarrencev committed Oct 2, 2023
1 parent 1aef1a9 commit 5091c78
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 309 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.

1 change: 1 addition & 0 deletions crates/torii/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ slab = "0.4.2"
sqlx = { version = "0.6.2", features = [ "chrono", "macros", "offline", "runtime-actix-rustls", "sqlite", "uuid" ] }
starknet-crypto.workspace = true
starknet.workspace = true
thiserror.workspace = true
tokio = { version = "1.32.0", features = [ "sync" ], default-features = true }
tokio-stream = "0.1.11"
tokio-util = "0.7.7"
Expand Down
12 changes: 6 additions & 6 deletions crates/torii/core/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,9 @@ where
}

pub async fn start(&mut self, cts: CancellationToken) -> Result<(), Box<dyn Error>> {
if self.db.head().await? == 0 {
self.db.set_head(self.config.start_block).await?;
let mut head = self.db.head().await?;
if head == 0 {
head = self.config.start_block;
} else if self.config.start_block != 0 {
warn!("start block ignored, stored head exists and will be used instead");
}
Expand All @@ -79,9 +80,8 @@ where
break Ok(());
}

let head = self.db.head().await?;
match self.sync_to_head(head).await {
Ok(block_with_txs) => block_with_txs,
Ok(latest_block_number) => head = latest_block_number,
Err(e) => {
error!("getting block: {}", e);
continue;
Expand Down Expand Up @@ -123,7 +123,7 @@ where

self.process(block_with_txs).await?;

self.db.set_head(from).await?;
self.db.set_head(from);
self.db.execute().await?;
from += 1;
}
Expand Down Expand Up @@ -237,7 +237,7 @@ async fn process_event<P: Provider + Sync>(
event: &Event,
event_idx: usize,
) -> Result<(), Box<dyn Error>> {
db.store_event(event, event_idx, invoke_receipt.transaction_hash).await?;
db.store_event(event, event_idx, invoke_receipt.transaction_hash);

for processor in processors {
if get_selector_from_name(&processor.event_key())? == event.keys[0] {
Expand Down
1 change: 1 addition & 0 deletions crates/torii/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod simple_broker;
pub mod sql;
pub mod types;

#[allow(dead_code)]
#[derive(FromRow, Deserialize)]
pub struct World {
#[sqlx(try_from = "String")]
Expand Down
58 changes: 6 additions & 52 deletions crates/torii/core/src/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use anyhow::{anyhow, Result};
use chrono::{DateTime, Utc};
use dojo_types::primitive::Primitive;
use dojo_types::schema::Ty;
use dojo_world::manifest::{Manifest, System};
use dojo_world::manifest::System;
use sqlx::pool::PoolConnection;
use sqlx::{Executor, Pool, Row, Sqlite};
use starknet::core::types::{Event, FieldElement};
Expand Down Expand Up @@ -48,30 +48,6 @@ impl Sql {
Ok(Self { pool, world_address, query_queue: vec![] })
}

pub async fn load_from_manifest(&mut self, manifest: Manifest) -> Result<()> {
let mut updates = vec![
format!("world_address = '{:#x}'", self.world_address),
format!("world_class_hash = '{:#x}'", manifest.world.class_hash),
format!("executor_class_hash = '{:#x}'", manifest.executor.class_hash),
];

if let Some(executor_address) = manifest.executor.address {
updates.push(format!("executor_address = '{:#x}'", executor_address));
}

self.query_queue.push(format!(
"UPDATE worlds SET {} WHERE id = '{:#x}'",
updates.join(","),
self.world_address
));

for system in manifest.systems {
self.register_system(system).await?;
}

self.execute().await
}

pub async fn head(&self) -> Result<u64> {
let mut conn: PoolConnection<Sqlite> = self.pool.acquire().await?;
let indexer: (i64,) = sqlx::query_as(&format!(
Expand All @@ -83,12 +59,11 @@ impl Sql {
Ok(indexer.0.try_into().expect("doesnt fit in u64"))
}

pub async fn set_head(&mut self, head: u64) -> Result<()> {
pub fn set_head(&mut self, head: u64) {
self.query_queue.push(format!(
"UPDATE indexers SET head = {head} WHERE id = '{:#x}'",
self.world_address
));
Ok(())
}

pub async fn world(&self) -> Result<World> {
Expand All @@ -101,19 +76,6 @@ impl Sql {
Ok(meta)
}

pub async fn set_world(&mut self, world: World) -> Result<()> {
self.query_queue.push(format!(
"UPDATE worlds SET world_address='{:#x}', world_class_hash='{:#x}', \
executor_address='{:#x}', executor_class_hash='{:#x}' WHERE id = '{:#x}'",
world.world_address,
world.world_class_hash,
world.executor_address,
world.executor_class_hash,
world.world_address,
));
Ok(())
}

pub async fn register_model(
&mut self,
model: Ty,
Expand Down Expand Up @@ -218,10 +180,9 @@ impl Sql {
Ok(())
}

pub async fn delete_entity(&mut self, model: String, key: FieldElement) -> Result<()> {
pub fn delete_entity(&mut self, model: String, key: FieldElement) {
let query = format!("DELETE FROM {model} WHERE id = {key}");
self.query_queue.push(query);
Ok(())
}

pub async fn entity(&self, model: String, key: FieldElement) -> Result<Vec<FieldElement>> {
Expand All @@ -239,12 +200,12 @@ impl Sql {
Ok(rows.drain(..).map(|row| serde_json::from_str(&row.2).unwrap()).collect())
}

pub async fn store_system_call(
pub fn store_system_call(
&mut self,
system: String,
transaction_hash: FieldElement,
calldata: &[FieldElement],
) -> Result<()> {
) {
let query = format!(
"INSERT OR IGNORE INTO system_calls (data, transaction_hash, system_id) VALUES ('{}', \
'{:#x}', '{}')",
Expand All @@ -253,15 +214,9 @@ impl Sql {
system
);
self.query_queue.push(query);
Ok(())
}

pub async fn store_event(
&mut self,
event: &Event,
event_idx: usize,
transaction_hash: FieldElement,
) -> Result<()> {
pub fn store_event(&mut self, event: &Event, event_idx: usize, transaction_hash: FieldElement) {
let keys_str = felts_sql_string(&event.keys);
let data_str = felts_sql_string(&event.data);

Expand All @@ -273,7 +228,6 @@ impl Sql {
);

self.query_queue.push(query);
Ok(())
}

fn build_register_queries_recursive(
Expand Down
Loading

0 comments on commit 5091c78

Please sign in to comment.