Skip to content

Build your first app

This tutorial walks one path from nothing to a running key-value app on the component SDK (calimero-sdk): you write a small Rust crate, test it on the real engine, build it into a calimero:app component, create an app instance from it on a local cluster, call its methods, and share it with a second person, checking the output at each step.

The app is a smaller cousin of core’s apps/kv-store: where that one keeps an UnorderedMap, this one keeps a Table of records and a Counter, the two state types most apps start from.

from a Rust crate to a running app1 · Rust cratecdylib + calimero-sdk#[app::state] struct#[app::logic] impl#[app::event] / errorcargo test: TestAppon the real engine2 · componentmeroctl app buildcargo build --release wasm32-wasip2lift calimero:abi→ app.wasm(+ compute.wasm)3 · signed .mpkmeroctl app packmanifest.json: package, appVersion, sha256 of app.wasmsigned: JCS+Ed25519→ pkg-1.0.0.mpk4 · on the clusterinstall the package: signature, digest imports ⊆ world prepare (wasmtime)create an app: init as the owner, in an organizationdevelopment cluster only: meroctl context create --path app.wasmevery call, at run timeclient → any node → app's leader: handle(kind, method, args) on the componentOk → writes + events become one entry in the app's Raft log; followers apply the diff, never re-runErr or trap → nothing written, no events; a view reads state and writes nothing
  1. Rust with the wasm32-wasip2 target, and a checkout of core for the node and the tools:

    Terminal window
    rustup target add wasm32-wasip2
    git clone https://github.com/calimero-network/core && cd core
    cargo install --locked --path crates/meroctl
    cargo install --locked --path crates/merod
  2. A development cluster. meroctl local up starts merod local in the background: one node on 127.0.0.1:2501 (--nodes 3 runs three, in one process, on 2501-2503), with mock attestation. It saves the first node in meroctl as local:

    Terminal window
    meroctl local up

    meroctl local down stops it.

  3. Sign in. Sign up with a passkey kept in a file (development clusters only):

    Terminal window
    meroctl login --dev-passkey ./dev-passkey.json --name alice

    login signs up when the file does not exist yet and saves the session. Her first instance, naming no organization, comes with a new one of her own; later ones go there unless she names another. See Run local nodes.

An app is a standalone cdylib crate that depends on the SDK and nothing else from Calimero. calimero-sdk is not on crates.io: take it from core’s git repository at the release your cluster runs.

kv-store/
├── Cargo.toml
├── src/lib.rs
├── tests/app.rs
└── scenarios/basic.json

Cargo.toml:

[package]
name = "kv-store"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
calimero-sdk = { git = "https://github.com/calimero-network/core", tag = "1.0.0-rc.20" }
# The test harness (TestApp) and the builder, for `cargo test` on the host.
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
calimero-sdk = { git = "https://github.com/calimero-network/core", tag = "1.0.0-rc.20", features = ["testing"] }
calimero-app-build = { git = "https://github.com/calimero-network/core", tag = "1.0.0-rc.20" }
serde_json = "1"
# Its own workspace root.
[workspace]

State is a struct of handles annotated with #[app::state]. Loading it reads nothing: each field names its own range of keys in the app’s storage, after the field’s camelCase name. Records live in a Table, declared with #[derive(Record)] and a #[table] attribute naming the key (and any indexes, unique constraints and counts, see Tables & Collections).

Start src/lib.rs:

//! A string key-value store shared by the members of the app's organization.
use calimero_sdk::prelude::*;
/// One stored value, keyed by `key`.
#[derive(Record)]
#[table(key = "key")]
pub struct Entry {
pub key: String,
pub value: String,
}
/// The app's state: a table of entries and how many there are.
#[app::state(version = 1)]
pub struct KvStore {
entries: Table<Entry>,
size: Counter,
}

The app runs on its cluster’s leader, which orders every write in the app’s log, so a later set of a key replaces an earlier one: there is nothing to merge. Counter::add is an add the host applies without a read, so size stays exact under any number of writers.

Add the logic block, the events and the errors to the same file. Every app has one #[app::init]; a &mut self method is a call (a write the leader logs), a #[app::view] reads:

#[app::logic]
impl KvStore {
/// Runs once, as the owner, when the app is created.
#[app::init]
pub fn init() -> app::Result<Self> {
Ok(Self::load())
}
/// Stores `value` under `key`, replacing any value already there.
pub fn set(&mut self, key: String, value: String) -> app::Result<()> {
let event = if self.entries.contains(&key)? {
Event::Updated { key: key.clone(), value: value.clone() }
} else {
self.size.add(1)?;
Event::Inserted { key: key.clone(), value: value.clone() }
};
self.entries.upsert(Entry { key, value })?;
env::emit(event, Audience::All)?;
Ok(())
}
/// Removes `key`; says whether it was there.
pub fn remove(&mut self, key: String) -> app::Result<bool> {
if !self.entries.remove(&key)? {
return Ok(false);
}
self.size.add(-1)?;
env::emit(Event::Removed { key }, Audience::All)?;
Ok(true)
}
/// The value under `key`, or `null`.
#[app::view]
pub fn get(&self, key: String) -> app::Result<Option<String>> {
Ok(self.entries.get(&key)?.map(|e| e.value))
}
/// The value under `key`, or the app error `NotFound`.
#[app::view]
pub fn get_result(&self, key: String) -> app::Result<String> {
match self.entries.get(&key)? {
Some(e) => Ok(e.value),
None => Err(Error::NotFound { key }.into()),
}
}
/// How many keys are stored (a `u64`: a decimal string on the wire).
#[app::view]
pub fn len(&self) -> app::Result<u64> {
Ok(self.size.get()?)
}
}
/// A change to the store, emitted after the write that caused it.
#[app::event]
pub enum Event {
Inserted { key: String, value: String },
Updated { key: String, value: String },
Removed { key: String },
}
/// A typed failure: `{ code, fields }` on the wire.
#[app::error]
pub enum Error {
NotFound { key: String },
}

A few things to notice:

  • Method and argument names reach the ABI in camelCase: get_result is getResult.
  • #[app::event] and #[app::error] must be in the same module as #[app::logic], where the ABI picks them up; every field has a name.
  • env::emit sends an #[app::event] value to an audience (All, the caller, named accounts, a team, the organization or its admins). It is delivered only if the call succeeds.
  • An #[app::error] variant reaches the client as 422 APP_ERROR with { "code": "NotFound", "fields": { "key": ".." } }. A failed call writes nothing and emits nothing.
  • u64 and i64 arguments and results travel as decimal strings, so len answers "1", not 1.
  • ? works on every SDK call: storage and table errors convert into AppError.

calimero_sdk::testing::TestApp runs the built component on the real wasmtime engine, in an organization you describe, as named accounts, with the node’s own checks. tests/app.rs:

#![cfg(not(target_arch = "wasm32"))]
use std::path::{Path, PathBuf};
use calimero_app_build::build_component;
use calimero_sdk::testing::{run_scenario, Failure, Org, TestApp};
use serde_json::json;
/// This crate built as a `calimero:app` component.
fn component() -> Vec<u8> {
let dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let target = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("guest");
build_component(dir, &target).expect("build the component").component
}
#[test]
fn set_get_remove() {
let mut t = TestApp::new(&component(), Org::new().members(["bob"]), 1_700_000_000_000);
t.as_("bob").call("set", json!({ "key": "k", "value": "v" })).unwrap();
assert_eq!(t.as_("owner").view("get", json!({ "key": "k" })).unwrap(), json!("v"));
assert_eq!(t.as_("owner").view("len", json!({})).unwrap(), json!("1"));
assert_eq!(t.events_for("owner")[0].0, "Inserted");
match t.as_("owner").view("getResult", json!({ "key": "x" })) {
Err(Failure::App { code, fields }) => {
assert_eq!(code, "NotFound");
assert_eq!(fields, json!({ "key": "x" }));
}
other => panic!("expected NotFound, got {other:?}"),
}
assert_eq!(t.as_("bob").call("remove", json!({ "key": "k" })).unwrap(), json!(true));
assert_eq!(t.as_("owner").view("len", json!({})).unwrap(), json!("0"));
}
#[test]
fn scenario() {
let dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let mut t = TestApp::new(&component(), Org::new().members(["bob"]), 1_700_000_000_000);
run_scenario(&mut t, &dir.join("scenarios/basic.json")).unwrap();
}

TestApp::new runs init as the account "owner"; Org::new().members(..) adds the other accounts the app’s organization holds. The same steps can live in a scenario file, which run_scenario runs here and the node’s cluster runner can run on real nodes (Testing). scenarios/basic.json:

[
{ "as": "bob", "op": "call", "method": "set", "args": { "key": "k", "value": "v" },
"events": { "owner": ["Inserted"] } },
{ "as": "owner", "op": "view", "method": "get", "args": { "key": "k" }, "expect": { "ok": "v" } },
{ "as": "owner", "op": "view", "method": "len", "args": {}, "expect": { "ok": "1" } },
{ "as": "owner", "op": "view", "method": "getResult", "args": { "key": "x" },
"expect": { "error": "NotFound", "fields": { "key": "x" } } }
]

Run both:

Terminal window
cargo test
running 2 tests
test scenario ... ok
test set_get_remove ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

The first run builds the component for wasm32-wasip2 and compiles wasmtime, so it takes a while; later runs reuse both.

Build the component:

Terminal window
meroctl app build path/to/kv-store --out kv_store.wasm

It compiles the crate for wasm32-wasip2, wraps it as a calimero:app component and lifts the ABI into the component’s calimero:abi section, which the node reads to dispatch and gate calls (App interface).

  1. Create an instance from it. On a development cluster --path uploads a raw .wasm (a real cluster installs signed .mpk packages, see Packaging & signing); init runs as you:

    Terminal window
    meroctl instance create --name my-kv --path kv_store.wasm --alias my-kv
  2. Call the setter. A call without --view is a write the leader logs:

    Terminal window
    meroctl call -i my-kv set --args '{"key": "hello", "value": "world"}'
  3. Read it back with a view:

    Terminal window
    meroctl call -i my-kv get --args '{"key": "hello"}' --view
    { "index": <n>, "result": "world", "receipt": { … } }

    index is the log index of the state the view read; the receipt is signed by the node that answered.

  4. Follow its events (stop with Ctrl-C, or --limit N):

    Terminal window
    meroctl instance watch my-kv --from 0

An instance belongs to an organization, and the organization decides who reaches it. Create one, create the instance in it, and invite a second person:

  1. Create an organization and an instance in it. org create answers the new organization’s id as orgId:

    Terminal window
    meroctl org create acme
    meroctl instance create --name team-kv --path kv_store.wasm \
    --org <org-id> --alias team-kv

    An instance created in an organization is reached by every member (access org, the default there).

  2. Invite a member. An invite is approved with your passkey, so pass the file on a development cluster; the answer carries the invitation token:

    Terminal window
    meroctl org invite <org-id> --role member --dev-passkey ./dev-passkey.json
  3. Join as the second person: a second account, with its own passkey file, on the same cluster. Save the node under another --home so the two sessions stay apart:

    Terminal window
    meroctl --home ./bob node add local http://127.0.0.1:2501/ --allow-mock
    meroctl --home ./bob login --dev-passkey ./bob-passkey.json --name bob
    meroctl --home ./bob org join <token>
  4. Write as one, read as the other. Aliases are per account, so bob names the instance by its id (meroctl instance get team-kv shows it):

    Terminal window
    meroctl --home ./bob call -i <app-id> set --args '{"key": "from", "value": "bob"}'
    meroctl call -i team-kv get --args '{"key": "from"}' --view
    { "index": <n>, "result": "bob", "receipt": { … } }

Both people wrote and read the same state, each with their own passkey, through any node of the cluster. The organization decides who reaches the instance; what each member may change inside it is the app’s own code and its access control. See Organizations, teams & access.

You have the full loop: write, test, build, create, call, share. From here: