SDK Macros
An app is a Rust library built into a calimero:app component. It declares
itself with the attributes calimero-sdk re-exports under calimero_sdk::app
(defined in crates/sdk-macros) and #[derive(Record)]. One import brings them
all in scope:
use calimero_sdk::prelude::*;Summary
Section titled “Summary”| Attribute | On | Does |
|---|---|---|
#[app::state(version = N)] |
struct | The state root: tables and collections. |
#[app::logic] |
impl of the state |
Every pub fn becomes a method; generates the handle export and the ABI. |
#[app::init] |
method | The constructor, run once when the app is created (as the owner). |
#[app::view] |
&self method |
A read: runs as a view, never as a write. |
#[app::confirm] |
method | The caller confirms with a fresh passkey assertion. |
#[app::public] / #[app::public(rate = "10/min")] |
method | Callable without signing in, where the instance admits a caller without an account (no access grant does), optionally rate-limited. |
#[app::every("1m")] |
method | A timer the node runs on that interval (<n>s, <n>m or <n>h). |
#[app::allow(system)] |
method | The node itself may call it (implied by every). |
#[app::allow(app = "<id>")] / allow(app = "*") |
method | Another app may call it with a cross-app call. |
#[app::action] |
method | An action: may fetch over HTTP and read and call the app, outside the log. #[app::action(wall_secs = N)] gives it N seconds (1 to 300) instead of 10. |
#[app::allow(action)] |
method | Only the app’s own actions may call it. |
#[app::compute(fuel = .., result = "..")] |
method | A compute method: runs on a job node over sealed files, outside the log. |
#[app::compute_result] |
method | The logged call the node runs with a compute run’s outcome. |
#[app::error] |
enum | The app’s errors: variant name = error code. |
#[app::event] |
enum | The app’s events: variant name = event name. |
#[derive(Record)] + #[table(..)] |
struct | A table row: key, unique constraints, indexes, counts, search. |
#[derive(AbiType)] |
serde struct or enum | Its JSON shape in the ABI’s types, so typed clients get its fields. |
app::bail!(err) |
expression | Return early with an app error. |
A complete app
Section titled “A complete app”The sample guest the SDK’s own tests run (crates/sdk/tests/guests/sample),
shortened:
use calimero_sdk::prelude::*;
#[derive(Record)]#[table( key = "id", unique(slot = ["room_id", "start"]), index(by_start = ["checked_in", "start"]), count(by_room = ["room_id"]),)]pub struct Booking { pub id: String, pub room_id: String, pub start: u64, pub title: String, pub checked_in: bool,}
#[app::state(version = 3)]pub struct Rooms { bookings: Table<Booking>, titles: UnorderedMap<String, String>, next_id: Counter,}
#[app::error]pub enum Error { NotFound, Taken { start: u64 }, Invalid { reason: String },}
#[app::event]pub enum Event { Booked { id: String, room_id: String, start: u64 }, Released { id: String },}
#[app::logic]impl Rooms { #[app::init] pub fn init() -> app::Result<Self> { Ok(Self::load()) }
pub fn book(&mut self, room_id: String, start: u64, title: String) -> app::Result<String> { if title.is_empty() { app::bail!(Error::Invalid { reason: "empty title".into() }); } let id = env::unique_id(); self.bookings.insert(Booking { id: id.clone(), room_id: room_id.clone(), start, title, checked_in: false })?; env::emit(Event::Booked { id: id.clone(), room_id, start }, Audience::All)?; Ok(id) }
#[app::view] #[app::public] pub fn room_count(&self, room_id: String) -> app::Result<u64> { Ok(self.bookings.count("byRoom", &[KeyPart::Str(room_id)])?) }
#[app::confirm] pub fn admin_release(&mut self, id: String) -> app::Result<()> { if !self.bookings.remove(&id)? { app::bail!(Error::NotFound); } env::emit(Event::Released { id }, Audience::All)?; Ok(()) }
#[app::every("30s")] pub fn heartbeat(&mut self) -> app::Result<()> { Ok(()) }}Compile-time refusals worth knowing: an every interval other than
<n>s|m|h, a rate other than <n>/s|min|h, init with any other attribute,
a u64/i64/Vec<u8> nested in another type the macro sees, and a table
partition (reserved).
#[app::state(version = N)]
Section titled “#[app::state(version = N)]”The struct holds handles only: each field is a table or collection,
built from its camelCase field name, so Self::load() reads nothing. version
is recorded in the ABI. The fields and their kinds (table, unorderedMap,
counter, cell, set, vector, frozen, perUser, text, richText) are
listed in the ABI too.
#[app::logic]
Section titled “#[app::logic]”On the state’s impl block. Every pub fn is a method, named in camelCase in
the ABI (room_count → roomCount); private fns stay helpers. A method’s
receiver says its kind: &mut self is a call, &self with #[app::view] a
view, and #[app::init] has no receiver and returns Self. Every method,
init included, may take parameters, and every method returns app::Result<T>.
A /// comment on an exposed method is copied into the ABI as its doc
(the ABI), so it is published with the app and shown to users
as the publisher’s description; keep internal notes in //. The node does not
check it. A #[doc = include_str!(..)] or concat!(..) is left out, as a macro
cannot read it.
init’s parameters work like a call’s: the node passes the app’s initArgs
(POST /apps, meroctl instance create --params) as a JSON object keyed by the
camelCase parameter names, and the ABI lists them, so typed clients declare
them as InitArgs (typed clients). A missing
required argument, a wrong type or an unknown name fails init with BadArgs,
and the create answers 422 INIT_FAILED. Make a parameter an Option when
the app should also start without it:
#[app::init]pub fn init(title: String, max_players: Option<u64>) -> app::Result<Self> { let mut app = Self::load(); app.title.set(&title)?; app.max_players.set(&max_players.unwrap_or(2))?; Ok(app)}meroctl instance create --name blitz --package com.example.game --params '{"title":"Friday blitz","maxPlayers":"4"}'The u64 travels as a decimal string, as in any call.
The generated handle:
- Arguments are a JSON object keyed by camelCase parameter names; unknown
keys are refused (
BadArgs). ABadArgserror’s fields carry themessageand, when one parameter is at fault, its name asparam(dotted into records, as inwindow.after). - 64-bit integers and bytes:
u64,i64andVec<u8>(andOptionof each) travel as decimal strings and base64url without padding, in arguments, results, record fields, and error and event fields, so no JavaScript client loses precision. The same types nested in another type the macro sees (Vec<u64>,Option<Vec<i64>>) are a compile error: wrap them in aRecordor use a string. - Kinds: a view may run as a call; a call run as a view is
NotAView; an unknown method isUnknownMethod. - Callers are checked after the kind:
allow(system)admits the node,allow(app = ..)another app,publica caller who is not signed in.
Method attributes
Section titled “Method attributes”#[app::init]runs once, as the owner, with the app’sinitArgs, and takes no other attribute.#[app::view]makes the method a read.#[app::confirm]asks the node to require a fresh passkey assertion for the call.#[app::public]lets a caller who is not signed in reach the method where the instance admits one (no access grant does);rate = "<n>/s|min|h"limits it.#[app::every("<n>s|m|h")]is a timer. It impliesallow(system). Inside it,env::timer()gives the tick (scheduled, andpreviouswhen there was one).#[app::allow(app = "<app id>")], or"*"for any app, admits cross-app calls.#[app::compute(fuel = N, memory_mib = M, wall_secs = S, result = "method")]marks a compute method: noself, run on a job node from the app’s compute component, withfuelandresultrequired and the memory and wall caps optional (the host checks them against its maxima).resultnames an#[app::compute_result]method of the same block: a plain call method, not public, that impliesallow(system)and takes the run’s wholeComputeOutcomeas its one parameter. A compute method takes no other kind or access attribute. See Compute actions.#[app::action]takes noself; its first parameter isctx: &mut ActionCtx, withctx.view,ctx.callandctx.fetch(see Outbound).#[app::action(wall_secs = N)]declares its wall clock, 1 to 300 s (10 s when left out), which its HTTP requests get too; the ABI carries it as"action": { "wallSecs": N }, and a timed-out action that declared more than 10 s is not retried.#[app::allow(action)]on a method lets only the app’s own actions call it.
#[app::error] and #[app::event]
Section titled “#[app::error] and #[app::event]”Both go in the #[app::logic] module, at most one of each. Every field has a
name: a tuple variant (Invalid(String)), or a tuple struct in place of the
enum, is a compile error; unit variants are fine.
#[app::error]implementsFrom<Error> for AppError. The variant name is the code; the fields become the error’smessage, a JSON object with camelCase keys (Taken { start: 7 }→ codeTaken,{"start":"7"}). A client sees it as422 APP_ERRORwithdetails.codeanddetails.fields.#[app::event]implementsAppEvent, emitted withenv::emit(event, audience)(see Events).
app::bail!(Error::NotFound) returns Err(Error::NotFound.into()).
#[derive(Record)] and #[table(..)]
Section titled “#[derive(Record)] and #[table(..)]”A table row. The derive writes the serde impls itself, so do not also derive
Serialize/Deserialize on the record.
| Key | Meaning |
|---|---|
key = "field" |
The primary key. |
unique(name = ["f", ..]) |
A unique constraint; an insert that breaks it fails. |
index(name = ["f", ..]) |
An index, read with Table::find. |
count(name = ["f", ..]) |
A count kept on every write, read with Table::count. |
search = ["f", ..] |
Fields indexed for full-text search. |
Index, count and unique names are used in camelCase (by_room → "byRoom").
The fields a key, unique constraint, index or count names must be key types
(strings, integers, bools, bytes, Option of these, or a ToKeyPart type of
your own); every other field is only stored, so it can be any serde value: a
Vec, an f64, a nested struct, a map, a BlobRef. To find records by one
element of a list, keep the list’s elements as rows of their own table, with an
index on them.
u64/i64 fields are CBOR integers when stored and decimal strings in JSON.
A record’s fields are listed in the ABI’s types too, so a
typed client types it as an interface.
#[derive(AbiType)]
Section titled “#[derive(AbiType)]”A record describes itself in the ABI. A plain serde type a method takes or
answers (a view of several records, a status enum, a generic page) does so when
it also derives AbiType:
#[derive(serde::Serialize, serde::Deserialize, AbiType)]#[serde(rename_all = "camelCase")]pub struct Listing<T> { pub items: Vec<T>, pub next_cursor: Option<String>, #[serde(with = "calimero_sdk::json::u64_str")] pub total: u64,}
#[derive(serde::Serialize, serde::Deserialize, AbiType)]#[serde(tag = "state", rename_all = "camelCase")]pub enum Slot { Free, Held { booking: Booking },}It reads the serde attributes that change the JSON (rename, rename_all,
rename_all_fields, tag, content, untagged, transparent, skip,
skip_serializing_if, default) and refuses what it cannot describe: flatten, into,
from, try_from, remote, and a with other than the SDK’s
calimero_sdk::json helpers. A
field skip_serializing_if may leave out, or #[serde(default)] (on the field, or
on the struct for every field) lets a caller leave out, is optional in the shape, so
generated argument types do not require it.
A u64, i64 or Vec<u8> field says which JSON it travels as. Either it names
its calimero_sdk::json helper (json::u64_str, i64_str, bytes_b64url, or their opt_
forms: a decimal string, base64url), or it is marked #[abi(plain)] and keeps
what plain serde writes, described as such: u64_number / i64_number (a JSON
number) and byte_list (an array of numbers), at any depth (Vec<u64>,
Option<i64>). #[abi(plain)] on the struct or enum marks every field; a json
helper in with on a field still wins. Unmarked, the field is refused: the ABI’s u64 and
bytes mean the strings.
#[derive(serde::Serialize, serde::Deserialize, AbiType)]pub struct ShotsView { #[abi(plain)] pub shots: Vec<u8>, // [3, 17, ...]: `byte_list` #[abi(plain)] pub updated_at: u64, // 1700000000000: `u64_number` #[serde(default)] pub note: Option<String>, // a caller may leave it out}A JSON number past 2^53 loses precision in JavaScript (the TypeScript client types
u64_number as number), so #[abi(plain)] suits values that stay below it
(timestamps in milliseconds, counts) or apps whose JSON is already fixed; a new
field is better as the decimal string.
Every app type in a method’s parameters or result, an error’s or event’s fields, or
a field of a described type needs one of the two derives (or a hand-written
impl AbiType): one without does not compile where it is used, so a bare u64
cannot reach an app’s JSON through a struct the macros never saw.
u128, i128, usize and isize are refused wherever the ABI describes a type,
#[abi(plain)] included: serde writes them as numbers and they have no string form;
use u32, or u64 with its calimero_sdk::json helper.
error: field `views`: plain serde writes u64/i64 as a number that loses precision past 2^53 ...error[E0277]: `Totals` travels as an app's JSON but has no ABI shape: it does not implement `AbiType`Two mutually recursive described types do not compile (a type that contains
itself does); describe one of them by hand (impl AbiType) or not at all.
The SDK’s name
Section titled “The SDK’s name”The crate is calimero-sdk. Its old name, calimero-app-sdk, still works while
apps move over: it re-exports calimero-sdk, and the attributes expand to paths
through whichever name the app’s Cargo.toml lists (or the name a renamed
dependency gives it).