Function syntax

Function source code specification

For a valid MEM function, it is crucial to follow the specifications used by Warp and SmartWeave protocols.

Source code guidelines

  • The source must be written in the supported programming languages.

  • The source must include a function named handle which can be either synchronous or asynchronous depending on your code logic. Also, it must have two arguments: state and action.

    • The state argument represents the current state of the function.

    • The action argument must include the input field and it holds the arguments passed along with the function interaction

  • The input field may contain the function property and any additional data required for the operation (depending on your logic).

Exiting the handle function

The handle function must exit by either returning a result or state or by throwing an error.

  • Returning { state: new_state } to update the function state.

  • Returning { result: new_result }. to return a result.

  • Throwing an ContractError("ERROR_TEXT") exception.

Throwing errors

When an error is thrown in MEM, it immediately terminates the execution of the current function and any subsequent code within that function.

Error statements

  • throw new ContractError("ERROR_TEXT") which is equivalent to throw new Error("") in JavaScript

  • ContractAssert(condition) which is equivalent to the assert statement in node:assert

Function example

function.js

export function handle(state, action) {
  const input = action.input;

  if (input.function === "ping") {
    return {
      result: "pong",
    };
  }

  if (input.function === "store") {
    const text = input.text;
    ContractAssert(text.trim().length, "ERROR_ZERO_LEN_TEXT");
    state.storage.push(text);
    return { state };
  }

  throw new ContractError("ERROR_INVALID_FUNCTION_REQUESTED");
}

state.json

{
  "storage": []
}

Last updated

mem.tech ยฉ 2023