use super::*;
use crate::ledger::{Block, Hash};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BlockState {
Confirmed,
Finalized,
}
impl BlockState {
const BLOCK_CONFIRMED: &'static str = "confirmed";
const BLOCK_FINALIZED: &'static str = "finalized";
pub const fn as_str(&self) -> &'static str {
match self {
Self::Confirmed => Self::BLOCK_CONFIRMED,
Self::Finalized => Self::BLOCK_FINALIZED,
}
}
}
#[derive(Clone, Debug)]
pub enum BlockEvent<'b> {
Accepted(&'b Block),
StateChange {
hash: Hash,
state: BlockState,
height: u64,
},
Reverted {
hash: Hash,
height: u64,
},
}
impl EventSource for BlockEvent<'_> {
const COMPONENT: &'static str = "blocks";
fn topic(&self) -> &'static str {
match self {
Self::Accepted(_) => "accepted",
Self::StateChange { .. } => "statechange",
Self::Reverted { .. } => "reverted",
}
}
fn data(&self) -> Option<serde_json::Value> {
let data = match self {
Self::Accepted(b) => {
let header = b.header();
let header = serde_json::to_value(header)
.expect("json to be serialized");
let txs: Vec<_> =
b.txs().iter().map(|t| hex::encode(t.id())).collect();
serde_json::json!({
"header": header,
"transactions": txs,
})
}
Self::StateChange { state, height, .. } => {
serde_json::json!({
"state": state.as_str(),
"atHeight": height,
})
}
BlockEvent::Reverted { height, .. } => {
serde_json::json!({
"atHeight": height,
})
}
};
Some(data)
}
fn entity(&self) -> String {
let hash = match self {
Self::Accepted(block) => block.header().hash,
Self::StateChange { hash, .. } => *hash,
Self::Reverted { hash, .. } => *hash,
};
hex::encode(hash)
}
}