blueprint_tangle_extra/extract/
block_number.rs

1use blueprint_core::{
2    __composite_rejection as composite_rejection, __define_rejection as define_rejection,
3};
4use blueprint_core::{FromJobCallParts, job::call::Parts as JobCallParts};
5
6/// Extracts the current block number from the job call.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub struct BlockNumber(pub u32);
9
10impl BlockNumber {
11    pub const METADATA_KEY: &'static str = "X-TANGLE-BLOCK-NUMBER";
12}
13
14blueprint_core::__impl_deref!(BlockNumber: u32);
15blueprint_core::__impl_from!(u32, BlockNumber);
16
17define_rejection! {
18  #[body = "No BlockNumber found in the metadata"]
19  /// A Rejection type for [`BlockNumber`] when it is missing from the Metadata.
20  pub struct MissingBlockNumber;
21}
22
23define_rejection! {
24  #[body = "The block number in the metadata is not a valid integer"]
25  /// A Rejection type for [`BlockNumber`] when it is not a valid integer.
26  pub struct InvalidBlockNumber;
27}
28
29composite_rejection! {
30    /// Rejection used for [`BlockNumber`].
31    ///
32    /// Contains one variant for each way the [`Form`](super::Form) extractor
33    /// can fail.
34    pub enum BlockNumberRejection {
35        MissingBlockNumber,
36        InvalidBlockNumber,
37    }
38}
39
40impl TryFrom<&mut JobCallParts> for BlockNumber {
41    type Error = BlockNumberRejection;
42
43    fn try_from(parts: &mut JobCallParts) -> Result<Self, Self::Error> {
44        let block_number_raw = parts
45            .metadata
46            .get(Self::METADATA_KEY)
47            .ok_or(MissingBlockNumber)?;
48        let block_number = block_number_raw
49            .try_into()
50            .map_err(|_| InvalidBlockNumber)?;
51        Ok(BlockNumber(block_number))
52    }
53}
54
55impl<Ctx> FromJobCallParts<Ctx> for BlockNumber
56where
57    Ctx: Send + Sync,
58{
59    type Rejection = BlockNumberRejection;
60
61    async fn from_job_call_parts(
62        parts: &mut JobCallParts,
63        _: &Ctx,
64    ) -> Result<Self, Self::Rejection> {
65        Self::try_from(parts)
66    }
67}