Skip to content

Commit

Permalink
Refactor the code
Browse files Browse the repository at this point in the history
  • Loading branch information
boundless-forest committed Apr 26, 2024
1 parent be88e86 commit 5807775
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 42 deletions.
4 changes: 2 additions & 2 deletions client/api/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ pub trait Backend<Block: BlockT>: Send + Sync {
self.log_indexer().is_indexed()
}

/// Get the latest substrate block hash.
async fn latest_block(&self) -> Block::Hash;
/// Get the latest substrate block hash in the sql database.
async fn best_hash(&self) -> Result<Block::Hash, String>;
}

#[derive(Debug, Eq, PartialEq)]
Expand Down
4 changes: 2 additions & 2 deletions client/db/src/kv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ impl<Block: BlockT, C: HeaderBackend<Block>> fc_api::Backend<Block> for Backend<
&self.log_indexer
}

async fn latest_block(&self) -> Block::Hash {
self.client.info().best_hash
async fn best_hash(&self) -> Result<Block::Hash, String> {
Ok(self.client.info().best_hash)
}
}

Expand Down
39 changes: 13 additions & 26 deletions client/db/src/sql/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -694,28 +694,6 @@ where
None
}

/// Retrieves the block hash for the latest indexed block, maybe it's not canon.
pub async fn last_indexed_block(&self) -> Result<H256, Error> {
let row = sqlx::query(
"SELECT b.substrate_block_hash FROM blocks AS b
INNER JOIN sync_status AS s
ON s.substrate_block_hash = b.substrate_block_hash
WHERE s.status = 1
ORDER BY b.block_number DESC LIMIT 1",
)
.fetch_one(self.pool())
.await?;

let latest_block_hash =
H256::from_slice(&row.try_get::<Vec<u8>, _>(0).unwrap_or_default()[..]);

log::debug!(target: "bear", "Try fetch last indexed block: {:?}", latest_block_hash);

Ok(H256::from_slice(
&row.try_get::<Vec<u8>, _>(0).unwrap_or_default()[..],
))
}

/// Retrieve the block hash for the last indexed canon block.
pub async fn last_indexed_canon_block(&self) -> Result<H256, Error> {
let row = sqlx::query(
Expand Down Expand Up @@ -886,10 +864,19 @@ impl<Block: BlockT<Hash = H256>> fc_api::Backend<Block> for Backend<Block> {
self
}

async fn latest_block(&self) -> Block::Hash {
let hash = self.last_indexed_block().await.unwrap_or_default();
log::debug!(target: "bear", "Try fetch the latest block hash: {:?}", hash);
hash
async fn best_hash(&self) -> Result<Block::Hash, String> {
// Retrieves the block hash for the latest indexed block, maybe it's not canon.
sqlx::query(
"SELECT b.substrate_block_hash FROM blocks AS b
INNER JOIN sync_status AS s
ON s.substrate_block_hash = b.substrate_block_hash
WHERE s.status = 1
ORDER BY b.block_number DESC LIMIT 1",
)
.fetch_one(self.pool())
.await
.map(|row| H256::from_slice(&row.get::<Vec<u8>, _>(0)[..]))
.map_err(|e| format!("Failed to fetch best hash: {}", e))
}
}

Expand Down
13 changes: 11 additions & 2 deletions client/rpc/src/eth/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ where
number_or_hash: BlockNumberOrHash,
full: bool,
) -> RpcResult<Option<RichBlock>> {
log::debug!(target: "bear", "RPC request: block_by_number: {:?}, full: {}", number_or_hash, full);
let client = Arc::clone(&self.client);
let backend = Arc::clone(&self.backend);
let block_data_cache = Arc::clone(&self.block_data_cache);
Expand All @@ -100,9 +101,11 @@ where
.await?
{
Some(id) => {
log::debug!(target: "bear", "RPC response id: {:?}", id);
let substrate_hash = client
.expect_block_hash_from_id(&id)
.map_err(|_| internal_err(format!("Expect block number from id: {}", id)))?;
log::debug!(target: "bear", "RPC response substrate_hash: {:?}", substrate_hash);

let schema = fc_storage::onchain_storage_schema(client.as_ref(), substrate_hash);

Expand Down Expand Up @@ -136,7 +139,10 @@ where

Ok(Some(rich_block))
}
_ => Ok(None),
_ => {
log::debug!(target: "bear", "RPC response, failed to get block information");
Ok(None)
}
}
}
None if number_or_hash == BlockNumberOrHash::Pending => {
Expand Down Expand Up @@ -182,7 +188,10 @@ where
_ => Ok(None),
}
}
None => Ok(None),
None => {
log::debug!(target: "bear", "RPC response: None");
Ok(None)
}
}
}

Expand Down
26 changes: 16 additions & 10 deletions client/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,21 +197,27 @@ pub mod frontier_backend_client {
B: BlockT,
C: HeaderBackend<B> + 'static,
{
Ok(match number.unwrap_or(BlockNumberOrHash::Latest) {
match number.unwrap_or(BlockNumberOrHash::Latest) {
BlockNumberOrHash::Hash { hash, .. } => {
if let Ok(Some(hash)) = load_hash::<B, C>(client, backend, hash).await {
Some(BlockId::Hash(hash))
Ok(Some(BlockId::Hash(hash)))
} else {
None
Ok(None)
}
}
BlockNumberOrHash::Num(number) => Some(BlockId::Number(number.unique_saturated_into())),
BlockNumberOrHash::Latest => Some(BlockId::Hash(backend.latest_block().await)),
BlockNumberOrHash::Earliest => Some(BlockId::Number(Zero::zero())),
BlockNumberOrHash::Pending => None,
BlockNumberOrHash::Safe => Some(BlockId::Hash(client.info().finalized_hash)),
BlockNumberOrHash::Finalized => Some(BlockId::Hash(client.info().finalized_hash)),
})
BlockNumberOrHash::Num(number) => {
Ok(Some(BlockId::Number(number.unique_saturated_into())))
}
BlockNumberOrHash::Latest => backend
.best_hash()
.await
.map(|hash| Some(BlockId::Hash(hash)))
.map_err(|err| internal_err(format!("fetch to fetch the best hash: {:?}", err))),
BlockNumberOrHash::Earliest => Ok(Some(BlockId::Number(Zero::zero()))),
BlockNumberOrHash::Pending => Ok(None),
BlockNumberOrHash::Safe => Ok(Some(BlockId::Hash(client.info().finalized_hash))),
BlockNumberOrHash::Finalized => Ok(Some(BlockId::Hash(client.info().finalized_hash))),
}
}

pub async fn load_hash<B: BlockT, C>(
Expand Down

0 comments on commit 5807775

Please sign in to comment.