From 564df5005fecc826c32adadaa77c38a5a7977511 Mon Sep 17 00:00:00 2001 From: Tom Date: Mon, 20 Oct 2025 11:03:38 +1100 Subject: [PATCH] apply_transition helper Adds helper function and trait for updating the latest block --- crates/app/src/lib.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index 427be63..e73003b 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -292,6 +292,14 @@ pub trait VoidStream: Stream { } } +/// Trait for updating the latest block height and hash in state. +pub trait UpdateLatestBlock { + /// Error type for update_latest_block. + type Error; + /// Update the latest block height and hash in state. + fn update_latest_block(&mut self, height: u64, hash: [u8; 32]) -> Result<(), Self::Error>; +} + impl VoidStream for T where T: Stream {} pin_project! { @@ -728,3 +736,32 @@ impl Default for Notification { Self::new() } } + +/// Apply a state transition function with a block and update state. +/// Updates the latest block height and hash in the state. +/// Derives T from the updated state. +/// Returns the height. +pub fn apply_transition( + block: Block, + state: &mut S, + state_transition_function: F, +) -> Result<(Block, Height), E> +where + F: FnOnce(&Block, &mut S) -> Result<(), Fe>, + T: for<'a> TryFrom<&'a mut S>, + E: From + + From<::Error> + + for<'a> From<>::Error>, + S: UpdateLatestBlock, +{ + state_transition_function(&block, state)?; + state.update_latest_block(block.height, void_hash::Hash::hash(&block))?; + let height = block.height; + Ok(( + block, + Height { + data: T::try_from(state)?, + block_height: height, + }, + )) +}