stratus/eth/primitives/
external_receipts.rs

1use std::collections::HashMap;
2
3use anyhow::anyhow;
4use fake::Dummy;
5use fake::Faker;
6
7use crate::eth::primitives::ExternalReceipt;
8use crate::eth::primitives::Hash;
9
10/// A collection of [`ExternalReceipt`].
11#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
12pub struct ExternalReceipts(HashMap<Hash, ExternalReceipt>);
13
14impl ExternalReceipts {
15    /// Tries to remove a receipt by its hash.
16    pub fn try_remove(&mut self, tx_hash: Hash) -> anyhow::Result<ExternalReceipt> {
17        match self.0.remove(&tx_hash) {
18            Some(receipt) => Ok(receipt),
19            None => {
20                tracing::error!(%tx_hash, "receipt is missing for hash");
21                Err(anyhow!("receipt missing for hash {}", tx_hash))
22            }
23        }
24    }
25}
26
27impl Dummy<Faker> for ExternalReceipts {
28    fn dummy_with_rng<R: rand::Rng + ?Sized>(faker: &Faker, rng: &mut R) -> Self {
29        let count = (rng.next_u32() % 5 + 1) as usize;
30        let receipts = (0..count).map(|_| ExternalReceipt::dummy_with_rng(faker, rng)).collect::<Vec<_>>();
31
32        Self::from(receipts)
33    }
34}
35
36// -----------------------------------------------------------------------------
37// Conversions: Other -> Self
38// -----------------------------------------------------------------------------
39
40impl From<Vec<ExternalReceipt>> for ExternalReceipts {
41    fn from(receipts: Vec<ExternalReceipt>) -> Self {
42        let mut receipts_by_hash = HashMap::with_capacity(receipts.len());
43        for receipt in receipts {
44            receipts_by_hash.insert(receipt.hash(), receipt);
45        }
46        Self(receipts_by_hash)
47    }
48}