Skip to main content

Motoko SDK Getting started

IC Mainnet demo

Motoko contract project

Requirements

You're required to have Vessel Motoko package manager binary installed and configured in your operating system.

  • Include the vessel sources command in the build > packtool of your dfx.json

    ...
    "defaults": {
    "build": {
    "packtool": "vessel sources"
    }
    }
    ...
  • Run Vessel install in your project root

    vessel install

Import ICES Library

import ICES "mo:ices/ICES";
import Router "mo:ices/Router";

Register the current Canister to ICES Main (Router) Canister. Only need to register once successfully

// Register the current Canister to ICES Main (Router) Canister
public shared({caller}) func register() : async Bool {
let result = await ices.register();
switch result {
case(#ok(msg)) Debug.print("Register success :" # msg);
case(#err(errmsg)) Debug.print("emit fail: " # errmsg);
};
true;
};

Emit event logs to ICES

  • Emit Common Event logs to ICES
public shared({caller}) func emitEvent(eventKey : Text, subKey : Text
, subValue : Text) : async Bool {
// TODO Your business

let event : Event = {
key = eventKey;
values = [(subKey, #Text subValue,#Indexed)];
caller = caller;
time = Time.now();
};

let result = await ices.emit(event);
switch result {
case(#ok(index)) Debug.print("emit success");
case(#err(errmsg)) Debug.print("emit fail: " # errmsg);
};
true;
};
  • Emit Transations Event logs to ICES

public shared({caller}) func transfer(from: Principal, to: Principal, amount : Nat) : async Bool {
// TODO Your business

let transaction : Transaction = {
from = Principal.toText(from);
to = Principal.toText(to);
amount = amount;
};

let event : Event = {
key = "Transaction";
values = [("subKey", #Transaction transaction,#Indexed)];
caller = caller;
time = Time.now();
};

let result = await ices.emit(event);
switch result {
case(#ok(index)) Debug.print("emit success");
case(#err(errmsg)) Debug.print("emit fail: " # errmsg);
};
true;
};

Aboout ICES Event values

  • Event values is a tuple array, the first element of the Tuple is a custom subKey type Text, the second element is subValue type enum EventValue, and the third element is an enum Indexed, which is stored in the canister as a search index
  • You can find the type definitions at ICES library Router
public type Transaction = {
from : Text;
to: Text;
amount: Nat;
};

public type EventValue = {
#I64 : Int64;
#U64 : Nat64;
#Vec : [EventValue];
#Slice : [Nat8];
#Text : Text;
#True;
#False;
#Float : Float;
#Principal : Principal;
#Transaction : Transaction;
};

public type Indexed = {
#Indexed;
#Not;
};

public type Event = {
time : Time.Time;
key : Text;
values : [(Text, EventValue, Indexed)];
caller : Principal;
};
tip

This is the example repository