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.
1. Prerequisites
Section titled “1. Prerequisites”-
Rust with the
wasm32-wasip2target, and a checkout of core for the node and the tools:Terminal window rustup target add wasm32-wasip2git clone https://github.com/calimero-network/core && cd corecargo install --locked --path crates/meroctlcargo install --locked --path crates/merod -
A development cluster.
meroctl local upstartsmerod localin the background: one node on127.0.0.1:2501(--nodes 3runs three, in one process, on2501-2503), with mock attestation. It saves the first node inmeroctlaslocal:Terminal window meroctl local upmeroctl local downstops it. -
Sign in. Sign up with a passkey kept in a file (development clusters only):
Terminal window meroctl login --dev-passkey ./dev-passkey.json --name aliceloginsigns 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.
2. Create the project
Section titled “2. Create the project”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.jsonCargo.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]3. Define the state
Section titled “3. Define the state”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.
4. Add logic, events and errors
Section titled “4. Add logic, events and errors”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_resultisgetResult. #[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::emitsends 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 as422 APP_ERRORwith{ "code": "NotFound", "fields": { "key": ".." } }. A failed call writes nothing and emits nothing. u64andi64arguments and results travel as decimal strings, solenanswers"1", not1.?works on every SDK call: storage and table errors convert intoAppError.
5. Test it
Section titled “5. Test it”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:
cargo testrunning 2 teststest scenario ... oktest set_get_remove ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered outThe first run builds the component for wasm32-wasip2 and compiles wasmtime,
so it takes a while; later runs reuse both.
6. Build and run
Section titled “6. Build and run”Build the component:
meroctl app build path/to/kv-store --out kv_store.wasmIt 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).
-
Create an instance from it. On a development cluster
--pathuploads a raw.wasm(a real cluster installs signed.mpkpackages, see Packaging & signing);initruns as you:Terminal window meroctl instance create --name my-kv --path kv_store.wasm --alias my-kv -
Call the setter. A call without
--viewis a write the leader logs:Terminal window meroctl call -i my-kv set --args '{"key": "hello", "value": "world"}' -
Read it back with a view:
Terminal window meroctl call -i my-kv get --args '{"key": "hello"}' --view{ "index": <n>, "result": "world", "receipt": { … } }indexis the log index of the state the view read; the receipt is signed by the node that answered. -
Follow its events (stop with Ctrl-C, or
--limit N):Terminal window meroctl instance watch my-kv --from 0
7. Make it multi-user
Section titled “7. Make it multi-user”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:
-
Create an organization and an instance in it.
org createanswers the new organization’s id asorgId:Terminal window meroctl org create acmemeroctl instance create --name team-kv --path kv_store.wasm \--org <org-id> --alias team-kvAn instance created in an organization is reached by every member (access
org, the default there). -
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 -
Join as the second person: a second account, with its own passkey file, on the same cluster. Save the node under another
--homeso the two sessions stay apart:Terminal window meroctl --home ./bob node add local http://127.0.0.1:2501/ --allow-mockmeroctl --home ./bob login --dev-passkey ./bob-passkey.json --name bobmeroctl --home ./bob org join <token> -
Write as one, read as the other. Aliases are per account, so bob names the instance by its id (
meroctl instance get team-kvshows 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.
8. Next steps
Section titled “8. Next steps”You have the full loop: write, test, build, create, call, share. From here: