Skip to content

Commit

Permalink
fix sync loop
Browse files Browse the repository at this point in the history
  • Loading branch information
kariy committed Sep 28, 2023
1 parent b64e5aa commit 00dd22a
Showing 1 changed file with 15 additions and 23 deletions.
38 changes: 15 additions & 23 deletions crates/torii/core/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::error::Error;
use std::time::Duration;

use starknet::core::types::{
BlockId, BlockTag, BlockWithTxs, Event, InvokeTransaction, InvokeTransactionReceipt,
BlockId, BlockWithTxs, Event, InvokeTransaction, InvokeTransactionReceipt,
MaybePendingBlockWithTxs, MaybePendingTransactionReceipt, Transaction, TransactionReceipt,
};
use starknet::core::utils::get_selector_from_name;
Expand Down Expand Up @@ -65,47 +65,39 @@ where
}

pub async fn start(&self, cts: CancellationToken) -> Result<(), Box<dyn Error>> {
let db_head = self.db.head().await?;

let current_block_number = match db_head {
0 => self.config.start_block,
_ => {
if self.config.start_block != 0 {
warn!("start block ignored, stored head exists and will be used instead");
}
db_head
}
};
if self.db.head().await? == 0 {
self.db.set_head(self.config.start_block).await?;
} else if self.config.start_block != 0 {
warn!("start block ignored, stored head exists and will be used instead");
}

loop {
if cts.is_cancelled() {
break Ok(());
}

sleep(self.config.block_time).await;
match self.sync_to_head(current_block_number).await {
let head = self.db.head().await?;
match self.sync_to_head(head).await {
Ok(block_with_txs) => block_with_txs,
Err(e) => {
error!("getting block: {}", e);
continue;
}
};

sleep(self.config.block_time).await;
}
}

pub async fn sync_to_head(&self, from: u64) -> Result<u64, Box<dyn Error>> {
let latest_block_with_txs =
self.provider.get_block_with_txs(BlockId::Tag(BlockTag::Latest)).await?;
let latest_block_number = self.provider.block_hash_and_number().await?.block_number;

let latest_block_number = match latest_block_with_txs {
MaybePendingBlockWithTxs::Block(latest_block_with_txs) => {
latest_block_with_txs.block_number
}
_ => return Err(anyhow::anyhow!("Getting latest block number").into()),
if from < latest_block_number {
// if `from` == 0, then the block may or may not be processed yet.
let from = if from == 0 { from } else { from + 1 };
self.sync_range(from, latest_block_number).await?;
};

self.sync_range(from, latest_block_number).await?;

Ok(latest_block_number)
}

Expand Down

0 comments on commit 00dd22a

Please sign in to comment.