casperlabs_contract_utils/
contract_context.rs

1use casper_contract::unwrap_or_revert::UnwrapOrRevert;
2use casper_types::{system::CallStackElement, Key};
3
4use crate::ContractStorage;
5
6pub trait ContractContext<Storage: ContractStorage> {
7    fn storage(&self) -> &Storage;
8
9    fn get_caller(&self) -> Key {
10        let call_stack = self.storage().call_stack();
11        let caller = call_stack.get(call_stack.len() - 2);
12        element_to_key(caller.unwrap_or_revert())
13    }
14
15    fn self_addr(&mut self) -> Key {
16        let call_stack = self.storage().call_stack();
17        element_to_key(call_stack.last().unwrap_or_revert())
18    }
19}
20
21fn element_to_key(element: &CallStackElement) -> Key {
22    match element {
23        CallStackElement::Session { account_hash } => (*account_hash).into(),
24        CallStackElement::StoredSession {
25            account_hash,
26            contract_package_hash: _,
27            contract_hash: _,
28        } => (*account_hash).into(),
29        CallStackElement::StoredContract {
30            contract_package_hash,
31            contract_hash: _,
32        } => (*contract_package_hash).into(),
33    }
34}