saa_custom/
caller.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#[cfg(feature = "cosmwasm")]
use saa_common::cosmwasm::{Api, Env, MessageInfo};
use saa_common::{ensure, utils::prefix_from_address, AuthError, CredentialId, ToString, Verifiable};
use saa_schema::wasm_serde;


#[wasm_serde]
pub struct Caller {
    pub id: CredentialId
}


#[cfg(feature = "substrate")]
impl From<&[u8]> for Caller {
    fn from(bytes: &[u8]) -> Self {
        Caller {
            id: bytes.to_vec()
        }
    }
}


#[cfg(feature = "cosmwasm")]
impl From<&MessageInfo> for Caller {
    fn from(info: &MessageInfo) -> Self {
        Caller {
            id: info.sender.as_bytes().to_vec()
        }
    }
}



impl Verifiable for Caller {

    fn id(&self) -> CredentialId {
        self.id.clone()
    }

    fn hrp(&self) -> Option<String> {
        #[cfg(feature = "cosmwasm")]
        if true {
            let res = String::from_utf8(self.id.clone());
            if res.is_err() {
                return None;
            }
            return Some(prefix_from_address(res.unwrap().as_str()));
        }
        None
    }

    fn validate(&self) -> Result<(), AuthError> {
        let id = self.id();
        if !(id.len() > 3) {
            return Err(AuthError::MissingData("Caller must have an id".to_string()));
        }
        ensure!(String::from_utf8(id).is_ok(), AuthError::generic("Can't derove calling address"));
        Ok(())
    }

    #[cfg(feature = "native")]
    fn verify(&self) -> Result<(), AuthError> {
        self.validate()
    }


    #[cfg(feature = "cosmwasm")]
    fn verify_cosmwasm(& self, _: &dyn Api, _: &Env) -> Result<(), AuthError> {
        self.validate()
    }

}