ab_system_contract_state/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#![no_std]

use ab_contracts_common::env::Env;
use ab_contracts_common::{Address, ContractError};
use ab_contracts_io_type::trivial_type::TrivialType;
use ab_contracts_io_type::variable_bytes::VariableBytes;
use ab_contracts_macros::contract;

// TODO: How/where should this limit defined?
pub const MAX_STATE_SIZE: u32 = 1024 * 1024;

#[derive(Copy, Clone, TrivialType)]
#[repr(C)]
pub struct State;

#[contract]
impl State {
    /// Write contract's state
    #[update]
    pub fn write(
        #[env] env: &mut Env,
        #[slot] (address, contract_state): (&Address, &mut VariableBytes<MAX_STATE_SIZE>),
        #[input] new_state: &VariableBytes<MAX_STATE_SIZE>,
    ) -> Result<(), ContractError> {
        // TODO: Check shard
        if env.caller() != address {
            return Err(ContractError::AccessDenied);
        }

        if !contract_state.copy_from(new_state) {
            return Err(ContractError::InvalidInput);
        }

        Ok(())
    }

    /// Read contract's state
    #[view]
    pub fn read(
        #[slot] contract_state: &VariableBytes<MAX_STATE_SIZE>,
        #[output] state: &mut VariableBytes<MAX_STATE_SIZE>,
    ) -> Result<(), ContractError> {
        if state.copy_from(contract_state) {
            Ok(())
        } else {
            Err(ContractError::InvalidInput)
        }
    }

    /// Check if contract's state is empty
    #[view]
    pub fn is_empty(#[slot] contract_state: &VariableBytes<MAX_STATE_SIZE>) -> bool {
        contract_state.size() == 0
    }
}