Skip to main content

hyli_client_sdk/
light_executor.rs

1use anyhow::Result;
2use borsh::BorshDeserialize;
3use sdk::{BlobIndex, BlobTransaction, StructuredBlob, TxContext};
4
5pub struct LightExecutorOutput {
6    pub success: bool,
7    pub program_outputs: Vec<u8>,
8}
9
10/// Defines convenience methods for handling light contract execution with minimal overhead.
11pub trait LightContractExecutor<'tx, 'extra_data> {
12    type Scratchpad;
13    type ExtraData;
14
15    /// Prepares for executing a transaction, returning any data necessary to revert/commit changes.
16    fn prepare_for_tx(
17        &mut self,
18        tx: &'tx BlobTransaction,
19        index: BlobIndex,
20        tx_ctx: Option<&'tx TxContext>,
21        extra_data: Self::ExtraData,
22    ) -> Result<Self::Scratchpad>;
23
24    /// Handles the execution of a transaction, returning the output of the execution.
25    fn handle_blob(
26        &mut self,
27        tx: &'tx BlobTransaction,
28        index: BlobIndex,
29        tx_ctx: Option<&'tx TxContext>,
30        extra_data: Self::ExtraData,
31    ) -> Result<LightExecutorOutput>;
32
33    /// Should be called after a transaction fails, allowing the executor to revert side effects.
34    fn on_failure(&mut self, scratchpad: Self::Scratchpad) -> Result<()>;
35
36    /// Should be called after a transaction succeeds, allowing the executor to commit side effects.
37    fn on_success(&mut self, scratchpad: Self::Scratchpad) -> Result<()>;
38}
39
40/// Variant of parse_structured_blob that returns a structured blob from a transaction.
41pub fn parse_structured_blob_from_tx<Action>(
42    tx: &BlobTransaction,
43    index: BlobIndex,
44) -> Option<StructuredBlob<Action>>
45where
46    Action: BorshDeserialize,
47{
48    let blob = match tx.blobs.get(index.0) {
49        Some(v) => v,
50        None => {
51            return None;
52        }
53    };
54
55    let parsed_blob: StructuredBlob<Action> = match StructuredBlob::try_from(blob.clone()) {
56        Ok(v) => v,
57        Err(_) => {
58            return None;
59        }
60    };
61    Some(parsed_blob)
62}