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
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#[doc(hidden)]
#[macro_export]
macro_rules! load_json {
    ($encoded_allocation_of_input:ident) => {{
        let maybe_input =
            $crate::holochain_wasm_utils::memory_serialization::load_json($encoded_allocation_of_input);
        if maybe_input.is_err() {
            return $crate::holochain_wasm_utils::holochain_core_types::error::RibosomeErrorCode::ArgumentDeserializationFailed
                as u32;
        }
        maybe_input
    }};
}

/// Every Zome must utilize the `define_zome`
/// macro in the main library file in their Zome.
/// The `define_zome` macro has 3 component parts:
/// 1. entries: an array of [ValidatingEntryType](entry_definition/struct.ValidatingEntryType.html) as returned by using the [entry](macro.entry.html) macro
/// 2. genesis: `genesis` is a callback called by Holochain to every Zome implemented within a DNA. 
///     It gets called when a new agent is initializing an instance of the DNA for the first time, and
///     should return `Ok` or an `Err`, depending on whether the agent can join the network or not.
/// 3. functions: `functions` is divided up into `capabilities`, which specify who can access those functions.
///     `functions` must be a tree structure where the first children are `capabilities`
///     and the children of those `capabilities` are actual function definitions.
/// # Examples
/// 
/// ```rust
/// #[macro_use]
/// extern crate hdk;
/// extern crate serde;
/// #[macro_use]
/// extern crate serde_derive;
/// #[macro_use]
/// extern crate serde_json;
/// extern crate boolinator;
/// 
/// #[derive(Serialize, Deserialize)]
/// pub struct Post {
///     content: String,
///     date_created: String,
/// }
/// 
/// fn handle_hash_post(content: String) -> serde_json::Value {
///     let maybe_address = hdk::hash_entry("post", json!({
///         "content": content,
///         "date_created": "now"
///     }));
///     match maybe_address {
///         Ok(address) => {
///             json!({"address": address})
///         }
///         Err(hdk_error) => hdk_error.to_json(),
///     }
/// }
/// 
/// define_zome! {
///     entries: [
///         entry!(
///             name: "post",
///             description: "",
///             sharing: Sharing::Public,
///             native_type: Post,
///         
///             validation_package: || {
///                 hdk::ValidationPackageDefinition::ChainFull
///             },
///         
///             validation: |post: Post, _ctx: hdk::ValidationData| {
///                 (post.content.len() < 280)
///                     .ok_or_else(|| String::from("Content too long"))
///             }
///         )
///     ]
/// 
///     genesis: || {
///         Ok(())
///     }
/// 
///     functions: {
///         // "main" is the name of the capability
///         // "Public" is the access setting of the capability
///         main (Public) {
///             // the name of this function, "hash_post" is the
///             // one to give while performing a `call` method to this function.
///             // the name of the handler function must be different than the
///             // name of the Zome function.
///             hash_post: {
///                 inputs: |content: String|,
///                 outputs: |post: serde_json::Value|,
///                 handler: handle_hash_post
///             }
///         }
///     }
/// }
/// ```
#[macro_export]
macro_rules! define_zome {
    (
        entries : [
            $( $entry_expr:expr ),*
        ]

        genesis : || {
            $genesis_expr:expr
        }

        functions : {
            $(
                $cap:ident ( $vis:ident ) {
                    $(
                        $zome_function_name:ident : {
                            inputs: | $( $input_param_name:ident : $input_param_type:ty ),* |,
                            outputs: | $( $output_param_name:ident : $output_param_type:ty ),* |,
                            handler: $handler_path:path
                        }
                    )+
                }
            )*
        }

    ) => {
        #[no_mangle]
        #[allow(unused_variables)]
        pub extern "C" fn zome_setup(zd: &mut $crate::meta::ZomeDefinition) {
            $(
                zd.define($entry_expr);
            )*
        }

        #[no_mangle]
        pub extern "C" fn genesis(encoded_allocation_of_input: u32) -> u32 {
            $crate::global_fns::init_global_memory(encoded_allocation_of_input);

            fn execute() -> Result<(), String> {
                $genesis_expr
            }

            $crate::global_fns::store_and_return_output(execute())
        }

        use $crate::holochain_dna::zome::capabilities::Capability;
        use std::collections::HashMap;

        #[no_mangle]
        #[allow(unused_imports)]
        pub fn __list_capabilities() -> HashMap<String, Capability> {

            use $crate::holochain_dna::zome::capabilities::{Capability, Membrane, CapabilityType, FnParameter, FnDeclaration};
            use std::collections::HashMap;

            let return_value: HashMap<String, Capability> = {
                let mut cap_map = HashMap::new();

                $(
                    {
                        let mut capability = Capability::new();
                        capability.cap_type = CapabilityType { membrane: Membrane::$vis };
                        capability.functions = vec![
                            $(
                                FnDeclaration {
                                    name: stringify!($zome_function_name).into(),
                                    inputs: vec![
                                        $(
                                            FnParameter::new(stringify!($input_param_name), stringify!($input_param_type))
                                        ),*
                                    ],
                                    outputs: vec![
                                        $(
                                            FnParameter::new(stringify!($output_param_name), stringify!($output_param_type))
                                        ),*
                                    ]
                                }

                            ),+
                        ];

                        cap_map.insert(stringify!($cap).into(), capability);
                    }
                ),*

                cap_map
            };

            return_value
        }

        $(
            $(
                #[no_mangle]
                pub extern "C" fn $zome_function_name(encoded_allocation_of_input: u32) -> u32 {
                    $crate::global_fns::init_global_memory(encoded_allocation_of_input);

                    // Macro'd InputStruct
                    #[derive(Deserialize)]
                    struct InputStruct {
                        $($input_param_name : $input_param_type),*
                    }

                    // #[derive(Serialize)]
                    // struct OutputStruct {
                    //     $( $output_param_name:ident : $output_param_type:ty ),*
                    // }

                    // Deserialize input
                    let maybe_input = load_json!(encoded_allocation_of_input);
                    let input: InputStruct = maybe_input.unwrap();

                    // Macro'd function body
                    fn execute(params: InputStruct) -> impl ::serde::Serialize {
                        let InputStruct { $($input_param_name),* } = params;

                        $handler_path($($input_param_name),*)
                    }

                    // Execute inner function
                    let output_obj = execute(input);

                    $crate::global_fns::store_and_return_output(output_obj)
                }
            )+
        )*
    };
}