fluence-sdk-macro 0.0.13

Definition of `#[invoke_handler]` attribute
Documentation

This module defines invocation_handler attribute procedural macro. It can simplify main module invocation handler signature. According to Fluence backend convensions this handler can look like this:

#[no_mangle]
pub unsafe fn invoke(ptr: *mut u8, len: usize) -> NonNull<u8> {
let user_name = fluence::memory::read_input_from_mem(ptr, len);
let user_name: String = String::from_utf8(user_name).unwrap();

// return a pointer to the result in memory
fluence::memory::write_result_to_mem(format!("Hello from Fluence to {}", user_name).as_bytes())
.expect("Putting result string to the memory was failed.")
}

We can use a neater way instead with #[invocation_handler]:

use fluence::sdk::*;

#[invocation_handler]
fn greeting(name: String) -> String {
format!("Hello from Fluence to {}", name)
}

To use this macro with a function f certain conditions must be met:

  1. f mustn't have more than one input argument.
  2. f mustn't be unsafe, const, generic, have custom abi linkage or variadic param.
  3. The type of f input (if it present) and output parameters must be one from {String, Vec} set.
  4. f mustn't have the name invoke.

For troubleshooting and macros debugging cargo expand can be used.

Internally this macros creates a new function invoke that converts a raw argument to a appropriate format, calls f and then write f result via memory::write_result_to_mem to module memory. So to use this crate apart from fluence fluence_sdk_main has to be imported.

The macro also has an init_fn attribute that can be used for specifying initialization function name. This function will be called only in the first invoke function call. It can be used like this:

use fluence::sdk::*;

fn init() {
logger::WasmLogger::init_with_level(log::Level::Info).is_ok()
}

#[invocation_handler(init_fn = init)]
fn greeting(name: String) -> String {
info!("{} has been successfully greeted", name);
format!("Hello from Fluence to {}", name)
}

Examples

Please find more examples in https://github.com/fluencelabs/fluence/tree/master/vm/examples.