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
73
74
75
76
77
78
79
80
81
82
83
use holochain_core_types::{entry_type::EntryType, hash::HashString};
use holochain_wasm_utils::api_serialization::ZomeApiGlobals;
use multihash::Hash as Multihash;
use nucleus::ribosome::Runtime;
use serde_json;
use wasmi::{RuntimeArgs, RuntimeValue, Trap};
pub fn invoke_init_globals(
runtime: &mut Runtime,
_args: &RuntimeArgs,
) -> Result<Option<RuntimeValue>, Trap> {
let mut globals = ZomeApiGlobals {
dna_name: runtime.dna_name.to_string(),
dna_hash: HashString::from(""),
agent_id_str: runtime.context.agent.to_string(),
agent_address: HashString::encode_from_str("FIXME-agent_address", Multihash::SHA2256),
agent_initial_hash: HashString::from(""),
agent_latest_hash: HashString::from(""),
};
if let Some(state) = runtime.context.state() {
if let Some(dna) = state.nucleus().dna() {
globals.dna_hash =
HashString::encode_from_serializable(dna.to_json(), Multihash::SHA2256);
}
let maybe_top = state.agent().top_chain_header();
if maybe_top.is_some() {
let mut found_entries: Vec<HashString> = vec![];
for chain_header in state
.agent()
.chain()
.iter_type(&maybe_top, &EntryType::AgentId)
{
found_entries.push(chain_header.entry_address().to_owned());
}
if found_entries.len() > 0 {
globals.agent_latest_hash = found_entries[0].clone();
globals.agent_initial_hash = found_entries.pop().unwrap();
globals.agent_address = globals.agent_latest_hash.clone();
}
}
};
return runtime.store_utf8(&serde_json::to_string(&globals).unwrap());
}
#[cfg(test)]
pub mod tests {
use holochain_agent::Agent;
use holochain_core_types::cas::content::AddressableContent;
use holochain_wasm_utils::api_serialization::ZomeApiGlobals;
use nucleus::ribosome::{
api::{tests::test_zome_api_function, ZomeApiFunction},
Defn,
};
#[test]
fn test_init_globals() {
let input: Vec<u8> = vec![];
let (mut call_result, _) =
test_zome_api_function(ZomeApiFunction::InitGlobals.as_str(), input);
call_result.pop();
let globals: ZomeApiGlobals = serde_json::from_str(&call_result).unwrap();
assert_eq!(globals.dna_name, "TestApp");
assert_eq!(globals.agent_id_str, "jane");
assert_eq!(
globals.agent_initial_hash,
Agent::from("jane".to_string()).address()
);
assert_eq!(globals.agent_initial_hash, globals.agent_latest_hash);
}
}