Build on other apps
Task: build an app on top of others: an app that brings its own database app, or a plugin, such as a booking page, that works on a calendar its user already runs.
Three things make this work, and an app can use any of them:
- References. Your release names the apps it uses, in its signed manifest.
- Links. The node tells your code which app instance answers to each reference.
- Grants. The person lets your app call another app as them, so that app’s own rules for that person apply.
The other app needs no support for any of it. It sees an ordinary call from you, or a call from its own user.
1. Name the apps you use
Section titled “1. Name the apps you use”Each reference has a name your code uses, the package it means and the versions it
takes. Put them in your crate’s Cargo.toml:
[package.metadata.calimero.uses]kv = { package = "com.calimero.confidential-kv", range = "^0.1", mode = "create" }calendar = { package = "com.example.calendar", range = "^2", mode = "attach", methods = ["listEvents", "createEvent"] }mode = "create": each instance of your app gets its own, made with it.mode = "attach": the owner points the reference at an app they already run.methods: what your app calls there as the person it serves, once they allow it (step 5). Leave it out to call only as your app.
Left, a create reference: its app is made with each instance and belongs to
it, in life, upgrades and deletion. Right, an attach reference: its app is
one the owner already runs, linked by hand and left alone by everything that
happens to your instance.
meroctl app pack signs them into the release and checks every method against the
target’s vendored ABI. The node checks the rest at install (400 BAD_USES), shows
the references on the release’s capability card, and an upgrade’s consent page
names the apps a new release starts using or uses differently. The full rules are in
Packaging and signing.
Pin a release and generate its client
Section titled “Pin a release and generate its client”Pin each reference to a release of its package and vendor that release’s ABI:
meroctl app uses update calendar --from ../calendar # its crate, built; or its .mpkmeroctl app uses check # what CI runs: the three agreeupdate checks that the release is the declared package, inside the range, and has
every method in methods, then writes calimero.lock (the exact version, the mode and
the ABI’s hash) and calimero/abi/calendar.json. Commit both. --from takes the target
app’s crate (built, its version read from its Cargo.toml), its signed .mpk, its
component or its ABI JSON (those two with --version). app pack packs the lock into
the release and refuses one that disagrees with the ABI.
Your build.rs then turns the vendored ABIs into one typed client per reference:
[build-dependencies]calimero-app-build = { git = "https://github.com/calimero-network/core", tag = "<release>" }fn main() { calimero_app_build::uses::build();}use calimero_sdk::prelude::*;
app::uses!(); // brings in the `uses` moduleEach reference becomes a module uses::<name> with:
- a
Clientwith one method per method of the target an app may call (#[app::allow(app = ..)], no passkey step); withmethodslisted, only those. Each answers a future you.awaitin anasync fnmethod, and futures awaited together run at once (below);send()has the calls as asynchronous messages (env::xcall), sent after your run commits; - the target’s types from its ABI’s
types, and a type it names without describing as its JSON (serde_json::Value); Error, the target’s own#[app::error]enum, plusOtherfor any other failure. On the wire it staysXcallFailed { code, fields }:?passes it on unchanged.
uses::<name>() reads the link (env::linked) and answers NotLinked { name } when
there is none; uses::<name>::Client::linked() is the same as an Option. A misspelled
method or a wrong argument is now a compile error, and a new release of the target
reaches your code only through meroctl app uses update.
Three example apps in core’s apps/ show each step, with harness tests:
calendar: the app the other two use. It keeps each caller’s events, andenv::via()keeps a person’s private events from an app acting for them.planner:create. Each planner comes with its own calendar and calls it as itself.booking:attachplus delegation. The owner attaches a calendar, and with a person’s grant a booking lands in their own calendar; the calendar’sPrivateThroughAppcomes back typed.
2. Use an app created with your instance
Section titled “2. Use an app created with your instance”When someone creates an instance of your release, the node first creates each
create reference in the same organization, owned by the same person, and named
<instance>.<name>; an instance from a deployment gives them its deployment, so
their usage is billed to you as the instance’s is. Deleting the instance deletes
them, and none is deleted alone while it stands. Your init can take their ids:
#[app::init]pub fn init(links: Option<BTreeMap<String, String>>) -> app::Result<Self> { .. }Any method calls it through its generated client, which reads the link
(env::linked) each time. A method that calls another app is an async fn: the
client’s methods are futures, and the SDK runs the method until it waits on them:
pub async fn put(&mut self, key: String, value: String) -> app::Result<()> { let kv = uses::kv()?; // `NotLinked { name: "kv" }` without a link let _version: u64 = kv.set(&key, &value, None).await?; Ok(())}Calls and views that do not depend on each other go together: app::join! (two to
eight futures, answered as a tuple) and app::join_all (a list) send them to the node
in one batch, which it runs at once, so your run waits for the slowest instead of
their sum:
#[app::view]pub async fn overview(&self, day: String) -> app::Result<Overview> { let (cal, rooms) = (uses::calendar()?, uses::rooms()?); let (events, free) = app::join!(cal.my_events(), rooms.free_rooms(&day)); Ok(Overview { events: events?, free: free? })}Awaited one after another, they run one after another. Every call and view counts toward a run’s 16 synchronous xcalls, joined or not (Synchronous calls and views).
A call commits in the other app’s own log before your run continues. It is not atomic with your run: if your method fails after it, your changes are dropped but the other app keeps what the call did. Make the call last, or make the other app’s method safe to have run. A view reads the other app’s latest committed state.
The member must admit your app, like any app called by another (Cross-app calls).
Serve the instance that created you
Section titled “Serve the instance that created you”The other way round, an app built to be created by others (a confidential KV
store, a private inference endpoint) asks who created it with env::unit_of():
the id of the instance whose unit it is a member of, None for an app created on
its own. Confidential KV and Private Inference releases take app:<env::unit_of()>
as their admin, so the app that created them uses them at once, with no grant step:
fn is_admin() -> bool { env::unit_of().is_some_and(|parent| env::caller() == env::Caller::App(parent))}It is derived from the instance’s record as the node holds it now, so it is None
again once that instance is deleted.
3. Use an app the owner already runs
Section titled “3. Use an app the owner already runs”An attach reference starts empty. The owner fills it with an app they manage in the
same organization, confirming with their passkey:
PUT /apps/{your-app}/links/calendar { "app": "<their calendar's id>" }DELETE on the same path detaches it, and deleting the calendar detaches it too.
GET /apps/{your-app}/links lists every reference, the app linked under it, the
release that app runs and whether that release is inside your range (inRange).
Read the link each time you call. The owner may attach another app later, or none:
let calendar = uses::calendar()?; // `NotLinked { name: "calendar" }` until one is attachedmatch calendar.add_event(&title, &at, private).await { Ok(()) => {} // The calendar's own error, typed. Err(uses::calendar::Error::PrivateThroughApp) => app::bail!(Error::PrivateNotAllowed), Err(other) => return Err(other.into()), // passed on as `XcallFailed`}4. Upgrade together
Section titled “4. Upgrade together”The apps your instance created upgrade with it, in one approval:
- From your frontend: ask the node’s consent page with
upgradeUnit { app, toVersion }. It shows every app’s changes on one page. - From a client: call
POST /apps/{app}/upgrade-unit { version }.
Each member moves to the release your new version pins for it, else the newest
installed one inside its range. A member cannot be upgraded on its own outside the
range your instance takes it with (409 OUTSIDE_UNIT_RANGE).
An attached app is never upgraded with yours: it is the owner’s own. When a new release of yours takes it in another range, the upgrade’s consent page warns them.
5. Act as the person
Section titled “5. Act as the person”By default your call reaches the other app as your app (Caller::App), and it never
learns whom you were serving. To work on the calendar as its user, for example to
book into their own calendar with their own permissions there, the person allows it
once:
- Your release lists the methods in the reference’s
methods(step 1). - Your frontend asks the node’s consent page with
delegate { app, target }. The page names both apps and every method, and the person confirms with their passkey. Your frontend cannot grant this through the API by itself. - From then on, when that person’s call runs your app, your calls of those methods reach the calendar as the person.
The calendar needs no change. It sees its own user calling, with its usual rules.
If it wants to treat a call through another app differently, env::via() names the
app it came through:
pub fn create_event(&mut self, event: Event) -> app::Result<()> { let env::Caller::Account(who) = env::caller() else { return Err(AppError::forbidden()); }; if env::via().is_some() && event.private { // Through a plugin, only public events. return Err(AppError::forbidden()); } self.events.insert(&event.id, &Event { owner: who, ..event })?; Ok(())}A grant covers only the listed methods, and only while the person still reaches
both apps. Anything else runs as your app: another method, a timer, an action, or a
call your app received from another app. A method that needs the person’s passkey
confirmation is refused, so a plugin never confirms for them. The person takes the
grant back with DELETE /apps/{app}/delegations/{target}, and
GET /apps/{app}/delegations lists what they allowed. The protocol is in
As the person.
Without a generated client
Section titled “Without a generated client”A target your app only learns at run time (an id a caller passes, not a reference) has
no vendored ABI. Call it with the raw calls the client is built on, env::xcall_call
and env::xcall_view (futures, as the client’s) and env::xcall, with the method’s
name and its arguments as JSON
(Cross-app calls):
let version: String = env::xcall_call(&app_id, "set", &json!({ "key": key, "value": value })).await?;Nothing checks the name or the arguments before the run: a mistake is an
XcallFailed from the target, and u64/i64 travel as decimal strings, bytes as
base64url, by hand.
Test it
Section titled “Test it”In the test harness, TestApp::link(name, Some(app)) sets what env::linked
returns, and deliver_for(from, account, method, args) runs a delivered call as the
person, with env::via() naming from (Testing). mock_app(app, handler)
plays the other app: return Err(json!({ "code": "PrivateThroughApp", "fields": {} }))
to see your code get its typed error.