kona_protocol/batch/
tx.rs

1//! Transaction Types
2
3use crate::Frame;
4use alloc::vec::Vec;
5use alloy_primitives::Bytes;
6
7/// BatchTransaction is a set of [Frame]s that can be [Into::into] [Bytes].
8/// if the size exceeds the desired threshold.
9#[derive(Debug, Clone)]
10pub struct BatchTransaction {
11    /// The frames in the batch.
12    pub frames: Vec<Frame>,
13    /// The size of the potential transaction.
14    pub size: usize,
15}
16
17impl BatchTransaction {
18    /// Returns the size of the transaction.
19    pub const fn size(&self) -> usize {
20        self.size
21    }
22
23    /// Returns if the transaction has reached the max frame count.
24    pub fn is_full(&self, max_frames: u16) -> bool {
25        self.frames.len() as u16 >= max_frames
26    }
27
28    /// Returns the [BatchTransaction] as a [Bytes].
29    pub fn to_bytes(&self) -> Bytes {
30        self.frames
31            .iter()
32            .fold(Vec::new(), |mut acc, frame| {
33                acc.append(&mut frame.encode());
34                acc
35            })
36            .into()
37    }
38}
39
40#[cfg(test)]
41mod test {
42    use super::*;
43    use alloc::vec;
44
45    #[test]
46    fn test_batch_transaction() {
47        let frame = Frame { id: [0xFF; 16], number: 0xEE, data: vec![0xDD; 50], is_last: true };
48        let batch = BatchTransaction { frames: vec![frame.clone(); 5], size: 5 * frame.size() };
49        let bytes: Bytes = batch.to_bytes();
50        let bytes =
51            [crate::DERIVATION_VERSION_0].iter().chain(bytes.iter()).copied().collect::<Vec<_>>();
52        let frames = Frame::parse_frames(&bytes).unwrap();
53        assert_eq!(frames, vec![frame; 5]);
54    }
55}