fluence-sdk-macro 0.0.10

Definition of `#[invoke_handler]` attribute
Documentation

This module defines invocation_handler attribute procedural macro. It allows simplifiing of principal module invocation handler signature. According to Fluence Wasm backend convensions is 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.")
}

Instead of this you can write more pretty one using #[invocation_handler]:

use fluence::sdk::*;

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

To use this macro with some function f some conditions have to be met:

  1. f has to have one input argument.
  2. f has to don't be unsafe, const, generic or have custom abi linkage or variadic param.
  3. The input and output types of f have to be in {String, Vec} set.
  4. f has to don'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 appropriate format, calls f and then converts its result via memory::write_result_to_mem from fluence_sdk_main. 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 at the first invoke function call. It can be used like this:

use fluence::sdk::*;

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

#[invocation_handler(init_fn = init)]
fn main(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.