ab_system_contract_block/
lib.rs

1#![no_std]
2
3use ab_contracts_common::block::{BlockHash, BlockNumber};
4use ab_contracts_common::env::Env;
5use ab_contracts_common::{Address, ContractError};
6use ab_contracts_io_type::trivial_type::TrivialType;
7use ab_contracts_macros::contract;
8
9#[derive(Debug, Copy, Clone, TrivialType)]
10#[repr(C)]
11pub struct Block {
12    pub number: BlockNumber,
13    pub parent_hash: BlockHash,
14}
15
16// TODO: Probably maintain a history of recent block headers and allow to extract them
17#[contract]
18impl Block {
19    /// Initialize block state at genesis
20    #[init]
21    pub fn genesis() -> Self {
22        Self {
23            number: 0,
24            parent_hash: BlockHash::default(),
25        }
26    }
27
28    /// Initialize new block
29    #[update]
30    pub fn initialize(
31        &mut self,
32        #[env] env: &mut Env<'_>,
33        #[input] &parent_hash: &BlockHash,
34    ) -> Result<(), ContractError> {
35        // Only execution environment can make a direct call here
36        if env.caller() != Address::NULL {
37            return Err(ContractError::Forbidden);
38        }
39
40        *self = Self {
41            number: self.number + 1,
42            parent_hash,
43        };
44
45        Ok(())
46    }
47
48    #[view]
49    pub fn get(&self) -> Self {
50        *self
51    }
52}