# Internet Computer Skills: full corpus > Agent-readable skill files for building on the Internet Computer. > Publisher: DFINITY Foundation (https://dfinity.org) > License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0) > Source: https://github.com/dfinity/icskills > Generated: 2026-11-16T18:14:55.237Z > Skills: 42 > This file concatenates every SKILL.md served at https://skills.internetcomputer.org/skills/. Each skill block is delimited by a header and an HTML comment with source URLs. --- ## Agent Web Identity Sign-In --- name: agent-web-identity description: "Lets an AI agent or CLI session sign in to Internet Identity and act as a user's app-specific principal (e.g. for oisy.com or nns.ic0.app) via `icp identity link web`. Use when the user asks an agent to log in to an II-powered app, obtain a delegation, or make authorized canister calls on their behalf. Do NOT use for adding II sign-in to a frontend — use the user-sign-in skill instead." license: Apache-2.0 compatibility: "icp-cli >= 0.3.0, browser on the same machine" metadata: title: Agent Web Identity Sign-In category: Auth --- # Agent Web Identity Sign-In ## What This Is Internet Identity (II) supports a CLI-auth flow that issues a delegation for a session key held *outside* the browser. `icp identity link web` uses it to let a terminal session — including an AI agent such as Claude Code — sign canister calls as the user's **app-specific principal**: the same principal the user has when signed in to that app's web UI (selected with `--app `). The user still authenticates interactively in their own browser with their passkey; the agent only ends up holding a time-limited delegation. The private key of the user's II identity is never exposed. ## Prerequisites - `icp` CLI installed (https://cli.internetcomputer.org). See the `icp-cli` skill for general usage. - The user must have an Internet Identity (id.ai) and be present to complete the browser sign-in. - First-time use requires the user to enable the **CLI access** toggle for their identity in II settings (see Pitfall 1). - The agent and the user's browser must be on the same machine: the flow delivers the delegation via a localhost callback. It does not work from remote/headless environments (containers, CI, web sessions). ## Common Pitfalls 1. **First-time sign-in fails with a "CLI access disabled" screen.** This is the expected first-run path, not an error. Tell the user to enable CLI access for their identity in II settings, then **restart the flow from scratch** — the previous sign-in URL is single-use (its nonce and localhost listener are dead). Plan for two rounds on first use. 2. **The link command waits for an Enter keypress before doing anything.** On 0.3.x it first prints `Press Enter to log in at https://id.ai/cli` and blocks reading stdin; only after that does it start the flow and try to open the browser. In a background or non-interactive run, **pipe an actual newline into it** (`printf '\n' | icp identity link web ...`). Do NOT redirect from `/dev/null`: a bare EOF does **not** satisfy the prompt on 0.3.2 — the command sits on `Press Enter to log in` and never starts the flow, so you waste the first attempt and have to restart, prompting the user twice. Feed the newline on the first try and the flow starts immediately. 3. **Don't assume the browser opened.** Sandboxed or non-interactive shells often can't launch a GUI browser. Read the command's output: if a full sign-in URL is printed, show it to the user to open themselves. If the output shows neither a browser launch nor a URL, report that — do not construct a URL by guessing, and ask the user whether a browser window appeared. 4. **The command blocks until sign-in completes and gets killed by tool timeouts.** Run `icp identity link web` as a background task, then wait for the user to confirm they finished signing in before checking the result. The command must also be able to bind a localhost port; if a sandbox blocks this, ask the user before rerunning unsandboxed. 5. **Relying on the default identity signs with the wrong principal.** Every `icp` command acting as the user must pass `--identity ` explicitly. Never depend on project or global default identity settings, and never change them. 6. **Reusing or overwriting identities.** Never reuse an existing identity, even if `icp identity list` already shows one linked for the same app — its delegation may be expired and it belongs to whoever created it. Always create a fresh identity per session: check `icp identity list`, then pick a unique name prefixed with the agent's own identifier, `--` — e.g. `claude-oisy-20260611-1530` for Claude, `cursor-oisy-...` for Cursor; use `agent-` if no identifier is known. Never overwrite an existing identity. `icp identity list` is read-only context for picking a free name — never delete, rename, reauth, or otherwise modify any identity you did not create this session, even ones with the agent's own prefix left over from a previous run. Operate only on `$NAME`. Why per-session and not one reused identity per app: `--app` derives the *same* app principal for a given II identity, so a fresh identity grants no extra authority isolation — the point is **provenance and blast radius**. A per-session identity keeps `icp identity list` auditable (which session created which live delegation), lets cleanup delete exactly that one, and avoids a shared identity where another session's `reauth` silently mutates a delegation this session is mid-task with. When scanning `icp identity list` to pick a name, if you see multiple stale agent-prefixed identities for the same app from past sessions (e.g. several `claude-oisy-*` entries), offer to clean them up before proceeding: present the list, wait for the user to confirm each one, then delete them with `icp identity delete `. Never delete without explicit confirmation. 7. **Wrong principal because `--app` was omitted.** Without `--app`, the provider uses its default derivation origin and the resulting principal will NOT match the user's principal in the target app. Pass the app's bare domain (no scheme, port, or path), e.g. `--app oisy.com`. 8. **Expired delegations.** Delegations are time-limited; the lifetime is set by the identity provider during sign-in. `icp identity link web` has NO flag to control it — do not invent one (e.g. `--ttl`; 0.3.x rejects it and the whole command fails). When calls start failing with signature/expiry errors, run `icp identity reauth ` — the user must sign in again as the same identity. 9. **Canister calls without explicit arguments auto-cancel.** When call arguments are omitted, `icp canister call` opens an interactive prompt to build the arguments and confirm sending (`Do you want to send this message? [y/N]`), which immediately cancels in a non-interactive shell (`User cancelled.`). Always pass arguments explicitly — including the empty tuple `'()'` for zero-argument methods like `whoami`. ## Implementation Generalized flow for linking the user into `` (e.g. `oisy.com`, `nns.ic0.app`): ```bash # 1. Pick a fresh name (never reuse an existing identity, even one # already linked for this app); confirm it doesn't exist icp identity list NAME="agent--$(date +%Y%m%d-%H%M)" # substitute your own agent prefix for "agent" if known, # e.g. claude-oisy-20260611-1530, cursor-oisy-... # 2. Start the link flow IN THE BACKGROUND (keeps the localhost # listener alive while the user signs in). Use your harness's # background-execution mode if it has one; in a plain shell: printf '\n' | icp identity link web "$NAME" --app \ > "/tmp/icp-link-$NAME.log" 2>&1 & # Pipe a real newline to answer the "Press Enter to log in" prompt. # Do NOT use `< /dev/null`: on 0.3.2 a bare EOF does not satisfy the # prompt, so the command hangs and you'd have to restart it — which # prompts the user a second time. The newline starts the flow on the # first try. # 3. Read the command's output (the log file above). After the Enter # prompt it tries to open the user's browser; if a sign-in URL is # printed instead, relay it to the user. Wait for them to confirm # sign-in (first run may require enabling CLI access in II settings # — restart from step 2 if so) # 4. Confirm the identity was created icp identity list ``` ## Verify It Works Call the public whoami canister as the linked identity: ```bash icp canister call --identity "$NAME" --network ic \ ivcos-eqaaa-aaaab-qablq-cai whoami '()' ``` (Adapt flags to the installed CLI version — see `icp canister call --help` — but always keep the explicit `--identity` and the explicit `'()'` arguments; omitting the arguments triggers an interactive prompt that auto-cancels in non-interactive shells, see Pitfall 9.) The returned principal should match the principal the app shows the user when they are signed in to ``; ask the user to confirm. ## Security Rules for Agents - The delegation grants **full authority as the user's app principal** until it expires — it is not scoped to specific canisters. Treat it like a signed blank check for that app. - Other than the whoami verification, ask the user explicitly before every state-changing canister call made with the linked identity. - The delegation's lifetime is decided by the identity provider, not the CLI — there is no flag to shorten it. - Never export, print, or log the identity's key material; leave it in the CLI's default keyring storage. - Give the identity a name unique to this session. The keyring entry holding the session key is keyed by service `icp-cli` plus the identity name, and that key is shared across the whole OS user — setting `ICP_HOME` does not isolate it. Two concurrent agents that link a web identity under the same name overwrite each other's session key. Prefix with the agent and app (e.g. `claude-oisy-`); see "Parallel agents and worktrees" in the `icp-cli` skill for the wider isolation picture. - Keep output to the minimum. When a step succeeds, don't echo command output or narrate progress — surface only what needs the user: the sign-in URL, confirmation requests, errors, and the final verified principal. - When done, do NOT delete the linked identity on your own initiative — the user may want to reuse the live delegation for follow-up calls. Ask the user whether to clean it up, and only on their confirmation run `icp identity delete ` (the subcommand is `delete`; `remove` is not a valid subcommand on 0.3.x). If they decline, just remind them of the identity name and that command so they can remove it later. - At the start of a session, when `icp identity list` reveals accumulated stale agent-prefixed identities from past sessions (e.g. multiple `claude-oisy-*` entries), offer to delete them before creating a new one. Present the list to the user, wait for confirmation, and delete only the approved ones with `icp identity delete ` — never in bulk, never without confirmation. --- ## Automatically Sync Latest IC Skills --- name: autosync-ic-skills description: One-time installer that makes a Claude Code project keep its Internet Computer skills up to date automatically. Sets up a SessionStart hook plus a sync script so .claude/skills/ always mirrors the latest skills published at skills.internetcomputer.org. Use when a user wants to install, bootstrap, or enable "always-latest" Internet Computer / IC / ICP / Motoko skills in a project, or pastes the link to this skill. This is a one-time setup action, not ongoing IC knowledge — after it runs, the installed hook keeps skills current on every session. Do NOT use for IC coding questions themselves — this only configures auto-updating skills. license: Apache-2.0 metadata: title: Automatically Sync Latest IC Skills category: Infrastructure --- # Set up self-updating Internet Computer skills This skill installs a small amount of project configuration so that **every new Claude Code session automatically downloads the latest Internet Computer skills** into `.claude/skills/`, where Claude discovers and triggers them natively. It is a **one-time installer**. After you complete the steps below, the user never needs this link again — the installed `SessionStart` hook does the work from then on. ## What you will create 1. `.claude/sync-ic-skills.sh` — a **differential** sync script that mirrors the live skill index into `.claude/skills/`. 2. A `SessionStart` hook in `.claude/settings.json` that runs that script. 3. An immediate first run, so skills are present right away. The script is a **differential mirror**. It fetches the discovery index once and compares each skill's published `hash` against a stored manifest, re-downloading only the skills that actually changed (and pruning ones removed upstream). Unchanged skills are skipped with no per-file downloads, and the script writes nothing to stdout unless something changed. If the server does not publish a `hash` for a skill, the script falls back to re-downloading it every run, so it remains correct either way. ## Important: tell the user what to expect Adding a hook means a shell script will run automatically at the start of future sessions. Claude Code will ask the user to **review and trust** the new hook before it activates — this is expected and correct. Let the user know: > "I'm adding a `SessionStart` hook that runs `.claude/sync-ic-skills.sh`. Claude Code > will ask you to approve/trust it before it runs automatically. After that, your IC > skills stay current on every session." Do **not** attempt to bypass that approval. ## Step 0 — Check prerequisites (`curl`, `jq`) The sync script needs `curl` (virtually always present) and `jq` (often not). Before writing anything, check for them: ```bash command -v curl >/dev/null 2>&1 && echo "curl: ok" || echo "curl: MISSING" command -v jq >/dev/null 2>&1 && echo "jq: ok" || echo "jq: MISSING" ``` - If `jq` is **missing**, offer to install it (ask the user before running an install command). Pick the right one for their platform: - macOS (Homebrew): `brew install jq` - Debian/Ubuntu: `sudo apt-get update && sudo apt-get install -y jq` - Fedora/RHEL: `sudo dnf install -y jq` - Alpine: `apk add jq` - Arch: `sudo pacman -S --noconfirm jq` - Windows (winget): `winget install jqlang.jq` - If the user declines, still proceed — the script is written to degrade gracefully (it exits cleanly with a warning when `jq` is absent), and they can install `jq` later and the next session will sync. ## Step 1 — Download the sync script The script is published as a file alongside this skill, so you fetch it verbatim rather than transcribing it (this guarantees byte-exact content). Create the `.claude` directory and download it: ```bash mkdir -p .claude curl -fsSL https://skills.internetcomputer.org/.well-known/skills/autosync-ic-skills/scripts/sync-ic-skills.sh \ -o .claude/sync-ic-skills.sh ``` Do **not** hand-write or paraphrase the script — always fetch the published copy so the sync logic stays correct as it is updated upstream. **What the script does** (for the user's awareness): - Fetches `https://skills.internetcomputer.org/.well-known/skills/index.json` once. - For each skill, compares the published `hash` against `.claude/skills/.ic-managed.json` (a `{ "": "" }` manifest of skills it manages) and re-downloads only the skills whose hash changed or are new. - Prunes skills it previously installed that are no longer in the index, and replaces a changed skill's whole directory via an atomic staging swap — so files renamed or removed upstream don't linger inside a skill, and an interrupted download leaves the existing copy intact. - Writes nothing to stdout on a no-op sync. When something changed it prints one JSON object whose `systemMessage` carries the `added / updated / removed` summary — that string is what the user sees, because SessionStart hooks surface JSON fields rather than raw output. Its diagnostics (interrupted-sync recovery, unsafe skill names) go to stderr and so are not displayed. - Degrades gracefully: exits cleanly (keeping cached skills) if the network is down or `jq` is missing, and falls back to re-downloading skills the server publishes no `hash` for. ## Step 2 — Register the SessionStart hook (idempotently) Add a `SessionStart` hook to `.claude/settings.json` that runs the script. - If `.claude/settings.json` does **not** exist, create it with the content below. - If it **does** exist, **merge** — preserve all existing keys, hooks, and permissions. Only add the `SessionStart` entry, and **only if an equivalent `bash .claude/sync-ic-skills.sh` command is not already present** (do not create a duplicate). Parse the existing JSON, insert into the `hooks.SessionStart` array, and write it back; never blindly overwrite the file. The entry to ensure is present: ```json { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "bash .claude/sync-ic-skills.sh" } ] } ] } } ``` ## Step 3 — Run it once now Run the script immediately so the skills are available in this session without waiting for the next session start: ```bash bash .claude/sync-ic-skills.sh ``` ## Step 4 — Verify and report - Confirm `.claude/skills/` now contains skill directories (e.g. `writing-motoko`, `static-site`, `user-sign-in`, …) each with a `SKILL.md`. - Confirm `.claude/skills/.ic-managed.json` maps each synced skill name to its hash. - Tell the user: how many skills were installed, that the `SessionStart` hook is in place, and that they'll be prompted to trust the hook before it auto-runs next session. From then on, their IC skills refresh automatically every session. ## Notes - **Safe to re-run.** Re-invoking this skill or the script is idempotent: the hook is not duplicated, and only skills tracked in `.ic-managed.json` are ever pruned. - **Differential by hash.** The script keys off the per-skill `hash` field in the discovery index, so a normal session that touches nothing downloads only `index.json` and exits silently. Skills are re-downloaded only when their hash changes. Migrating from an older version of this script (whose manifest was a bare name array) is handled automatically on the next run. - **Optional mid-session refresh.** For very long-running sessions, the user can also run `bash .claude/sync-ic-skills.sh` manually, or schedule it (e.g. via `/loop` or a cron routine) — but the SessionStart hook covers the normal case. --- ## Automatically Upgrade the ICP CLI --- name: autoupgrade-icp-cli description: One-time installer that keeps a project's Internet Computer CLI toolchain current. Sets up a SessionStart hook plus a script that compares the installed `icp` and `ic-wasm` against the latest release and either reports the upgrade or applies it, using whichever channel each tool was installed from (npm, Homebrew, or the shell installer). Use when a user wants to install, bootstrap, or enable automatic icp-cli / ic-wasm updates, asks to stop running an outdated `icp`, asks how to upgrade or check the version of the ICP CLI, or pastes the link to this skill. This is a one-time setup action, not ongoing IC knowledge. Do NOT use for writing icp.yaml, deploying canisters, or other icp-cli usage questions — load `icp-cli` for those. license: Apache-2.0 compatibility: "curl, bash; network access to github.com (and formulae.brew.sh for Homebrew installs)" metadata: title: Automatically Upgrade the ICP CLI category: Infrastructure --- # Set up automatic `icp` CLI upgrades A **one-time installer**: it adds a `SessionStart` hook that checks whether `icp` and `ic-wasm` are current and — if the user wants — upgrades them before work starts. Once these steps are done the user never needs this skill again. `ic-wasm` is covered alongside `icp` because the official recipes (`@dfinity/motoko`, `@dfinity/rust`, `@dfinity/static-site`, `@dfinity/asset-canister`) invoke it on every build. An `ic-wasm` left behind while `icp` moves forward produces build failures that read as recipe bugs, so upgrading only one of the pair is the worse default. `icp` has its own check (`icp settings update-check`) that is worth leaving on, but it only speaks once the user runs an `icp` command — by which point the agent has already chosen what to write. This hook runs before the session's first prompt, so the version reaches Claude's context up front, and it covers `ic-wasm` too. ## Step 1 — Ask the user which mode they want The installer cannot make this call for the user, so ask before writing anything: > "Two options for how the hook behaves when a newer version exists: > **notify** — it prints the versions and the exact upgrade command, and nothing is > installed until you run it. **auto** — it runs that upgrade itself at session start. > Which do you want? You can switch later by editing one flag in the hook." Default to **notify** if the user has no preference — it is the reversible choice. Also tell them what adding a hook means, and do not attempt to bypass the approval: > "I'm adding a `SessionStart` hook that runs `.claude/upgrade-icp-cli.sh`. Claude Code > will ask you to approve/trust it before it runs automatically." ## Step 2 — Check prerequisites ```bash command -v curl >/dev/null 2>&1 && echo "curl: ok" || echo "curl: MISSING" icp --version 2>/dev/null || echo "icp: not installed" ic-wasm --version 2>/dev/null || echo "ic-wasm: not installed" ``` If either tool is missing, mention the install command (`npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm`) but do not run it unprompted — installing a toolchain is a different decision from keeping one current. ## Step 3 — Download the script Fetch the published script verbatim rather than transcribing it, so the channel detection stays correct as it is updated upstream: ```bash mkdir -p .claude curl -fsSL https://skills.internetcomputer.org/.well-known/skills/autoupgrade-icp-cli/scripts/upgrade-icp-cli.sh \ -o .claude/upgrade-icp-cli.sh ``` Do **not** hand-write or paraphrase it. ## Step 4 — Register the SessionStart hook (idempotently) If `.claude/settings.json` does not exist, create it with the content below. If it does, **merge**: preserve every existing key, hook, and permission, add the `SessionStart` entry only if an equivalent `bash .claude/upgrade-icp-cli.sh` command is not already there, and write the parsed JSON back. Never overwrite the file. **Notify mode** (the default): ```json { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "bash .claude/upgrade-icp-cli.sh --mode notify" } ] } ] } } ``` **Auto mode** — same entry with `--mode auto`, plus a raised `timeout`, because installing a CLI binary can exceed the default 60 s and a timed-out install leaves the tool half-written: ```json { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "bash .claude/upgrade-icp-cli.sh --mode auto", "timeout": 300 } ] } ] } } ``` Whenever you hand someone an auto-mode hook, say the thing that makes it a real choice: it upgrades the build toolchain **while a project is open** and blocks session start while it runs, so a session can begin against a different `icp` than the last one ended with — which can change build behaviour and output for a project that built fine yesterday. That is what some teams want and what others pin against. ## Step 5 — Run it once, verify, report ```bash bash .claude/upgrade-icp-cli.sh --mode notify # or --mode auto, matching the hook ``` Silence means both tools are current — that is the success case, not a failure. A hand-run always checks the network; the hook throttles (below), so this is also the command for whenever someone wants an answer now. Then confirm the hook entry appears exactly once, report the versions found and whether anything was upgraded, and remind the user of the trust prompt. If the project commits `.claude/`, add `.claude/.icp-upgrade-check` to `.gitignore` — it is a per-machine timestamp, not shared configuration. ## How the script decides what to run It resolves each binary through its symlinks and reads the install channel off the path, because the upgrade command differs per channel and guessing wrong leaves two copies of the CLI on `PATH` shadowing each other: | Where the binary resolves to | Channel | Upgrade command (`icp` / `ic-wasm`) | |---|---|---| | `…/node_modules/@icp-sdk/…` | npm | `npm install -g @icp-sdk/icp-cli@latest` / `npm install -g @icp-sdk/ic-wasm@latest` | | `…/Cellar/…` | Homebrew | `brew upgrade icp-cli` / `brew upgrade ic-wasm` | | a cargo-dist receipt in `~/.config//` | shell installer | `icp-cli-update` / `ic-wasm-update` | | anything else | unknown | *(none — reports the release URL instead)* | That last row is deliberate: an unrecognised install is reported, never guessed at. Two consequences worth passing on to users: - **A shadowed install never moves.** If an upgrade succeeds but `PATH` still resolves to the old version, a second copy from another channel is winning — commonly an npm global under `nvm` alongside a shell-installer copy in `~/.cargo/bin`. Upgrading one channel can never touch the other's copy; resolve the binary (`command -v icp`) to see which wins, then remove one or upgrade the one actually on `PATH`. - **Auto mode never runs `sudo`.** A non-writable npm prefix is reported as a `sudo …` command instead, since a password prompt inside a hook has no terminal to answer it. ## Throttling A check that reached a release feed is stamped in `.claude/.icp-upgrade-check` and not repeated for 6 hours, so the hook costs ~10 ms on most session starts instead of ~1 s. Override with `ICP_UPGRADE_CHECK_INTERVAL=` (`0` disables it) or bypass once with `--force`; a run from a terminal always checks. A failed probe is not stamped, so an offline session retries at the next one. ## What this does *not* upgrade The hook manages the two CLI binaries only. Recipe versions in `icp.yaml` (`@dfinity/motoko@v5.0.0` and friends) and the Motoko toolchain (`moc`, `mops`, the `[toolchain]` pin in `mops.toml`) are pinned per project and stay the user's call — load `icp-cli` and `mops-cli` respectively for those. If a build starts failing right after an auto upgrade, check the [icp-cli release notes](https://github.com/dfinity/icp-cli/releases) before assuming the project broke. ## Additional References - **`icp-cli`** — using the CLI itself: `icp.yaml`, recipes, environments, deployment. - **`mops-cli`** — the Motoko toolchain and its own version pinning. - **`autosync-ic-skills`** — the companion installer that keeps the IC *skills* in `.claude/skills/` current. The two are independent; installing both is common. --- ## Buy Cycles With a Card --- name: buy-cycles description: "Buy cycles with a credit card for the CLI's own identity with `icp cycles buy`, through CyclePay's on-chain gateway, then continue deploying. Use when a mainnet deploy or canister creation fails for lack of cycles, the user has no ICP, no wallet or no exchange account, or asks to pay for cycles by card, Stripe, fiat or USD. Do NOT use for converting ICP you already hold (cycles-management: `icp cycles mint`), for topping up a canister from an existing balance, or for Internet Identity sign-in (agent-web-identity)." license: Apache-2.0 compatibility: "icp-cli with `icp cycles buy` (dfinity/icp-cli#815; `icp cycles --help` lists `buy`), or any icp-cli >= 1.0 for the `icp canister call` fallback. Mainnet (`-n ic`). A human with a browser on any device to pay." metadata: title: Buy Cycles With a Card category: Infrastructure --- # Buy Cycles With a Card ## What This Is A cycles gateway is a canister that takes an order for cycles, has the buyer pay for it by card on a hosted Stripe page, and delivers the cycles on-chain. `icp cycles buy` makes the **CLI identity the buyer**: the identity that will run `icp deploy` creates the order itself, so the cycles land on that identity's own cycles-ledger account and nothing has to be linked, signed in or transferred afterwards. The agent's job is to create the order, hand the payment link to the human, wait for delivery, and carry on deploying. The default gateway is [CyclePay](https://www.cyclepay.org), run by the DFINITY Foundation: backend canister `2bwus-iiaaa-aaaac-bee3a-cai`, **mainnet only**, USD only. Everything the command quotes with is read from the gateway at run time (`get_card_terms`, `get_xdr_rate_status`): the per-order range (USD 1 to 200 at the time of writing), the card fee (2.9 % + 0.30 USD), the cycles-ledger delivery fee (200 M cycles) and the USD per XDR rate (1 XDR = 1 T cycles). Do not hardcode any of them. Card details never touch the canister or the CLI. ## Prerequisites - `icp` CLI installed (https://cli.internetcomputer.org); load the `icp-cli` skill for general usage and the `-n` / `-e` flag rule. `icp cycles --help` must list `buy`; otherwise use the fallback below. - A **named** `icp` identity for the project. The anonymous identity is refused, and the identity that buys must be the one that deploys. - A human who can open a URL on **some** device (laptop, phone). The agent's machine needs no browser. ## The Flow ```bash # 1. Who is buying, and what they hold now icp identity principal --identity "$ID" icp cycles balance -n ic --identity "$ID" # 2. Buy (spend 10 USD; or `--cycles 5t` to pay the least that buys 5 T cycles -- for a deploy, # the gap from the `icp-cli` skill's pre-deploy estimate, N canisters × (2T + 100M) − balance) icp cycles buy --amount 10 -n ic --identity "$ID" --no-open --yes --json # stdout, line 1, as soon as the order exists: # {"order_id":"co-12-…","checkout_url":"https://buy.stripe.com/…","amount":{"currency":"USD","value":"10.00"}, # "net":{"currency":"USD","value":"9.41"},"fee":{"currency":"USD","value":"0.59"}, # "estimated_cycles":"6959859171597","expires_at":"2026-10-15T18:03:12Z"} # → show checkout_url to the user VERBATIM and ask them to pay on it (any device). # The command polls every 3 s for up to an hour, then prints line 2 and exits 0 only on delivery: # {"order_id":"co-12-…","status":"delivered","cycles_delivered":"6938000000000", # "paid":{"currency":"USD","value":"10.00"},"refunded":null,"detail":null,"balance":"6938000000000"} # 3. Continue as the same identity icp cycles balance -n ic --identity "$ID" icp deploy -e ic --identity "$ID" ``` Without `--yes` the command shows the quote and asks for confirmation, which needs a terminal; without one it prints the quote and refuses (`Use --yes to proceed`), creating nothing — a usable dry run when the user wants to see the figures first: ``` Identity: dev Buyer: 7k7px-dcypq-wulnh-byzgd-6sib2-udn6c-lfo6e-6oujd-veifp-62woo-5ae Gateway: 2bwus-iiaaa-aaaac-bee3a-cai (CyclePay) Price: 10.00 USD (9.41 USD after a 0.59 USD card fee) Estimate: about 6.959T cycles, at 1.3520 USD per 1T cycles ``` Flags that matter to an agent: `--no-open` (never let the CLI try a browser), `--json` (two objects on stdout, one per line, never an array; progress and prompts go to stderr), `-q` (stdout is the link, then the final status tag), `--no-wait` (print the link and return; the order needs nothing more from the CLI), `--gateway ` / `ICP_CYCLES_GATEWAY_CANISTER_ID` (another canister serving the same interface, on any network). ### Fallback: the same order with `icp canister call` Only when the installed CLI has no `cycles buy`. Same canister, same identity rules. The argument and reply shapes are those of [`cycles_gateway.did`](https://github.com/dfinity/icp-cli/blob/main/crates/icp-cli/src/cyclepay/cycles_gateway.did), which icp-cli holds against CyclePay's backend interface; this sequence was run against icp-cli's stand-in gateway and mainnet's public queries on 2026-10-14. ```bash GW=2bwus-iiaaa-aaaac-bee3a-cai icp canister call "$GW" get_card_terms '()' -n ic --query # deliveries_paused, min/max_order_usd_cents, fee_bps, fee_fixed_usd_cents, ledger_delivery_fee_cycles icp canister call "$GW" get_xdr_rate_status '()' -n ic --query # xdr_usd_x10000, stale # Create: USD cents, destination = the caller's own cycles-ledger account. icp canister call "$GW" create_order \ '(record { destination = variant { Ledger }; beneficiary = null; project_id = null; amount_usd_cents = 1000 : nat64; confirm_system_canister = null })' \ -n ic --identity "$ID" # Ok = record { order_id = "co-…"; payment_url = "https://…"; net_usd_cents; expires_at } # Err = record { code = "AMOUNT_OUT_OF_RANGE"; message = "…" } (nothing was created) # Wait: poll until the status is Delivered, or one of the end states in Pitfall 6. icp canister call "$GW" order_status '("'"$ORDER_ID"'")' -n ic --query --identity "$ID" \ | grep -oE 'status = variant \{ [A-Za-z]+' ``` To extract the link from the Candid text, take the quoted string after `payment_url =` **unchanged**: `grep -oE 'payment_url = "[^"]+"' | sed -E 's/.*"(.*)"/\1/'` (Pitfall 2). Cycles to expect, before the ledger fee: `net_usd_cents / 100 / (xdr_usd_x10000 / 10000)` trillion, where `net = amount − (amount × fee_bps / 10000 + fee_fixed_usd_cents)`, rounded to the cent. ## Common Pitfalls 1. **The cycles go to the buyer's own cycles-ledger account, nowhere else.** The CLI has no "send to my canister" option. From there, `icp deploy -e ic` creates canisters out of the balance and `icp canister top-up --amount -e ic` funds one. `icp cycles transfer` to a canister principal credits that principal's *ledger* balance, not the canister's execution balance (see `cycles-management`). 2. **Never "clean up" the Candid text a link arrives in.** Candid prints numbers with underscore separators (`6_938_000_000_000`), and a regex that strips underscores turns `client_reference_id=o_co-12-…` into a link to the wrong order. Prefer `--json`; in the fallback, extract the quoted URL exactly and strip underscores only from values that are all digits. 3. **The agent cannot pay, and usually cannot open a browser.** Print the link and ask the human to open it; they may use another device. Never ask for or type card details. `--yes` is fine for an amount the user asked for: creating an order charges nothing, and the human sees the price again on the payment page before paying. 4. **`-n ic` is required, `-e ic` is not accepted here.** CyclePay sells on mainnet only. Run outside a project or against a local network and the command fails with `this network is not mainnet` or `is not running`, each ending in ``CyclePay sells cycles on mainnet: use `-n ic` ``. The deploy that follows takes `-e ic` as usual (`icp-cli` Pitfall 2). 5. **Buy and deploy as the same, named identity.** The command refuses the anonymous identity, and `icp deploy` spends the *default* identity's balance unless `--identity` is passed. A purchase as one identity and a deploy as another fails with insufficient cycles while the balance sits one identity over. Pass `--identity "$ID"` everywhere, or check `icp identity default` first. 6. **Stopping the command does not stop the order, and there is no resume.** Ctrl-C (or a killed process) leaves the order payable; once paid, the cycles land anyway and `icp cycles balance -n ic` shows them. Do not create a second order for the same purchase; the gateway caps open orders per principal (`TOO_MANY_OPEN_ORDERS`). To watch the first one again, poll `order_status` as in the fallback. An unpaid order expires (the `expires_at` in the JSON, about a day) with nothing charged; start a new one then. 7. **Read the final status before deciding anything.** The command exits 0 only for `delivered`; the JSON `status` (or the human message) says why otherwise: - `processing` / `payment_pending`: the card was charged and delivery is under way. Keep waiting or poll; never re-order. - `needs_review`: charged, and a CyclePay operator settles it by hand. Report the order id and the charge to the user and stop. - `refunding` / `refunded`: not delivered, the money comes back (`refunded` says how much). A new order is fine once the user agrees. - `refund_owed`: not delivered, an operator refunds by hand. Keep the order id. - `unknown` (`--json`) / "a state this version of icp does not know": a status newer than the CLI; poll `order_status` to read it. 8. **The quote is an estimate; delivery is net of a ledger fee.** The cycles are minted at the rate in force when the payment lands, so `cycles_delivered` can differ slightly from `estimated_cycles`, and the gateway's `ledger_delivery_fee_cycles` (200 M) comes off a ledger delivery. That is not a short delivery. A stale-rate warning on stderr means CyclePay has not refreshed its rate for longer than it tolerates; tell the user before they pay. With `--cycles N` the command pays the smallest amount, to the cent, that buys at least `N` at the quoted rate. 9. **A refusal is `CyclePay refused the order: : `, and nothing was created.** `AMOUNT_OUT_OF_RANGE`: the terms set the range (USD 1 to 200), pick an amount in it. `CARDS_UNAVAILABLE` / `PAUSED`: the gateway is not taking card orders, try later. `RATE_LIMITED` / `TOO_MANY_OPEN_ORDERS`: wait, or pay the open order (Pitfall 6). Do not loop on any of them. 10. **`failed to read the card terms`** means the canister does not serve the gateway interface: a `--gateway` that is not a cycles gateway, or an old CyclePay deployment. Check the canister id; do not fall back to guessing a Payment Link. ## Verify It Works ```bash icp cycles balance -n ic --identity "$ID" # ≈ estimated_cycles − 200_000_000 after a first purchase icp canister call 2bwus-iiaaa-aaaac-bee3a-cai order_status '("'"$ORDER_ID"'")' -n ic --query --identity "$ID" \ | grep -E 'status|cycles_delivered|paid_usd_cents' # status = variant { Delivered }; cycles_delivered = opt (6_938_000_000_000 : nat64) ``` `order_status` answers only the identity that created the order (`null` for anyone else, and for an unpaid order after it expired). Purchases also appear under "My purchases" on www.cyclepay.org when the user signs in there with the same identity: `icp identity link web cyclepay --app 4w3yu-fyaaa-aaaac-beeoa-cai.icp0.io` makes one. ## Security Rules for Agents - Create orders only for an amount the user named, as the identity they will deploy with, and relay the `amount`, `fee` and `estimated_cycles` the command prints. - Hand over the payment link and stop. Do not attempt to automate the payment page. - Never collect, store or echo card details; the hosted Stripe page is the only place they are entered. - Treat the order id as a reference, not a secret: it travels in the payment link. - When a purchase ends in `needs_review` or `refund_owed`, report the order id and the charge to the user and do not retry. --- ## Caffeine App (build from scratch) --- name: caffeine-app description: "Scaffold and build a complete Caffeine app (caffeine.ai) from scratch — the project layout, the caffeine.toml workspace + canister manifests, the mops.toml for the single Motoko `backend` canister, the React/Vite frontend, and the caffeine CLI build loop (auth login, doctor, install, check --fix, preview --build). Use whenever the user wants to create, scaffold, set up, or build a Caffeine app or a caffeine.ai project, asks about caffeine.toml or mops.toml structure, or needs the caffeine CLI workflow — even if they do not say the words 'from scratch'. Always pair it with the `writing-motoko` skill for the backend code. Do NOT use it for Motoko language syntax or compiler errors (use the `writing-motoko` skill), and do NOT use it for generic Internet Computer / dfx / icp deployment (use the `icp-cli` skill)." license: Apache-2.0 compatibility: "@caffeineai/cli (the `caffeine` command), Node.js >= 20.19, pnpm, mops >= 3.0.0, network access + a caffeine.ai account" metadata: title: "Caffeine App (build from scratch)" category: Integration --- # Caffeine App (build from scratch) Caffeine (caffeine.ai) builds and hosts full-stack apps on the Internet Computer: a single **Motoko backend canister** plus a **React/Vite frontend** served as an assets canister. This skill teaches the exact **project shape** and the **CLI build loop** so you can produce a buildable Caffeine app from nothing. **This skill owns the project shape and the build workflow. It does NOT own the Motoko language.** Before you write or edit any backend code, fetch and follow the `writing-motoko` skill: . That skill is authoritative for actor syntax, stable state, `mo:core`, and compiler errors. This skill only shows the minimal empty actor and where it lives. ## When to use this skill - Creating/scaffolding a new Caffeine app or caffeine.ai project from scratch. - Writing or fixing `caffeine.toml` (workspace or canister manifest) or `mops.toml`. - Running the caffeine CLI loop: `auth login`, `doctor`, `install`, `check`, `preview`. Do **not** use it for Motoko language details (use `writing-motoko`) or for raw IC/`dfx`/`icp` deployment (use `icp-cli`). Caffeine apps are built and deployed through the `caffeine` CLI and the caffeine.ai web app, **not** through `dfx`. ## Critical facts - **There is no `caffeine init` / `caffeine new`.** "From scratch" means you create the files in this skill by hand, then run the build loop. (`caffeine projects clone ` only downloads an *existing* cloud project, and `caffeine projects import ` only unpacks a project archive such as one made by `caffeine export`; neither is a greenfield scaffold.) - **Exactly one backend canister, and it must be named `backend`.** `mops.toml` declares a single `[canisters.backend]`. - **The frontend↔backend binding files are generated, never hand-written.** `src/frontend/src/backend.ts` and `src/frontend/src/declarations/` are produced by `caffeine-bindgen` during the build. Editing them is pointless — they are overwritten. - **Deploying to a live URL is done in the caffeine.ai web app, not the CLI.** The CLI takes you as far as a built **draft** (`caffeine preview --build`, which needs a cloud `project.id` — see the build loop). There is no `caffeine deploy`/`publish` command. ## Prerequisites (run once) ```bash # Install the CLI (public npm package). The binary is `caffeine`. npm install -g @caffeineai/cli # Authenticate against caffeine.ai. Opens a browser; without one (or with --device) it # uses the device flow. On a host with no OS keychain (headless Linux, containers), add # --insecure-storage to keep the token in ~/.caffeine/tokens.json (mode 0600) instead. caffeine auth login caffeine auth status # Check the environment: Node, pnpm, mops, caffeine-bindgen, that you are logged in, # and that the Caffeine API is reachable (installs what it can). caffeine doctor --fix ``` If a global install is undesirable or fails, run every `caffeine` command through an `npx -y @caffeineai/cli@latest` prefix instead — e.g. `npx -y @caffeineai/cli@latest auth status`. `caffeine doctor` requires Node.js 20 or later (the template's `engines` field asks for `>=20.19.0`) and checks pnpm, mops (2.13.0 or later), `caffeine-bindgen`, your login, and whether the Caffeine API is reachable. With `--fix` it installs a missing pnpm, a missing or outdated mops (`ic-mops`), and a missing `caffeine-bindgen` (`@caffeineai/bindgen`) with `npm install -g`; it does not install Node.js. It does **not** install the Motoko compiler (`moc`) or linter (`lintoko`): mops fetches those automatically from the `[toolchain]` pins in `mops.toml`. On Windows, compiling Motoko requires WSL. `dfx` is not part of the Caffeine build. ## Project shape A Caffeine app is a pnpm workspace with a root manifest and two canisters. Create this exact tree (file contents below): ```text my-app/ ├── .old/src/backend/dist/ │ └── backend.most # stable-signature baseline — seed with an empty actor (see below) ├── caffeine.toml # root workspace manifest — MUST contain [workspace] ├── mops.toml # Motoko build config — ONE per project, at the root ├── package.json # pnpm workspace root + the `bindgen` script ├── pnpm-workspace.yaml # declares src/**/* as workspace packages ├── tsconfig.json # root TS config └── src/ ├── backend/ # the single Motoko canister, named "backend" │ ├── caffeine.toml # canister manifest: type = "motoko" │ ├── main.mo # actor entry point (write with the `writing-motoko` skill) │ └── migrations/ # enhanced-migration chain (see the `mops.toml` notes) │ └── 00000000_000000.mo # first migration: initializes the actor's stable state └── frontend/ # the assets canister (React + Vite) ├── caffeine.toml # canister manifest: type = "assets" ├── package.json # frontend deps + scripts (see references/frontend-template.md) ├── vite.config.js # (see references/frontend-template.md) ├── tsconfig.json # (see references/frontend-template.md) ├── biome.json # (see references/frontend-template.md) ├── tailwind.config.js # (see references/frontend-template.md) ├── postcss.config.js # (see references/frontend-template.md) ├── index.html ├── env.json # runtime config — copied into dist/ on build ├── public/ # static files served as-is (for example favicon.ico) └── src/ ├── main.tsx # React entry (providers) ├── App.tsx ├── index.css ├── backend.ts # GENERATED by caffeine-bindgen — do NOT edit └── declarations/ # GENERATED by caffeine-bindgen — do NOT edit ``` Only the **root** manifest, the two **canister** manifests, `mops.toml`, `main.mo`, and the small root config files are shown inline below. The full frontend boilerplate (`package.json`, `vite.config.js`, the Tailwind/PostCSS/Biome configs, `index.html`, `env.json`, `main.tsx`, a starter `App.tsx`) is in [`references/frontend-template.md`](references/frontend-template.md) — read it when you create the frontend. ## Manifests ### Root `caffeine.toml` — the workspace The root manifest **must** contain a `[workspace]` section. That section is what marks it as the workspace root; without it, the CLI treats this file as an ordinary canister manifest and discovery fails. ```toml manifest_version = "0.1.0" [project] name = "My App" # id is the cloud project id, a UUID. Omit it for a brand-new local project; once # `caffeine projects create` reports one, set it here (or pass --project-id to preview). # A placeholder such as "my-app" makes `caffeine preview` refuse to upload. [workspace] include = [ "src/**" ] # Build the backend before the frontend, because the frontend imports generated # bindings produced from the backend's Candid interface. [canisters.frontend] depends_on = [ "backend" ] ``` `[workspace].include` is a list of globs the CLI scans for nested canister manifests. `src/**` finds `src/backend/caffeine.toml` and `src/frontend/caffeine.toml`. ### `src/backend/caffeine.toml` — the Motoko canister ```toml manifest_version = "0.1.0" [project] name = "backend" type = "motoko" main = "main.mo" [build] commands = ["mops build", "pnpm bindgen"] out = "dist" [check] commands = ["mops check"] [check.fix] commands = ["mops check --fix"] ``` `[build].commands` run in order: `mops build` compiles `main.mo` to Wasm + Candid, then `pnpm bindgen` (defined in the root `package.json`) turns that Candid into the frontend's TypeScript client. `caffeine check --fix` runs `[check.fix].commands`. ### `src/frontend/caffeine.toml` — the assets canister ```toml manifest_version = "0.1.0" [project] name = "frontend" type = "assets" [build] commands = ["pnpm build"] out = "dist" [check] commands = ["pnpm typecheck", "pnpm check"] [check.fix] commands = ["pnpm typecheck", "pnpm fix"] ``` ### `mops.toml` — the Motoko build (one per project, at the root) There is exactly **one** `[canisters.backend]`. `caffeine preview` checks only the structural pieces, which are invariant: the single `[canisters.backend]`, `[canisters.backend.check-stable]` with the path shown and no `skipIfMissing`, and `[build] outputDir = "src/backend/dist"`. Everything else — the **toolchain versions, the `[moc]` flags and `-E`/`-W`/`-A` diagnostic codes, and the dependency list — is a current snapshot** that the Caffeine template bumps over time; see "Versions and dependencies drift" below. ```toml [package] name = "backend" version = "0.1.0" [build] outputDir = "src/backend/dist" args = ["--release"] check-wasm = true [canisters.backend] main = "src/backend/main.mo" [canisters.backend.check-stable] path = ".old/src/backend/dist/backend.most" [toolchain] moc = "2.1.0" lintoko = "0.12.0" [lint] extends = true [moc] args = [ "--implicit-package=core", "-no-check-ir", "-E=M0254", "-W=M0235,M0223,M0236,M0237", "-A=M0241" ] [dependencies] core = "2.6.1" ic = "5.0.0" caffeineai-authorization = "1.0.0" caffeineai-lints = "0.1.0" caffeineai-oql = "0.8.0" [canisters.backend.migrations] chain = "src/backend/migrations" check-limit = 1 ``` Notes: - **New projects use moc 2.** Under moc 2 a bare `actor` is persistent, and the `persistent` keyword only triggers warning M0217. Older guides add `--default-persistent-actors` or `--generate-view-queries` to `[moc] args`: those are moc 1.x flags that moc 2.0 removed, and passing them fails every compile with `unknown option`. Projects cloned from before the switch may still pin moc 1.x (the template's moc 1 variant is `moc = "1.16.0"` with `--default-persistent-actors` first in `[moc] args`); leave such a project on its pinned version, or move it with the `migrating-to-moc-2` skill: . - **`check-stable`** points at `.old/src/backend/dist/backend.most`, the stable-signature snapshot of the last deployed backend. `caffeine check` compares your stable state against it, and `caffeine projects clone` restores it from the cloud. Do not delete `.old/`. **A from-scratch project must seed it** with an empty actor, as the Caffeine template does, or `caffeine check` fails with `Deployed file not found: .old/src/backend/dist/backend.most`: ```motoko // Version: 1.0.0 actor {}; ``` Do not set `skipIfMissing = true` instead: mops deprecated it, and `caffeine preview` rejects it because a skipped check only fails later, at deploy. - **`[canisters.backend.migrations]`** turns on enhanced migration (mops adds `--enhanced-migration` itself; do not put it in `[moc] args`). Every `.mo` file in `src/backend/migrations/`, in name order, is one step that maps the previous stable state to the next. Stable fields in the actor have **no initializers**; their initial values come from the chain. A new project starts with `00000000_000000.mo`, which creates the state the starting `main.mo` declares (below) and sorts before the `YYYYMMDD_HHMMSS.mo` files later migrations use: ```motoko import AccessControl "mo:caffeineai-authorization/access-control"; module { public type OldActor = {}; public type NewActor = { accessControlState : AccessControl.AccessControlState }; public func migration(_ : OldActor) : NewActor { { accessControlState = AccessControl.initState() }; }; }; ``` `check-limit = 1` allows **one pending (not yet deployed) migration**. Against the seeded empty baseline, `00000000_000000.mo` is itself pending, so until the first deploy you add new stable fields by editing that file, not by adding a second one; a second file fails `caffeine check` with `too many pending migrations for check-limit=1`. Never edit, rename, or delete a migration after it is deployed. The rules for writing migrations are in the `migrating-motoko-actors` skill: . - **`core`** is the `mo:core` standard library. Use `mo:core`, never the deprecated `mo:base` — see the `writing-motoko` skill. **`caffeineai-oql`** provides the `Expose` mixin the starting `main.mo` includes (below). - **`caffeineai-authorization`** provides Internet Identity sign-in and roles (`MixinAuthorization`, `AccessControl`). It also ships a lint rule that fails `caffeine check` unless `main.mo` includes `MixinAuthorization`. To use custom authentication instead before the first deploy, remove the package (`mops remove caffeineai-authorization`) together with its imports, include, state field, and migration line — see the `extension-authorization` skill: . After a deploy, the applied first migration imports the package, so removing it breaks the build: keep the package and `MixinAuthorization`, and add custom checks alongside them. - **`[lint] extends = true`** runs the lint rules that dependencies ship (such as the one above) with the `lintoko` pinned in `[toolchain]`, as part of `mops check`. - **`ic`** provides the IC management canister's types and calls (`mo:ic/Types`, `mo:ic/Call`). Use it instead of `import ... "ic:aaaaa-aa"`, which only resolves with an `--actor-idl` flag that the template no longer passes. - **Add a package** with `mops add ` (one package per command) rather than by editing `[dependencies]`, so `mops.lock` stays in sync. The `mops-cli` skill covers the mops commands: . > **Versions and dependencies drift.** The `[toolchain]` versions, the `[moc]` > `-E`/`-W`/`-A` codes, and the frontend dependency set are template-managed and change > over time (e.g. the `@dfinity/*` → `@icp-sdk/*` migration, moc/core bumps). Treat the > exact values here as a snapshot — for current ones, `caffeine projects clone` a recent > project and copy its `mops.toml` + `src/frontend/package.json`. Stable across versions: > the file layout, the single `backend` canister, `check-stable` with the seeded > baseline, `[build] outputDir`, `mo:core`, and `useActor(createActor)`. ### `package.json` (root) — pnpm workspace + the `bindgen` script The `bindgen` script is the bridge from backend Candid to the frontend TS client. It is invoked by the backend canister's `[build]` step (`pnpm bindgen`). ```json { "name": "@caffeine/template-app", "type": "module", "engines": { "node": ">=20.19.0", "pnpm": ">=7.0.0", "npm": "please use pnpm" }, "scripts": { "build": "pnpm -r --if-present run build", "typecheck": "pnpm -r --if-present run typecheck", "check": "pnpm -r --if-present run check", "fix": "pnpm -r --if-present run fix", "bindgen": "caffeine-bindgen --did-file ./src/backend/dist/backend.did --out-dir ./src/frontend/src --actor-interface-file --force" }, "devDependencies": { "@icp-sdk/core": "^5.3.0", "sharp": "^0.34.4" } } ``` The Caffeine template also pins pnpm with a `packageManager` field and adds `@dfinity/pic` for its hosted backend tests; a local project needs neither. ### `pnpm-workspace.yaml` pnpm 10 reads `onlyBuiltDependencies`; pnpm 11 and later read only `allowBuilds`. Keep both so either version runs the packages' install scripts. ```yaml packages: - src/**/* allowBuilds: '@biomejs/biome': true esbuild: true sharp: true onlyBuiltDependencies: - '@biomejs/biome' - esbuild - sharp ``` ### `tsconfig.json` (root) ```json { "compilerOptions": { "strict": true, "target": "ES2020", "experimentalDecorators": true, "strictPropertyInitialization": false, "module": "esnext", "moduleResolution": "bundler", "allowJs": true, "outDir": "HACK_BECAUSE_OF_ALLOW_JS" } } ``` ### `src/backend/main.mo` — the starting backend The canonical template's starting `main.mo` includes two mixins: **`MixinAuthorization`** from `caffeineai-authorization`, which provides Internet Identity sign-in and roles (the first user to sign in becomes admin), and **`Expose`** from `caffeineai-oql`, which publishes the backend's query interface. `accessControlState` is a stable field with no initializer; `00000000_000000.mo` gives it its value. Add your own functions inside the actor, following the **`writing-motoko` skill**. ```motoko import AccessControl "mo:caffeineai-authorization/access-control"; import MixinAuthorization "mo:caffeineai-authorization/MixinAuthorization"; import Expose "mo:caffeineai-oql/Expose"; actor { let accessControlState : AccessControl.AccessControlState; include MixinAuthorization(accessControlState, null); include Expose({ entities = [] }); }; ``` To guard methods by role, store user profiles, or capture verified names and emails at sign-in, follow the `extension-authorization` skill. Do not write more Motoko than this without loading the `writing-motoko` skill — it covers persistent actors, stable types, `mo:core`, and the compiler-error pitfalls that an agent will otherwise hallucinate. ## The frontend **Fetch this skill's companion reference file** — [`references/frontend-template.md`](references/frontend-template.md), which sits next to this `SKILL.md` (i.e. `…/skills/caffeine-app/references/frontend-template.md`) — and create the frontend files from it; it holds the verified `package.json`, the Vite/Tailwind/Biome configs, `main.tsx`, and the worked `useActor(createActor)` backend call. The essentials: - The entry point `src/frontend/src/main.tsx` wraps the app in `InternetIdentityProvider` (from `@caffeineai/core-infrastructure`) and a TanStack `QueryClientProvider`. - The frontend talks to the backend through the **generated** module `src/frontend/src/backend.ts` (and `src/frontend/src/declarations/`), which exports a `createActor(...)` factory typed from your backend's Candid. You do not write these — they appear after the first build. Call the backend by passing that `createActor` to `useActor(createActor)` from `@caffeineai/core-infrastructure` (the same package provides the auth provider used in `main.tsx`); you do **not** hand-write the actor/config/storage glue. See the worked example in [`references/frontend-template.md`](references/frontend-template.md). - Sign-in uses `useInternetIdentity()` from the same package (`login()` from a button's `onClick`, `clear()`, `isAuthenticated`, and Google, Microsoft, or company SSO variants). `useActor` re-creates the actor with the signed-in identity. The hook's full API and the sign-in UI rules are in the `extension-core-infrastructure` skill: . - `env.json` holds runtime config placeholders (`backend_host`, `backend_canister_id`, `project_id`, `ii_derivation_origin`, `storage_gateway_url`), all `"undefined"` locally; the frontend `build` script copies it into `dist/` (`cp env.json dist/`), and `@caffeineai/core-infrastructure` fetches it at runtime. Caffeine injects real values when it serves the app. Keep `env.json` and the `copy:env` step. ## The build loop Run from the project root. Order matters. ```bash # 1. Install dependencies. On a brand-new project, generate the pnpm lockfile FIRST # (first run only — see Common Pitfalls), then install the rest (pnpm + mops). pnpm install caffeine install # 2. Write your backend in src/backend/main.mo using the `writing-motoko` skill, and your # frontend in src/frontend/src/. # 3. Build: compiles the backend, then `pnpm bindgen` regenerates the frontend client # (src/frontend/src/backend.ts + declarations/), then the frontend `pnpm build` runs. # Run this BEFORE check, so the frontend has the generated ./backend to typecheck # against. Artifacts land in src/backend/dist + src/frontend/dist (no cloud / no id). caffeine build # 4. Lint + typecheck + auto-fix (runs each canister's [check.fix] commands: # backend `mops check --fix`, frontend `pnpm typecheck` + `pnpm fix`). caffeine check --fix # 5. Upload a built draft (needs a cloud project id). For a brand-new app, create the # cloud project once to obtain an id, then preview: caffeine projects create # reports a new project id # put that id in caffeine.toml [project] id = "...", OR pass --project-id: caffeine preview --build --project-id ``` `caffeine preview` refuses to upload when sources changed since the last `caffeine build`; `--build` rebuilds first. It also checks the `mops.toml` structure described above and needs `src/backend/dist/backend.wasm` and `src/frontend/dist/index.html`. Do not `caffeine projects clone` a project you just created: it has no code yet, so the clone fails with `No committed draft found`. Set `CAFFEINE_VERBOSE=1` to stream complete subprocess output from `caffeine install`, `caffeine build`, and `caffeine check`. This is equivalent to passing `--verbose` to each command. `--json` continues to suppress streamed output. Without a TTY (an agent's shell, CI, piped output) progress and results print as plain lines. Add `--json` to any command for a machine-readable `{ "ok": true, "data": ... }` or `{ "ok": false, "error": ... }` envelope. **Generation ordering.** `src/frontend/src/backend.ts` does not exist until a build runs `pnpm bindgen`. So if your frontend imports from `./backend`, you must run `caffeine build` at least once before `caffeine check` can typecheck the frontend. A brand-new app whose `App.tsx` does not yet import `./backend` typechecks fine before the first build. **Going live.** `caffeine preview --build` (with a `project.id`) produces a *draft* and returns its URL. Promote a draft to a live URL in the caffeine.ai web app (open it with `caffeine chat open` or visit caffeine.ai), or with the `caffeine_go_live` tool of the Caffeine MCP connector. There is no CLI deploy command. Use `caffeine projects show ` to see draft and live URLs, and any custom domains. ### Alternative: let Caffeine's own AI build it If you cannot run the CLI locally (no shell, no toolchain), drive Caffeine's hosted AI instead: create a cloud project with `caffeine projects create`, then describe the app in natural language with `caffeine chat send --project-id ""` (or use the caffeine.ai web chat). Caffeine's hosted AI then scaffolds, builds, and deploys it server-side. `chat send` only sends the prompt and follows the AI's progress (or returns at once with `--detach`), so this does not contradict the CLI having no deploy command. This skill is for the **local, hand-authored** path. ## Component skills Caffeine ships ready-made components for sign-in and roles, file storage, payments, email, invite links, and third-party connectors (Google, Slack, Twilio, and more). Each is a mops package (`caffeineai-*`), often an npm package (`@caffeineai/*`), and a skill that shows how to wire them. Before building one of those features, read its skill and use the component instead of writing it yourself. - **A cloned project** lists its component skills in `skills-lock.json`. Restore them into `.agents/skills/` from the project root: ```bash npx skills experimental_install -y ``` - **A project you scaffold by hand** has no lock file. Fetch the skill you need from : one `skills//SKILL.md` per component, listed in its README. ## Using the app from Claude or another AI assistant A deployed Caffeine app already works with DFINITY's ICP MCP connector, `https://mcp.internetcomputer.org/mcp`. The user adds it to their assistant as a custom connector, signs in with Internet Identity, and asks it to open the app by its web address; the assistant then calls the app's backend methods as that user. Do **not** build an MCP server, an HTTP endpoint, or a secret link into the app for this. Clear backend method names and Candid types are what the assistant reads, so a capability it should have is an ordinary backend method. ## Common Pitfalls 1. **Missing `[workspace]` in the root `caffeine.toml`.** Without it the root file is parsed as a canister manifest and the CLI cannot find your canisters. The root manifest is defined by the presence of `[workspace]`, not by being at the top. 2. **Renaming the backend canister.** It must be `backend` — `mops.toml` declares `[canisters.backend]` and the root `bindgen` script reads `./src/backend/dist/backend.did`. Renaming breaks the build and the generated client. 3. **Hand-writing or editing `src/frontend/src/backend.ts` or `declarations/`.** These are generated by `caffeine-bindgen` and overwritten on every build. Add backend methods in `main.mo`, rebuild, and the client regenerates. The generated header says "You should NOT make any changes in this file"; it is also excluded from Biome. 4. **Importing `./backend` before the first build.** The binding module is created by the build's `pnpm bindgen` step. Run `caffeine preview --build` (or `caffeine build`) once before relying on `import { createActor } from "./backend"`. 5. **Trying to `dfx deploy` or expecting `caffeine deploy`.** Caffeine apps build via the `caffeine` CLI and go live via the web app. There is no `dfx` in the workflow and no CLI deploy/publish command. 6. **Dropping required `mops.toml` settings.** Keep the single `[canisters.backend]`, `[canisters.backend.check-stable]`, `[build] outputDir`, and a `[toolchain] moc` pin (mops cannot compile without one). 7. **Deleting `.old/` or `env.json`, or skipping `copy:env`.** `.old/` holds the stable-signature snapshot `check-stable` compares against; `env.json` must be copied into `dist/` so the served frontend can read its runtime config. 8. **Writing Motoko without the `writing-motoko` skill.** Modern Caffeine Motoko uses `mo:core`, persistent actors, and specific patterns. Guessing produces compiler errors. Load first. 9. **Using `npm`/`yarn` instead of `pnpm`.** The workspace is pnpm-based (`pnpm-workspace.yaml`, `pnpm -r` scripts). `caffeine install` uses pnpm + mops. 10. **`caffeine install`/`build` fails with `ERR_PNPM_NO_LOCKFILE` on a fresh project.** In a non-interactive shell (an agent, CI, or any run without a TTY) these commands run `pnpm install --frozen-lockfile`, which requires a `pnpm-lock.yaml` that a brand-new project does not have. Run `pnpm install` once first to generate the lockfile, then the loop works. (An interactive terminal creates it for you.) 11. **First `caffeine check` fails with `Deployed file not found: …/backend.most`.** The stable-signature check needs the last deployed snapshot, which a never-deployed project lacks. Seed `.old/src/backend/dist/backend.most` with an empty actor (shown under the `mops.toml` above). `caffeine build` does not create it. 12. **`caffeine preview --build` fails with `No project.id in caffeine.toml`.** Uploading a draft needs a cloud project. Run `caffeine projects create` to get an id, set it in `[project] id` (or pass `--project-id `), then preview. `caffeine build` alone needs no id and is enough to verify the app compiles. 13. **`too many pending migrations for check-limit=1`.** Only one migration can be pending at a time, and on a never-deployed project `00000000_000000.mo` already is. Fold the new state into that pending file instead of adding another. 14. **`include-authorization` lint error, or `M0169` "stable variable `accessControlState` … cannot be implicitly discarded".** `main.mo` dropped `MixinAuthorization` or its `accessControlState` field while the package and the first migration still provide them. Keep the starting `main.mo` lines, or remove authorization completely as the `extension-authorization` skill describes. ## Related skills - **`writing-motoko`** — REQUIRED companion. Authoritative for all backend Motoko code: . Always load it before editing `src/backend/main.mo`. - **`migrating-motoko-actors`** — load before changing the actor's stable state: how to write and fold migrations in `src/backend/migrations/`. - **`extension-core-infrastructure`** — `InternetIdentityProvider`, `useInternetIdentity`, and `useActor` on the frontend. - **`extension-authorization`** — roles, guards, user profiles, and the sign-in screen built on `caffeineai-authorization`. - **`mops-cli`** — mops commands: `mops add`, `mops check`, toolchain pins. - **`migrating-to-moc-2`** — moving a cloned moc 1 project to moc 2. - **`icp-cli`** — for raw Internet Computer / `dfx` / `icp` projects. Not used by Caffeine; reach for it only when the user is *not* building a Caffeine app. ## Additional references - [`references/frontend-template.md`](references/frontend-template.md) — the full, verbatim frontend boilerplate (`package.json`, `vite.config.js`, Tailwind/PostCSS/Biome configs, `tsconfig.json`, `index.html`, `env.json`, `main.tsx`, a starter `App.tsx`, and the backend-actor wiring pattern). Read it when you create `src/frontend/`. --- ## Canister Audit --- name: canister-audit description: "Audit an existing Internet Computer Rust canister (ic-cdk) for security flaws and PROVE a confirmed one with a PocketIC reproduction. Covers detecting the canister, a high-recall static first pass, a systematic review against the canister-security pitfalls, and the distinctive step: building the canister to wasm and executing the exploit in PocketIC to turn a suspected flaw into a demonstrated one. Use when reviewing or auditing a canister you did NOT write, or proving a finding before you report it. Complements canister-security (which teaches the secure patterns); this one finds and proves violations of them." license: Apache-2.0 compatibility: "a Rust ic-cdk canister repo (ic-cdk >= 0.18); cargo + the wasm32-unknown-unknown target; the pocket-ic crate (16.x) for the proof step, which downloads its matching server; Semgrep and cargo-audit optional" metadata: title: Canister Audit category: Security --- # Canister Audit ## What This Is A workflow for auditing a Rust `ic-cdk` canister you did not write, and for turning a suspected flaw into a *proven* one. `canister-security` teaches the patterns a canister should follow; this skill is the other side of that coin - given existing code, find where those patterns are violated, and prove the highest-severity finding by reproducing the exploit in PocketIC. A grep hit or a hunch is a *candidate*; a PocketIC test that drives the deployed wasm and crosses the security boundary is *evidence*. The worked example throughout is a deliberately-broken ledger canister, `token_vault`, whose accounting invariant `sum(balances) <= total_deposited` is broken by exactly one unguarded method. ## Prerequisites - Rust toolchain + the wasm target: `rustup target add wasm32-unknown-unknown`. - Optional static tools: `cargo-audit` (RustSec dependency CVEs) and Semgrep (a coarse first pass; Rust support is experimental, so treat it as high-recall). - For the proof step: the `pocket-ic` crate (e.g. `16.1`). With `POCKET_IC_BIN` unset, `PocketIc::new()` downloads the matching server release from `dfinity/pocketic` on first use. To pin a binary you have verified (sha256) instead, point `POCKET_IC_BIN` at it; the server's major version must match the crate's. ## The audit workflow 1. **Detect the canister.** Confirm it is a Rust ic-cdk canister: a `Cargo.toml` depending on `ic-cdk`/`candid`, `#[ic_cdk::update]`/`#[ic_cdk::query]` entrypoints, a `.did`. A canister's logic is not recoverable from its deployed wasm, so you need the source - there is no audit-by-mainnet-address mode. 2. **Model the invariants first.** Before reading for bugs, write down what must always hold: the accounting identity, who may call what, which state moves across each `await`. The audit then hunts for a path that breaks each invariant. For `token_vault` the invariant is `sum(balances) <= total_deposited`. 3. **Static first pass (high-recall, best-effort).** Grep or Semgrep for the obvious footguns, treating every hit as a candidate to confirm, never an automatic finding: - state-changing update fns — `#[update]`, `#[ic_cdk::update]`, with or without arguments (`guard = ...`, `name = ...`), `async` or not — with no caller check (`is_controller`, an owner check, or a `== Principal::anonymous()` rejection). `CallerGuard` is a reentrancy lock, **not** a caller check: it admits the anonymous principal; - `fetch_root_key` / `fetchRootKey` / `shouldFetchRootKey` **anywhere** in the repo, including calls behind an environment check (`canister-security` pitfall #7 forbids it even there — environment branches leak into production builds); only test-only code is exempt. The fix to recommend is removing the call and passing the root key from the `ic_env` cookie (`IC_ROOT_KEY`, via `safeGetCanisterEnv()`) as `rootKey` to `HttpAgent.create()`; - `let _ = CallerGuard::new(...)` - a guard bound to `_` is dropped at the end of the statement, so the lock is released immediately; - `ic_cdk::caller()` - deprecated in favour of `msg_caller()`; legacy call sites often predate the current guard conventions. A deliberately high-recall rule flags `deposit`, `withdraw`, *and* `claim_bonus` here, even though `deposit` rejects the anonymous principal and `withdraw` takes a `CallerGuard` - the point is to surface candidates for review, not to decide. Example Semgrep rule (tested with Semgrep 1.185): ```yaml rules: - id: ic-update-missing-caller-auth message: update method with no visible caller check - candidate for review languages: [rust] severity: ERROR patterns: # Every update entrypoint: bare or parameterized attribute, sync or async. - pattern-either: - pattern: | #[$ATTR] fn $F(...) { ... } - pattern: | #[$ATTR] fn $F(...) -> $R { ... } - pattern: | #[$ATTR] async fn $F(...) { ... } - pattern: | #[$ATTR] async fn $F(...) -> $R { ... } - pattern: | #[$ATTR(...)] fn $F(...) { ... } - pattern: | #[$ATTR(...)] fn $F(...) -> $R { ... } - pattern: | #[$ATTR(...)] async fn $F(...) { ... } - pattern: | #[$ATTR(...)] async fn $F(...) -> $R { ... } - metavariable-regex: metavariable: $ATTR regex: ^(ic_cdk::)?update$ # A bare `== Principal::anonymous()` is deliberately NOT a suppressor (a # comparison that does not reject the caller is not a guard), and neither # is CallerGuard (a reentrancy lock). Under-reporting is worse than noise. - pattern-not-regex: (is_controller|require_owner|require_admin) ``` The suppression is by name only, so methods it hides are still reviewed in step 4 - it just orders the queue. 4. **Systematic review against the pitfalls.** Walk each entrypoint against the `canister-security` checklist (anonymous principal #2, TOCTOU across `await` #3, unguarded admin #8, storage / cycle-drain DoS #10/#5, callback-trap-after-mutation #11, and the rest). For each candidate, read the code and decide real or refuted. Trace every guard to its body: a `guard = "..."` function or helper proves nothing until you have read it, `require_authenticated`-style guards stop only the anonymous principal (not enough for admin methods), and a guard called as a statement whose `Result` is discarded (`require_owner();`) is a bypass - the mutation runs whether or not it returned `Err`. In `token_vault`, `claim_bonus` credits the caller with no guard and never touches `total_deposited`, so it breaks the invariant and is reachable by the anonymous principal (pitfalls #2 and #8); `deposit`'s `== Principal::anonymous()` check refutes its own candidate. 5. **Prove a confirmed HIGH/CRITICAL with PocketIC** (next section). 6. **Report.** Per finding: the pitfall, the `file:line`, the invariant broken, and - for a proven one - the reproduction. Frame an unproven candidate honestly as "suspected, not reproduced," and never ship a working exploit for an unpatched canister publicly - it belongs in a private report to the canister's controllers. ## Proving a finding with PocketIC This is the step that separates an audit from a lint. Build the audited canister to wasm, load it into PocketIC, call the suspect method as the attacker (usually `Principal::anonymous()`), and assert the prohibited outcome. If the test passes, the exploit is real. Keep the reproduction in a **separate, standalone crate** outside the audited repo's workspace, so PocketIC's dev-dependency never touches the target's manifests and your audit leaves the target unmodified. Drive the canister through its built wasm - ic-cdk canister code does not link for the host target. `token_vault_repro/Cargo.toml`: ```toml [package] name = "token_vault_repro" version = "0.1.0" edition = "2021" publish = false # Empty [workspace] keeps this crate out of any enclosing workspace. [workspace] [dev-dependencies] candid = "0.10" pocket-ic = "16.1" ``` ### 1. The flaw (`token_vault/src/lib.rs`) ```rust // INTENTIONAL FLAW: credits the caller out of thin air - no anonymous-principal // rejection, no owner guard, and it never touches total_deposited. Breaks the // invariant sum(balances) <= total_deposited. #[ic_cdk::update] fn claim_bonus(amount: u64) { let caller = msg_caller(); STATE.with(|s| { *s.borrow_mut().balances.entry(caller).or_default() += amount; }); } ``` ### 2. The reproduction (separate `token_vault_repro` crate, `tests/repro.rs`) ```rust use candid::{decode_one, encode_args, encode_one, Principal}; use pocket_ic::PocketIc; fn install(pic: &PocketIc) -> Principal { let c = pic.create_canister(); pic.add_cycles(c, 2_000_000_000_000); // Must be an absolute path: cargo runs integration tests from this crate's root. let path = std::env::var("CANISTER_WASM").expect("set CANISTER_WASM to the built .wasm"); let wasm = std::fs::read(&path).unwrap_or_else(|e| panic!("read {path}: {e}")); pic.install_canister(c, wasm, encode_args(()).unwrap(), None); c } fn query_u64(pic: &PocketIc, c: Principal, method: &str, arg: Vec) -> u64 { let reply = pic.query_call(c, Principal::anonymous(), method, arg).expect("query rejected"); decode_one(&reply).expect("reply decodes to u64") } #[test] fn anonymous_principal_mints_unbacked_balance() { let pic = PocketIc::new(); let c = install(&pic); let anon = Principal::anonymous(); // Precondition: an empty ledger. assert_eq!(query_u64(&pic, c, "total_deposited", encode_args(()).unwrap()), 0); // Attack: the anonymous principal credits itself 1_000 out of thin air. pic.update_call(c, anon, "claim_bonus", encode_one(1_000u64).unwrap()) .expect("claim_bonus is callable by the anonymous principal - that is the bug"); let bal = query_u64(&pic, c, "balance_of", encode_one(anon).unwrap()); let total = query_u64(&pic, c, "total_deposited", encode_args(()).unwrap()); assert_eq!(bal, 1_000, "anonymous principal minted a balance"); assert!( bal > total, "INVARIANT BROKEN: sum(balances) {bal} > total_deposited {total} - \ the ledger records a balance no deposit backs" ); } ``` ### 3. Run it ```bash rustup target add wasm32-unknown-unknown # Build the audited canister in its own repo (no changes to it). (cd token_vault && cargo build --target wasm32-unknown-unknown --release) # Run the repro with an ABSOLUTE wasm path - a relative one resolves against # token_vault_repro/, not the directory you ran this from. (cd token_vault_repro && \ CANISTER_WASM="$PWD/../token_vault/target/wasm32-unknown-unknown/release/token_vault.wasm" \ cargo test --test repro -- --nocapture) ``` If the audited crate is part of a Cargo workspace, its wasm lands in the **workspace** `target/` directory - adjust the path accordingly. A passing test is the whole point: it proves the anonymous principal can create a balance no deposit backs - the accounting invariant is broken on the deployed wasm. That is the difference between "`claim_bonus` looks unguarded" and "here is the anonymous principal minting a balance." Claim exactly what the test shows: it does **not** by itself prove funds can be stolen. To prove theft, extend the test - fund the vault from an honest principal, have the attacker `claim_bonus` then `withdraw`, and assert the withdrawal succeeds and the honest user's funds can no longer be fully paid out. ## Notes - The PocketIC server and the `pocket-ic` crate share a major version. Pin both and update the `update_call`/`query_call` signatures together if you bump (the 16.x API returns `Result, _>`). - A clean or failed reproduction does **not** refute the static / review finding. A flaw can be real but awkward to reproduce in a unit test (timing, multi-canister setup); keep the reasoning and record the proof as pending. - Static hits are candidates, not verdicts. The high-recall ruleset exists to miss nothing obvious; the review and the PocketIC proof are what confirm. --- ## Canister Help --- name: canhelp description: Display a human-readable summary of a canister's interface given its mainnet canister ID or a human-readable name. Like --help but for canisters. Only for mainnet canisters — for local canisters, read the generated .did file in your project directly. license: Apache-2.0 compatibility: "icp-cli >= 0.1.0" allowed-tools: Bash(./scripts/resolve-canister-id.sh *), Bash(./scripts/fetch-candid.sh *), Read, Grep, Glob argument-hint: metadata: title: Canister Help category: Infrastructure --- Given a canister ID or name in `$ARGUMENTS`, fetch and summarize its Candid interface. ## Steps 1. Resolve the canister ID by running the resolve script from the skill's base directory: ```bash ./scripts/resolve-canister-id.sh "$ARGUMENTS" ``` If `$ARGUMENTS` is already a valid principal, the script echoes it back. Otherwise, it queries the IC Dashboard API and outputs matches as ` ` (one per line). - If there is a single result, clearly display the resolved canister ID and use it directly. - If there are multiple results, present the list to the user and ask them to pick one before continuing. 2. Fetch the Candid interface using the resolved canister ID: ```bash ./scripts/fetch-candid.sh ``` The script outputs the path to the downloaded `.did` file. 3. Read the file using the `Read` tool. 4. Present the output as a readable summary with the following structure: **Canister ``** **Query methods:** - `method_name(arg1: type1, arg2: type2) → return_type` — one-line description if inferable from the name **Update methods:** - `method_name(arg1: type1) → return_type` **Types:** - List any custom record/variant types defined in the interface, with their fields ## Guidelines - Group methods by query vs update - Sort methods alphabetically within each group - For complex nested types, show the top-level structure and note nesting - If the candid is very large (>100 methods), show a summary count and list only the most important-looking methods, offering to show the full list on request - If the fetch succeeds, but the Candid interface is empty,explain that the canister is not exposing its Candid interface in the wasm metadata - If the fetch fails, suggest the user verify the canister ID and that `icp` is installed --- ## Canister Security --- name: canister-security description: "IC-specific security patterns for canister development in Motoko and Rust. Covers access control, anonymous principal rejection, reentrancy prevention (CallerGuard pattern), async safety (saga pattern), callback trap handling, cycle drain protection, and safe upgrade patterns. Use when writing or modifying any canister that modifies state, handles tokens, makes inter-canister calls, or implements access control." license: Apache-2.0 metadata: title: Canister Security category: Security --- # Canister Security ## What This Is Security patterns for IC canisters in Motoko and Rust. The async messaging model creates TOCTOU (time-of-check-time-of-use) vulnerabilities where state changes between `await` calls. `canister_inspect_message` is NOT a reliable security boundary. Anyone on the internet can burn your cycles by sending update calls. This skill provides copy-paste correct patterns for access control, reentrancy prevention, async safety, and callback trap handling. ## Prerequisites - For Motoko: `mops` package manager, `core = "2.0.0"` in mops.toml - For Rust: `ic-cdk = "0.19"`, `candid = "0.10"` ## Security Pitfalls 1. **Relying on `canister_inspect_message` for access control.** This hook runs on a single replica without full consensus. If that replica is malicious, it can simply skip the check and execute the update call without any message inspection. It is also never called for inter-canister calls, query calls, or management canister calls. Always duplicate access checks inside every update method. Use `inspect_message` only as a cycle-saving optimization, never as a security boundary. 2. **Forgetting to reject the anonymous principal.** Every endpoint that requires authentication must check that the caller is not the anonymous principal (`2vxsx-fae`). In Motoko use `Principal.isAnonymous(caller)`, in Rust compare `msg_caller() != Principal::anonymous()`. Without this, unauthenticated callers can invoke protected methods — and if the canister uses the caller principal as an identity key (e.g., for balances), the anonymous principal becomes a shared identity anyone can use. 3. **Reading state before an async call and assuming it's unchanged after (TOCTOU).** When your canister `await`s an inter-canister call, other messages can interleave and mutate state. This is one of the most critical sources of DeFi exploits on IC. Use per-caller locking (CallerGuard pattern) to prevent concurrent operations. For financial operations, also consider the saga pattern (deduct before `await`, compensate on failure) — but implementing it correctly is complex due to edge cases like callback traps and call timeouts where the outcome is ambiguous. 4. **Trapping in `pre_upgrade`.** If `pre_upgrade` traps (e.g., serializing too much data exceeds the instruction limit), the canister becomes permanently non-upgradeable. Avoid storing large data structures in the heap that must be serialized during upgrade. In Rust, use `ic-stable-structures` for direct stable memory access. In Motoko, the `persistent actor` declaration stores all `let` and `var` variables automatically in stable memory — no manual serialization needed. 5. **Not monitoring cycles balance.** Every canister has a default `freezing_threshold` of 2,592,000 seconds (~30 days). When cycles drop below the threshold reserve, the canister freezes (rejects all update calls). When cycles reach zero, the canister is uninstalled — its code and memory are removed, though the canister ID and controllers survive. The real pitfall is not actively monitoring and topping up cycles. For production canisters holding valuable state, increase the freezing threshold and set up automated monitoring. ```bash # Check current settings (mainnet) icp canister settings show backend -e ic # Increase freezing threshold for high-value canisters icp canister settings update backend --freezing-threshold 7776000 -e ic # 90 days ``` 6. **Single controller with no backup.** If you lose the controller identity's private key, the canister becomes unupgradeable forever. There is no recovery mechanism. Always add a backup controller or governance canister: ```bash icp canister settings update backend --add-controller -e ic ``` When deploying, ask the developer if they have a backup controller principal to add. 7. **Calling `fetchRootKey()` to make local development work.** `fetchRootKey()` fetches the root public key from the replica at runtime and trusts whatever it returns — if that code path ever runs on mainnet, a man-in-the-middle can substitute a different key, breaking all verification. Never call it, even behind an environment check; environment branching is exactly how the call leaks into production builds. Instead, read the root key from the `ic_env` cookie (`IC_ROOT_KEY`, via `safeGetCanisterEnv()` from `@icp-sdk/core/agent/canister-env`) and pass it as the `rootKey` option to `HttpAgent.create()`. The cookie is set automatically by static-site/asset-canister frontends and by the icp-cli Vite dev server, so the same code works locally and in production with no branching — the cookie always carries the network's root key, and on mainnet that key is identical to the one hardcoded in the agent, so passing it is a harmless no-op. See the icp-cli skill's `references/binding-generation.md` for the full pattern. 8. **Exposing admin methods without guards.** Every update method is callable by anyone on the internet. Admin methods (migration, config, minting) must explicitly check the caller against an allowlist. There is no built-in role system — you must implement it yourself. Always include admin revocation — missing revocation is a common source of bugs. 9. **Storing secrets in canister state.** Canister memory on standard application subnets is readable by node operators. Never store private keys, API secrets, or passwords in canister state. For on-chain secret management, use vetKD (threshold key derivation). 10. **Allowing unbounded user-controlled storage.** If users can store data without limits, an attacker can fill the 4 GiB Wasm heap or stable memory, bricking the canister. Always enforce per-user storage quotas and validate input sizes. 11. **Trapping in a callback after state mutation.** If your canister mutates state before an inter-canister call and the callback traps, the pre-call mutations persist but the callback's mutations are rolled back. A malicious callee can exploit this to skip security-critical actions like debiting an account. Structure code so that critical state mutations happen before the async boundary and are correctly rolled back if a failure or trap occurs. Use `try/finally` (Motoko) or `Drop` guards (Rust) to ensure cleanup always runs. Keep cleanup code minimal — trapping in cleanup recreates the problem. Consider using `call_on_cleanup` for rollback logic and journaling for crash-safe state transitions. 12. **Unbounded wait calls preventing upgrades.** If your canister makes a call to an untrustworthy or buggy callee that never responds, the canister cannot be stopped (and therefore cannot be upgraded) while awaiting outstanding responses. Use bounded wait calls (timeouts) to ensure calls complete in bounded time regardless of callee behavior. ## How It Works ### IC Security Model 1. **Update calls** go through consensus — all nodes on a subnet execute the code and must agree on the result. Standard application subnets have 13 nodes; system and fiduciary subnets have more (28+). This makes update calls tamper-proof but slower (~2s). 2. **Query calls** run on a single replica — fast (~200ms) but the replica can return incorrect or malicious results. Replica-signed queries provide partial mitigation (the responding replica signs the response), but for full trust, use certified data or update calls for security-critical reads. 3. **Inter-canister calls** are async messages. Between sending a request and receiving the response, your canister can process other messages. State may change under you (see TOCTOU pitfall above). 4. **State rollback on trap.** If a message execution traps, all its state changes are rolled back. For inter-canister calls, the first execution (before `await`) and the callback (after `await`) are separate messages — a trap in the callback rolls back only the callback's changes, while the first execution's changes persist. This is why cleanup logic (like releasing locks) must go in cleanup context (`finally`/`Drop`), not regular callback code. ## Implementation ### Motoko #### Access control Uses the `shared(msg)` pattern to capture the deployer atomically — no separate `init()` call, no front-running risk. ```motoko import Principal "mo:core/Principal"; import Set "mo:core/pure/Set"; import Runtime "mo:core/Runtime"; shared(msg) persistent actor class MyCanister() { // --- Authorization state --- // transient: recomputed on each install/upgrade from msg.caller (the controller) transient let owner = msg.caller; var admins : Set.Set = Set.empty(); // --- Guards --- func requireAuthenticated(caller : Principal) { if (Principal.isAnonymous(caller)) { Runtime.trap("anonymous caller not allowed"); }; }; func requireOwner(caller : Principal) { requireAuthenticated(caller); if (caller != owner) { Runtime.trap("caller is not the owner"); }; }; func requireAdmin(caller : Principal) { requireAuthenticated(caller); if (caller != owner and not Set.contains(admins, Principal.compare, caller)) { Runtime.trap("caller is not an admin"); }; }; // --- Admin management --- public shared ({ caller }) func addAdmin(newAdmin : Principal) : async () { requireOwner(caller); admins := Set.add(admins, Principal.compare, newAdmin); }; public shared ({ caller }) func removeAdmin(admin : Principal) : async () { requireOwner(caller); admins := Set.remove(admins, Principal.compare, admin); }; // --- Endpoints --- public shared ({ caller }) func publicAction() : async Text { requireAuthenticated(caller); "ok"; }; public shared ({ caller }) func adminAction() : async () { requireAdmin(caller); // ... protected logic }; }; ``` #### Reentrancy prevention (CallerGuard pattern) Per-caller locking prevents a second call from the same caller while the first is awaiting a response. The guard must be released in the `finally` block — if the callback traps, `catch` state changes are rolled back, but `finally` runs in cleanup context where state changes persist. ```motoko import Map "mo:core/Map"; import Principal "mo:core/Principal"; import Error "mo:core/Error"; import Result "mo:core/Result"; // Inside the persistent actor class { ... } // otherCanister is application-specific — replace with your canister reference. let pendingRequests = Map.empty(); func acquireGuard(principal : Principal) : Result.Result<(), Text> { if (Map.get(pendingRequests, Principal.compare, principal) != null) { return #err("already processing a request for this caller"); }; Map.add(pendingRequests, Principal.compare, principal, true); #ok; }; func releaseGuard(principal : Principal) { ignore Map.delete(pendingRequests, Principal.compare, principal); }; public shared ({ caller }) func doSomethingAsync() : async Result.Result { requireAuthenticated(caller); // 1. Acquire per-caller lock — rejects concurrent calls from same principal switch (acquireGuard(caller)) { case (#err(msg)) { return #err(msg) }; case (#ok) {}; }; // 2. Make inter-canister call try { let result = await otherCanister.someMethod(); #ok(result) } catch (e) { #err("call failed: " # Error.message(e)) } finally { // Runs in cleanup context even if the callback traps — changes here persist. releaseGuard(caller); }; }; ``` #### inspect_message (cycle optimization only) ```motoko // Inside persistent actor { ... } // Method variants must match your public methods system func inspect( { caller : Principal; msg : { #adminAction : () -> (); #addAdmin : () -> Principal; #removeAdmin : () -> Principal; #publicAction : () -> (); #doSomethingAsync : () -> (); } } ) : Bool { switch (msg) { // Admin methods: reject anonymous to save cycles on Candid decoding case (#adminAction _) { not Principal.isAnonymous(caller) }; case (#addAdmin _) { not Principal.isAnonymous(caller) }; case (#removeAdmin _) { not Principal.isAnonymous(caller) }; case (#doSomethingAsync _) { not Principal.isAnonymous(caller) }; // Public methods: accept all case (_) { true }; }; }; ``` ### Rust #### Access control (using CDK guard pattern) The `guard` attribute runs a check before the method body. If the guard returns `Err`, the call is rejected before any method code executes. This is more robust than calling guard functions inside the method — you cannot forget to add it. ```rust use ic_cdk::{init, update}; use ic_cdk::api::msg_caller; use candid::Principal; use std::cell::RefCell; thread_local! { static OWNER: RefCell = RefCell::new(Principal::anonymous()); static ADMINS: RefCell> = RefCell::new(vec![]); } // --- Guards (for #[update(guard = "...")] attribute) --- // Must return Result<(), String>. Err rejects the call. fn require_authenticated() -> Result<(), String> { if msg_caller() == Principal::anonymous() { return Err("anonymous caller not allowed".to_string()); } Ok(()) } fn require_owner() -> Result<(), String> { require_authenticated()?; OWNER.with(|o| { if msg_caller() != *o.borrow() { return Err("caller is not the owner".to_string()); } Ok(()) }) } fn require_admin() -> Result<(), String> { require_authenticated()?; let caller = msg_caller(); let is_authorized = OWNER.with(|o| caller == *o.borrow()) || ADMINS.with(|a| a.borrow().contains(&caller)); if !is_authorized { return Err("caller is not an admin".to_string()); } Ok(()) } // --- Init --- #[init] fn init(owner: Principal) { OWNER.with(|o| *o.borrow_mut() = owner); } // --- Endpoints --- #[update(guard = "require_authenticated")] fn public_action() -> String { "ok".to_string() } #[update(guard = "require_admin")] fn admin_action() { // ... protected logic — guard already validated caller } #[update(guard = "require_owner")] fn add_admin(new_admin: Principal) { ADMINS.with(|a| a.borrow_mut().push(new_admin)); } #[update(guard = "require_owner")] fn remove_admin(admin: Principal) { ADMINS.with(|a| a.borrow_mut().retain(|p| p != &admin)); } ic_cdk::export_candid!(); ``` #### Reentrancy prevention (CallerGuard pattern) `CallerGuard` uses the `Drop` trait to release the lock when the guard goes out of scope — including when the callback traps (since ic-cdk 0.5.1, local variables go out of scope during cleanup). Never use `let _ = CallerGuard::new(caller)?` — this drops the guard immediately, making locking ineffective. ```rust use std::cell::RefCell; use std::collections::BTreeSet; use candid::Principal; use ic_cdk::update; use ic_cdk::api::msg_caller; use ic_cdk::call::Call; // other_canister_id is application-specific — replace with your canister reference. thread_local! { static PENDING: RefCell> = RefCell::new(BTreeSet::new()); } struct CallerGuard { principal: Principal, } impl CallerGuard { fn new(principal: Principal) -> Result { PENDING.with(|p| { if !p.borrow_mut().insert(principal) { return Err("already processing a request for this caller".to_string()); } Ok(Self { principal }) }) } } impl Drop for CallerGuard { fn drop(&mut self) { PENDING.with(|p| { p.borrow_mut().remove(&self.principal); }); } } #[update] async fn do_something_async() -> Result { let caller = msg_caller(); if caller == Principal::anonymous() { return Err("anonymous caller not allowed".to_string()); } // Acquire per-caller lock — rejects concurrent calls from same principal. // Drop releases lock even if callback traps. let _guard = CallerGuard::new(caller)?; // Make inter-canister call let response = Call::bounded_wait(other_canister_id(), "some_method") .await .map_err(|e| format!("call failed: {:?}", e))?; let result: String = response.candid() .map_err(|e| format!("decode failed: {:?}", e))?; Ok(result) // _guard dropped here → lock released } ``` #### inspect_message (cycle optimization only) ```rust use ic_cdk::api::{accept_message, msg_caller, msg_method_name}; use candid::Principal; /// Pre-filter to reduce cycle waste from spam. /// Runs on ONE node. Can be bypassed. NOT a security check. /// Always duplicate real access control inside each method or via guard attribute. #[ic_cdk::inspect_message] fn inspect_message() { let method = msg_method_name(); match method.as_str() { // Admin methods: only accept from non-anonymous callers "admin_action" | "add_admin" | "remove_admin" | "do_something_async" => { if msg_caller() != Principal::anonymous() { accept_message(); } // Silently reject anonymous — saves cycles on Candid decoding } // Public methods: accept all _ => accept_message(), } } ``` --- ## Certified Variables --- name: certified-variables description: "Serve cryptographically verified responses from query calls using Merkle trees and subnet BLS signatures. Covers the certified data API, RbTree/CertTree construction, witness generation, HTTP response certification for custom http_request canisters (ic-http-certification), and frontend certificate validation (@dfinity/certificate-verification). Use when query responses need verification, certified data, or response authenticity proofs. For static frontends served by the certified-assets canister, use the static-site skill instead: certification is automatic there." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2" metadata: title: Certified Variables category: Security --- # Certified Variables A query call is answered by a single replica, without consensus, so a faulty or malicious replica can return fabricated data. Certification closes that gap: during update calls the canister stores a 32-byte hash (usually the root of a Merkle tree over its data) in the subnet's certified state, and query responses carry a certificate signed by the subnet's threshold BLS key. Clients verify the certificate and a Merkle witness, and get a fast query response that is as trustworthy as an update call. ## Who Verifies What Decide this first. Certification only helps if something checks it. | Response | Verified by | Client code needed | |----------|-------------|--------------------| | HTTP from a frontend canister or `http_request`, via `.icp.net` or a custom domain | the HTTP gateway | none | | The same, via `.raw.icp.net` or your own HTTP client | nobody | `@dfinity/response-verification` (`verifyRequestResponsePair`) | | Update call through an actor (`agent.update`) | consensus; the agent checks the response certificate | none | | Candid **query** call through an actor | only the answering node's signature | **certified data + `@dfinity/certificate-verification`** (this skill) | The gateway never verifies Candid API calls (`/api/...`), even when the page came from a verifying host: on `ic0.app`, `icp0.io` or local origins the agent sends them through the page origin, and the gateway only proxies them. Certify a query when a client acts on its result: balances, permissions, prices, anything security-relevant. The alternative is to call the method as an update and accept consensus latency. Ledgers implementing ICRC-3 already certify their tip: `icrc3_get_tip_certificate` returns `opt { certificate; hash_tree }`, which verifies with `verifyCertification` like any witness below (labels `last_block_index`, a LEB128 number, and `last_block_hash`, so decode them instead of the helper's UTF-8 compare). Static frontends served by the certified-assets canister (`@dfinity/static-site` recipe) are certified automatically: load the `static-site` skill for those. ## Versions | Side | Package | Version | Used for | |------|---------|---------|----------| | Rust | `ic-cdk` | 0.20 | `certified_data_set` / `data_certificate` | | Rust | `ic-certification` (feature `serde`) | 4 | `RbTree` Merkle map with witnesses | | Rust | `ic-http-certification` | 4 | certifying `http_request` responses | | Motoko | `core` | 2.6 | `mo:core/CertifiedData` | | Motoko | `ic-certification` (mops) | 1.1 | `CertTree` Merkle tree with witnesses | | Motoko | `sha2` (mops) | 0.2 | hashing a single certified value | | Frontend | `@icp-sdk/core` | ^6 | agent, `Certificate`, `lookup_path` | | Frontend | `@dfinity/certificate-verification` | ^4 | witness verification (peers `@icp-sdk/core` ^6, takes `Uint8Array`) | `ic-certified-map` 0.4 exposes the same `RbTree`/`AsHashTree` API and still works, but `ic-certification` is maintained alongside `ic-http-certification` and is what the official examples use. ## Root Key Client-side verification needs the root key of the network the canister runs on: - **Browser:** `safeGetCanisterEnv()?.IC_ROOT_KEY` from the `ic_env` cookie (`@icp-sdk/core/agent/canister-env`), set by the frontend canister on local networks and mainnet alike. It is the key of the network serving the page; to verify a canister on another network (e.g. mainnet data from a local dev server), use that network's key. It is only as trustworthy as the page: on a verifying hostname the gateway verifies the cookie along with the page, but a page from a `raw` hostname can carry a forged key, so a client verifying `raw` responses needs an independently obtained key. - **Node scripts and tests:** `root_key` from `icp network status --json`, hex-decoded to bytes. - **Mainnet:** the agent's built-in default (`agent.rootKey` on an agent created without `rootKey`): `308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae` Never call `fetchRootKey()` in shipped code: it trusts whatever key the replica sends (see the `canister-security` skill). ## Pitfalls 1. **Certifying more than 32 bytes.** `certified_data_set` / `CertifiedData.set` accept at most 32 bytes. Build a Merkle tree over the data and certify its root hash; the tree provides per-key proofs. 2. **Setting certified data in a query, or not at install and after every change.** `certified_data_set` can be called from `canister_init`, `canister_post_upgrade`, `canister_pre_upgrade`, update methods, reply/reject callbacks, and system tasks (heartbeat, global timer, low-Wasm-memory hook); it traps anywhere else, including any query (even one called as an update) and cleanup callbacks. Certified data starts empty on install, so certify the initial state in `init` (Rust) or the actor body (Motoko), or queries fail verification until the first write. Forgetting to set it after a mutation leaves a stale hash with the same result. Batch writes need only one `certified_data_set` after the last insert. 3. **Expecting a certificate from a call that is not a query call.** `data_certificate()` / `CertifiedData.getCertificate()` return `None`/`null` in update calls, and a query method invoked as an update call counts as one. **`icp canister call` sends an update call unless you pass `--query`**: without it, the Rust example below traps on its `expect`, and the Motoko examples return `certificate = null`. Frontend code calling a `query` method through an actor sends a query call automatically. 4. **Losing the tree on upgrade, not the certified data.** The certified data itself survives upgrades (install and reinstall start it empty). What does not survive is a Merkle tree kept on the heap: the Rust `RbTree` below is wiped on upgrade while the old hash stays set, so `#[post_upgrade]` must rebuild the tree (from stable storage in a real app, see the `stable-memory` skill) and call `certified_data_set` again. A Motoko `CertTree.Store` persists with the actor, so nothing needs re-setting after an upgrade. 5. **Building the witness for the wrong key.** The witness must reveal the exact path being queried; a witness for `users/alice` proves nothing about `users/bob`. 6. **Treating every non-`Found` lookup as "absent".** `lookup_path` returns a status: `Found` (value proven), `Absent` (absence proven), or `Unknown`/`Error` (the witness does not cover the path). Only `Absent` proves a key does not exist. Collapsing `Unknown` into "not found" (for example with `lookupResultToBuffer`, which returns `undefined` for all three) lets a replica send a witness for a different key and make a real value look missing. 7. **Skipping the freshness check.** The certificate's `/time` is when the subnet signed it; without a bound, a stale certificate with outdated data can be replayed. `verifyCertification` enforces `maxCertificateTimeOffsetMs` (5 minutes is a sensible value); `Certificate.create` enforces ±5 minutes by default (`maxAgeInMinutes`). 8. **Declaring the Motoko `CertTree.Ops` object as stable.** In a persistent actor, `let ct = CertTree.Ops(certStore)` fails with `M0131` (`variable ct is declared stable but has non-stable type`). Declare it `transient let ct = CertTree.Ops(certStore);`; only the `CertTree.Store` is stable. 9. **Certifying an HTTP response without its `IC-CertificateExpression` header.** With `ic-http-certification`, the header carrying the CEL expression must be part of the response you certify; `HttpCertification::response_only`/`full` return `CertificateExpressionHeaderMissing` otherwise. Serve exactly that response, plus the `IC-Certificate` header from `add_v2_certificate_header`, or the HTTP gateway rejects it with `backend_response_verification`. ## Canister ### Rust ```toml [package] name = "certified_vars_backend" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] candid = "0.10" ic-cdk = "0.20" ic-certification = { version = "4", features = ["serde"] } serde = { version = "1", features = ["derive"] } serde_bytes = "0.11" ciborium = "0.2" ``` ```rust use candid::{CandidType, Deserialize}; use ic_cdk::{init, post_upgrade, query, update}; use ic_certification::{AsHashTree, RbTree}; use serde_bytes::ByteBuf; use std::cell::RefCell; thread_local! { // RbTree is a Merkle-tree-backed map: keys and values are byte slices static TREE: RefCell, Vec>> = RefCell::new(RbTree::new()); } // Update the certified data hash after any modification fn update_certified_data() { TREE.with(|tree| { let tree = tree.borrow(); // root_hash() returns a 32-byte SHA-256 hash of the entire tree ic_cdk::api::certified_data_set(&tree.root_hash()); }); } #[init] fn init() { update_certified_data(); } #[post_upgrade] fn post_upgrade() { // This example keeps TREE on the heap only: it is empty after an upgrade, while the // old certified hash is kept. A real canister reinserts its entries from stable storage // here first; this one re-certifies the empty tree so the hash matches it again. update_certified_data(); } #[update] fn set(key: String, value: String) { TREE.with(|tree| { let mut tree = tree.borrow_mut(); tree.insert(key.as_bytes().to_vec(), value.as_bytes().to_vec()); }); // Must update certified hash after every data change update_certified_data(); } #[update] fn delete(key: String) { TREE.with(|tree| { let mut tree = tree.borrow_mut(); tree.delete(key.as_bytes()); }); update_certified_data(); } #[derive(CandidType, Deserialize)] struct CertifiedResponse { value: Option, certificate: ByteBuf, // subnet BLS signature witness: ByteBuf, // Merkle proof for this key } #[query] fn get(key: String) -> CertifiedResponse { // data_certificate() is only available in query calls (icp canister call --query) let certificate = ic_cdk::api::data_certificate() .expect("data_certificate only available in query calls"); TREE.with(|tree| { let tree = tree.borrow(); // Look up the value let value = tree.get(key.as_bytes()) .map(|v| String::from_utf8(v.clone()).unwrap()); // Build a witness (Merkle proof) for this specific key let witness = tree.witness(key.as_bytes()); // Serialize the witness as CBOR let mut witness_buf = vec![]; ciborium::into_writer(&witness, &mut witness_buf) .expect("Failed to serialize witness as CBOR"); CertifiedResponse { value, certificate: ByteBuf::from(certificate), witness: ByteBuf::from(witness_buf), } }) } // Required by the icp-cli Rust recipe, which extracts the Candid interface from the wasm ic_cdk::export_candid!(); ``` ### Motoko: single value A single value needs no Merkle tree: certify its hash, and the client compares `sha256(value)` with the certificate's `certified_data` (see "Single value without a witness"). ```motoko import CertifiedData "mo:core/CertifiedData"; import Text "mo:core/Text"; // Requires: mops add sha2 import Sha256 "mo:sha2/Sha256"; persistent actor { // Simple certified single-value example: var certifiedValue : Text = ""; // Certify the hash of the current value (max 32 bytes; traps in a query call) func certify() { CertifiedData.set(Sha256.fromBlob(#sha256, Text.encodeUtf8(certifiedValue))); }; // Certify the initial value at install: certified data starts empty, not as sha256("") certify(); // Set a certified value (update call only) public func setCertifiedValue(value : Text) : async () { certifiedValue := value; certify(); }; // Get the certified value with its certificate (query call) public query func getCertifiedValue() : async { value : Text; certificate : ?Blob; } { { value = certifiedValue; certificate = CertifiedData.getCertificate(); } }; }; ``` ### Motoko: key-value store with witnesses `CertTree` from the `ic-certification` mops package (`mops add ic-certification`) is a Merkle tree that produces per-key witnesses: ```motoko import CertifiedData "mo:core/CertifiedData"; import Blob "mo:core/Blob"; import Text "mo:core/Text"; // Requires: mops add ic-certification import CertTree "mo:ic-certification/CertTree"; persistent actor { // CertTree.Store is stable -- the tree persists across upgrades, and so does the certified data let certStore : CertTree.Store = CertTree.newStore(); // Ops is an object with functions, not stable data: it must be transient transient let ct = CertTree.Ops(certStore); // Set certified data on init ct.setCertifiedData(); // Set a key-value pair and update certification public func set(key : Text, value : Text) : async () { ct.put([Text.encodeUtf8(key)], Text.encodeUtf8(value)); // CRITICAL: call after every mutation to update the subnet-certified root hash ct.setCertifiedData(); }; // Delete a key and update certification public func delete(key : Text) : async () { ct.delete([Text.encodeUtf8(key)]); ct.setCertifiedData(); }; // Query with certificate and Merkle witness for the requested key public query func get(key : Text) : async { value : ?Blob; certificate : ?Blob; witness : Blob; } { let path = [Text.encodeUtf8(key)]; // reveal() generates a Merkle proof for this specific path let witness = ct.reveal(path); { value = ct.lookup(path); certificate = CertifiedData.getCertificate(); witness = ct.encodeWitness(witness); } }; }; ``` ### Custom `http_request` canisters Canisters that serve HTTP from their own `http_request` must certify each response with `ic-http-certification` so the HTTP gateway can verify it. Read `references/http-certification.md` before writing one: it has a complete, minimal canister (certify in `init`/`post_upgrade`, attach the witness in `http_request`, and a certified 404 for every other path) and the header rules from pitfall 9. Every path the gateway can request needs a certified response: an uncertified error or 404 is rejected with `backend_response_verification`. ## Client Verification (TypeScript) `@icp-sdk/core` ships every primitive (`Certificate.create`, `Cbor`, `reconstruct`, `lookup_path`); `@dfinity/certificate-verification` wraps them for the witness case: it verifies the certificate signature, checks `/time`, decodes the witness, and checks that its root hash equals the certificate's `certified_data`. Candid `blob` fields arrive as `Uint8Array` in `@icp-sdk/bindgen` bindings. bindgen turns `opt` record fields into optional properties that are `undefined` when empty. The helpers take the getters' responses as returned: a Motoko `?Blob` value or certificate is `Uint8Array | undefined`, and the witness helper decodes a `Uint8Array` value as UTF-8. Take the root key from "Root Key". ### With a witness ```typescript import { verifyCertification } from "@dfinity/certificate-verification"; import { lookup_path, LookupPathStatus } from "@icp-sdk/core/agent"; import { Principal } from "@icp-sdk/core/principal"; const MAX_CERT_TIME_OFFSET_MS = 5 * 60 * 1000; // 5 minutes export async function getVerifiedValue( rootKey: Uint8Array, canisterId: string, key: string, // value is opt text (Rust) or ?blob (Motoko); certificate is a blob (Rust) or ?blob (Motoko) response: { value?: string | Uint8Array | null; certificate?: Uint8Array | null; witness: Uint8Array; }, ): Promise { if (!response.certificate) throw new Error("no certificate: call the getter as a query"); const value = response.value instanceof Uint8Array ? new TextDecoder().decode(response.value) : (response.value ?? null); // Checks signature, time and root hash; throws CertificateTimeError or CertificateVerificationError. const tree = await verifyCertification({ canisterId: Principal.fromText(canisterId), encodedCertificate: response.certificate, encodedTree: response.witness, rootKey, maxCertificateTimeOffsetMs: MAX_CERT_TIME_OFFSET_MS, }); // The path must match how the canister inserted the key (here: UTF-8 bytes). const result = lookup_path([new TextEncoder().encode(key)], tree); switch (result.status) { case LookupPathStatus.Found: { const verified = new TextDecoder().decode(result.value); if (value !== verified) throw new Error("value does not match witness"); return verified; } case LookupPathStatus.Absent: if (value !== null) throw new Error("witness proves the key is absent"); return null; default: // Unknown/Error: the witness does not cover this key, so it proves nothing throw new Error(`witness does not cover key (${result.status})`); } } ``` ### Single value without a witness `verifyCertification` needs a witness tree, so verify the Motoko single-value example with `Certificate.create` directly. It checks the signature and the ±5 minute freshness window: ```typescript import { Certificate, lookupResultToBuffer, uint8Equals } from "@icp-sdk/core/agent"; import { Principal } from "@icp-sdk/core/principal"; export async function verifySingleValue( rootKey: Uint8Array, canisterId: string, // certificate is ?blob in the Motoko getter; empty means it did not run as a query call response: { value: string; certificate?: Uint8Array | null }, ): Promise { if (!response.certificate) throw new Error("no certificate: call the getter as a query"); const principal = Principal.fromText(canisterId); const cert = await Certificate.create({ certificate: response.certificate, rootKey, principal: { canisterId: principal }, }); const certifiedData = lookupResultToBuffer( cert.lookup_path(["canister", principal.toUint8Array(), "certified_data"]), ); // Recompute what the canister certified: sha256 of the UTF-8 value const hash = new Uint8Array( await crypto.subtle.digest("SHA-256", new TextEncoder().encode(response.value)), ); if (!certifiedData || !uint8Equals(certifiedData, hash)) { throw new Error("value does not match certified data"); } return response.value; } ``` A runnable single-value example with a browser frontend that verifies with `Certificate.create` is [dfinity/examples `motoko/cert-var`](https://github.com/dfinity/examples/tree/master/motoko/cert-var). It certifies the raw 4-byte `Nat32` instead of a hash. ## Checking It Works ```bash icp canister call backend set '("greeting", "hello world")' icp canister call --query backend get '("greeting")' # Expected: certificate = blob "..." (Rust) / opt blob "..." (Motoko); null or a trap means the call was not a query ``` Then run the client function against a response: it must return the value, and must throw once `response.value` is changed. --- ## ckBTC (chain-key Bitcoin) --- name: ckbtc description: "Accept, send, and manage ckBTC (chain-key Bitcoin). Covers BTC deposit flow via minter, ckBTC transfers, withdrawal to BTC, subaccount derivation, and UTXO management. Use when integrating Bitcoin, ckBTC, BTC deposits, or BTC withdrawals in a canister. Do NOT use for plain token transfers without BTC minting/withdrawal — use icrc-ledger instead." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2" metadata: title: ckBTC (chain-key Bitcoin) category: DeFi --- # Chain-Key Bitcoin (ckBTC) Integration ## What This Is ckBTC is a 1:1 BTC-backed token native to the Internet Computer. No bridges, no wrapping, no third-party custodians. The ckBTC minter canister holds real BTC and mints/burns ckBTC tokens. Transfers settle in 1-2 seconds with a 10 satoshi fee (versus minutes and thousands of satoshis on Bitcoin L1). ## Prerequisites - For Motoko: `mops` package manager, `core = "2.0.0"` in mops.toml - For Rust: `ic-cdk`, `icrc-ledger-types`, `candid`, `serde` ## Canister IDs ### Bitcoin Mainnet | Canister | ID | |---|---| | ckBTC Ledger | `mxzaz-hqaaa-aaaar-qaada-cai` | | ckBTC Minter | `mqygn-kiaaa-aaaar-qaadq-cai` | | ckBTC Index | `n5wcd-faaaa-aaaar-qaaea-cai` | | ckBTC Checker | `oltsj-fqaaa-aaaar-qal5q-cai` | ### Bitcoin Testnet4 | Canister | ID | |---|---| | ckBTC Ledger | `mc6ru-gyaaa-aaaar-qaaaq-cai` | | ckBTC Minter | `ml52i-qqaaa-aaaar-qaaba-cai` | | ckBTC Index | `mm444-5iaaa-aaaar-qaabq-cai` | ## How It Works ### Deposit Flow (BTC -> ckBTC) 1. Call `get_btc_address` on the minter with the user's principal + subaccount. This returns a unique Bitcoin address controlled by the minter. 2. User sends BTC to that address using any Bitcoin wallet. 3. Wait for Bitcoin confirmations (the minter requires confirmations before minting). 4. Call `update_balance` on the minter with the same principal + subaccount. The minter checks for new UTXOs and mints equivalent ckBTC to the user's ICRC-1 account. ### Transfer Flow (ckBTC -> ckBTC) Call `icrc1_transfer` on the ckBTC ledger. Fee is 10 satoshis. Settles in 1-2 seconds. ### Withdrawal Flow (ckBTC -> BTC) 1. Call `icrc2_approve` on the ckBTC ledger to grant the minter canister an allowance to spend from your account. 2. Call `retrieve_btc_with_approval` on the minter with `{ address, amount, from_subaccount: null }`. 3. The minter uses the approval to burn the ckBTC and submits a Bitcoin transaction. 4. The BTC arrives at the destination address after Bitcoin confirmations. ### Subaccount Generation Each user gets a unique deposit address derived from their principal + an optional 32-byte subaccount. To give each user a distinct deposit address within your canister, derive subaccounts from a user-specific identifier (their principal or a sequential ID). ## Mistakes That Break Your Build 1. **Using the wrong minter canister ID.** The minter ID is `mqygn-kiaaa-aaaar-qaadq-cai`. Do not confuse it with the ledger (`mxzaz-...`) or index (`n5wcd-...`). 2. **Forgetting the 10 satoshi transfer fee.** Every `icrc1_transfer` deducts 10 satoshis beyond the amount. If the user has exactly 1000 satoshis and you transfer 1000, it fails with `InsufficientFunds`. Transfer `balance - 10` instead. 3. **Not calling `update_balance` after a BTC deposit.** Sending BTC to the deposit address does nothing until you call `update_balance`. The minter does not auto-detect deposits. Your app must call this. 4. **Using Account Identifier instead of ICRC-1 Account.** ckBTC uses the ICRC-1 standard: `{ owner: Principal, subaccount: ?Blob }`. Do NOT use the legacy `AccountIdentifier` (hex string) from the ICP ledger. 5. **Subaccount must be exactly 32 bytes or null.** Passing a subaccount shorter or longer than 32 bytes causes a trap. Pad with leading zeros if deriving from a shorter value. 6. **Calling `retrieve_btc` with amount below the minimum.** The minter has a minimum withdrawal amount (currently 50,000 satoshis / 0.0005 BTC). Below this, you get `AmountTooLow`. 7. **Not checking the `retrieve_btc` response for errors.** The response is a variant: `Ok` contains `{ block_index }`, `Err` contains specific errors like `MalformedAddress`, `InsufficientFunds`, `TemporarilyUnavailable`. Always match both arms. 8. **Forgetting `owner` in `get_btc_address` args.** If you omit `owner`, Candid sub-typing assigns null, and the minter returns the deposit address of the caller (the canister) instead of the user. 9. **Leaving `created_at_time` null on `icrc1_transfer` / `icrc2_approve`.** The ICRC-1 spec says a ledger SHOULD NOT deduplicate a transaction whose `created_at_time` is unset, so a retried transfer executes a second time and moves real BTC-backed value twice. Set it, and retry with the **same** timestamp — the ledger only matches duplicates when every argument is identical, so a fresh `Time.now()` on retry defeats dedup. A retry that was already applied returns `#Err(#Duplicate { duplicate_of })`, which is a success, not a failure. ## Implementation ### Motoko #### mops.toml ```toml [package] name = "ckbtc-app" version = "0.1.0" [dependencies] core = "2.0.0" icrc2-types = "1.1.0" [canisters.backend] main = "src/backend/main.mo" ``` The `@dfinity/motoko@v5+` recipe compiles via `mops build `, so `main` lives here — not in `recipe.configuration` in `icp.yaml`. The `[canisters.]` key must exactly match the canister `name` in `icp.yaml`. #### icp.yaml Your backend canister calls the ckBTC ledger and minter by principal directly — no local ckBTC canister deployment needed. ```yaml canisters: - name: backend recipe: type: "@dfinity/motoko@v5.0.0" ``` #### src/backend/main.mo ```motoko import Principal "mo:core/Principal"; import Blob "mo:core/Blob"; import Nat "mo:core/Nat"; import Nat8 "mo:core/Nat8"; import Nat64 "mo:core/Nat64"; import Int "mo:core/Int"; import Time "mo:core/Time"; import Array "mo:core/Array"; import Result "mo:core/Result"; import Error "mo:core/Error"; import Runtime "mo:core/Runtime"; persistent actor Self { // -- Types -- type Account = { owner : Principal; subaccount : ?Blob; }; type TransferArgs = { from_subaccount : ?Blob; to : Account; amount : Nat; fee : ?Nat; memo : ?Blob; created_at_time : ?Nat64; }; type TransferResult = { #Ok : Nat; // block index #Err : TransferError; }; type TransferError = { #BadFee : { expected_fee : Nat }; #BadBurn : { min_burn_amount : Nat }; #InsufficientFunds : { balance : Nat }; #TooOld; #CreatedInFuture : { ledger_time : Nat64 }; #Duplicate : { duplicate_of : Nat }; #TemporarilyUnavailable; #GenericError : { error_code : Nat; message : Text }; }; type UpdateBalanceResult = { #Ok : [UtxoStatus]; #Err : UpdateBalanceError; }; type UtxoStatus = { #ValueTooSmall : Utxo; #Tainted : Utxo; #Checked : Utxo; #Minted : { block_index : Nat64; minted_amount : Nat64; utxo : Utxo }; }; type Utxo = { outpoint : { txid : Blob; vout : Nat32 }; value : Nat64; height : Nat32; }; type UpdateBalanceError = { #NoNewUtxos : { required_confirmations : Nat32; pending_utxos : ?[PendingUtxo]; current_confirmations : ?Nat32; }; #AlreadyProcessing; #TemporarilyUnavailable : Text; #GenericError : { error_code : Nat64; error_message : Text }; }; type PendingUtxo = { outpoint : { txid : Blob; vout : Nat32 }; value : Nat64; confirmations : Nat32; }; type ApproveArgs = { from_subaccount : ?Blob; spender : Account; amount : Nat; expected_allowance : ?Nat; expires_at : ?Nat64; fee : ?Nat; memo : ?Blob; created_at_time : ?Nat64; }; type ApproveError = { #BadFee : { expected_fee : Nat }; #InsufficientFunds : { balance : Nat }; #AllowanceChanged : { current_allowance : Nat }; #Expired : { ledger_time : Nat64 }; #TooOld; #CreatedInFuture : { ledger_time : Nat64 }; #Duplicate : { duplicate_of : Nat }; #TemporarilyUnavailable; #GenericError : { error_code : Nat; message : Text }; }; type RetrieveBtcWithApprovalArgs = { address : Text; amount : Nat64; from_subaccount : ?Blob; }; type RetrieveBtcResult = { #Ok : { block_index : Nat64 }; #Err : RetrieveBtcError; }; type RetrieveBtcError = { #MalformedAddress : Text; #AlreadyProcessing; #AmountTooLow : Nat64; #InsufficientFunds : { balance : Nat64 }; #InsufficientAllowance : { allowance : Nat64 }; #TemporarilyUnavailable : Text; #GenericError : { error_code : Nat64; error_message : Text }; }; // -- Remote canister references (mainnet) -- transient let ckbtcLedger : actor { icrc1_transfer : shared (TransferArgs) -> async TransferResult; icrc1_balance_of : shared query (Account) -> async Nat; icrc1_fee : shared query () -> async Nat; icrc2_approve : shared (ApproveArgs) -> async { #Ok : Nat; #Err : ApproveError }; } = actor "mxzaz-hqaaa-aaaar-qaada-cai"; transient let ckbtcMinter : actor { get_btc_address : shared ({ owner : ?Principal; subaccount : ?Blob; }) -> async Text; update_balance : shared ({ owner : ?Principal; subaccount : ?Blob; }) -> async UpdateBalanceResult; retrieve_btc_with_approval : shared (RetrieveBtcWithApprovalArgs) -> async RetrieveBtcResult; } = actor "mqygn-kiaaa-aaaar-qaadq-cai"; // -- Subaccount derivation -- // Derive a 32-byte subaccount from a principal for per-user deposit addresses. func principalToSubaccount(p : Principal) : Blob { let bytes = Blob.toArray(Principal.toBlob(p)); let size = bytes.size(); // First byte is length, remaining padded to 32 bytes let sub = Array.tabulate(32, func(i : Nat) : Nat8 { if (i == 0) { Nat8.fromNat(size) } else if (i <= size) { bytes[i - 1] } else { 0 } }); Blob.fromArray(sub) }; // -- Deposit: Get user's BTC deposit address -- public shared ({ caller }) func getDepositAddress() : async Text { if (Principal.isAnonymous(caller)) { Runtime.trap("Authentication required") }; let subaccount = principalToSubaccount(caller); await ckbtcMinter.get_btc_address({ owner = ?Principal.fromActor(Self); subaccount = ?subaccount; }) }; // -- Deposit: Check for new BTC and mint ckBTC -- public shared ({ caller }) func updateBalance() : async UpdateBalanceResult { if (Principal.isAnonymous(caller)) { Runtime.trap("Authentication required") }; let subaccount = principalToSubaccount(caller); await ckbtcMinter.update_balance({ owner = ?Principal.fromActor(Self); subaccount = ?subaccount; }) }; // -- Check user's ckBTC balance -- public shared ({ caller }) func getBalance() : async Nat { if (Principal.isAnonymous(caller)) { Runtime.trap("Authentication required") }; let subaccount = principalToSubaccount(caller); await ckbtcLedger.icrc1_balance_of({ owner = Principal.fromActor(Self); subaccount = ?subaccount; }) }; // -- Transfer ckBTC to another user -- public shared ({ caller }) func transfer(to : Principal, amount : Nat) : async TransferResult { if (Principal.isAnonymous(caller)) { Runtime.trap("Authentication required") }; let fromSubaccount = principalToSubaccount(caller); let now = Nat64.fromNat(Int.abs(Time.now())); await ckbtcLedger.icrc1_transfer({ from_subaccount = ?fromSubaccount; to = { owner = to; subaccount = null }; amount = amount; fee = ?10; // 10 satoshis memo = null; created_at_time = ?now; // required for dedup — see Pitfall 9 }) }; // -- Withdraw: Convert ckBTC back to BTC -- public shared ({ caller }) func withdraw(btcAddress : Text, amount : Nat64) : async RetrieveBtcResult { if (Principal.isAnonymous(caller)) { Runtime.trap("Authentication required") }; // Step 1: Approve the minter to spend ckBTC from the user's subaccount let fromSubaccount = principalToSubaccount(caller); let now = Nat64.fromNat(Int.abs(Time.now())); let approveResult = await ckbtcLedger.icrc2_approve({ from_subaccount = ?fromSubaccount; spender = { owner = Principal.fromText("mqygn-kiaaa-aaaar-qaadq-cai"); subaccount = null; }; amount = Nat64.toNat(amount) + 10; // amount + fee for the minter's burn expected_allowance = null; expires_at = null; fee = ?10; memo = null; created_at_time = ?now; // required for dedup — see Pitfall 9 }); switch (approveResult) { case (#Err(e)) { return #Err(#GenericError({ error_code = 0; error_message = "Approve for minter failed" })) }; case (#Ok(_)) {}; }; // Step 2: Call retrieve_btc_with_approval on the minter await ckbtcMinter.retrieve_btc_with_approval({ address = btcAddress; amount = amount; from_subaccount = ?fromSubaccount; }) }; }; ``` ### Rust #### Cargo.toml ```toml [package] name = "ckbtc_backend" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] ic-cdk = "0.19" ic-cdk-timers = "1.0" candid = "0.10" serde = { version = "1", features = ["derive"] } serde_bytes = "0.11" icrc-ledger-types = "0.1" ``` #### src/lib.rs ```rust use candid::{CandidType, Deserialize, Nat, Principal}; use ic_cdk::update; use ic_cdk::call::Call; use icrc_ledger_types::icrc1::account::Account; use icrc_ledger_types::icrc1::transfer::{TransferArg, TransferError}; use icrc_ledger_types::icrc2::approve::{ApproveArgs, ApproveError}; // -- Canister IDs -- const CKBTC_LEDGER: &str = "mxzaz-hqaaa-aaaar-qaada-cai"; const CKBTC_MINTER: &str = "mqygn-kiaaa-aaaar-qaadq-cai"; // -- Minter types -- #[derive(CandidType, Deserialize, Debug)] struct GetBtcAddressArgs { owner: Option, subaccount: Option>, } #[derive(CandidType, Deserialize, Debug)] struct UpdateBalanceArgs { owner: Option, subaccount: Option>, } #[derive(CandidType, Deserialize, Debug)] struct RetrieveBtcWithApprovalArgs { address: String, amount: u64, from_subaccount: Option>, } #[derive(CandidType, Deserialize, Debug)] struct RetrieveBtcOk { block_index: u64, } #[derive(CandidType, Deserialize, Debug)] enum RetrieveBtcError { MalformedAddress(String), AlreadyProcessing, AmountTooLow(u64), InsufficientFunds { balance: u64 }, InsufficientAllowance { allowance: u64 }, TemporarilyUnavailable(String), GenericError { error_code: u64, error_message: String }, } #[derive(CandidType, Deserialize, Debug)] struct Utxo { outpoint: OutPoint, value: u64, height: u32, } #[derive(CandidType, Deserialize, Debug)] struct OutPoint { txid: Vec, vout: u32, } #[derive(CandidType, Deserialize, Debug)] struct PendingUtxo { outpoint: OutPoint, value: u64, confirmations: u32, } #[derive(CandidType, Deserialize, Debug)] enum UtxoStatus { ValueTooSmall(Utxo), Tainted(Utxo), Checked(Utxo), Minted { block_index: u64, minted_amount: u64, utxo: Utxo, }, } #[derive(CandidType, Deserialize, Debug)] enum UpdateBalanceError { NoNewUtxos { required_confirmations: u32, pending_utxos: Option>, current_confirmations: Option, }, AlreadyProcessing, TemporarilyUnavailable(String), GenericError { error_code: u64, error_message: String }, } type UpdateBalanceResult = Result, UpdateBalanceError>; type RetrieveBtcResult = Result; // -- Subaccount derivation -- // Derive a 32-byte subaccount from a principal for per-user deposit addresses. fn principal_to_subaccount(principal: &Principal) -> [u8; 32] { let mut subaccount = [0u8; 32]; let principal_bytes = principal.as_slice(); subaccount[0] = principal_bytes.len() as u8; subaccount[1..1 + principal_bytes.len()].copy_from_slice(principal_bytes); subaccount } fn ledger_id() -> Principal { Principal::from_text(CKBTC_LEDGER).unwrap() } fn minter_id() -> Principal { Principal::from_text(CKBTC_MINTER).unwrap() } // -- Deposit: Get user's BTC deposit address -- #[update] async fn get_deposit_address() -> String { let caller = ic_cdk::api::msg_caller(); assert_ne!(caller, Principal::anonymous(), "Authentication required"); let subaccount = principal_to_subaccount(&caller); let args = GetBtcAddressArgs { owner: Some(ic_cdk::api::canister_self()), subaccount: Some(subaccount.to_vec()), }; let (address,): (String,) = Call::unbounded_wait(minter_id(), "get_btc_address") .with_arg(args) .await .expect("Failed to get BTC address") .candid_tuple() .expect("Failed to decode response"); address } // -- Deposit: Check for new BTC and mint ckBTC -- #[update] async fn update_balance() -> UpdateBalanceResult { let caller = ic_cdk::api::msg_caller(); assert_ne!(caller, Principal::anonymous(), "Authentication required"); let subaccount = principal_to_subaccount(&caller); let args = UpdateBalanceArgs { owner: Some(ic_cdk::api::canister_self()), subaccount: Some(subaccount.to_vec()), }; let (result,): (UpdateBalanceResult,) = Call::unbounded_wait(minter_id(), "update_balance") .with_arg(args) .await .expect("Failed to call update_balance") .candid_tuple() .expect("Failed to decode response"); result } // -- Check user's ckBTC balance -- #[update] async fn get_balance() -> Nat { let caller = ic_cdk::api::msg_caller(); assert_ne!(caller, Principal::anonymous(), "Authentication required"); let subaccount = principal_to_subaccount(&caller); let account = Account { owner: ic_cdk::api::canister_self(), subaccount: Some(subaccount), }; let (balance,): (Nat,) = Call::unbounded_wait(ledger_id(), "icrc1_balance_of") .with_arg(account) .await .expect("Failed to get balance") .candid_tuple() .expect("Failed to decode response"); balance } // -- Transfer ckBTC to another user -- #[update] async fn transfer(to: Principal, amount: Nat) -> Result { let caller = ic_cdk::api::msg_caller(); assert_ne!(caller, Principal::anonymous(), "Authentication required"); let from_subaccount = principal_to_subaccount(&caller); let args = TransferArg { from_subaccount: Some(from_subaccount), to: Account { owner: to, subaccount: None, }, amount, fee: Some(Nat::from(10u64)), // 10 satoshis memo: None, created_at_time: Some(ic_cdk::api::time()), // required for dedup — see Pitfall 9 }; let (result,): (Result,) = Call::unbounded_wait(ledger_id(), "icrc1_transfer") .with_arg(args) .await .expect("Failed to call icrc1_transfer") .candid_tuple() .expect("Failed to decode response"); result } // -- Withdraw: Convert ckBTC back to BTC -- #[update] async fn withdraw(btc_address: String, amount: u64) -> RetrieveBtcResult { let caller = ic_cdk::api::msg_caller(); assert_ne!(caller, Principal::anonymous(), "Authentication required"); // Step 1: Approve the minter to spend ckBTC from the user's subaccount let from_subaccount = principal_to_subaccount(&caller); let approve_args = ApproveArgs { from_subaccount: Some(from_subaccount), spender: Account { owner: minter_id(), subaccount: None, }, amount: Nat::from(amount) + Nat::from(10u64), // amount + fee for the minter's burn expected_allowance: None, expires_at: None, fee: Some(Nat::from(10u64)), memo: None, created_at_time: Some(ic_cdk::api::time()), // required for dedup — see Pitfall 9 }; let (approve_result,): (Result,) = Call::unbounded_wait(ledger_id(), "icrc2_approve") .with_arg(approve_args) .await .expect("Failed to call icrc2_approve") .candid_tuple() .expect("Failed to decode response"); if let Err(e) = approve_result { return Err(RetrieveBtcError::GenericError { error_code: 0, error_message: format!("Approve for minter failed: {:?}", e), }); } // Step 2: Call retrieve_btc_with_approval on the minter let args = RetrieveBtcWithApprovalArgs { address: btc_address, amount, from_subaccount: Some(from_subaccount.to_vec()), }; let (result,): (RetrieveBtcResult,) = Call::unbounded_wait(minter_id(), "retrieve_btc_with_approval") .with_arg(args) .await .expect("Failed to call retrieve_btc_with_approval") .candid_tuple() .expect("Failed to decode response"); result } // -- Export Candid interface -- ic_cdk::export_candid!(); ``` ## Deploy & Test ### Local Development There is no local ckBTC minter. For local testing, mock the minter interface or test against mainnet/testnet. ### Deploy to Mainnet ```bash # Deploy your backend canister icp deploy backend -e ic # Your canister calls the mainnet ckBTC canisters directly by principal ``` ### Using icp to Interact with ckBTC Directly ```bash # Check ckBTC balance for an account icp canister call mxzaz-hqaaa-aaaar-qaada-cai icrc1_balance_of \ '(record { owner = principal "YOUR-PRINCIPAL"; subaccount = null })' \ -e ic # Get deposit address icp canister call mqygn-kiaaa-aaaar-qaadq-cai get_btc_address \ '(record { owner = opt principal "YOUR-PRINCIPAL"; subaccount = null })' \ -e ic # Check for new deposits and mint ckBTC icp canister call mqygn-kiaaa-aaaar-qaadq-cai update_balance \ '(record { owner = opt principal "YOUR-PRINCIPAL"; subaccount = null })' \ -e ic # Transfer ckBTC (amount in e8s — 1 ckBTC = 100_000_000) # created_at_time is null here: no dedup, which is fine for a one-off manual # call but not for canister code — see Pitfall 9. icp canister call mxzaz-hqaaa-aaaar-qaada-cai icrc1_transfer \ '(record { to = record { owner = principal "RECIPIENT-PRINCIPAL"; subaccount = null }; amount = 100_000; fee = opt 10; memo = null; from_subaccount = null; created_at_time = null; })' -e ic # Withdraw ckBTC to a BTC address (amount in satoshis, minimum 50_000) # Note: In production, use icrc2_approve + retrieve_btc_with_approval (see withdraw function above) icp canister call mqygn-kiaaa-aaaar-qaadq-cai retrieve_btc_with_approval \ '(record { address = "bc1q...your-btc-address"; amount = 50_000; from_subaccount = null })' \ -e ic # Check transfer fee icp canister call mxzaz-hqaaa-aaaar-qaada-cai icrc1_fee '()' -e ic ``` ## Verify It Works ### Check Balance ```bash icp canister call mxzaz-hqaaa-aaaar-qaada-cai icrc1_balance_of \ '(record { owner = principal "YOUR-PRINCIPAL"; subaccount = null })' \ -e ic # Expected: (AMOUNT : nat) — balance in satoshis (e8s) ``` ### Verify Transfer ```bash # Transfer 1000 satoshis icp canister call mxzaz-hqaaa-aaaar-qaada-cai icrc1_transfer \ '(record { to = record { owner = principal "RECIPIENT"; subaccount = null }; amount = 1_000; fee = opt 10; memo = null; from_subaccount = null; created_at_time = null; })' -e ic # Expected: (variant { Ok = BLOCK_INDEX : nat }) # Verify recipient received it icp canister call mxzaz-hqaaa-aaaar-qaada-cai icrc1_balance_of \ '(record { owner = principal "RECIPIENT"; subaccount = null })' \ -e ic # Expected: balance increased by 1000 ``` ### Verify Deposit Flow ```bash # 1. Get deposit address icp canister call YOUR-CANISTER getDepositAddress -e ic # Expected: "bc1q..." or "3..." — a valid Bitcoin address # 2. Send BTC to that address (external wallet) # 3. Check for new deposits icp canister call YOUR-CANISTER updateBalance -e ic # Expected: (variant { Ok = vec { variant { Minted = record { ... } } } }) # 4. Check ckBTC balance icp canister call YOUR-CANISTER getBalance -e ic # Expected: balance reflects minted ckBTC ``` ### Verify Withdrawal ```bash icp canister call YOUR-CANISTER withdraw '("bc1q...destination", 50_000 : nat64)' -e ic # Expected: (variant { Ok = record { block_index = BLOCK_INDEX : nat64 } }) # The BTC will arrive at the destination address after Bitcoin confirmations ``` --- ## ckETH and ckERC20 (chain-key Ethereum) --- name: cketh description: "Integrate ckETH and ckERC20 tokens (ckUSDC, ckUSDT, ckEURC, ckWBTC, ckLINK, ...) into an IC app. Covers discovering supported ckERC20 tokens, converting ETH/ERC-20 to ckETH/ckERC20 via per-account deposit addresses (deposit_eth / deposit_erc20, works from exchanges) or the helper smart contract (depositEth / depositErc20), withdrawing with withdraw_eth / withdraw_erc20, address derivation, fees, minimums, and which calls belong in the frontend vs the backend. Use when the user mentions ckETH, ckERC20, ckUSDC, ckUSDT, or depositing/withdrawing ETH or ERC-20 tokens to/from ICP. Do NOT use for plain ICRC-1 transfers of ck tokens (use icrc-ledger) or for signing arbitrary Ethereum transactions from a canister (use evm-rpc)." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2, Node.js >= 22 for frontend code" metadata: title: ckETH and ckERC20 (chain-key Ethereum) category: DeFi --- # ckETH and ckERC20 Integration ## What This Is ckETH (1:1 ETH) and ckERC20 tokens (1:1 ERC-20, e.g. ckUSDC) are ICRC-1/ICRC-2 tokens on ICP. **One minter canister handles ETH and every ERC-20.** It holds the Ethereum funds at addresses derived from its threshold-ECDSA key, talks to Ethereum through the EVM RPC canister, mints after a deposit is final on Ethereum, and burns via an ICRC-2 allowance before it sends a withdrawal. Every ckERC20 token has its own ledger and index. Gas for ERC-20 withdrawals is paid in **ckETH**. Plain transfers between ICP accounts are ordinary ICRC-1 calls: load `icrc-ledger` for those. This skill covers conversion and token discovery. ## Canister IDs and Ethereum addresses | | Ethereum Mainnet | Sepolia testnet | |---|---|---| | Minter (ETH + all ckERC20) | `sv3dd-oaaaa-aaaar-qacoa-cai` | `jzenf-aiaaa-aaaar-qaa7q-cai` | | ckETH ledger | `ss2fx-dyaaa-aaaar-qacoq-cai` (ckETH) | `apia6-jaaaa-aaaar-qabma-cai` (ckSepoliaETH) | | ckETH index | `s3zol-vqaaa-aaaar-qacpa-cai` | `sh5u2-cqaaa-aaaar-qacna-cai` | | ckERC20 ledger suite orchestrator | `vxkom-oyaaa-aaaar-qafda-cai` | `2s5qh-7aaaa-aaaar-qadya-cai` | | Helper contract (`deposit_with_subaccount_helper_contract_address`) | `0x18901044688D3756C35Ed2b36D93e6a5B8e00E68` | `0x2D39863d30716aaf2B7fFFd85Dd03Dda2BFC2E38` | | Minter main address (holds funds, sends withdrawals) | `0xb25eA1D493B49a1DeD42aC5B1208cC618f9A9B80` | `0x1789F79e95324A47c5Fd6693071188e82E9a3558` | The minter, ckETH and every ckERC20 ledger live on the fiduciary subnet. Read Ethereum addresses at runtime from `get_minter_info` (they change on upgrades); the table is a snapshot from 2026-11. ## Discovering ckERC20 tokens The **minter** decides which tokens can be deposited and withdrawn. Read `get_minter_info` (query): - `supported_ckerc20_tokens: opt vec record { ckerc20_token_symbol; erc20_contract_address; ledger_canister_id }`. This is the authoritative list. - `minimum_deposit_amounts: opt vec record { erc20_contract_address; minimum_deposit_amount }` and `minimum_eth_deposit_amount`. These apply only to the deposit-address flow. - `minimum_withdrawal_amount` (ckETH, in wei), `cketh_ledger_id`, `deposit_with_subaccount_helper_contract_address`. For each ledger, read `icrc1_metadata` for `icrc1:decimals`, `icrc1:fee` and `icrc1:logo`. **Decimals differ per token** (ckETH 18, ckUSDC 6, ckWBTC 8). For the index canister id use the orchestrator: `get_orchestrator_info` (`managed_canisters[].{erc20_contract, ledger, index, archives}`) or `canister_ids(record { chain_id = 1; address = "0x..." })`. Mainnet tokens on 2026-11-02: ckUSDC `xevnm-gaaaa-aaaar-qafnq-cai` (6 decimals), ckUSDT `cngnf-vqaaa-aaaar-qag4q-cai` (6), ckEURC `pe5t5-diaaa-aaaar-qahwa-cai` (6), ckXAUT `nza5v-qaaaa-aaaar-qahzq-cai` (6), ckWBTC `bptq2-faaaa-aaaar-qagxq-cai` (8), ckWSTETH `j2tuh-yqaaa-aaaar-qahcq-cai` (18), ckLINK `g4tto-rqaaa-aaaar-qageq-cai` (18), ckUNI `ilzky-ayaaa-aaaar-qahha-cai` (18), ckSHIB `fxffn-xiaaa-aaaar-qagoa-cai` (18), ckPEPE `etik7-oiaaa-aaaar-qagia-cai` (18), ckOCT `ebo5g-cyaaa-aaaar-qagla-cai` (18), ckBAT `j7x7x-syaaa-aaaar-qcbea-cai` (18). On Sepolia, only ckSepoliaUSDC `yfumr-cyaaa-aaaar-qaela-cai` (Sepolia USDC `0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`) is supported. New tokens are added by NNS proposal, so never hardcode the list. ## Account model: who calls the minter The minter credits and debits ICRC accounts `{ owner; subaccount }`. Choose one of two models: - **Non-custodial (frontend calls the minter directly).** The user's identity (Internet Identity, or an ICRC signer: see `user-sign-in` / `wallet-integration`) calls `deposit_erc20`/`deposit_eth`, `icrc2_approve` and `withdraw_*`. The tokens belong to the user's own principal. This needs no backend. - **Custodial (your canister calls the minter).** The canister is the owner and keeps one 32-byte subaccount per user. All calls come from the canister's principal (see [references/backend.md](references/backend.md)). `deposit_erc20` and `deposit_eth` have **no `owner` argument**: the account is always `caller + subaccount`. A backend cannot register a deposit address for a user-owned account. Only the owner can arm its own address. ## Deposit flow A: per-account deposit address (recommended) Works from any wallet **and from centralized exchanges**, because it needs only a plain transfer to an address. It has been live on mainnet since 2026-09 for ERC-20 and ETH. 1. **Register.** The owner calls `deposit_erc20(record { erc20_contract_address = "0x…"; mode = variant { Unsponsored = record { subaccount = opt <32 bytes> | null } } })` or `deposit_eth(record { mode = … })`. These are update calls, free, and idempotent. The response is `{ address; minimum_deposit_amount; status }`. 2. **Send.** The user sends the ERC-20 (a plain `transfer`) or ETH to `address`, **on Ethereum L1 only**. Several transfers add up, because the minter reads the address' total balance. 3. **Detect.** The minter scans the registered `(address, asset)` pair for **24 h**: at 30 s, 30 s, 60 s, 2 min, … then hourly. A balance ≥ `minimum_deposit_amount` moves the status from `Scanning { valid_until; last_scanned_block; scan_count }` to `AwaitingSweep { scanned_balance; detected_at_block; … }`. 4. **Sweep and mint.** The minter signs a one-time EIP-7702 delegation of the deposit address to the sweeper contract plus an attestation of `(principal, subaccount)`. It then sweeps the funds through the helper contract to its main address. The sweep emits `ReceivedEthOrErc20`, and the minter mints the **full swept amount** once that block is finalized, typically about 20 min. The sweep gas is paid by the minter, not the user. 5. **Re-arm.** Call `deposit_*` again whenever the user returns, or to poll status. After the window expires, or after a sweep, the next call re-arms the pair for 24 h. Funds that arrived while the pair was not armed are not lost: they are detected after re-arming. **How the address is computed.** It uses non-hardened derivation from the minter's tECDSA secp256k1 `key_1` with path `[minter canister id bytes, [0x01], owner principal bytes, 32-byte subaccount (all zeros for the default)]`, and the address is `keccak256(uncompressed pubkey)[12..]`. It is one address per account, shared by ETH and every ERC-20, and stable across calls. You can derive it offline (`deriveEthDepositAddress` in [references/frontend.md](references/frontend.md)) to display or verify it, but only a `deposit_*` call arms scanning. Limits: at most 5 assets armed per account (`TooManyTokensForAccount`), and a global cap (`TooManyActiveDeposits`). A `minimum_deposit_amount` of `2^256-1` means deposits are unavailable for that token. On mainnet on 2026-11-02 the minimum was 0.005 ETH, 10 USDC/USDT and 8 EURC. ## Deposit flow B: helper smart contract (Ethereum wallet signs) The user's Ethereum wallet (MetaMask etc.) calls the helper contract. Funds move straight to the minter's main address, and the contract emits `ReceivedEthOrErc20(address indexed erc20ContractAddress, address indexed owner, uint256 amount, bytes32 indexed principal, bytes32 subaccount)`. The minter scrapes these logs and mints after finalization, about 20 min. No IC call is needed. ```solidity function depositEth(bytes32 principal, bytes32 subaccount) payable function depositErc20(address erc20Address, uint256 amount, bytes32 principal, bytes32 subaccount) // after ERC20.approve(helper, amount) ``` - **principal → bytes32**: `[len(principal bytes)] ++ principal bytes ++ zero padding` to 32 bytes, hex with a `0x` prefix. Use `encodePrincipalToEthAddress(principal)` from `@icp-sdk/canisters/cketh`. The name is misleading: it returns bytes32, not an address. - **subaccount → bytes32**: the 32 raw bytes, or 32 zero bytes for the default account. - ETH sent to `depositEth` emits the event with `erc20ContractAddress = 0x0`. ## Withdrawal: ckETH → ETH 1. `icrc2_approve` on the ckETH ledger, with spender = the minter and amount ≥ the withdrawal amount. Burns are fee-free, but the approve itself costs the 0.000002 ckETH ledger fee. 2. `withdraw_eth(record { recipient = "0x…"; amount = ; from_subaccount = opt … })` returns `Ok { block_index }`, the ckETH burn index, which doubles as the **withdrawal id**. 3. The minter sends an EIP-1559 transfer with a **21,000 gas limit**, usually within about 6 min. The recipient receives `amount − max_transaction_fee`. The estimate comes from `eip_1559_transaction_price(null)`, and the unspent part is not refunded. The minimum is `minimum_withdrawal_amount`: 0.005 ETH on mainnet since 2026-05 (older docs say 0.03). ## Withdrawal: ckERC20 → ERC-20 1. `eip_1559_transaction_price(opt record { ckerc20_ledger_id = })` returns `max_transaction_fee` in wei, using a 65,000 gas limit. 2. `icrc2_approve` on the **ckETH** ledger for at least `max_transaction_fee` plus a margin, because the minter re-estimates at call time. 3. `icrc2_approve` on the **ckERC20** ledger for at least `amount`. 4. `withdraw_erc20(record { amount; ckerc20_ledger_id; recipient; from_cketh_subaccount = opt …; from_ckerc20_subaccount = opt … })` returns `Ok { cketh_block_index; ckerc20_block_index }`. `cketh_block_index` is the withdrawal id. 5. The recipient receives the **full** `amount` in ERC-20, and the gas is burned from ckETH. If the ckERC20 burn fails (`CkErc20LedgerError`), the ckETH burn is reimbursed minus the ckETH ledger fee. **Tracking either withdrawal:** call `withdrawal_status(variant { ByWithdrawalId = })` (query; also `BySenderAccount`, `ByRecipient`). The status goes `Pending → TxCreated → TxSent { transaction_hash } → TxFinalized (Success | Reimbursed | PendingReimbursement)`. For ckETH, `retrieve_eth_status(block_index)` also works. ## Mistakes That Break Your Build 1. **Hardcoding the token list or helper address.** Read `supported_ckerc20_tokens` and `deposit_with_subaccount_helper_contract_address` from `get_minter_info`. `smart_contract_address`, `eth_helper_contract_address` and `erc20_helper_contract_address` are the **legacy** helpers: ETH-only or without subaccount. Do not build on them. 2. **Depositing an unsupported ERC-20.** The helper contract has no whitelist: an unsupported token is transferred to the minter and never minted. Check the token against `supported_ckerc20_tokens` first. In flow A, an unsupported token sent to a deposit address is not credited either. 3. **Sending to the wrong place.** ETH or tokens sent directly to the minter's main address are not attributed to anyone. Deposit addresses work on **Ethereum L1 only**: transfers on Arbitrum, Base, BSC, etc. to the same address are not credited. Mainnet and Sepolia use different helpers and minters. 4. **Expecting the backend to arm a user's deposit address.** `deposit_erc20`/`deposit_eth` credit `caller + subaccount`. In a non-custodial app the **frontend** must call it with the user's identity. The anonymous principal traps. 5. **Treating the deposit address as "fire and forget" forever.** Scanning lasts 24 h per registration. Call `deposit_*` again when the user comes back. A balance below `minimum_deposit_amount` is never swept until it is topped up. 6. **Using `u64` for amounts.** Wei amounts exceed `u64` above about 18.4 ETH, and many 18-decimal tokens overflow too. Use `Nat` (Rust `candid::Nat`, TS `bigint`). Always scale by the ledger's `icrc1_decimals`. 7. **Forgetting ckETH for ckERC20 withdrawals.** A user holding only ckUSDC cannot withdraw. They need ckETH ≥ `max_transaction_fee` plus margin, **and** an approval on the ckETH ledger. Each approve costs that ledger's fee: 0.000002 ckETH, or 0.01 ckUSDC/ckUSDT. 8. **Approving the wrong ledger or spender.** The spender is always the **minter** (`sv3dd-…`), never the ledger or the helper contract. An ERC-20 withdrawal needs two approvals on two ledgers. 9. **Withdrawing ETH to a contract.** `withdraw_eth` uses 21,000 gas, so contract recipients with non-trivial `receive()` logic fail. The zero address traps, and blocklisted addresses return `RecipientAddressBlocked`. 10. **Concurrent minter calls from one principal.** `withdraw_*`, `deposit_erc20` and `deposit_eth` take a per-principal guard and **trap** (the call is rejected) on `AlreadyProcessing`, `TooManyConcurrentRequests` or `TooManyPendingRequests`. A custodial canister acts as a single principal for all users, so serialize its minter calls and retry rejected calls. 11. **USDT approve.** USDT reverts on changing a non-zero allowance to another non-zero value. Approve 0 first (helper flow only). 12. **Leaving `created_at_time` unset on retries.** Approvals from canisters should set `created_at_time` so that retries deduplicate (see `icrc-ledger`). ## Implementation: frontend (TypeScript) `@icp-sdk/canisters/cketh` (v4) wraps `withdrawEth`, `withdrawErc20`, `getMinterInfo` and `eip1559TransactionPrice`, but **not** `deposit_erc20`/`deposit_eth`/`withdrawal_status`. Generate bindings from the deployed interface instead: ```bash npm i @icp-sdk/core@^6 @icp-sdk/canisters@^4 @dfinity/utils@^5 viem@^2 @dfinity/ic-pub-key@^1 icp canister metadata sv3dd-oaaaa-aaaar-qacoa-cai candid:service -n ic > cketh_minter.did npx @icp-sdk/bindgen --did-file ./cketh_minter.did --out-dir ./src/bindings ``` The generated wrapper uses `{ __kind__: "Variant", Variant: … }` for variants and `field?: T` for `opt`. The complete module is in [references/frontend.md](references/frontend.md). It covers `listCkErc20Tokens`, `getErc20DepositAddress`/`getEthDepositAddress` (flow A), `deriveEthDepositAddress` (offline), `depositViaHelper` (flow B with viem, including the USDT approve reset), `withdrawEth`, `withdrawErc20` and `withdrawalStatus`. Its core calls: ```typescript const res = await minter.deposit_erc20({ erc20_contract_address: usdc, mode: { __kind__: "Unsponsored", Unsponsored: { subaccount } } }); const price = await minter.eip_1559_transaction_price({ ckerc20_ledger_id: ckUsdcLedger }); await ckEthLedger.approve({ spender: { owner: minterId, subaccount: [] }, amount: (price.max_transaction_fee * 3n) / 2n }); await ckUsdcLedger.approve({ spender: { owner: minterId, subaccount: [] }, amount }); const w = await minter.withdraw_erc20({ ckerc20_ledger_id: ckUsdcLedger, recipient, amount }); ``` Detect a completed deposit by polling `icrc1_balance_of` on the token's ledger, or the index canister's `get_account_transactions`. Mints carry a CBOR memo that `decode_ledger_memo` on the minter decodes into `Convert { from_address; tx_hash; log_index }`. ## Implementation: backend (custodial, Rust and Motoko) See [references/backend.md](references/backend.md). It has per-user subaccounts, `deposit_erc20` called by the canister (owner = canister), and `withdraw_erc20` with both approvals from the user's subaccount. Both the Rust and the Motoko versions are complete. A backend does not need the EVM RPC canister. Only if the **canister itself** must sign the helper-contract deposit on Ethereum, load `evm-rpc`. ## Verify It Works ```bash # Minter config: supported tokens, helper address, minimums icp canister call sv3dd-oaaaa-aaaar-qacoa-cai get_minter_info '()' -n ic --query # Register/inspect a deposit address on Sepolia (caller = your identity) icp canister call jzenf-aiaaa-aaaar-qaa7q-cai deposit_eth \ '(record { mode = variant { Unsponsored = record { subaccount = null } } })' -n ic # Expected: (variant { Ok = record { address = "0x..."; minimum_deposit_amount = 5_000_000_000_000_000 : nat; status = variant { Scanning = record { ... } } } }) # Gas a ckUSDC withdrawal would burn (wei of ckETH) icp canister call sv3dd-oaaaa-aaaar-qacoa-cai eip_1559_transaction_price \ '(opt record { ckerc20_ledger_id = principal "xevnm-gaaaa-aaaar-qafnq-cai" })' -n ic --query # Withdrawal status by id (ckETH burn index) icp canister call sv3dd-oaaaa-aaaar-qacoa-cai withdrawal_status '(variant { ByWithdrawalId = 12345 : nat64 })' -n ic --query # Balance on a ckERC20 ledger icp canister call xevnm-gaaaa-aaaar-qafnq-cai icrc1_balance_of '(record { owner = principal "YOUR-PRINCIPAL"; subaccount = null })' -n ic ``` --- ## ckSOL (chain-key SOL) --- name: cksol description: "Integrate ckSOL (chain-key SOL) into an IC app. Covers converting SOL to ckSOL via per-account Solana deposit addresses (get_deposit_address + deposit_sol with cycles, works from exchanges), withdrawing ckSOL to SOL (icrc2_approve + withdraw_sol), tracking deposit/withdrawal status, deposit-address derivation, fees, minimums, and which calls belong in the frontend vs a backend canister. Use when the user mentions ckSOL, Solana deposits or withdrawals on ICP, or moving SOL to/from the Internet Computer. Do NOT use for plain ICRC-1 ckSOL transfers (use icrc-ledger), SPL tokens, or signing arbitrary Solana transactions from a canister (use the SOL RPC canister / threshold Ed25519 directly)." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2, Node.js >= 22 for frontend code" metadata: title: ckSOL (chain-key SOL) category: DeFi --- # ckSOL Integration ## What This Is ckSOL is an ICRC-1/ICRC-2 token backed 1:1 by SOL (9 decimals, 1 ckSOL = 1_000_000_000 lamports). The **ckSOL minter** derives one Solana deposit address per ICRC account from its threshold-Ed25519 key. It sweeps deposited SOL to its main address and mints once the sweep is finalized. For withdrawals it burns ckSOL via an ICRC-2 allowance and sends SOL using durable-nonce transactions, which never expire. It talks to Solana through the SOL RPC canister. Only native **SOL** is supported: no SPL tokens. Source: `github.com/dfinity/cksol`. Minter v0.1.0 has run on mainnet since 2026-10. ## Canister IDs | | Mainnet (Solana mainnet) | Staging (Solana Devnet, token "ckDevnetSOL") | |---|---|---| | Minter | `lh22c-kyaaa-aaaar-qb5nq-cai` | `ljyxk-riaaa-aaaar-qb5mq-cai` | | Ledger | `ls5lp-lqaaa-aaaar-qb5oa-cai` | `la34w-haaaa-aaaar-qb5na-cai` | | Index | `2ezyf-hqaaa-aaaar-qb6ga-cai` | `2r6ji-gyaaa-aaaar-qb6fq-cai` | | Minter main Solana address | `GXVewvv6HehcLFYCmwpqh5CrMjqN9zJ8rqzGq3HEt9Ax` | `Br8eRkeya8hy3sHCYqtWqGeNNZ349aPSUKGVYFWKKer1` | The ledger fee is 500 lamports. `get_minter_info` (query) on 2026-11-02 returned: `minimum_deposit_amount = 20_000_000` (0.02 SOL), `minimum_withdrawal_amount = 2_000_000` (0.002 SOL), `withdrawal_fee = 1_000_000` (0.001 SOL), `deposit_sol_required_cycles = 1_000_000_000_000`, and `deposit_sol_fee = 45_000_000_000`. **`deposit_sol_fee` is in cycles, not lamports.** Read these values at runtime. ## How the deposit address is computed The minter uses non-hardened derivation from the IC threshold **Ed25519** key `key_1`, with path `[minter canister id bytes, [0x01], owner principal bytes, 32-byte subaccount (zeros for default)]`. The Solana address is the base58 of the derived 32-byte public key. It is deterministic and stable, one address per `(owner, subaccount)`, and is a plain system account. The minter's main address is the key at the empty path, so it can never collide with a deposit address. You can derive it offline (`deriveDepositAddressOffline` below) or call `get_deposit_address`, an **update** call that anyone may make for any non-anonymous owner. ## Deposit: SOL → ckSOL (deployed "manual" flow) 1. **Address.** `get_deposit_address(record { owner = opt ; subaccount = opt <32 bytes> | null })` returns a base58 address. If `owner` is null, it defaults to the **caller**. 2. **Send SOL** to that address from any wallet or exchange, in one or several transfers (no memo). The **total balance** must reach `minimum_deposit_amount`. 3. **Notify.** `deposit_sol(record { owner = opt ; subaccount })` **with cycles attached** (≥ `deposit_sol_required_cycles`). The minter reads the finalized balance and charges about 2.3B cycles for `getBalance` plus `deposit_sol_fee` (45B), refunding the rest. It then queues `sweepable = balance − 890_880` (the rent-exemption threshold stays on the address, once per address) and returns `Ok(deposit_id : nat64)`. Only canisters can attach cycles, so **a frontend cannot call `deposit_sol` directly**: route it through your backend canister. `owner` may be any principal, so a backend can pay for a user-owned account. 4. **Sweep and mint** happen on minter timers, about a minute each. Up to 10 deposits are swept per Solana transaction, and each deposit pays a 5_000-lamport fee share. ckSOL is minted only after the sweep is **finalized**. The user receives `sweepable − 5_000` lamports. 5. **Track** with `deposit_sol_status(deposit_id)` (query): `Queued { sweepable_amount } → Swept { signature } → Finalized { signature } → Minted { block_index; minted_amount }`. A `Dropped { signature }` status means the sweep failed or expired, nothing was minted, and the funds are still on the address: call `deposit_sol` again. A `Quarantined { signature }` status needs a minter upgrade: use a different subaccount for new deposits. At most one deposit per account is in flight. Calling `deposit_sol` again while one is queued, swept or finalized returns **the same `deposit_id`** and refunds all cycles, so retries are safe. Example: the first deposit of exactly 1 SOL mints 999_104_120 lamports, the minimum 0.02 SOL mints 19_104_120, and a later deposit to the same address loses only the 5_000 fee share. **Upcoming automatic flow, not on mainnet as of 2026-11-02.** `watch_deposit_address(record { subaccount })` is free, needs no cycles, and has owner = caller. The minter then scans the address for about 24 h and sweeps automatically, deducting `automatic_deposit_fee` (0.002 SOL). Status is `Watching | Detected { deposit_id }`, and you follow it with `deposit_sol_status`. Before using it, check that the endpoint exists: `icp canister metadata lh22c-kyaaa-aaaar-qb5nq-cai candid:service -n ic`. ## Withdrawal: ckSOL → SOL 1. `icrc2_approve` on the ckSOL ledger, with spender = **minter** and amount ≥ the withdrawal amount. Burns are fee-free, and the approve itself costs 500 lamports. 2. `withdraw_sol(record { address = ""; amount = ; from_subaccount = opt … })` burns from `caller + from_subaccount`. There is no owner argument. It returns `Ok { block_index }`, the burn index, which is also the withdrawal id. 3. The minter batches up to 10 withdrawals per durable-nonce transaction. The destination receives `amount − withdrawal_fee`. 4. Track with `withdraw_sol_status(record { block_index })`, an **update** call: `Pending → TxSent { transaction_id } → TxFinalized (Success | Failure) { transaction_id }`. Business errors come back as `Err`, not as traps: `ValueTooSmall`, `MalformedAddress`, `InvalidDestination` (Solana reserved/sysvar/program keys, the minter's main address, its nonce accounts), `InsufficientFunds`, `InsufficientAllowance`, `AlreadyProcessing` (one withdrawal per principal at a time), and `TemporarilyUnavailable`. ## Who calls what | Step | Frontend (user identity) | Backend canister | |---|---|---| | `get_deposit_address` | ✅ (owner = user) | ✅ | | `deposit_sol` (needs cycles) | ❌ | ✅ passes `owner = opt user` | | `deposit_sol_status` | ✅ query | ✅ | | `icrc2_approve` + `withdraw_sol` | ✅ (burns from the user's own account) | ✅ only for tokens the canister owns (custodial subaccounts) | | `withdraw_sol_status` | ✅ | ✅ | Non-custodial pattern: the frontend shows the address, then calls the backend's `notifySolDeposit`, which calls `deposit_sol` for `owner = caller` with cycles. The frontend then polls `deposit_sol_status`, and the user withdraws directly from the frontend. ## Mistakes That Break Your Build 1. **Calling `deposit_sol` from the browser or without cycles.** It fails with `InsufficientCycles`. It must be called by a canister with `(with cycles = …)` / `.with_cycles(…)`, or via `icp canister call … --proxy --cycles `. 2. **Omitting `owner` when a canister calls `get_deposit_address` / `deposit_sol`.** It defaults to the caller, which is your canister. The user's SOL is then looked up at, and minted to, the canister's account. Pass `owner = opt user`, and use the **same** `(owner, subaccount)` in both calls. 3. **Using stale API names from older docs.** There is no `process_deposit` and no transaction-signature argument, and the withdrawal endpoint is `withdraw_sol`, not `withdraw`. The minter reads the address **balance**, so the user never needs a transaction signature. Track the result with `deposit_sol_status(deposit_id)`. 4. **Expecting automatic detection on mainnet today.** Without `deposit_sol`, deposited SOL just sits on the deposit address. Nothing is lost, but nothing is minted until someone calls `deposit_sol`, or `watch_deposit_address` once it is deployed. 5. **Depositing below the minimum.** `ValueTooSmall { balance; minimum_deposit_amount }` is checked against the address balance, which includes the 890_880-lamport rent threshold left by earlier sweeps. Top up and call again. Each rejected call still costs your canister about 2.3B cycles. 6. **Sending SPL tokens (USDC on Solana, etc.) or using another chain.** Only native SOL is credited. 7. **Promising 1:1 on the first deposit.** The first sweep of an address keeps 890_880 lamports there, each sweep costs a 5_000-lamport share, and withdrawals cost `withdrawal_fee`. Show users `minted_amount` from `deposit_sol_status`. 8. **Unbounded `deposit_sol` relays.** Each accepted call spends about 47B cycles (about 0.07 USD) of **your** canister. Authenticate, rate-limit per user, and reject anonymous callers (see `canister-security`). 9. **Using `u64` vs `nat` incorrectly.** Minter amounts are `nat64` lamports (`Lamport`), and ledger amounts are `nat`. `deposit_sol_fee` and `deposit_sol_required_cycles` are `nat` cycles. 10. **Concurrent withdrawals from one principal.** `withdraw_sol` returns `AlreadyProcessing` while another withdrawal by the same principal is in progress. A custodial canister must serialize its withdrawals. ## Implementation: frontend (TypeScript) The `@icp-sdk/canisters` package has no ckSOL module, so generate bindings from the deployed interface: ```bash npm i @icp-sdk/core@^6 @icp-sdk/canisters@^4 @dfinity/utils@^5 @dfinity/ic-pub-key@^1 bs58@^6 icp canister metadata lh22c-kyaaa-aaaar-qb5nq-cai candid:service -n ic > cksol_minter.did npx @icp-sdk/bindgen --did-file ./cksol_minter.did --out-dir ./src/bindings ``` ```typescript import { HttpAgent, type Identity } from "@icp-sdk/core/agent"; import { Principal } from "@icp-sdk/core/principal"; import { IcrcLedgerCanister } from "@icp-sdk/canisters/ledger/icrc"; import { createActor } from "./bindings/cksol_minter"; import { schnorr } from "@dfinity/ic-pub-key"; import bs58 from "bs58"; const CKSOL_MINTER = Principal.fromText("lh22c-kyaaa-aaaar-qb5nq-cai"); const CKSOL_LEDGER = Principal.fromText("ls5lp-lqaaa-aaaar-qb5oa-cai"); export async function ckSol(identity: Identity) { const agent = await HttpAgent.create({ identity }); return { minter: createActor(CKSOL_MINTER.toText(), { agent }), ledger: IcrcLedgerCanister.create({ agent, canisterId: CKSOL_LEDGER }), }; } type Ctx = Awaited>; // Deposit address: an update call; owner defaults to the caller when omitted. export async function depositAddress({ minter }: Ctx, owner: Principal, subaccount?: Uint8Array) { return minter.get_deposit_address({ owner, subaccount }); // base58 Solana address } // Same address computed offline (no IC call): mainnet Ed25519 "key_1", // path = [minter canister id, [0x01], owner principal bytes, 32-byte subaccount]. export function deriveDepositAddressOffline(owner: Principal, subaccount: Uint8Array = new Uint8Array(32)) { const master = schnorr.ed25519.PublicKeyWithChainCode.forMainnetKey("key_1"); const path = new schnorr.ed25519.DerivationPath([ CKSOL_MINTER.toUint8Array(), new Uint8Array([1]), owner.toUint8Array(), subaccount, ]); const hex = master.deriveSubkeyWithChainCode(path).public_key.toHex(); return bs58.encode(Uint8Array.from(hex.match(/../g)!.map((b) => parseInt(b, 16)))); } // Track a deposit queued by deposit_sol (called by your backend, which attaches cycles). export async function depositStatus({ minter }: Ctx, depositId: bigint) { return minter.deposit_sol_status(depositId); // NotFound | Queued | Swept | Finalized | Minted | Dropped | Quarantined } export async function withdrawSol(ctx: Ctx, address: string, amountLamports: bigint) { const info = await ctx.minter.get_minter_info(); if (amountLamports < info.minimum_withdrawal_amount) throw new Error("below minimum_withdrawal_amount"); await ctx.ledger.approve({ spender: { owner: CKSOL_MINTER, subaccount: [] }, amount: amountLamports }); const res = await ctx.minter.withdraw_sol({ address, amount: amountLamports }); if (res.__kind__ === "Err") throw new Error(res.Err.__kind__); // recipient receives amountLamports - info.withdrawal_fee return res.Ok.block_index; // poll withdraw_sol_status({ block_index }) } export async function withdrawStatus({ minter }: Ctx, blockIndex: bigint) { return minter.withdraw_sol_status({ block_index: blockIndex }); // NotFound | Pending | TxSent | TxFinalized } ``` The user sends SOL with their own wallet (Phantom, Solflare, an exchange) to the returned address. No Solana SDK is needed in your app unless you want to build that transfer yourself. ## Implementation: backend relay for `deposit_sol` ### Rust `Cargo.toml` dependencies: `ic-cdk = "0.19"`, `candid = "0.10"`, `serde = { version = "1", features = ["derive"] }`, `serde_bytes = "0.11"`. ```rust use candid::{CandidType, Deserialize, Nat, Principal}; use ic_cdk::call::Call; use ic_cdk::update; const CKSOL_MINTER: &str = "lh22c-kyaaa-aaaar-qb5nq-cai"; const DEPOSIT_SOL_CYCLES: u128 = 1_000_000_000_000; // >= get_minter_info().deposit_sol_required_cycles; unused part is refunded #[derive(CandidType, Deserialize)] struct AccountArgs { owner: Option, subaccount: Option } #[derive(CandidType, Deserialize, Debug)] struct InsufficientCyclesError { expected: Nat, received: Nat } #[derive(CandidType, Deserialize, Debug)] enum DepositSolError { InsufficientCycles(InsufficientCyclesError), TemporarilyUnavailable(String), AlreadyProcessing, ValueTooSmall { balance: u64, minimum_deposit_amount: u64 }, Quarantined { deposit_id: u64 }, } fn minter() -> Principal { Principal::from_text(CKSOL_MINTER).unwrap() } fn caller_not_anonymous() -> Principal { let caller = ic_cdk::api::msg_caller(); assert_ne!(caller, Principal::anonymous(), "Authentication required"); caller } /// Solana deposit address of the caller's own ckSOL account (owner = caller, default subaccount). #[update] async fn sol_deposit_address() -> Result { let user = caller_not_anonymous(); let (address,): (String,) = Call::unbounded_wait(minter(), "get_deposit_address") .with_arg(AccountArgs { owner: Some(user), subaccount: None }) .await .map_err(|e| format!("{e:?}"))? .candid_tuple() .map_err(|e| format!("{e:?}"))?; Ok(address) } /// After the user sent SOL to the deposit address: pay the cycles and queue the sweep. /// ckSOL is minted to the USER's account (owner = user), not to this canister. #[update] async fn notify_sol_deposit() -> Result { let user = caller_not_anonymous(); // Abuse guard: this call spends ~47B cycles of THIS canister per successful deposit. // Add per-user rate limiting / an in-flight set in production (see canister-security skill). let (res,): (Result,) = Call::unbounded_wait(minter(), "deposit_sol") .with_arg(AccountArgs { owner: Some(user), subaccount: None }) .with_cycles(DEPOSIT_SOL_CYCLES) .await .map_err(|e| format!("deposit_sol rejected: {e:?}"))? .candid_tuple() .map_err(|e| format!("{e:?}"))?; res.map_err(|e| format!("{e:?}")) // Ok(deposit_id) -> poll deposit_sol_status(deposit_id) } ic_cdk::export_candid!(); ``` ### Motoko ```motoko import Principal "mo:core/Principal"; import Runtime "mo:core/Runtime"; persistent actor { type DepositSolError = { #InsufficientCycles : { expected : Nat; received : Nat }; #TemporarilyUnavailable : Text; #AlreadyProcessing; #ValueTooSmall : { balance : Nat64; minimum_deposit_amount : Nat64 }; #Quarantined : { deposit_id : Nat64 }; }; transient let minter : actor { get_deposit_address : shared { owner : ?Principal; subaccount : ?Blob } -> async Text; deposit_sol : shared { owner : ?Principal; subaccount : ?Blob } -> async { #Ok : Nat64; #Err : DepositSolError }; } = actor "lh22c-kyaaa-aaaar-qb5nq-cai"; // >= get_minter_info().deposit_sol_required_cycles (1T on 2026-11); the unused part is refunded. transient let DEPOSIT_SOL_CYCLES = 1_000_000_000_000; // Solana deposit address of the caller's own ckSOL account. public shared ({ caller }) func solDepositAddress() : async Text { if (caller.isAnonymous()) { Runtime.trap("Authentication required") }; await minter.get_deposit_address({ owner = ?caller; subaccount = null }) }; // After the user sent SOL: pay the cycles and queue the sweep. ckSOL is minted to the CALLER's account. // Spends ~47B cycles of this canister per accepted deposit: rate-limit per user in production. public shared ({ caller }) func notifySolDeposit() : async { #Ok : Nat64; #Err : DepositSolError } { if (caller.isAnonymous()) { Runtime.trap("Authentication required") }; await (with cycles = DEPOSIT_SOL_CYCLES) minter.deposit_sol({ owner = ?caller; subaccount = null }) }; }; ``` ## Verify It Works ```bash # Fees, minimums, required cycles icp canister call lh22c-kyaaa-aaaar-qb5nq-cai get_minter_info '()' -n ic --query # Deposit address for a principal (update call; any caller) icp canister call lh22c-kyaaa-aaaar-qb5nq-cai get_deposit_address \ '(record { owner = opt principal "YOUR-PRINCIPAL"; subaccount = null })' -n ic # Expected: ("7N9yLidkZCEvb1uWUQqRPD53KDUVXoghTF9gxJFBChDS") — a base58 Solana address # After sending SOL: notify through a cycles-holding proxy canister you control icp canister call lh22c-kyaaa-aaaar-qb5nq-cai deposit_sol \ '(record { owner = opt principal "YOUR-PRINCIPAL"; subaccount = null })' \ -n ic --proxy --cycles 1000000000000 # Expected: (variant { Ok = 42 : nat64 }) icp canister call lh22c-kyaaa-aaaar-qb5nq-cai deposit_sol_status '(42 : nat64)' -n ic --query # Expected eventually: (variant { Minted = record { block_index = …; minted_amount = … } }) # Withdraw 0.01 SOL icp canister call ls5lp-lqaaa-aaaar-qb5oa-cai icrc2_approve \ '(record { spender = record { owner = principal "lh22c-kyaaa-aaaar-qb5nq-cai"; subaccount = null }; amount = 10_000_000 : nat })' -n ic icp canister call lh22c-kyaaa-aaaar-qb5nq-cai withdraw_sol \ '(record { address = ""; amount = 10_000_000 : nat64; from_subaccount = null })' -n ic icp canister call lh22c-kyaaa-aaaar-qb5nq-cai withdraw_sol_status '(record { block_index = : nat64 })' -n ic ``` --- ## Cloud Engine Canisters --- name: cloud-engine-canisters description: "Rules for canister code on a cloud engine (CloudEngine subnet, e.g. OpenCloud). Engine canisters hold 0 cycles: drop `(with cycles = …)` clauses (IC0504). Cross-subnet calls must be bounded-wait and cycle-free (`(with timeout = N)`, `Call::bounded_wait`) or rejected: 'Unbounded-wait calls and calls with cycles are not allowed to CloudEngine subnets'. HTTPS outcalls use the ordinary wrapper and are free; never via the proxy ('Replicas had different responses'). XRC, threshold ECDSA/Schnorr, vetKD, the Bitcoin API and EVM/SOL RPC go via the engine's proxy canister: ask the user for its id first. Hand-encode arguments: chain-key helpers attach cycles. Derived keys belong to the proxy. AI inference goes through the engine-operator's `inference_request` (it holds the key; never call the provider yourself; set `max_tokens`, outcalls have 30 s). Use when planning, writing or debugging engine canister code, signing or deriving keys, or on these errors. Do NOT use for deploying a proxy (deploy-to-cloud-engine)." license: Apache-2.0 compatibility: "A cloud engine (CloudEngine subnet) to run on, plus a deployed proxy canister for any chain-key or XRC call; Motoko examples need moc >= 0.14.2 (parenthetical `(with cycles = …)` / `(with timeout = N)` call attributes) and `to_candid` / `from_candid`, Rust examples need ic-cdk >= 0.18 (bounded-wait `Call` API); Rust outcalls use whichever wrapper the crate line provides (`ic-cdk-management-canister` 0.2 needs ic-cdk >= 0.20.3; `ic_cdk::management_canister` only up to 0.19)" metadata: title: Cloud Engine Canisters category: CloudEngine --- # Cloud Engine Canisters ## What This Is A **cloud engine** is a user-owned slice of Internet Computer capacity, administered from a web console (see the `deploy-to-cloud-engine` skill for getting code onto one). Engines run on a dedicated **`CloudEngine` subnet type** with a **free cycles cost schedule**: nothing an engine canister does is metered in cycles — execution, storage, messaging, and HTTPS outcalls all cost zero — and engine canisters hold a **0 cycles balance by design**. That model comes with protocol-enforced call rules. Code that works on a normal Application subnet can fail on an engine, and the failures look like cycles or consensus problems rather than what they are: code written for the wrong subnet type. The rules: | Rule | On a cloud engine | |------|-------------------| | 1 | **Never attach cycles** to any call — remove `(with cycles = …)` and cycle-attaching wrappers | | 2 | **Cross-subnet calls must be bounded-wait** — `(with timeout = N)` in Motoko, `Call::bounded_wait` in Rust | | 3 | **HTTPS outcalls: ordinary code, zero cost** — keep the standard wrapper, transform on your own canister, never through the proxy | | 4 | **Cycle-bearing cross-subnet targets** (XRC, threshold signing, vetKD, the Bitcoin API, EVM/SOL RPC) go **through the console proxy canister**. Ask the user for its id before writing that code | | 5 | **AI inference goes through the engine operator** — call its `inference_request` with no provider or model; it adds the key of the provider that is on. Never hold a key, never call a provider yourself | ## Rule 1 — Never attach a cycles amount you computed yourself Engine canisters hold 0 cycles and there is nothing to pay for: under the engine's free cost schedule every fee an Application-subnet canister would pay (execution, message transmission, HTTPS outcalls, threshold signing, vetKD, storage) is charged as zero. - **Inter-canister calls you write: no cycles clause at all.** There is nothing to buy — every fee on an engine is charged as zero — so a cycles attachment is never *needed*, independently of whether the protocol tolerates it. Write `await service.method(args)`, never `await (with cycles = 1_000_000) service.method(args)`. Verified on a live engine canister (`Cycles: 0`): **any non-zero amount fails** with ``` Canister is out of cycles, error code Some("IC0504") ``` Do not "fix" this by zeroing the amount. The platform team's guidance is simply **not to mention cycles at all** on an engine call, and a `cycles = 0` left in place is noise that breaks again the moment the amount becomes non-zero (a computed fee, a copied constant). If you see `IC0504` from an engine canister, some call is attaching a non-zero amount. - **Rust:** the same rule — never call `.with_cycles(…)` on a `Call` builder. (The platform team states the Motoko rule as "just don't mention cycles"; omitting `.with_cycles` is its Rust equivalent.) - **Management-canister calls keep their standard wrapper.** `Call.httpRequest` (Motoko, `mo:ic`) and the Rust outcall wrapper for your crate line (Rule 3) ask the `ic0.cost_*` system API for the fee, and that API is cost-schedule aware: for an outcall it prices against **your own** subnet's cost schedule, which is free on an engine, so it returns **0**, the wrapper attaches nothing, and the same source stays portable to an Application subnet. What breaks is substituting a hardcoded or hand-computed fee — never take a number from the `https-outcalls` cost tables and attach it on an engine. - **Which subnet's schedule is consulted is the whole distinction.** The chain-key cost APIs (`ic0.cost_sign_with_ecdsa` and friends) price against the subnet that **holds the key**, not yours — that subnet charges normally, so they return a non-zero fee even when called from an engine, and the wrapper then attaches it. That is why a helper that signs cannot work here while the same crate's outcall builder can (Rules 3 and 4). - The one exception: cycles that a **cross-subnet target** charges are placed *inside* `ProxyArgs.cycles` of the console proxy (Rule 4), never attached to a call your canister sends. ## Rule 2 — Cross-subnet calls must be bounded-wait The protocol rejects any cross-subnet (XNet) request **from or to** a CloudEngine subnet that is unbounded-wait (guaranteed-response) or carries cycles. The caller gets a reject with exactly this text: ``` Unbounded-wait calls and calls with cycles are not allowed to CloudEngine subnets ``` Verified live from an engine canister: a plain `await` to a canister on another subnet comes back as that exact `#system_fatal` reject, while the same call with `(with timeout = 30)` and no cycles clause succeeds. Make every cross-subnet call bounded-wait and cycle-free: ```motoko // Motoko: `timeout : Nat32` is in seconds let result = await (with timeout = 30) service.method(args); ``` ```rust // Rust, ic-cdk >= 0.18 — bounded_wait defaults to a 300-second timeout (the IC maximum) let reply: T = Call::bounded_wait(canister_id, "method") .with_arg(arg) .await? // Err on reject / SYS_UNKNOWN — handle, do not unwrap .candid()?; // decode the reply ``` - **Same-subnet calls are exempt**: canisters on the same engine may call each other unbounded-wait. Bounded-wait is still the better default — an unbounded-wait call to an unresponsive callee blocks the caller's upgrades indefinitely (see the `multi-canister` skill). - The restriction applies in **both directions**: a canister on a normal subnet calling *into* an engine canister must also use a bounded-wait, cycle-free call. - A bounded-wait call can complete with `SYS_UNKNOWN` (outcome unknown). Handle it — the `multi-canister` skill covers the patterns. ## Rule 3 — HTTPS outcalls: ordinary code, zero cost HTTPS outcalls execute on the engine's own subnet, and the cost API reports them as free there, so the standard wrapper works unchanged — there is no engine-specific outcall code: ```motoko import IC "mo:ic/Types"; import Call "mo:ic/Call"; // Build `request : IC.HttpRequestArgs` exactly as in the https-outcalls skill, // with the transform query on THIS canister. Call.httpRequest asks the cost API, // which returns 0 on an engine, so nothing is attached. let response = await Call.httpRequest(request); ``` - **Keep the wrapper; never swap in a hardcoded fee** (Rule 1). Letting the wrapper price the call is how outcalls are written in the Motoko engine apps running today. - **In Rust, use the wrapper your crate line provides** — `HttpRequest::new(url)…send()` from `ic-cdk-management-canister` 0.2, the free `ic_cdk_management_canister::http_request` in 0.1, or `ic_cdk::management_canister::http_request` on ic-cdk 0.19 (that module was **removed in ic-cdk 0.20**). All three behave identically here: each asks `ic0.cost_*`, which prices against your own subnet and so returns 0 on an engine, and each attaches that 0. Write for the line the project is actually on, and never bump crate versions to "fix" an engine outcall — there is nothing to fix. `https-outcalls` covers the differences between the three. - **`ic-cdk-management-canister`'s outcall builders are the supported path here** — only its *chain-key* helpers are unusable on an engine (Rule 4). The crate is not off-limits; the target subnet is what decides. - **Pricing version 2 needs no tuning on an engine.** The 0.2 builder always prices version 2 ("pay-as-you-go"), where the cycles attached double as each node's spending budget — so on a paying subnet an under-narrowed `with_expected_*` lets a call fail partway, after the remote server was contacted. On an engine that cannot happen: the free cost schedule never charges, so the budget never narrows anything — the round-trip timeout and the transform-instruction limit sit at the protocol maximum, and `InsufficientCycles` is never raised. Treat the `with_expected_*` setters as no-ops here: set them for portability if you like, but never tune them to fix an engine outcall, and never read an engine outcall failure as a budget problem. What still applies is your **own** `max_response_bytes` — it bounds the response on an engine exactly as anywhere else, so an oversized reply is a real failure cause and the one outcall limit worth checking here. - **Either pricing version works on an engine, so the version is not something to manage here.** Version 2 is accepted only where the replica has pay-as-you-go enabled; where it does not, a requested version 2 is **silently filtered back to version 1** with no error. That is a funding mismatch on a paying subnet, but harmless on an engine, because an outcall is charged zero under *both* versions. Do not add engine-specific version handling. - Everything else about outcalls is unchanged — transform function on your own canister, `max_response_bytes`, idempotency. Engines support the **full** outcall feature set per the platform team, replicated or not, so `is_replicated = ?false` is available for non-idempotent or rate-limited APIs — and for bulk workloads, where a replicated call multiplies every request by the replica count. Load the `https-outcalls` skill for those. - **Never route HTTPS outcalls through the console proxy canister.** The platform team is explicit: all HTTP outcalls should be direct, and the proxy exists only for mainnet services that require cycles. The IC requires the transform function to live on the canister that issues `http_request` — behind the proxy that is the proxy itself, and the proxy exposes no transform method (verified against its live interface, and the team confirms none is planned). Untransformed responses differ across replicas for most real APIs, and the call fails with: ``` SYS_TRANSIENT: No consensus could be reached. Replicas had different responses ``` A proxied outcall also **pays**. The proxy sits on a normal Application subnet, so it is charged the real outcall fee out of the balance you funded, while the same call issued from your engine canister is charged nothing. At migration scale — thousands of calls — that balance drains and every call starts failing with `ProxyError::InsufficientCycles`. That is a symptom of proxying outcalls, not of an under-funded engine. Both failures have the same fix: issue the outcall directly from your canister (free, works). Neither is fixed by retries or by topping the proxy up. ## Rule 4 — Cross-subnet cycle-bearing calls via the console proxy Two separate facts land in the same place. The Rule 2 restriction means an engine canister **cannot** send a cross-subnet message carrying cycles — and, per the platform team, **cloud engines do not provide threshold signing at all**, so those facilities have to be reached on mainnet. Either way the call cannot be made directly: - **threshold ECDSA / Schnorr** signing (`sign_with_ecdsa`, `sign_with_schnorr`) and their public-key methods, and **vetKD** (`vetkd_derive_key`, `vetkd_public_key`) — not available on an engine; use mainnet's via the proxy, - the **exchange-rate canister** (XRC) — a mainnet canister that charges cycles, - the **Bitcoin API** (the management canister's `bitcoin_*` methods) and the **EVM RPC** and **SOL RPC** canisters, which charge cycles per call. A console proxy relays nothing else for your canisters (see "What a console proxy relays" below). This is the proxy's entire purpose: reaching mainnet services that require cycles. It is **not** for HTTPS outcalls (Rule 3). The workaround is the **console proxy canister**: deployed on a normal Application subnet and kept funded out of the engine's balance. Your engine canister makes a cheap, cycle-less, bounded-wait call to the proxy, which re-issues it locally **with the cycles attached** and relays the raw reply back. Same-subnet or cycle-less calls do **not** need it — and neither do HTTPS outcalls (Rule 3). ### Before writing the code: ask the user for the proxy Neither your canister code nor you can create the console proxy: the engine's **owner** deploys it from the console, and the app only receives its canister id as configuration. So as soon as a task needs any target in the list above (a feature request, a plan, a port of existing code), raise it with the user **before** writing that code, not after the first call fails on the engine: 1. Say the app needs the engine's proxy canister, and why, in one sentence. 2. Ask whether the engine already has one: - **It does**: ask for its canister id (engine → **Integrations** → **Proxy canisters**). If there are several and the app signs or derives keys, ask which one the app is to use: every derived key follows that choice (see "Threshold keys through the proxy"). Never pick one for them. - **It does not**: ask the owner to deploy one: engine → **Integrations** → **Proxy canisters** → **Deploy a proxy**, then confirm. There is no card and no amount to choose: the proxy is paid for out of the engine's balance and tops itself up from it when it runs low. Then ask for the id it shows. For example: "This app signs through your engine's proxy canister. If the engine has one, send me its id (engine → Integrations → Proxy canisters). If not, the engine owner can deploy one there with Deploy a proxy: it is paid from the engine's balance, no card. Then send me its id." 3. Keep working meanwhile: read the id from a canister environment variable (`PROXY_CANISTER_ID`, see `deploy-to-cloud-engine`), never a literal in source. The id is needed to deploy, not to write the code. 4. When the id arrives, check it is a console proxy. This query is free and needs no project: ```bash icp canister call get_allowed_subnet '()' -n ic --query ``` `opt principal "…"` (the engine's subnet) is a console proxy, open to every canister on that subnet. `null`, or an error that the canister has no such method, means it is not one (a self-deployed proxy, or not a proxy at all): ask again. Do not judge by `get_allowed_ranges`: a console proxy answers it with an empty list. `get_funding` (same form) also shows its `balance`, and `funding = opt record { engine_canister = …; … }` because the engine tops it up. Never invent an id, reuse one from another engine or project, or deploy a self-deployed proxy as a stand-in while you wait: it rejects your engine canisters and derives different keys (see the table below). ### Getting a proxy Two different canisters can play the role, and they are **not** interchangeable: | | **Console proxy** (the engine's) | **Self-deployed proxy** (`icp new … --subfolder proxy`) | |---|---|---| | Deployed by | The engine's **owner**, from the console | You, with `icp` | | Who may call it | Every canister on the engine's **subnet** (checked with the NNS registry), plus its controller | **Controllers only** | | Your engine canisters can call it | Yes, with no extra setup | Only if you add each of them as a controller | | What it relays for them | Only the targets listed above | Anything | | Threshold-key derivation | **Caller-isolated** (see below) | No isolation: raw pass-through | | Funded with | The engine's balance: it tops itself up when low, no card | Cycles you already hold (`icp cycles mint`) | For engine canisters, **use the console proxy**. A self-deployed proxy is the right tool for calls *you* make from the CLI (`icp canister call --proxy`, `icp deploy --proxy`), and the console proxy cannot serve that purpose, because it rejects ingress calls from any principal that is not one of its controllers, which your CLI identity is not. Deploying and funding either one is not a canister-code task. It is covered in the **`deploy-to-cloud-engine`** skill; from here you need only the resulting **proxy canister id**. Take it from the user or from the app's configuration, never hardcode a guess, and read the derivation warning below before assuming one proxy id can be swapped for another. ### Call through the proxy from your canister Instead of calling the target canister directly, call the proxy's `proxy` method with the target id, method name, candid-encoded argument bytes, and the cycles to attach. Its candid interface: ```candid type ProxyArgs = record { canister_id : principal; method : text; args : blob; cycles : nat }; type ProxySucceed = record { result : blob }; type ProxyError = variant { InsufficientCycles : record { available : nat; required : nat }; CallFailed : record { reason : text }; UnauthorizedUser; }; type ProxyResult = variant { Ok : ProxySucceed; Err : ProxyError }; service : { proxy : (ProxyArgs) -> (ProxyResult); get_allowed_subnet : () -> (opt principal) query; }; ``` - `args` is the **candid-encoded argument of the _target_ method** (you encode it); `result` is the target's **raw reply bytes** (you decode it). - `cycles` is what the proxy attaches to the relayed call — size it to what the target charges (e.g. the XRC or signing fee). The platform team confirms the **caller** chooses how much the proxy attaches, and the proxy receives `args` as an **opaque blob**, so it cannot size the amount for you: a constant you pass is exactly what it will require, and the `required` field of `InsufficientCycles` echoes your own number back rather than reporting a proxy-side reservation. Do **not** attach cycles to the outer `proxy` call itself; the engine subnet forbids that and it is unnecessary. - Handle `ProxyError`: `InsufficientCycles` means the proxy's balance is too low (a console proxy tops itself up from the engine's balance, so a lasting one means that balance is short: pitfall 8), `UnauthorizedUser` means the caller is not on the engine's subnet, `CallFailed` carries the downstream reject reason, or says the console proxy does not relay that target (see "What a console proxy relays"), or that it could not yet check the caller's subnet with the NNS registry (`could not verify which subnet the caller … is on (…); retry`). That last one comes only while the proxy looks a caller up (typically a canister's first call after the proxy was installed or upgraded), and nothing was relayed: just retry. - **Over-attaching is safe; under-attaching is not.** The callee refunds what it does not consume, and the refund goes back to the **proxy** (the proxy is the caller on that leg), so a generous `cycles` figure costs nothing and survives a fee increase. `available` in `InsufficientCycles` is the proxy's *liquid* balance (its freezing reserve is already excluded), so a proxy can report `InsufficientCycles` while still showing a balance in the console. - **A `CallFailed` is not proof the call did not happen.** The proxy relays with a bounded-wait call, so a downstream `SYS_UNKNOWN` reaches you as `CallFailed` with that reject code in `reason`. The target may have executed and the cycles may already be spent. Treat it as "outcome unknown", not "failed": the `multi-canister` skill covers the patterns. Motoko sketch (Rust is analogous with `candid::encode_one` / `decode_one`): ```motoko // `proxy` is an actor typed to the candid interface above. let arg = to_candid (request); // encode the TARGET method's argument let res = await (with timeout = 30) proxy.proxy({ canister_id = xrcPrincipal; method = "get_exchange_rate"; args = arg; cycles = 1_000_000_000; // the XRC fee the proxy forwards }); switch (res) { case (#Ok { result }) { let ?reply = from_candid (result) else return; /* … */ }; case (#Err e) { /* InsufficientCycles | CallFailed | UnauthorizedUser */ }; }; ``` ### What a console proxy relays A console proxy pays out of the engine's balance, so for the engine's canisters it relays only what a proxy is for: - the management canister (`aaaaa-aa`): `sign_with_ecdsa`, `ecdsa_public_key`, `sign_with_schnorr`, `schnorr_public_key`, `vetkd_derive_key`, `vetkd_public_key`, `http_request`, and the `bitcoin_*` methods (`bitcoin_get_balance`, `bitcoin_get_utxos`, `bitcoin_send_transaction`, `bitcoin_get_current_fee_percentiles`, `bitcoin_get_block_headers`); - any method of these mainnet canisters: the exchange-rate canister `uf6dk-hyaaa-aaaaq-qaaaq-cai`, EVM RPC `7hfb6-caaaa-aaaar-qadga-cai`, SOL RPC `tghme-zyaaa-aaaar-qarca-cai`, Bitcoin mainnet `ghsi2-tqaaa-aaaan-aaaca-cai` and testnet `g4xu7-jiaaa-aaaan-aaaaq-cai`, and Dogecoin `gordg-fyaaa-aaaan-aaadq-cai`. Anything else (another canister, `deposit_cycles`, `create_canister`, the cycles ledger) comes back as `CallFailed` with a reason starting `a proxy funded by its engine relays only to …`. Topping up does not change that. `http_request` is on the list, but Rule 3 still applies: make outcalls from your own canister. If the app genuinely has to pay a canister outside this list, that takes a self-deployed proxy with each calling canister added as a controller (see `deploy-to-cloud-engine`), funded with cycles you hold. ### Threshold keys through the proxy (read this before deriving keys) Threshold ECDSA, Schnorr, and vetKD are the proxy's main job on an engine, and the one place where getting the call *wrong* costs more than an error message: a key you cannot reproduce is a Bitcoin or Ethereum address whose funds you cannot move. **The chain-key helpers do not work here.** `ic-vetkeys`, `ic-cdk-management-canister`'s chain-key functions (`sign_with_ecdsa`, `sign_with_schnorr`, `vetkd_derive_key` and their public-key siblings), and Motoko's `mo:ic-vetkeys/ManagementCanister` all call `aaaaa-aa` directly and attach the fee for you. Because the chain-key cost API prices against the key-holding subnet, that fee is non-zero even on an engine, and the helper issues an unbounded-wait call carrying it — a cross-subnet, cycle-bearing call, rejected twice over (Rules 1 and 2). Their convenience is exactly what you must give up: encode the management-canister argument yourself and send it through the proxy. The `vetkeys` skill's code is written for a normal subnet and needs this rewrite before it will run on an engine. **This is scoped to the chain-key functions, not to the crates.** `ic-cdk-management-canister` also carries the HTTPS-outcall builders, and those are the supported way to make an outcall from an engine canister (Rule 3): they target your own subnet, price at 0, and must **not** be routed through the proxy. Reading "the helpers don't work on an engine" as "hand-encode outcalls through the proxy too" produces exactly the consensus and funding failures in pitfall 4. Split the crate by target subnet: local outcall ⇒ ordinary builder; remote chain-key ⇒ proxy. **What the proxy rewrites.** For the six key methods (`sign_with_ecdsa`, `ecdsa_public_key`, `sign_with_schnorr`, `schnorr_public_key`, `vetkd_derive_key`, `vetkd_public_key`) the console proxy decodes your argument, **isolates the derivation to you**, and re-encodes it: - ECDSA / Schnorr: your calling canister's principal is inserted as the **first element of `derivation_path`**. - vetKD: your principal is prepended to `context`, **length-tagged**: one byte holding the principal's length, then the principal bytes, then your context. - On the three `*_public_key` methods, `canister_id` is additionally forced to `None`. The principal comes from `msg_caller()`, so it cannot be forged and one engine canister can never reach another's keys. (Verified: `cargo test -p proxy-canister --lib`, 10/10; `ecdsa_sign_prepends_caller_and_preserves_the_rest`, `vetkd_prefixes_caller_into_context_length_tagged`, `distinct_callers_get_distinct_derivations`.) **Fees.** `ecdsa_public_key`, `schnorr_public_key`, and `vetkd_public_key` are **free**: pass `cycles = 0`. The paying methods are charged by the subnet that holds the key, not yours: | Key name | `sign_with_ecdsa` / `sign_with_schnorr` / `vetkd_derive_key` | |---|---| | `key_1` (production) | 26_153_846_153 | | `test_key_1` (testing) | 10_000_000_000 | Round up rather than passing the exact figure: the unused remainder is refunded to the proxy. **Worked example: ECDSA, Motoko.** Declare the management-canister types yourself; field names and variant tags must match the candid interface exactly, because the proxy decodes and re-encodes the blob; a missing or misnamed field, or an unknown variant tag, fails the decode (surfacing as `CallFailed`, not a mis-derived key). A field the proxy does not model is not caught: candid's record subtyping skips it on decode and the re-encode drops it. ```motoko type EcdsaKeyId = { curve : { #secp256k1 }; name : Text }; type EcdsaPublicKeyArgs = { canister_id : ?Principal; derivation_path : [Blob]; key_id : EcdsaKeyId }; type EcdsaPublicKeyReply = { public_key : Blob; chain_code : Blob }; type SignWithEcdsaArgs = { message_hash : Blob; derivation_path : [Blob]; key_id : EcdsaKeyId }; type SignWithEcdsaReply = { signature : Blob }; let mgmt = Principal.fromText("aaaaa-aa"); let keyId : EcdsaKeyId = { curve = #secp256k1; name = "key_1" }; let signFee = 30_000_000_000; // >= 26_153_846_153; the excess comes back // One helper for every proxied management call. func viaProxy(method : Text, arg : Blob, cycles : Nat) : async Blob { let res = await (with timeout = 30) proxy.proxy({ canister_id = mgmt; // the TARGET, not the proxy method = method; args = arg; cycles = cycles; // 0 for the *_public_key methods }); switch (res) { case (#Ok { result }) { result }; case (#Err e) { Runtime.trap("proxy: " # debug_show e) }; // real code: return an error }; }; // Address: free, no cycles. let pkArg = to_candid ({ canister_id = null; // forced to null by the proxy anyway derivation_path = [Text.encodeUtf8("user-42")]; // your own path; the proxy prefixes itself key_id = keyId; } : EcdsaPublicKeyArgs); let ?pk : ?EcdsaPublicKeyReply = from_candid (await viaProxy("ecdsa_public_key", pkArg, 0)) else Runtime.trap("decode ecdsa_public_key"); // Signature: pays the fee. `message_hash` must be exactly 32 bytes. let sigArg = to_candid ({ message_hash = messageHash; derivation_path = [Text.encodeUtf8("user-42")]; // the SAME path as above key_id = keyId; } : SignWithEcdsaArgs); let ?sig : ?SignWithEcdsaReply = from_candid (await viaProxy("sign_with_ecdsa", sigArg, signFee)) else Runtime.trap("decode sign_with_ecdsa"); ``` Note that `sign_with_ecdsa` has **no** `canister_id` field: the key it signs with is always the caller's, and behind the proxy the caller is the proxy. That is precisely why the public key you publish and the signature you produce must both come through the **same** proxy. **Worked example: vetKD, Motoko.** Same shape, different types. `vetkd_public_key` is free; `vetkd_derive_key` pays. ```motoko type VetkdKeyId = { curve : { #bls12_381_g2 }; name : Text }; type VetkdPublicKeyArgs = { canister_id : ?Principal; context : Blob; key_id : VetkdKeyId }; type VetkdPublicKeyReply = { public_key : Blob }; type VetkdDeriveKeyArgs = { input : Blob; context : Blob; transport_public_key : Blob; key_id : VetkdKeyId }; type VetkdDeriveKeyReply = { encrypted_key : Blob }; let vetKeyId : VetkdKeyId = { curve = #bls12_381_g2; name = "key_1" }; let dkArg = to_candid ({ input = Text.encodeUtf8("note-7"); context = Text.encodeUtf8("my-app"); // the proxy length-tags its prefix onto this transport_public_key = transportPk; key_id = vetKeyId; } : VetkdDeriveKeyArgs); let ?dk : ?VetkdDeriveKeyReply = from_candid (await viaProxy("vetkd_derive_key", dkArg, 30_000_000_000)) else Runtime.trap("decode vetkd_derive_key"); ``` **Rust** is the same flow with `candid::encode_one` / `decode_one` and a bounded-wait call, see the shape in the `Call::bounded_wait(proxy_id, "proxy")` example under Rule 2. **The derived key belongs to the proxy, not to your app.** The management canister derives from *its* caller, which is the proxy, so the key you get depends on **which proxy canister id you went through**: - Point the app at a different proxy (a second one from the console's "Deploy another proxy", or a self-deployed one) and every address changes. The old address is not recoverable from the new proxy. - **Deleting a proxy destroys access to its keys.** The console's delete button sends the unspent cycles back to the engine's balance; it cannot give back the derivation. Any Bitcoin or Ethereum funds held at an address derived through that proxy become permanently unspendable. Treat the proxy id of a signing app as permanent infrastructure, and never delete a proxy to "save cycles" without first moving every asset off the addresses derived through it. - A self-deployed upstream proxy does **no** isolation at all (no principal prefix, no forced `canister_id = None`), so its keys differ again from the console proxy's: the two are not substitutes even before the id changes. - Anything reproducing a derivation off-chain (deriving the same public key in a frontend, say) must replicate the prefix the proxy injects, including vetKD's length tag. ## Rule 5 — Inference through the engine operator Every engine has an **engine-operator** canister, and it is the engine's route to AI inference. The operator holds a list of providers with their keys: today `iig` and `caffeine`. The engine's owner or an admin turns one on in the console (engine → **Integrations** → **Inference**) and can switch it at any time. A canister on the engine sends an OpenAI request to the operator's `inference_request`, and the operator adds the key of the provider that is on and makes the outcall. - **No provider key in the canister** (source, init args, environment variables) and **no outcall to a provider's host.** Such a canister spends credit from code anyone can read and ignores the owner's switch. - **Leave `provider` and `model` out.** The provider that is on answers with its own default model, so the code keeps working when the owner switches. A named provider that is off answers `BadRequest`, and model ids differ per provider. - **No cycles, and a plain `await` is allowed** (same subnet, Rule 2). A bounded wait needs a timeout above the outcall's 30 second deadline (`(with timeout = 60)`, or `Call::bounded_wait`'s 300 second default): a shorter one returns `SYS_UNKNOWN` while the operator may still spend the credit. ### Finding the operator The operator's id is configuration, not a literal: read it from a canister environment variable (`OPERATOR_CANISTER_ID`, see `deploy-to-cloud-engine` M6) or an init argument. The user finds it on the engine's **Canisters** page in the console, and the ICP MCP route reads it as `engine_operator_id` from the engine registry (`deploy-to-cloud-engine` M1). Ask for it as soon as the app needs inference. Check that a provider is on with the public query `listInferenceProviders`: ```bash icp canister call listInferenceProviders '()' -n ic --query ``` ```candid (record { providers = opt vec { record { id = opt "iig"; name = opt "IIG"; base_url = opt "https:///v1"; enabled = opt true; ready = opt true }; record { id = opt "caffeine"; name = opt "Caffeine"; base_url = opt "https://inference.caffeine.ai/v1"; enabled = opt false; ready = opt true }; } }) ``` At most one provider is `enabled`, and `ready` means the operator holds its key. With none on, or with a named one off or not ready, every call answers `BadRequest`: the owner fixes that in the console, not in code. ### The call ```candid type HttpHeader = record { name : text; value : text }; type InferenceRequestArgs = record { provider : opt text; // null: the provider that is on method : opt variant { get; post }; // defaults to post with a body, get without path : opt text; // required: "/chat/completions", "/embeddings", "/models" headers : opt vec HttpHeader; // the operator sets Authorization itself body : opt blob; // a JSON body with no "model" gets the provider's default max_response_bytes : opt nat64; }; type InferenceResponse = record { status : opt nat; headers : opt vec HttpHeader; body : opt blob; provider : opt text }; type Error = variant { Unauthorized; NotFound; BadRequest : text; Internal : text }; service : { inference_request : (InferenceRequestArgs) -> (variant { ok : InferenceResponse; err : Error }); }; ``` ```motoko type HttpHeader = { name : Text; value : Text }; type InferenceRequestArgs = { provider : ?Text; method : ?{ #get; #post }; path : ?Text; headers : ?[HttpHeader]; body : ?Blob; max_response_bytes : ?Nat64; }; type InferenceResponse = { status : ?Nat; headers : ?[HttpHeader]; body : ?Blob; provider : ?Text }; type OperatorError = { #Unauthorized; #NotFound; #BadRequest : Text; #Internal : Text }; type Operator = actor { inference_request : InferenceRequestArgs -> async { #ok : InferenceResponse; #err : OperatorError }; }; let operator : Operator = actor (Principal.toText(operatorId)); // from configuration let request = "{\"max_tokens\":350,\"stream\":false,\"messages\":[{\"role\":\"user\",\"content\":\"What is a canister?\"}]}"; let res = await operator.inference_request({ provider = null; method = null; path = ?"/chat/completions"; headers = ?[{ name = "content-type"; value = "application/json" }]; body = ?Text.encodeUtf8(request); max_response_bytes = ?200_000; }); switch (res) { case (#ok { status = ?200; body = ?bytes }) { /* OpenAI chat completion: choices[0].message.content */ }; case (#ok { status }) { /* the provider's own status: 401 key refused, 402 no credit */ }; case (#err (#BadRequest msg)) { /* no provider on, the named one off or not ready, or a bad path */ }; case (#err (#Unauthorized)) { /* the caller is not a canister on this engine */ }; case (#err (#Internal msg)) { /* the outcall failed, see "The deadline" */ }; case (#err (#NotFound)) { /* a named provider the engine does not list */ }; }; ``` In Rust, make the same call with `Call::unbounded_wait(operator, "inference_request")` and the types above as `CandidType` structs (`#[serde(rename = "ok")]` / `"err"` on the result variant, `Option` for `status`), with the body built by `serde_json`. - **Only canisters on the engine may call it.** An ingress call from the CLI is `Unauthorized`; to try it, deploy a small caller canister on the engine. - **The answer is the provider's HTTP response as it is**, and `provider` names the one that answered. A 401 (key refused) or a 402 (no credit) is the owner's to fix, not yours: tell the user. - **Keep `stream` false.** An outcall returns one whole response. ### The deadline An outcall has a **30 second deadline**. A completion that is still generating when it passes fails as ``` err = Internal("the outcall to failed: Canister http request timed out") ``` and the provider may bill the reply anyway. Bound every completion: `max_tokens` (350 took about 5 seconds end to end through Caffeine), short replies, a small conversation. A `GET /models` answers in seconds and spends no credit: it shows that the route works, not why a completion timed out. ### Who may call your canister The operator checks only that the caller is on the engine, so **your** canister decides who spends the engine's credit. A public `chat` method is a faucet, and a sign-in is not an authorization: anyone can make a keypair and call as a non-anonymous principal. Do one of these, and tell the user which: - **Restrict the method** to the canister's controllers (`is_controller`) or an allow-list the owner keeps. - **Meter an open service:** a quota per principal and a total cap, both in stable state, besides per-call bounds (`max_tokens`, message size). ## Common Pitfalls 1. **Attaching a cycles amount to a call you write.** A `(with cycles = N)` clause on an inter-canister call from an engine canister is never needed, and any non-zero `N` fails with `IC0504` / `is out of cycles` (verified live). Remove the clause entirely rather than setting `cycles = 0`: a zero is accepted, so it hides the mistake instead of fixing the habit. Nothing an engine canister does needs cycles: outcall, signing, and messaging fees are all zero under the engine's free cost schedule. 2. **Unbounded-wait cross-subnet calls.** A plain `await service.method(args)` to a canister on another subnet is unbounded-wait and is rejected with "Unbounded-wait calls and calls with cycles are not allowed to CloudEngine subnets". Use `(with timeout = N)` in Motoko or `Call::bounded_wait` in Rust — and handle `SYS_UNKNOWN`. Same-subnet (engine-local) calls are exempt. 3. **Rewriting outcall code for an engine — or hardcoding its fee.** Outcalls need no engine-specific form: keep `Call.httpRequest` (Motoko) or, in Rust, whichever wrapper the project's crate line provides (`HttpRequest::new(url)…send()` on `ic-cdk-management-canister` 0.2; `ic_cdk::management_canister::http_request` only up to ic-cdk 0.19, since 0.20 removed that module). The `ic0.cost_*` API they consult prices against your own subnet and returns 0 on an engine. The mistake is replacing that call with a hand-computed fee from an Application-subnet cost table, which attaches a non-zero amount against a 0 balance. 4. **Routing HTTPS outcalls through the console proxy.** Two different failures, one cause. Consensus: `SYS_TRANSIENT: No consensus could be reached. Replicas had different responses`, because the transform must live on the calling canister — behind the proxy that is the proxy itself, and it exposes none (nor is one planned). Cost: the proxy is on a normal Application subnet, so it pays the real outcall fee out of its balance, which the engine's balance refills, and a bulk workload drains it into `ProxyError::InsufficientCycles`. Issue outcalls directly from your canister instead: on an engine they are free and unmetered, so no budget exists to exhaust. 5. **Topping up an engine canister with cycles.** Engine canisters hold 0 cycles by design; you cannot and need not send cycles to them. A "0 cycles" reading from an engine canister is normal, not an emergency — do not add top-up logic or cycles-balance alarms ported from Application-subnet apps. 6. **Calling the XRC / threshold signing / vetKD directly from an engine canister.** Cloud engines do not provide threshold signing at all (platform team), so `sign_with_ecdsa` / `sign_with_schnorr` / vetKD must be reached on mainnet — and a cross-subnet, cycle-bearing call is exactly what a CloudEngine-subnet canister cannot send. Route them through the funded console proxy (Rule 4). Plain same-subnet or cycle-less calls do not need the proxy. 7. **Attaching cycles to the outer `proxy` call.** The engine subnet forbids cycle-bearing cross-subnet messages — that is the whole reason for the proxy. Put the cycles inside `ProxyArgs.cycles` (the proxy attaches them locally); never `with cycles` on the call to `proxy` itself. 8. **Topping up the proxy without first asking what it was relaying.** On `ProxyError::InsufficientCycles`, check the call type before treating it as a funding problem. **An HTTPS outcall does not belong on the proxy at all** (Rule 3, pitfall 4): move it onto your own canister, where it is free, rather than buying budget for work that should cost nothing; raising the balance only delays the same stall. A drained balance is a genuine funding problem only for the proxy's real jobs (XRC, threshold signing, vetKD, the Bitcoin API, EVM/SOL RPC). A console proxy tops itself up out of the engine's balance every few minutes, within an hourly cap, so a lasting `InsufficientCycles` means the engine's balance has nothing free to send (the owner adds funds to the engine) or the app spends faster than the cap refills. There is no top-up button for it. See `deploy-to-cloud-engine` for the balances. 9. **Expecting a direct-call key through the proxy.** Threshold-key derivation via the proxy is caller-isolated, so the derived key/address is not the same as a direct management-canister call. Fetch the public key and sign through the proxy consistently; do not mix direct and proxied key calls for the same identity. 10. **Using a chain-key helper library on an engine.** `ic-vetkeys`, `ic-cdk-management-canister`'s chain-key functions, and `mo:ic-vetkeys/ManagementCanister` call `aaaaa-aa` directly and attach the fee themselves — non-zero even on an engine, because the chain-key cost API prices against the key-holding subnet — making it a cross-subnet, cycle-bearing call that the engine rejects under Rules 1 and 2. Their whole value proposition (correct types, automatic cycles) is what has to go: hand-encode the management-canister argument and relay it through the proxy. Code copied from the `vetkeys` skill will not run on an engine unmodified. 11. **Over-reading that warning and proxying outcalls too.** The warning above is about the chain-key functions, not the crates that contain them. `ic-cdk-management-canister` is also what Rust outcall code should use (Rule 3), and its `HttpRequest` builder is correct on an engine as written. Concluding "this crate doesn't work on an engine, so the outcall must be hand-encoded through the proxy" lands straight in pitfall 4 — a transform that cannot apply and a proxy balance that drains. Decide by target subnet, not by crate name: `aaaaa-aa` `http_request` is local and free; signing and vetKD are remote and paid. 12. **Tuning pricing-version-2 budgets for an engine.** `ic-cdk-management-canister` 0.2 always prices version 2, where the attached cycles are also each node's budget and a too-narrow `with_expected_*` can fail a call partway. On an engine the free cost schedule never charges, so the budget narrows nothing: the timeout and transform-instruction limits sit at the protocol maximum and `InsufficientCycles` cannot be raised. The setters therefore change nothing here — do not add them to fix an engine outcall, and do not diagnose an engine outcall failure as an exhausted budget. Your own `max_response_bytes` is the exception: it still bounds the response, so an oversized reply remains a genuine cause. (Nor does the pricing version itself need managing: where the replica lacks pay-as-you-go, version 2 is silently filtered to version 1, and both cost zero on an engine.) 13. **Deleting or swapping the proxy of a signing app.** The management canister derives keys from *its* caller (the proxy), so the proxy's canister id is part of every address the app owns. Deleting a proxy (the console sends its cycles back to the engine's balance) or repointing the app at another one silently produces different addresses and leaves any Bitcoin or Ethereum funds at the old ones permanently unspendable. A signing app's proxy id is permanent infrastructure, not a fungible resource. 14. **Reading `CallFailed` as "it did not happen".** The proxy relays with a bounded-wait call, so a downstream `SYS_UNKNOWN` arrives as `ProxyError::CallFailed` with that reject code in `reason`. The target may have run and the cycles may be gone. Retrying a signature is harmless; retrying a stateful call on this basis is not: treat it as an unknown outcome (see `multi-canister`). 15. **Calling the console proxy from the CLI.** `icp canister call --proxy ` fails: the console proxy admits only the canisters on the engine's subnet and its own controller (the platform canister that created it), and an ingress call from your CLI identity is neither (it is rejected by `inspect_message` before it reaches replicated state). For CLI-side proxying, deploy your own proxy (`icp new … --subfolder proxy`) which authorizes controllers, i.e. you. 16. **Writing proxy-dependent code without asking for the proxy.** Signing, vetKD, XRC, Bitcoin API or EVM/SOL RPC code can be written and even deployed with no proxy behind it, and then fails on its first call: a placeholder or guessed id gets `UnauthorizedUser` or reaches nothing, and an id copied from another engine or project signs with someone else's keys. You cannot create the console proxy yourself: there is no `icp` command for it, and only the engine's owner can deploy one, from the console. Ask as soon as the need is known ("Before writing the code" in Rule 4), read the id from configuration, and never substitute a self-deployed proxy for the engine's. 17. **Relaying to a target the console proxy does not serve.** A console proxy relays for the engine's canisters only the management canister's threshold-key, `http_request` and `bitcoin_*` methods and the XRC, EVM RPC, SOL RPC, Bitcoin and Dogecoin canisters. Anything else, a third-party canister that charges cycles included, comes back as `CallFailed` (`a proxy funded by its engine relays only to …`), whatever its balance. Do not top it up or retry: route such a call through a self-deployed proxy that has the calling canister as a controller, or drop the dependency. 18. **A provider key in the canister.** On an engine, inference goes through the operator's `inference_request` (Rule 5). Drop the key and the outcall to the provider. 19. **A completion with no bound.** `Internal("… Canister http request timed out")` from `inference_request` is the 30 second outcall deadline. Set `max_tokens` first, then measure; a working `GET /models` does not explain it. 20. **Reading every `BadRequest` from `inference_request` as a console problem, or every one as a code bug.** Read the message. A message about `path` is yours: send a path that starts with `/`. A message that a provider is off, has no key, or that none is on is the engine's state: leave `provider` out if `listInferenceProviders` shows another one on and ready, and otherwise tell the user to pick a provider in the console. ## Additional References - Load `deploy-to-cloud-engine` for getting the app onto the engine: which route to take (the ICP MCP connector from a sandboxed chat, or the icp CLI), CLI identity linking, subnet-targeted deploy, console app metadata, and for **deploying and funding the proxy** this skill's Rule 4 depends on: the console flow (the engine owner deploys it, paid from the engine's balance), which balance pays for what, and the self-deployed CLI alternative. - Load `vetkeys` for what vetKD is and how its keys are used (IBE, encrypted maps, transport keys). Its call code targets a normal subnet and attaches cycles through helper libraries: on an engine, keep the concepts and replace the calls with the proxied form above. - Load `https-outcalls` for everything about outcalls that is not engine-specific: transform functions, `max_response_bytes`, idempotency, debugging consensus failures. - Load `multi-canister` for inter-canister call design, bounded vs unbounded wait semantics, and `SYS_UNKNOWN` handling. --- ## Custom Domains --- name: custom-domains description: "Register and manage custom domains for IC canisters via the HTTP gateway custom domain service. Covers DNS record configuration (CNAME, TXT, ACME challenge), the .well-known/ic-domains file, domain registration/validation/update/deletion via the REST API, TLS certificate provisioning, and HttpAgent host configuration. Use when the user wants to serve a canister under a custom domain, configure DNS for IC, register a domain with boundary nodes, troubleshoot custom domain issues (including a cloud engine console warning that the engine can't write /.well-known/ic-domains), or update/remove a custom domain. Do NOT use for general frontend hosting or asset/static-site canister configuration without custom domains — use static-site instead." license: Apache-2.0 compatibility: "curl, DNS registrar access, deployed canister" metadata: title: "Custom Domains" category: Frontend --- # Custom Domains ## What This Is By default, canisters are accessible at `.icp.net`. The custom domains service lets you serve any canister under your own domain (e.g., `yourdomain.com`). You configure DNS, deploy a domain ownership file to your canister, and register via a REST API. The HTTP gateways then handle TLS certificate provisioning, renewal, and routing automatically. Custom domains work at the boundary node level — they map a domain to any canister ID via DNS. This works with any canister that can serve `/.well-known/ic-domains` over HTTP, not just asset canisters. That includes asset canisters, Juno satellites, and custom canisters implementing `http_request`. ## Prerequisites - A registered domain from any registrar (e.g., Namecheap, GoDaddy, Cloudflare) - Access to edit DNS records for that domain - A deployed canister that serves `/.well-known/ic-domains` over HTTP (asset canisters, Juno satellites, or any canister implementing `http_request`). On a cloud engine (OpenCloud) the engine writes that file, and the frontend canister must run certified-assets 0.4.3 or newer (`@dfinity/static-site@v0.4.3`): see pitfall 10 - `curl` for the registration API calls - `jq` (optional, for formatting JSON responses) ## Mistakes That Break Your Setup 1. **Not disabling your DNS provider's SSL/TLS.** Providers like Cloudflare enable Universal SSL by default. This interferes with the ACME challenge the IC uses to provision certificates and can prevent certificate renewal. Disable any certificate/SSL/TLS offering from your DNS provider before registering. 2. **Setting a CNAME on the apex domain.** Many DNS providers don't allow CNAME records on the apex (e.g., `example.com` with no subdomain). Use ANAME or ALIAS record types (CNAME flattening) if your provider supports them. Otherwise, use a subdomain like `www.example.com`. 3. **Missing the `_acme-challenge` CNAME.** Without `_acme-challenge.CUSTOM_DOMAIN` pointing to `_acme-challenge.CUSTOM_DOMAIN.icp2.io`, the HTTP gateways cannot obtain a TLS certificate. Registration will fail. 4. **Multiple TXT records on `_canister-id`.** If more than one TXT record exists for `_canister-id.CUSTOM_DOMAIN`, registration fails. Keep exactly one containing your canister ID. 5. **Forgetting the `.well-known/ic-domains` file.** The canister must serve `/.well-known/ic-domains` listing your custom domain. Without it, domain ownership verification fails during registration. 6. **Stale `_acme-challenge` TXT records from your DNS provider.** Previous ACME challenges by your provider may leave TXT records on `_acme-challenge.CUSTOM_DOMAIN` that don't appear in your dashboard. These conflict with the IC's ACME flow. Disable all TLS offerings from your provider to clear them. Verify with `dig TXT _acme-challenge.CUSTOM_DOMAIN`. 7. **Not explicitly registering the domain.** DNS configuration alone is not enough. You must call `POST /custom-domains/v1/CUSTOM_DOMAIN` to start registration. It is not automatic. 8. **Setting `HttpAgent`'s `host` to your custom domain.** `host` is the **API endpoint** canister calls go to, not the domain your frontend is served from. Your custom domain is the HTTP gateway — it does not serve `/api/v2`, so pointing `host` at it (or at `window.location.origin`) makes calls fail. You do not need to set `host`: a recent `@icp-sdk/core` `HttpAgent` resolves an omitted `host` to `https://icp-api.io` (the mainnet API boundary nodes) on a custom domain. Leave it unset, or set it explicitly to `https://icp-api.io` — never the gateway domain. 9. **Adding a custom domain to an app that already has users.** II principals are per-origin, so the new domain hands every returning user a brand-new account. Pin a derivation origin — the canister address, which a custom domain can never displace — and list the domain in `.well-known/ii-alternative-origins` **before** the domain goes live. A domain that has already collected sign-ins cannot be repointed without orphaning those accounts. See the `user-sign-in` skill. 10. **Shipping your own `ic-domains` file on a cloud engine, or a frontend older than certified-assets 0.4.3 there.** On a cloud engine (OpenCloud), the engine writes `/.well-known/ic-domains` (the HTTP gateway checks the domain against it) and `/.well-known/ii-alternative-origins` (Internet Identity reads it) into the app's frontend canister with certified-assets' `upload_asset`, which arrived in 0.4.3. Its copy replaces whatever the app ships at those two paths, so a domain listed only in the app's own `ic-domains` file disappears at the engine's next write. Add the domain in the engine console instead (Step 2). On a canister older than 0.4.3 the console warns `The engine can't write this app's /.well-known/ic-domains and /.well-known/ii-alternative-origins: its canister doesn't run certified-assets 0.4.3 or newer`, and the domain does not work. Fix: pin `@dfinity/static-site@v0.4.3` or newer and run `icp deploy -e ic`. If the sync then stops with `assets canister version mismatch`, run `icp canister install --mode upgrade -e ic` (v0.4.x to v0.4.3 is a patch, so the state stays), then `icp deploy -e ic` again. Never `--mode reinstall` for that bump; from v0.3.x the bump is breaking (see the `static-site` skill, pitfall 11). Then list both paths in `_preserve` (Step 2). ## Implementation ### Step 1: Configure DNS Records Add three DNS records (replace `CUSTOM_DOMAIN` with your domain, e.g., `app.example.com`): | Record Type | Host | Value | |---|---|---| | CNAME | `CUSTOM_DOMAIN` | `CUSTOM_DOMAIN.icp1.io` | | TXT | `_canister-id.CUSTOM_DOMAIN` | your canister ID (e.g., `hwvjt-wqaaa-aaaam-qadra-cai`) | | CNAME | `_acme-challenge.CUSTOM_DOMAIN` | `_acme-challenge.CUSTOM_DOMAIN.icp2.io` | Some DNS providers omit the main domain suffix. For `app.example.com` on such providers: - `app` instead of `app.example.com` - `_canister-id.app` instead of `_canister-id.app.example.com` - `_acme-challenge.app` instead of `_acme-challenge.app.example.com` For apex domains without CNAME support, use your provider's ANAME or ALIAS record type pointing to `CUSTOM_DOMAIN.icp1.io`. ### Step 2: Create the `ic-domains` File Your canister must serve `/.well-known/ic-domains` over HTTP. Create this file listing each custom domain on its own line: ```text app.example.com www.example.com ``` **Frontend canister users:** place `.well-known/` inside your `public/` directory (Vite projects) or alongside your source files so it ends up in your `dir`. With the recommended `@dfinity/static-site` recipe, `.well-known/` is uploaded automatically (no config needed). With the legacy `@dfinity/asset-canister` recipe, ensure `.ic-assets.json5` includes `{ "match": ".well-known", "ignore": false }` so the hidden directory gets deployed. See the `static-site` skill for details on file placement. **Custom `http_request` canisters:** serve the file contents at `/.well-known/ic-domains` directly from your HTTP request handler. **Apps on a cloud engine (OpenCloud):** do not create this file. In the engine console, open the app's domains, choose **Add a domain** → **A domain you own**, and enter it. The engine then writes `/.well-known/ic-domains` and `/.well-known/ii-alternative-origins` into the frontend canister itself, with no redeploy. This needs `@dfinity/static-site@v0.4.3` or newer (pitfall 10). Keep both files out of `dir`: the engine overwrites them anyway. A deploy deletes every file that is not in `dir`, so list both paths in a `_preserve` file at the root of `dir`: ```text # Written by the engine with upload_asset; this build doesn't ship them. /.well-known/ic-domains /.well-known/ii-alternative-origins ``` Without `_preserve`, every deploy deletes both files until the engine writes them again (within 10 minutes). You still add the three DNS records (Step 1) and register the domain: the console's **Check** button registers it with the HTTP gateway, or run Steps 4–6. ### Step 3: Deploy Deploy your canister so that `/.well-known/ic-domains` is accessible at `https://.icp.net/.well-known/ic-domains`. ### Step 4: Validate Check DNS records and canister configuration before registering: ```bash curl -sL -X GET "https://icp.net/custom-domains/v1/CUSTOM_DOMAIN/validate" | jq ``` Success response: ```json { "status": "success", "message": "Domain is eligible for registration: DNS records are valid and canister ownership is verified", "data": { "domain": "CUSTOM_DOMAIN", "canister_id": "CANISTER_ID", "validation_status": "valid" } } ``` If validation fails, common errors and fixes: | Error | Fix | |---|---| | Missing DNS CNAME record | Add the `_acme-challenge` CNAME pointing to `_acme-challenge.CUSTOM_DOMAIN.icp2.io` | | Missing DNS TXT record | Add the `_canister-id` TXT record with your canister ID | | Invalid DNS TXT record | Ensure the TXT value is a valid canister ID | | More than one DNS TXT record | Remove duplicate `_canister-id` TXT records, keep one | | Failed to retrieve known domains | Ensure `.well-known/ic-domains` is deployed and served by the canister. On a cloud engine, check the console's domain page for a warning that the engine can't write the file (pitfall 10) | | Domain missing from list | Add the domain to the `ic-domains` file and redeploy. On a cloud engine, add it in the console instead (Step 2) | ### Step 5: Register ```bash curl -sL -X POST "https://icp.net/custom-domains/v1/CUSTOM_DOMAIN" | jq ``` Success response: ```json { "status": "success", "message": "Domain registration request accepted and may take a few minutes to process", "data": { "domain": "CUSTOM_DOMAIN", "canister_id": "CANISTER_ID" } } ``` ### Step 6: Wait for Certificate Provisioning Poll until `registration_status` is `registered`: ```bash curl -sL -X GET "https://icp.net/custom-domains/v1/CUSTOM_DOMAIN" | jq ``` Status values: `registering` → `registered` (success), or `failed` (check error message). After `registered`, wait a few more minutes for propagation to all HTTP gateways before testing. ## Updating a Custom Domain To point an existing custom domain at a different canister: 1. Update the `_canister-id` TXT record to the new canister ID. 2. Notify the service: ```bash curl -sL -X PATCH "https://icp.net/custom-domains/v1/CUSTOM_DOMAIN" | jq ``` 3. Check status: ```bash curl -sL -X GET "https://icp.net/custom-domains/v1/CUSTOM_DOMAIN" | jq ``` ## Removing a Custom Domain 1. Remove the `_canister-id` TXT record and `_acme-challenge` CNAME from DNS. 2. Notify the service: ```bash curl -sL -X DELETE "https://icp.net/custom-domains/v1/CUSTOM_DOMAIN" | jq ``` 3. Confirm deletion (should return 404): ```bash curl -sL -X GET "https://icp.net/custom-domains/v1/CUSTOM_DOMAIN" | jq ``` ## HttpAgent Configuration A frontend served from your custom domain still makes its canister calls through the mainnet **API boundary nodes** (`https://icp-api.io`), not through the domain it is served from. `HttpAgent`'s `host` is that API endpoint — *not* your frontend's origin. The custom domain is the HTTP gateway and does not serve `/api/v2`. You do not need to set `host`. When it is omitted, a recent `@icp-sdk/core` `HttpAgent` resolves to `https://icp-api.io` on a custom domain (and on `icp.net`). Do **not** point `host` at your custom domain or `window.location.origin` — that is the gateway, so calls would fail. ```typescript import { HttpAgent } from "@icp-sdk/core/agent"; // host omitted on a custom domain → resolves to https://icp-api.io const agent = await HttpAgent.create(); // equivalent, explicit: const agentExplicit = await HttpAgent.create({ host: "https://icp-api.io" }); ``` ## Deploy & Test ```bash # 1. Deploy your canister with the ic-domains file served at /.well-known/ic-domains # 2. Validate DNS + canister config curl -sL -X GET "https://icp.net/custom-domains/v1/yourdomain.com/validate" | jq # 3. Register curl -sL -X POST "https://icp.net/custom-domains/v1/yourdomain.com" | jq # 4. Poll until registered curl -sL -X GET "https://icp.net/custom-domains/v1/yourdomain.com" | jq ``` ## Verify It Works ```bash # 1. Verify DNS records dig CNAME yourdomain.com # Expected: yourdomain.com. CNAME yourdomain.com.icp1.io. dig TXT _canister-id.yourdomain.com # Expected: "" dig CNAME _acme-challenge.yourdomain.com # Expected: _acme-challenge.yourdomain.com. CNAME _acme-challenge.yourdomain.com.icp2.io. # 2. Verify ic-domains file is served by the canister curl -sL "https://.icp.net/.well-known/ic-domains" # Expected: your domain listed # 3. Verify registration status is "registered" curl -sL -X GET "https://icp.net/custom-domains/v1/yourdomain.com" | jq '.data.registration_status' # Expected: "registered" # 4. Verify the custom domain serves your canister curl -sI "https://yourdomain.com" # Expected: HTTP/2 200 # 5. Verify no stale ACME TXT records dig TXT _acme-challenge.yourdomain.com # Expected: no TXT records (only the CNAME) ``` --- ## Cycles Management --- name: cycles-management description: "Manage cycles and canister lifecycle. Covers cycle balance checks, top-ups, freezing thresholds, canister creation, and ICP-to-cycles conversion via the CMC. Use when working with cycles, canister funding, freezing threshold, frozen canister, out of cycles, top-up, canister creation, or cycle balance. Do NOT use for wallet-to-dApp integration or ICRC signer flows — use wallet-integration instead." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2" metadata: title: Cycles Management category: Infrastructure --- # Cycles & Canister Management ## What This Is Cycles are the computation fuel for canisters on Internet Computer. Every canister operation (execution, storage, messaging) burns cycles. When a canister runs out of cycles, it freezes and is eventually uninstalled -- its code and data are deleted, but its metadata (canister ID, controllers, settings) survives. 1 trillion cycles (1T) costs approximately 1 USD equivalent in ICP (the exact rate is set by the NNS and fluctuates with ICP price via the CMC). **Note:** icp-cli uses the **cycles ledger** (`um5iw-rqaaa-aaaaq-qaaba-cai`) by default. The cycles ledger is a single canister that tracks cycle balances for all principals, similar to a token ledger. Commands like `icp cycles balance`, `icp cycles mint`, and `icp canister top-up` go through the cycles ledger. There is no legacy wallet concept in icp-cli. The programmatic patterns below (accepting cycles, creating canisters via management canister) remain the same regardless of which funding mechanism is used. ## Prerequisites - For Motoko: `mops` package manager, `core = "2.0.0"` in mops.toml - For Rust: `ic-cdk >= 0.19` ## Canister IDs | Service | Canister ID | Purpose | |---------|------------|---------| | Cycles Minting Canister (CMC) | `rkp4c-7iaaa-aaaaa-aaaca-cai` | Converts ICP to cycles, creates canisters | | Cycles Ledger | `um5iw-rqaaa-aaaaq-qaaba-cai` | Tracks cycle balances for all principals | | Management Canister | `aaaaa-aa` | Canister lifecycle (create, install, stop, delete, status) | The Management Canister (`aaaaa-aa`) is a virtual canister -- it does not exist on a specific subnet but is handled by every subnet's execution layer. ## Mistakes That Break Your Build 1. **Running out of cycles silently freezes the canister** -- There is no warning. A frozen canister stops executing messages but keeps paying rent for its memory and allocations, so the balance continues to drain. When it reaches zero the canister is uninstalled: code and data are gone permanently, and only the metadata (canister ID, controllers, settings) remains. Set a freezing threshold and monitor balances. 2. **Not setting freezing_threshold** -- Default is 30 days. If your canister burns cycles fast (high traffic, large stable memory), 30 days may not be enough warning. Set it higher for production canisters. The freezing threshold defines how many seconds worth of idle cycles the canister must retain before it freezes. 3. **Confusing local vs mainnet cycles** -- Local replicas give canisters virtually unlimited cycles. Code that works locally may fail on mainnet because the canister has insufficient cycles. Always test with realistic cycle amounts before mainnet deployment. 4. **Sending cycles to the wrong canister** -- Cycles sent to a canister cannot be retrieved. There is no refund mechanism for cycles transferred to the wrong principal. Double-check the canister ID before topping up. 5. **Forgetting to set the canister controller** -- If you lose the controller identity, you permanently lose the ability to upgrade, top up, or manage the canister. Always add a backup controller. Use `icp canister settings update --add-controller PRINCIPAL` to add one. 6. **Using ExperimentalCycles in mo:core** -- In mo:core 2.0, the module is renamed to `Cycles`. `import ExperimentalCycles "mo:base/ExperimentalCycles"` will fail. Use `import Cycles "mo:core/Cycles"`. 7. **Using `icp cycles transfer` to fund a canister** -- `icp cycles transfer ` moves cycles between cycles-ledger balances, the same as a token transfer between accounts. Passing a canister's principal as the recipient credits that principal's cycles-ledger balance, not the canister's actual execution/compute cycle balance -- `icp canister status` will not show the cycles as received, and the canister keeps burning down its real balance toward freezing with no indication anything went wrong. Use `icp canister top-up --amount -e ic` instead, which deposits cycles directly onto the canister via the management canister. See "Top Up a Canister" below for both commands side by side. 8. **Using `-n ic` on a command that names a canister** -- `-n`/`--network` and `-e`/`--environment` are different selectors and conflict with each other; passing both is an error. A canister **name** can only be resolved through an environment, so `-n` fails on it: ```bash icp canister status backend -n ic # Error: Specifying a network is not supported if you are targeting a canister # by name, specify an environment instead ``` So `-e ic` for anything naming a canister (`top-up`, `status`, `settings update`, `create`), and `-n ic` for commands that take a principal or no canister at all (`cycles mint`, `cycles balance`, `cycles transfer`). This is why the mainnet examples below mix the two flags. Load `icp-cli` for the full flag rules. ## Implementation ### Motoko #### Checking and Accepting Cycles ```motoko import Cycles "mo:core/Cycles"; import Principal "mo:core/Principal"; import Runtime "mo:core/Runtime"; persistent actor { // Check this canister's cycle balance public query func getBalance() : async Nat { Cycles.balance() }; // Accept cycles sent with a call (for "tip jar" or payment patterns) public func deposit() : async Nat { let available = Cycles.available(); if (available == 0) { Runtime.trap("No cycles sent with this call") }; let accepted = Cycles.accept(available); accepted }; // Send cycles to another canister via inter-canister call public func topUpCanister(target : Principal) : async () { let targetActor = actor (Principal.toText(target)) : actor { deposit_cycles : shared () -> async (); }; // Attach 1T cycles to the call await (with cycles = 1_000_000_000_000) targetActor.deposit_cycles(); }; } ``` #### Creating a Canister Programmatically ```motoko import Principal "mo:core/Principal"; persistent actor Self { type CanisterId = { canister_id : Principal }; type CreateCanisterSettings = { controllers : ?[Principal]; compute_allocation : ?Nat; memory_allocation : ?Nat; freezing_threshold : ?Nat; }; // Management canister interface let ic = actor ("aaaaa-aa") : actor { create_canister : shared { settings : ?CreateCanisterSettings } -> async CanisterId; canister_status : shared { canister_id : Principal } -> async { status : { #running; #stopping; #stopped }; memory_size : Nat; cycles : Nat; settings : CreateCanisterSettings; module_hash : ?Blob; }; deposit_cycles : shared { canister_id : Principal } -> async (); stop_canister : shared { canister_id : Principal } -> async (); delete_canister : shared { canister_id : Principal } -> async (); }; // Create a new canister with 1T cycles public func createNewCanister() : async Principal { let result = await (with cycles = 1_000_000_000_000) ic.create_canister({ settings = ?{ controllers = ?[Principal.fromActor(Self)]; compute_allocation = null; memory_allocation = null; freezing_threshold = ?2_592_000; // 30 days in seconds }; }); result.canister_id }; // Check a canister's status and cycle balance public func checkStatus(canisterId : Principal) : async Nat { let status = await ic.canister_status({ canister_id = canisterId }); status.cycles }; // Top up another canister public func topUp(canisterId : Principal, amount : Nat) : async () { await (with cycles = amount) ic.deposit_cycles({ canister_id = canisterId }); }; } ``` ### Rust #### Checking Balance and Accepting Cycles ```rust use ic_cdk::{query, update}; use candid::Nat; #[query] fn get_balance() -> Nat { Nat::from(ic_cdk::api::canister_cycle_balance()) } #[update] fn deposit() -> Nat { let available = ic_cdk::api::msg_cycles_available(); if available == 0 { ic_cdk::trap("No cycles sent with this call"); } let accepted = ic_cdk::api::msg_cycles_accept(available); Nat::from(accepted) } ``` #### Creating and Managing Canisters ```rust use candid::{Nat, Principal}; use ic_cdk::update; use ic_cdk::management_canister::{ create_canister_with_extra_cycles, canister_status, deposit_cycles, stop_canister, delete_canister, CreateCanisterArgs, CanisterStatusArgs, DepositCyclesArgs, StopCanisterArgs, DeleteCanisterArgs, CanisterSettings, CanisterStatusResult, }; #[update] async fn create_new_canister() -> Principal { let caller = ic_cdk::api::canister_self(); // capture canister's own principal let user = ic_cdk::api::msg_caller(); // capture caller before await let settings = CanisterSettings { controllers: Some(vec![caller, user]), compute_allocation: None, memory_allocation: None, freezing_threshold: Some(Nat::from(2_592_000u64)), // 30 days reserved_cycles_limit: None, log_visibility: None, wasm_memory_limit: None, wasm_memory_threshold: None, environment_variables: None, }; let arg = CreateCanisterArgs { settings: Some(settings), }; // Send 1T cycles with the create call let result = create_canister_with_extra_cycles(&arg, 1_000_000_000_000u128) .await .expect("Failed to create canister"); result.canister_id } #[update] async fn check_status(canister_id: Principal) -> CanisterStatusResult { canister_status(&CanisterStatusArgs { canister_id }) .await .expect("Failed to get canister status") } #[update] async fn top_up(canister_id: Principal, amount: u128) { deposit_cycles(&DepositCyclesArgs { canister_id }, amount) .await .expect("Failed to deposit cycles"); } #[update] async fn stop_and_delete(canister_id: Principal) { stop_canister(&StopCanisterArgs { canister_id }) .await .expect("Failed to stop canister"); delete_canister(&DeleteCanisterArgs { canister_id }) .await .expect("Failed to delete canister"); } ``` ## Deploy & Test ### Check Cycle Balance ```bash # Check your canister's cycle balance icp canister status backend # Look for "Balance:" line in output # Check balance on mainnet icp canister status backend -e ic # Check any canister by ID icp canister status ryjl3-tyaaa-aaaaa-aaaba-cai -e ic ``` ### Top Up a Canister ```bash # Top up with cycles from the cycles ledger (local) icp canister top-up backend --amount 1000000000000 # Adds 1T cycles to the backend canister # Top up on mainnet icp canister top-up backend --amount 1000000000000 -e ic # Convert ICP to cycles and top up in one step (mainnet) icp cycles mint --icp 1.0 -n ic # no canister argument, so -n is fine (see Pitfall 8) # No ICP to convert? Buy cycles with a card for the identity instead (load the `buy-cycles` skill) icp cycles buy --amount 10 -n ic icp canister top-up backend --amount 1000000000000 -e ic ``` ```bash # CORRECT -- funds the canister's execution balance: icp canister top-up backend --amount 600b -e ic # WRONG -- sends to the recipient's cycles-ledger balance, canister cannot use it: icp cycles transfer 600000000000 -n ic ``` `--amount` on `icp canister top-up` accepts `k`/`m`/`b`/`t` suffixes (thousand/million/billion/trillion). ### Create a Canister via icp ```bash # Create an empty canister (local) icp canister create my_canister # Create on mainnet with specific cycles icp canister create my_canister -e ic --cycles 2000000000000 # Add a backup controller icp canister settings update my_canister --add-controller BACKUP_PRINCIPAL_HERE ``` Each creation takes `--cycles` (default 2T) plus the cycles ledger's 100M fee out of the identity's balance. Before `icp deploy -e ic` creates several canisters at once, estimate `N × (2T + 100M)`, compare with `icp cycles balance -n ic`, and close any gap before deploying -- `icp cycles mint --cycles -n ic` with ICP, `icp cycles buy --cycles -n ic` with a card. The `icp-cli` skill's "Funding an identity for mainnet" section has the steps. ### Set Freezing Threshold ```bash # Set freezing threshold to 90 days (in seconds: 90 * 24 * 60 * 60 = 7776000) icp canister settings update backend --freezing-threshold 7776000 # Mainnet icp canister settings update backend --freezing-threshold 7776000 -e ic ``` ## Verify It Works ```bash # Deploy and check status icp network start -d icp deploy backend icp canister status backend # Expected output includes: # Status: Running # Balance: 3_100_000_000_000 Cycles (local default, varies) # Freezing threshold: 2_592_000 # Check balance programmatically (if you added getBalance) icp canister call backend getBalance '()' # Expected: a large nat value, e.g. (3_100_000_000_000 : nat) # On mainnet: verify cycles balance is not zero icp canister status backend -e ic # If Balance shows 0, the canister will freeze. Top up immediately. ``` --- ## Deploy to Cloud Engine --- name: deploy-to-cloud-engine description: "Deploys a built Internet Computer project to a cloud engine (OpenCloud). From a sandboxed chat or cloud session with the ICP MCP connector (ChatGPT, Claude, https://mcp.internetcomputer.org/mcp): install the wasm through the engine-operator's `proxy`. Otherwise with the icp CLI: `icp identity link web` (defaults to https://opencloud.org), `icp deploy` on the engine's subnet. Also: `__META_*` for a named console app, version metadata (service:git:sha), and the proxy canister for Bitcoin/Ethereum signing, VetKeys or exchange rates (paid from the engine's balance, or `icp new --subfolder proxy`). Use when shipping to a cloud engine; on mention of OpenCloud, an engine subnet id, ICP MCP deploys, or linking the icp CLI; when sign-in never completes from a sandbox; when naming, versioning or giving an icon to a console app; when funding a proxy or picking which balance to top up (failing proxied calls: cloud-engine-canisters). Do NOT use for a mainnet deploy with no engine (icp-cli) or canister logic." license: Apache-2.0 compatibility: "ICP MCP route: the ICP MCP connector (native in ChatGPT and Claude, or https://mcp.internetcomputer.org/mcp) with Actions & questions access, on an engine whose engine-operator has `proxy`. CLI route: icp-cli >= 0.3.0 (verified against 0.3.0, 1.0.2, 1.3.0; delegation handoff needs 1.0.x; the `proxy` template needs `icp new --subfolder`) and a browser for the Internet Identity sign-in. Both: a cloud engine console account; for a console proxy, the engine owner to deploy it" metadata: title: Deploy to Cloud Engine category: CloudEngine --- # Deploy to Cloud Engine ## What This Is A **cloud engine** is a user-owned slice of Internet Computer capacity, administered from a web console (by default `https://opencloud.org`). Each engine runs on a single **subnet**. This skill takes a project that already builds and gets it deployed onto that engine, from a coding agent or an AI chat app. This skill only covers the cloud-engine-specific steps: choosing how to deploy, signing in as an identity the engine accepts, and putting the canisters on the engine. For everything else about the CLI (`icp.yaml`, recipes, environments, bindings, identities), load the **`icp-cli`** skill. ## Choose the Deploy Route First There are two ways onto an engine. Pick one **before you write any code**: the route decides how the deploy signs in and what you can ship. - **ICP MCP connector.** DFINITY's official MCP server for the Internet Computer. It is available natively in ChatGPT (the plugin **Internet Computer (ICP)** by DFINITY Stiftung) and in Claude, and any MCP-capable app can add it as a custom connector at `https://mcp.internetcomputer.org/mcp` (setup steps: https://mcp.internetcomputer.org/). It signs as the user with the Internet Identity session they authorized in the chat app, so nothing needs a local CLI, a browser on your machine, or a loopback. You deploy a wasm through the engine's engine-operator canister. See **"ICP MCP Route"**. - **icp CLI.** `icp identity link web`, then `icp deploy --subnet`. The full toolchain (recipes, asset canisters, `icp.yaml`), but the sign-in completes only when `icp` runs on the same machine as the user's browser. See **Steps 1 to 4**. Decide like this: 1. **You run in a sandbox and the ICP MCP tools are available to you** (`open_app`, `get_app_principal`, `canister_update_call`, …) → **use the ICP MCP route.** A sandbox is a web or mobile chat (ChatGPT, Claude on the web or a phone) or a cloud coding session. Do not ask the user to move to a local session, and do not attempt `icp identity link web` or the delegation handoff there. 2. **Otherwise → the CLI route: link the CLI** (Step 1). - **Local session** (a coding agent on the user's own computer: Claude Code, Codex CLI, Cursor, or the local environment of the Claude desktop app): link the CLI and deploy with it, even when the ICP MCP tools are also available. The normal link flow works there, and the CLI can ship what the connector cannot, such as the files of an asset canister (see "What the connector cannot do"). - **Sandbox without the ICP MCP tools**: the CLI sign-in cannot finish there (see Step 1.0). Tell the user before you build anything, and ask them to start a local session instead. If their chat app can add MCP connectors, adding the ICP MCP connector is the other way. A cloud session cannot move to their computer later, so ask before you build, not after, and wait for the answer. Continue in the sandbox with the CLI only when the user has neither option. Then do the delegation handoff in Step 1.0 **first**, and build only after the sandbox CLI signs as the user: do not leave the sign-in for deploy time. Before running any `icp` command you are unsure of, run `icp --help` (e.g. `icp identity link --help`, `icp deploy --help`) to confirm the command and flags exist. Do not infer flags. Authoritative reference: https://cli.internetcomputer.org/llms.txt ## What You Need Two values, and a third for some apps. Look for them first in `icp.yaml` or earlier in the conversation. One has a default; the others you must ask for: 1. **Console origin** — the URL the user signs in to their cloud engine console with. **Defaults to `https://opencloud.org`** (the main OpenCloud console). Its host is the `--app` value in Step 1, so the linked CLI identity derives the **same principal that administers the engine**. Use the default, but say so and give the user a chance to override before linking: - Say: "I'll link the CLI against `https://opencloud.org`, the default console. If you sign in to your engine console at a different URL, tell me now." - Only use a different origin when the user names one — never substitute another URL on your own; the `--app` domain determines the derived principal (see Pitfall 2). - On the ICP MCP route there is no `--app`; the console origin is where you look the engine up and where the owner confirms access (M1, M3). 2. **Subnet id** (CLI route): the subnet the engine deploys to, required by `icp deploy --subnet`. There is **no default**; never guess it. The user finds it on the engine's **Settings** page in the console (under the engine's identifiers), or copies it from the console's command palette. If absent, **ask and do not proceed without it**: - Ask: "What is your engine's subnet id? It is on your engine's Settings page in the console." - On the ICP MCP route you need the **engine id** instead (M1). The operator creates canisters on its own engine, so there is no subnet to pass. 3. **Proxy canister id**: only if the app calls threshold ECDSA/Schnorr, vetKD, the exchange-rate canister, the Bitcoin API, or the EVM/SOL RPC canisters (look for a `PROXY_CANISTER_ID` variable, or a call to a `proxy` method). There is **no default**, you cannot create the console proxy yourself, and a self-deployed one is no substitute (Step 5). If absent, **ask before deploying**: - Ask: "This app needs your engine's proxy canister. If the engine has one, send me its id (engine → Integrations → Proxy canisters). If not, the engine owner can deploy one there with Deploy a proxy: it is paid from the engine's balance, no card. Then send me its id." Record them so you do not re-ask within the session. ## Prerequisites - CLI route: `icp` on `$PATH` — see the **`icp-cli`** skill to install. Verify with `icp --version` (this skill's commands are verified against 0.3.0 and 1.0.2). If the installed version differs, confirm the flag set with `icp --help` before running — flags have changed across major versions. - A project that already builds. If it does not build or package yet, set that up first (see the `icp-cli` skill), then return here. - **No project yet, and no description of one?** Ask the user what to build before you write any code or create any files: "What app do you want to build?" Do **not** pick a sample app (a guestbook, a counter, a to-do list) on your own. A prompt that only says "build and deploy an app" is a request to ask, not a request to choose. - CLI route, macOS: `icp` stores its data under `~/Library/Application Support/org.dfinity.icp-cli/`. If the shell cannot write there (`Operation not permitted` from macOS TCC, e.g. when commands run through a bridge), redirect the data to an unprotected path for the session — `HOME=/tmp/icp-home icp …` — and keep that same `HOME` on **every** subsequent `icp` command, or the later commands will not see the linked identity. - ICP MCP route: the connector's tools in your tool list, connected with **Actions & questions** access (M0). ## ICP MCP Route For a sandboxed agent that has the ICP MCP tools (see "Choose the Deploy Route First"). No `icp` CLI, no loopback, no delegation handoff. Steps 1 and 3 are the CLI route and do not apply. Step 2 (naming the app) and Step 5 (the proxy canister for chain-key services) still do: M6 shows how to set their variables without `icp.yaml`. The engine-operator canister's own API guide is the authoritative, current walkthrough of the calls below: read it in M2 before you call anything. ### M0. The connector and its access level If the tools are missing and the user's app can add MCP connectors, ask them to add it: in ChatGPT the plugin **Internet Computer (ICP)** by DFINITY Stiftung, in Claude its connector, and in any other MCP-capable app a custom connector at `https://mcp.internetcomputer.org/mcp`. The steps are at https://mcp.internetcomputer.org/. On connecting, the user signs in with Internet Identity, picks how long the session lasts, and picks an access level. A deploy needs **Actions & questions**. With **Questions only**, reads work, but the network rejects every state-changing call, so `create_canister` and `install_code` fail. If an update call is rejected that way, ask the user to reconnect with Actions & questions. Sessions expire by design: reconnecting later is normal. ### M1. Find the engine You need three values: the engine's **id**, its **engine-operator canister id** (`engine_operator_id`), and its **platform domain** (`platform_domain`, like `--.opencloud.org`). - Ask the user for the engine id. It is in the console URL (`/console/engines//…`) and on the engine's **Settings** page. - `open_app` on the console origin (`https://opencloud.org`) lists the engine registry canister. Read its public `getEngineViews` query with `(vec { "" })`; the record carries `engine_operator_id` and `platform_domain`. Signed as the user, its `listVisibleEngines` query returns the engines they own, with the same fields. A new or renamed engine's platform domain takes about ten minutes to register. Do not open or fetch it before then: a lookup that finds no record can be cached as missing for up to 30 minutes, and the domain keeps failing for you after it is live. Reach the engine through its operator's `https://.icp.net` host instead, which works as soon as `engine_operator_id` is set. `GET https://icp.net/custom-domains/v1/` answers `registration_status` `registered` once the platform domain serves: give the user that address from then on. ### M2. Open the engine and read the operator's guide 1. `open_app` on `https://.icp.net`. The engine-operator publishes the engine's `/.well-known/ic-architecture` manifest, so it comes back as `[declared]`; that is what lets the connector call it. The connector refuses calls to any canister an app does not declare. Check that the `derivation_origin` it returns is `https://`. If it is the icp.net origin, the operator does not hold the engine's domain yet: wait a minute and `open_app` again before M3, or the principal you get there changes later. 2. `get_canister_api_doc` on the operator, and read its section **"Creating a canister and installing a wasm"**. 3. `get_canister_candid` on the operator, and check that its service has a `proxy` method. If it has none, the engine still runs an engine-operator from before the ICP MCP route existed: tell the user, and use the CLI route. ### M3. Get the connector's principal added to the engine Internet Identity derives a principal per origin. At the engine, the connector signs as the principal derived for the engine's **platform domain** (the origin in its `/.well-known/ii-derivation-origin`). That is **not** the principal the user signs in to the console with, nor a CLI identity linked against the console origin. So the engine does not know it yet, even when the user owns the engine. 1. `get_app_principal` with the `derivation_origin` that `open_app` returned in M2 gives you that principal, `P`. Its reply also says whether the session is query-only: if it is, stop and have the user reconnect with Actions & questions (M0). If the user has several accounts at the engine, pick one with `account` and keep passing the same one, since each account is a different principal. 2. Check whether it is a member: the operator's public `getRole` query with `(record { principal_id = opt principal "

" })`. Any role is enough, because every role has the `CreateCanister` permission that `proxy` needs. 3. If the role is null, you cannot add `P` yourself. Give the user (the engine owner, or an engine admin) this link. It opens the engine's invite dialog with the grant filled in, so they only sign in and confirm: ``` https://opencloud.org/console/engines//team?modal=invite-member&principal=

&role=developer ``` Use their console origin instead of `https://opencloud.org` if it differs. `developer` is enough to deploy: do not ask for `admin`. Wait for them to confirm, then repeat step 2. Renaming the engine changes its platform domain, and with it `P`: the new principal needs the invite again. ### M4. Build a wasm the connector can ship The connector installs a **wasm module** and nothing else. - **Build it where you can.** In a code sandbox with the toolchain, `icp build` needs no sign-in (see `icp-cli`), and its recipe bakes in Step 2's version metadata as usual. Or use a prebuilt `.wasm` / `.wasm.gz` the user attaches. Canister code follows the engine's call rules: load `cloud-engine-canisters`. - **Keep it small.** The module travels inside the tool call as a Candid blob, so build for release and gzip it: the operator accepts a gzipped module. Above about 2 MB, it has to go up in chunks (M5, step 4). #### What the connector cannot do The connector calls only canisters that an app declares, and the engine's manifest declares only its operator. So your new canister is reachable only through the operator's relayed management calls (M5): the connector **cannot call the new canister's own methods**. That rules out anything that needs calls after the install, such as uploading the files of an asset canister (`@dfinity/static-site`, `@dfinity/asset-canister`). Pass configuration in the init argument (`arg`), or as environment variables (M6). If the app needs an asset upload, it needs the CLI route: tell the user. ### M5. Create the canister and install the wasm through the operator's `proxy` The connector may not call the IC management canister (`aaaaa-aa`) directly. The engine-operator's **`proxy` method** calls it for you, as the caller you sign as. Do not confuse it with the **proxy canister** of Step 5: that one relays chain-key calls for your app's code, and has nothing to do with deploying. Each step is one `canister_update_call` with `canister_id` the engine-operator, `method = "proxy"`, `app_url` the app URL and `derivation_origin` the derivation origin that `open_app` returned in M2 (plus the same `account` as in M3, if you chose one). **Always pass `derivation_origin`**: without it the call runs anonymously, and `proxy` answers `UnauthorizedUser`. The `args` are: ```candid (record { canister_id = principal "aaaaa-aa"; method = ""; args = blob ""; cycles = 0; }) ``` `args` holds the **binary** Candid encoding (bytes starting with `DIDL`) of the management method's argument, written as a `blob "…"` literal with `\xx` escapes. It is not textual Candid: encode it with a Candid library in your code sandbox. A success is `variant { Ok = record { result = blob "…" } }`, where `result` is the method's reply in binary Candid. The argument and reply types are in https://docs.internetcomputer.org/references/ic.did. 1. **Create.** `method = "create_canister"`, and `args` encodes: ```candid (record { settings = opt record { controllers = opt vec { principal "" } } }) ``` List the engine-operator as a controller. You (`P`) are added as a controller automatically, but without the operator `proxy` can never reach the canister again: no install, no settings, and no `deleteCanisters` for the owner either. If the code reads an environment variable when it initializes (such as `PROXY_CANISTER_ID`), add `environment_variables` to these `settings` now: it must be in place before step 2 (see M6). `result` decodes to `(record { canister_id : principal })`. 2. **Install.** `method = "install_code"`, and `args` encodes: ```candid (record { mode = variant { install }; canister_id = principal ""; wasm_module = blob ""; arg = blob "DIDL\00\00"; sender_canister_version = null; }) ``` `arg` is the binary-Candid init argument; `DIDL\00\00` passes none. `result` decodes to `()`. 3. **Replace the code later.** The same call with `mode = variant { upgrade = null }` keeps the stable memory; `variant { reinstall }` wipes all state. A canister built with enhanced orthogonal persistence (current Motoko) rejects `upgrade = null`: upgrade it with `variant { upgrade = opt record { wasm_memory_persistence = opt variant { keep } } }`. Use `keep` **only** for such a build: the IC rejects it when the new module lacks the `enhanced-orthogonal-persistence` custom section (a Rust canister, or classical-persistence Motoko), so those keep `upgrade = null`. (The operator's guide says other canisters ignore `keep`; the IC interface spec says otherwise, and the spec wins.) 4. **A module over about 2 MB** (the single-message limit) goes up with `upload_chunk`, then installs with `install_chunked_code`. The operator relays only `create_canister`, `canister_status`, `update_settings`, `install_code`, `upload_chunk`, `clear_chunk_store`, `install_chunked_code`, `start_canister` and `stop_canister`, and only on canisters that list you as a controller. Any other method, the operator itself, and protected canisters come back as `Err` `CallFailed` with a `reason`, as does any `proxy` call on a canister while an `update_settings` on it is in flight: retry once it completes. `cycles` is ignored, since the engine charges nothing. `Err` `UnauthorizedUser` means the call was not signed by a member: check that you passed `derivation_origin`, then go back to M3. ### M6. Name the app, and pass configuration Step 2's `__META_*` variables, and `PROXY_CANISTER_ID` from Step 5, are canister environment variables. With no `icp.yaml` to carry them, you set them yourself, and **when** matters: - **A variable the code reads at init or upgrade** (`PROXY_CANISTER_ID`, a key name, any configuration) must be set **before** the `install_code` that reads it. Otherwise init sees it missing, and traps or bakes in a fallback that a later upgrade does not undo. Put it in `create_canister`'s `settings` (M5, step 1), or set it with `update_settings` between steps 1 and 2. Before an upgrade or reinstall that should see a new value, set that value first. - **Display-only metadata** (`__META_*`) is read by the console, not by your code, so it can follow at any time. `__META_BASE_URL` needs the canister id, so it comes after step 1 anyway. Either way it is `update_settings` through `proxy`, with `args` encoding: ```candid (record { canister_id = principal ""; settings = record { environment_variables = opt vec { record { name = "__META_PROJECT"; value = "My App" }; record { name = "__META_NAME"; value = "App" }; record { name = "__META_MAIN_CANISTER"; value = "true" }; }; }; }) ``` The list **replaces** the canister's whole set of variables, so send all of them every time. The rules for their values are in Step 2. ### M7. Verify - `canister_status` through `proxy`, with `args` encoding `(record { canister_id = principal "" })`, shows `status = variant { running }` and the installed `module_hash`. - A canister that serves HTTP is reachable at `https://.icp.net`. On an all-in-one engine it is under the engine's own domain instead: the operator's guide names which. - The canister appears on the engine's **Your apps and services** page in the console. Report the canister id(s), and the URL if any, back to the user. ## Step 1 — Link the CLI to your engine identity (CLI route, once per machine) The CLI must sign as the **same identity that administers the engine** — that is the principal you log in to the console with. ### Step 1.0 — First determine WHERE the CLI runs relative to the browser `icp identity link web` completes the sign-in via a redirect to `http://127.0.0.1:` **on the machine where the CLI runs**. The browser in which the user completes the Internet Identity sign-in must be able to reach that loopback address. Determine the environment before linking: - **CLI and browser on the same machine, with network** (local development, or a terminal-integrated agent on the user's own machine) → use the normal link flow below. - **CLI in a remote or isolated sandbox, with network** (the agent runs in the cloud; the user's browser is on a different machine) → the normal flow **cannot** work: the sign-in URL carries a `callback=http://127.0.0.1:` bound to the sandbox, the user's browser resolves `127.0.0.1` to its *own* machine, and the delegation never reaches the CLI. Later commands then fail with authorization errors. If you have the ICP MCP tools, stop here and use the ICP MCP route. Otherwise ask the user to switch to a local session, or to add the ICP MCP connector (see "Choose the Deploy Route First"). Use the **delegation handoff** below only if they can do neither. - **CLI shell with no network at all** (e.g. a sandboxed device bridge on the user's own machine: DNS blocked, HTTPS requests fail, writes limited to `/tmp`) → **no** `icp` network command can run there — not the link, and not `icp deploy` either. The delegation handoff does not help: it only moves signing authority, not network access. Do not retry, tunnel, or proxy. Prepare the project and hand the user **one script** to run in their real terminal — see "No-network CLI host" below. When in doubt, probe before linking: `curl -sI https://` failing (or DNS not resolving) from the CLI shell means the no-network case. **Never** present a sandbox `127.0.0.1` URL to the user as something to open in their browser — it is unreachable from their machine. And do not invent a headless flag on `icp identity link web`: as of icp-cli 1.0.2 it has none (confirm with `icp identity link web --help`). ### Delegation handoff (CLI host and browser on different machines) `icp identity delegation` transfers signing authority from an identity linked on the **user's** machine to a session key on the **CLI host**, without the browser ever reaching the CLI host. It requires `icp` installed on the user's machine too, and exists in icp-cli 1.0.x — verify with `icp identity delegation --help` on both machines. If the user's machine has `icp` and you can run commands there, the simplest path is to run this whole skill there instead; otherwise: 1. **On the CLI host (sandbox)** — create a pending identity with a fresh session key: ```bash icp identity delegation request ``` It prints the session **public** key as a PEM to stdout. Give that PEM block to the user. (If the default `--storage keyring` fails in a headless sandbox, retry with `--storage plaintext`.) 2. **On the user's machine** — the user links there if not already linked (`icp identity link web --app ` — the normal flow works locally), saves the PEM to a file, and signs a delegation to it: ```bash icp identity delegation sign --identity --key-pem session-key.pem --duration 8h > delegation.json ``` `--duration` takes e.g. `30m`, `8h`, `1d`; optionally `--canisters ` restricts the delegation. The user sends `delegation.json` back. If `sign` fails with `delegation for identity has expired or will expire within 5 minutes`, the local web session has lapsed — run `icp identity reauth ` (the normal browser flow, which works locally) and retry. 3. **On the CLI host** — complete the pending identity and activate it: ```bash icp identity delegation use --from-json delegation.json icp identity default icp identity principal # must print the user's console principal ``` Treat `delegation.json` as a **time-limited credential**: whoever holds the sandbox's session key can sign as the user's console principal until it expires. Keep the duration short and re-run the handoff when it lapses. ### No-network CLI host — hand the user one script If the CLI shell cannot reach the network, the user's real terminal is the deploy machine — and because their terminal and browser share a loopback there, the **normal** link flow works; no delegation handoff is needed. Your job shifts to preparation: 1. Get the built project into a directory the user's terminal can reach. 2. Write one script at the project root that does the whole network-bound sequence — adapt this template (fill in the real identity name, console domain, and subnet id; do not leave placeholders): ```bash #!/usr/bin/env bash set -euo pipefail icp --version icp identity list | grep -E '^\*? * ' >/dev/null || icp identity link web --app icp identity default icp deploy -e ic --subnet ``` 3. Ask the user to run it in their terminal, complete the Internet Identity sign-in when the browser opens, and paste the output back. 4. Verify from the pasted output (canister ids, frontend URL) and continue — a re-deploy for the Step 2 `__META_*` variables goes through the same script. ### Normal link flow (CLI and browser share a loopback) First check what already exists: ```bash icp identity list # names + principals; * marks the active identity ``` The list does **not** show which console (if any) an identity was linked against — that cannot be determined from the CLI. Decide like this: - **Only `anonymous` (or plain local identities) listed** — no web-linked identity exists; run the link command below. - **An identity the user recognizes as their engine identity** (by name or principal) — set it active (below) and skip to Step 2. - **Unsure** — ask the user, or simply relink under a new name; linking again is cheap and safe. To link, run this, substituting a name the user picks — `` is any local label, not a fixed value (do not hardcode something like `my-engine-admin`); reuse the **same** name in every command below: ```bash icp identity link web --app ``` - `` is the host of the console origin, with no scheme, port or path: `opencloud.org` for the default console, `beta.opencloud.org` for `https://beta.opencloud.org`. The console derives its principal from the host it serves, so this is the domain to name. Do not take it from `/.well-known/ii-derivation-origin`: that file serves the ICP MCP route and can name another host. - Never omit `--app`. Without it, Internet Identity derives the principal for `cli.id.ai`, which is **not** your console, and the engine rejects every deploy as unauthorized. - Do not use `--auth ` for the OpenCloud console. It reaches the same principal, but through the console's own `/cli` page, so the user signs in on two screens instead of one. Use `--auth ` (no `--app`) only when the user says their console signs in with its own Internet Identity rather than `id.ai`, as a test deployment does. - The command first waits at a **"Press Enter to log in"** prompt before anything happens. Run it interactively when you can; in a non-interactive shell (e.g. a background process) pipe a real newline: ```bash printf '\n' | icp identity link web --app ``` Do **not** redirect stdin from `/dev/null` — the bare EOF does not satisfy the prompt, and the command sits on "Press Enter to log in" indefinitely with no browser ever opening. - After Enter it opens a **browser tab**. The **user** completes the Internet Identity sign-in there. Wait for them to confirm before continuing — you cannot complete the sign-in for them. - On first use, id.ai can stop at a **"CLI access disabled"** screen. That is the expected first run, not an error. Tell the user to turn on **CLI access** for their identity in the Internet Identity settings, then run the link command again from the start: the old sign-in URL is single-use. See the `agent-web-identity` skill, Pitfall 1. - `--app` must be the **exact** console host, e.g. `opencloud.org`. Another domain derives a *different* principal, and the engine will reject the deploy as unauthorized. - This is a **one-time, per-machine** step. Then make it the active identity and verify: ```bash icp identity default icp identity default # prints the active identity name icp identity principal # prints the principal the deploy will sign as ``` ## Step 2 — Name the app (and give it an icon) in the console (recommended) By default, CLI-deployed canisters appear on the engine console's **Your apps and services** page as bare rows labelled only by their principal id. A set of **canister environment variables** makes the console group them into a single named application with readable per-canister labels, an "Open" button, and an icon. Set them once in your project config: - `__META_PROJECT` — the application name. Canisters that share the **same** value are grouped into one named app, so set an identical value on every canister of the app. - `__META_NAME` — the per-canister display label (e.g. `Backend`, `Frontend`). - `__META_MAIN_CANISTER` — the literal string `"true"` on exactly one canister (the entry point, usually the frontend/asset canister). This marks the app's **main canister**: the console reads `__META_BASE_URL` and `__META_ICON_PATH` only from it, and the "Open" button targets it. - `__META_BASE_URL` — an **absolute `https://` URL**, set on the main canister (e.g. the frontend canister's URL `https://.icp.net`, or a custom domain). When present and valid, it is the URL the "Open" button opens; when absent or not `https`, the "Open" button falls back to the main canister's gateway URL. It is also the base that `__META_ICON_PATH` resolves against. - `__META_ICON_PATH` — the path to the app icon, resolved against `__META_BASE_URL` to form the icon the console renders (e.g. `/favicon.svg` → `https:///favicon.svg`). Set it on the **main** canister, alongside `__META_BASE_URL`. The icon and "Open" link are read **only from the main canister** (the one marked `__META_MAIN_CANISTER: "true"`) — `__META_BASE_URL` / `__META_ICON_PATH` on any other canister are ignored. On the ICP MCP route there is no project config: set the same variables with `update_settings` (M6). On the CLI route, set them under each canister's `settings.environment_variables` — this is valid alongside a recipe. With per-canister `canister.yaml` files: ```yaml # frontend/canister.yaml name: frontend recipe: type: "@dfinity/static-site@v0.4.3" configuration: build: - npm install - npm run build dir: dist settings: environment_variables: __META_PROJECT: "My App" __META_NAME: "Frontend" __META_MAIN_CANISTER: "true" __META_BASE_URL: "https://.icp.net" __META_ICON_PATH: "/favicon.svg" ``` ```yaml # backend/canister.yaml name: backend recipe: type: "@dfinity/motoko@v5.0.0" # v5 reads main/candid from mops.toml ([canisters.backend]) — see the icp-cli skill settings: environment_variables: __META_PROJECT: "My App" __META_NAME: "Backend" ``` For a single inline `icp.yaml` (canisters defined there directly), put the same `settings.environment_variables` block under each canister entry. Note the inline form: `canisters` is an **array** of `{name, recipe, settings}` items, not a map keyed by canister name: ```yaml # icp.yaml — canisters defined inline canisters: - name: frontend recipe: # … as in the canister.yaml example above settings: environment_variables: __META_PROJECT: "My App" __META_NAME: "Frontend" __META_MAIN_CANISTER: "true" __META_BASE_URL: "https://.icp.net" __META_ICON_PATH: "/favicon.svg" - name: backend recipe: # … as in the canister.yaml example above settings: environment_variables: __META_PROJECT: "My App" __META_NAME: "Backend" ``` Notes: - icp-cli **merges** these with the `PUBLIC_CANISTER_ID:` variables it injects automatically at deploy time — the asset canister keeps serving and the app keeps working. (Verified against icp-cli 0.3.0.) - All values are strings; `__META_MAIN_CANISTER` must be the exact string `"true"`. - They are applied during `icp deploy` (the "Setting environment variables" step). After deploy, confirm with `icp canister settings show -e ic`. Icon specifics (the console builds the icon as `__META_BASE_URL` + `__META_ICON_PATH`): - **Both** must be present and **on the main canister** for an icon to appear — there is no fallback. `__META_ICON_PATH` alone does nothing. - `__META_BASE_URL` must parse as an absolute **`https://`** URL. A bare host, an `http://` URL, or a `data:` / `javascript:` value is rejected: the icon then does not render, and the "Open" button falls back to the main canister's gateway URL (it does not disappear). (The console validates the scheme before using it.) - `__META_ICON_PATH` is a **path to an asset your frontend actually serves** (e.g. `/favicon.svg`), not an inline image. The resolved URL is rendered as an `` `src`, so it must return an image. Do **not** put a `data:` URI here: engine env values are length-capped (≤128 chars observed), so it would not fit, and the field is a path by design. - The frontend canister's id is only known **after** the first deploy. The usual flow is: deploy once, read the frontend canister id from the output, set `__META_BASE_URL` to `https://.icp.net` (and `__META_ICON_PATH`), then re-deploy to apply. If you control a custom domain for the app, you can set it up front instead. ### Pin the Internet Identity derivation origin (if the app signs users in) Internet Identity derives a principal **per origin**. An app reached at both its canister address and a custom domain signs the same person in as two different users. The engine console names the app's **canister address** as the origin to derive from. It cannot be renamed or removed, so it survives adding, changing, or dropping a custom domain. It is the address of the canister that **serves your frontend** (the asset/static-site canister the browser loads the app from), built from that canister's id: ``` https://.icp.net ``` That is usually the canister you marked `__META_MAIN_CANISTER: "true"`, but that flag is a console display setting, not a guarantee. If you marked a backend canister, still derive from the frontend canister. A backend canister cannot be a derivation origin: the browser is never on it, and it cannot serve the `.well-known/ii-alternative-origins` file Internet Identity fetches from that origin to validate the claim. Build the value from the canister id, **not** from `__META_BASE_URL`. The two match only while `__META_BASE_URL` still points at the canister address. Pointing it at a custom domain is normal and supported (see the icon notes above), and the two then differ. A custom domain is the one value that must never become the derivation origin. **Do this before the app has users, not after.** A domain that has already collected sign-ins cannot be repointed at a derivation origin without orphaning every account created under it. If the app might ever get a custom domain, set `derivationOrigin` on the first deploy even while the canister address is the only origin — it costs nothing then and cannot be applied retroactively without losing accounts. For the mechanics — the `derivationOrigin` option and the `.well-known/ii-alternative-origins` file, including the `_headers` entry the `@dfinity/static-site` recipe needs — load the **`user-sign-in`** skill. Caffeine apps are the exception: Caffeine owns their address, so it is not the app's to derive from. The console withholds the canister-address row for them. ### Version metadata (recommended) Embed build provenance into each canister's wasm so tooling and the console can show what version is running (console support is rolling out; the metadata is already readable — see the verify note below). Add this **by default on every deploy** — do not wait for the user to ask. All official recipes (motoko, rust, static-site, asset-canister, prebuilt) accept a `metadata` list under the recipe `configuration`; each entry is baked into the wasm as a custom section. Values are interpolated into a shell command at build time, so `$(…)` command substitution works. (Verified by live builds against `@dfinity/motoko` v4.1.0 and v5.0.0 on icp-cli 1.0.2.) **Git project** (check first: `git rev-parse HEAD` succeeds): ```yaml recipe: type: "@dfinity/motoko@v5.0.0" configuration: metadata: - name: service:git:sha value: $(git rev-parse HEAD)$(git diff --quiet HEAD 2>/dev/null || echo +dirty) - name: service:git:origin value: $(git remote get-url origin) - name: service:git:updated_at value: $(git log -1 --format=%cI) - name: service:version value: $(node -p "require('./package.json').version" 2>/dev/null || echo 1.0.0) ``` **Non-git project** — the git substitutions above do **not** fail the build; they silently bake garbage (`service:git:sha` becomes the literal `+dirty`, `service:git:origin` comes out empty). Use only an explicit version, and bump it on each subsequent deploy: ```yaml metadata: - name: service:version value: "1.0.0" ``` Notes: - Use these exact names (`service:git:sha`, `service:git:origin`, `service:git:updated_at`, `service:version`) — they are the agreed convention the console will read; differently named entries will not be picked up. - Prefer command results over literals where possible: `+dirty` on the sha flags uncommitted changes, so a deploy is traceable to its exact source state. - Values must be **deterministic** for a given source tree: sha, origin, the last commit's date, a version string. Never embed a build time (`$(date)`) or other build-time-varying values. The commit date (`%cI`) is allowed because it is a property of the commit, not of the build — but note it means "code last changed", not "last deployed": deploying an old commit shows the old date. The deploy time itself comes from the canister history the network records automatically. - If the project has no `package.json` (or no version field), the fallback `1.0.0` applies; replace it with the project's real versioning scheme when one exists. - The sections are injected as `icp:private`, readable by the canister's controllers (you, and the console acting as you) via read_state — no canister call needed. Verify after deploy, with the linked identity active: `icp canister metadata service:git:sha -e ic`. ## Step 3 — Deploy to the engine's subnet (CLI route) From the project root: ```bash icp deploy -e ic --subnet ``` - `-e ic` targets mainnet (the engine runs on an IC subnet); `--subnet ` pins the deploy to **your engine's** subnet. Confirm the exact flags with `icp deploy --help` before running if unsure. - Deploying consumes capacity on the engine; make sure the engine has room. **Alternative: packaged upload.** If the project is distributed as a built `.icp` package and a direct `icp deploy` is not available, the user can upload the bundle instead: engine → **Your apps and services** → **Upload a bundle**, which walks through uploading the `.icp` bundle. The page's other button, **Build with agents**, gathers the other ways in: a coding agent, Caffeine, the CLI instructions this skill automates, and OpenSaaS for ready-made apps. ## Step 4 — Verify - The `icp deploy` output reports the deployed canister ids. - The canisters appear on the engine's **Your apps and services** page in the console; each canister's detail view offers an "Open in browser" link. - If you set the metadata in Step 2, the canisters are grouped under your `__META_PROJECT` name with their `__META_NAME` labels, and the main canister shows an "Open" button — instead of bare principal rows. With `__META_BASE_URL` + `__META_ICON_PATH` set, the app also shows its icon (allow for a short console cache delay). - A frontend (asset) canister is served at `https://.icp.net`. Report the deployed canister ids (and the frontend URL, if any) back to the user. ## Step 5: Deploy a proxy canister (only if the app needs chain-key services) Skip this step unless the app calls **threshold ECDSA or Schnorr** (Bitcoin, Ethereum), **vetKD / VetKeys**, the **exchange-rate canister** (XRC), the **Bitcoin API**, or the **EVM / SOL RPC** canisters: a console proxy relays nothing else for the engine's canisters (the exact list is in `cloud-engine-canisters`). Everything else (the app's own execution, storage, messaging, and HTTPS outcalls) is free on an engine and needs no proxy at all. Those services live on other subnets and charge cycles per call, and an engine canister can neither hold cycles nor send a cycle-bearing message across the engine boundary. A **proxy canister** on a normal Application subnet makes the call on its behalf and pays from its own balance. If you are writing or deploying such an app and do not have the proxy id yet, ask for it now (What You Need, item 3) rather than deploying with a placeholder: the first proxied call would fail. ### Which proxy Two different canisters can play this role, and picking the wrong one produces a working-looking setup that fails at the first call: | | **Console proxy** | **Self-deployed proxy** | |---|---|---| | Deployed by | The engine's **owner**, from the console | You, with `icp` | | Authorized callers | Every canister on the engine's **subnet** (checked with the NNS registry), plus its controller | **Controllers only** | | Your engine canisters may call it | Yes, automatically | Only after you add each one as a controller | | What it relays for them | Only chain-key, Bitcoin and exchange-rate / RPC services (list in `cloud-engine-canisters`) | Anything | | Your CLI identity may call it | **No** (rejected as `UnauthorizedUser`) | Yes: you are a controller | | Threshold-key derivation | Isolated per calling canister | No isolation | | Funded with | The engine's balance, automatically (no card) | Cycles you hold (`icp cycles mint`) | - **App code calling chain-key services → the console proxy.** It is the one that admits your engine's canisters without per-canister configuration. - **You calling something from the CLI** (`icp canister call --proxy`, `icp deploy --proxy`, canister-only management methods like `canister_info` or `raw_rand`) **→ your own proxy.** The console proxy cannot serve this: it rejects ingress from any non-controller principal, and your CLI identity is not one. They are not substitutes, and they derive **different keys**: see the derivation warning in `cloud-engine-canisters` before switching an app from one to the other. ### Console proxy: the engine owner deploys it (a console action, not a CLI one) Only the engine's **owner** can deploy one, and only from the console. There is no `icp` command for it, and nothing an agent can call creates one: the console endpoints behind the button authenticate with a browser session cookie minted by the Internet Identity login. Hand the user these steps and wait for the proxy canister id: 1. Open the engine in the console → **Integrations** in the engine's sidebar → the **Proxy canisters** card. 2. **Deploy a proxy**, then **Deploy proxy** in the dialog. There is no amount to choose and no card is charged: the proxy is created on a normal Application subnet out of the engine's balance, starting with a few dollars' worth of cycles. 3. Copy the **proxy canister id** from the card's table (it opens after a deploy; otherwise expand it with the **N deployed** toggle). That id is what the app calls. The deploy is refused while the engine is not serving, or when the engine's balance has too little free to cover the proxy's first cycles: the owner adds funds to the engine, then retries. **How it stays funded.** Every few minutes while its balance is below a low threshold, the proxy asks for a top-up, which is sent out of the engine's balance: capped per hour, and never out of what the engine owes for its nodes. There is no **Top up** button and no automatic top-up setting for it; its row shows the balance and the cycles it has drawn so far. If it runs dry anyway, fund the engine (see "Paying for an engine" below). Also on that table: **Refresh balance** (a live read, since the displayed figure is cached) and **Delete proxy** (stops and deletes the canister; its unspent cycles, less the small reserve a canister keeps to run, go back to the engine's balance). An engine may have **more than one** proxy ("Deploy another proxy"). Each has its own balance (all refilled from the same engine balance) and, for a signing app, its own key namespace. ### Wire the proxy id into the app The app needs the id at runtime. Pass it as a canister environment variable rather than hardcoding it in source, so the same code can run against a local mock and against the engine: ```yaml settings: environment_variables: PROXY_CANISTER_ID: "" ``` On the ICP MCP route, set it with `update_settings` (M6). Read it in the canister the same way as any other environment variable, and treat it as **permanent configuration**: for an app that derives threshold keys, changing this value changes every address the app owns. ### Self-deployed proxy: the CLI path For proxying *your own* calls. This one is the upstream `dfinity/proxy-canister`, deployed from a template: ```bash icp new my-proxy --subfolder proxy # pre-built wasm, no init args cd my-proxy icp deploy -e ic # NOT --subnet : see below export PROXY_ID=$(icp canister status -e ic --id-only proxy) ``` Fund it, and check on it, with the cycles ledger: ```bash icp cycles balance -e ic # what you hold icp cycles mint --icp 1 -e ic # ICP -> cycles, if you need more icp canister top-up "$PROXY_ID" --amount 5t -e ic icp canister status "$PROXY_ID" -e ic # the proxy's own balance ``` Then pass it to any command that needs cycles or a canister-only management method: ```bash icp canister call my-canister charge_me '()' -e ic --proxy "$PROXY_ID" --cycles 1_000_000_000_000 icp deploy -e ic --proxy "$PROXY_ID" ``` Three things to get right: - **Do not deploy it onto the engine's subnet.** A proxy on a `CloudEngine` subnet is useless: it holds 0 cycles and cannot send a cycle-bearing message either. Omit `--subnet` (Step 3's engine-subnet flag is for your app, not for this) so it lands on a normal Application subnet. - **It authorizes controllers only.** For an *engine canister* to call it, that canister's principal must be added as a controller (`icp canister settings update "$PROXY_ID" --add-controller -e ic`), one call per canister, repeated whenever a canister is added. This is the maintenance burden the console proxy exists to remove. - **It does not isolate key derivation.** Any authorized caller can request any derivation path, and the keys it produces differ from the console proxy's. Do not point a signing app at one casually. ## Paying for an engine: which balance Two balances exist, they are funded differently, and the app's own canisters have neither. Do not "top up the canister" on an engine without first establishing which of these is meant: | Balance | What it pays for | How it is funded | What happens when it empties | |---|---|---|---| | **Engine balance** | The engine itself (its nodes, day by day), and the top-ups of its console proxies | **Add funds** on the engine's **Billing** page (charged to the card on file), and automatic top-ups that charge the card about a week before the balance would run out | The engine is **deleted**, with everything on it: not reversible, so treat a low-runway warning as urgent. An engine whose automatic top-up keeps failing is **halted**, and runs again once a payment lands | | **Proxy cycle balance** | Only the calls the proxy relays (signing, vetKD, XRC, Bitcoin API, EVM/SOL RPC) | A console proxy refills itself from the engine balance (Step 5); a self-deployed one takes `icp canister top-up` | Relayed calls fail with `InsufficientCycles`; the proxy freezes rather than being deleted, and recovers on a later top-up | A console proxy's top-ups come out of the engine balance, so a busy proxy shortens the engine's runway, though never by what the engine owes for its nodes. The app's own canisters have **none** of these: they hold 0 cycles by design and cannot be topped up. A "0 cycles" reading on an engine canister is normal (see `cloud-engine-canisters`, pitfall 5). ## Code that runs on the engine A cloud engine runs on a **`CloudEngine` subnet** with protocol-level call rules that differ from normal Application subnets: engine canisters hold 0 cycles and must **never attach cycles** to any call, **cross-subnet calls must be bounded-wait**, HTTPS outcalls are made directly and free, and cycle-bearing cross-subnet targets (exchange-rate XRC, threshold ECDSA/Schnorr, vetKD) go through the engine's funded **console proxy canister**. Before writing or debugging any canister code that will run on the engine, load the **`cloud-engine-canisters`** skill — it has the rules, the proxy interface, and the pitfalls. ## Common Pitfalls 1. **Sign-in not completed.** Running `icp identity link web …` but not finishing the Internet Identity sign-in in the browser leaves the CLI unlinked; later commands fail with authorization errors. Re-run and wait for the user to confirm the browser flow finished. If no browser ever opened, the command is stalled at the "Press Enter to log in" prompt — relaunch with a piped newline, `printf '\n' | icp identity link web …`, never `< /dev/null` (see Step 1). If the CLI runs in a remote sandbox, re-running can never complete — see Pitfall 10 and the delegation handoff in Step 1.0. 2. **Wrong or missing `--app` domain.** Any domain other than the console host, or no `--app` at all, derives a different principal, and the engine rejects the deploy as not authorized. Relink with the exact domain (Step 1). If the deploy is rejected as unauthorized after linking with the default `--app opencloud.org`, ask the user for the exact URL they sign in with and relink with its host. 3. **Guessing the subnet id.** Never invent it: the deploy fails or targets the wrong subnet. It is on the engine's **Settings** page in the console; ask the user. 4. **Deploying with the anonymous identity.** The default local identity is anonymous and is not the engine admin. You must link and `icp identity default ` first. 5. **Using `dfx`.** This ecosystem uses `icp`, never `dfx`. The correct sequence is `icp identity link web --app ` (Step 1), then `icp deploy -e ic --subnet ` (Step 3). See the `icp-cli` skill. 6. **Skipping the app metadata.** Without `__META_PROJECT` (Step 2), the canisters still deploy and work but render as bare, unnamed principal rows in the console. Setting `__META_*` is what produces a named app with labelled canisters and an "Open" button. 7. **Wrong `__META_MAIN_CANISTER` value.** It is matched as the exact string `"true"`. A boolean, `"True"`, or marking more than one canister means no (or the wrong) "Open" button. Mark exactly one entry-point canister. 8. **Inventing an icon variable.** The icon variable is `__META_ICON_PATH` (a path resolved against `__META_BASE_URL`). Do not guess `__META_ICON`, `__META_LOGO`, or `__META_ICON_LINK` — they are ignored, so the icon silently never appears. 9. **Icon set on the wrong canister, or without a base URL.** The icon is read only from the **main** canister and needs **both** `__META_BASE_URL` (a valid absolute `https://` URL) and `__META_ICON_PATH`. Setting the icon path on a side canister, omitting the base URL, or giving a non-https / `data:` base means no icon renders. (The "Open" button still works — it falls back to the main canister's gateway URL — so a bad base URL costs the icon and the custom Open URL, not the button.) 10. **Assuming the browser and CLI share localhost.** `icp identity link web` returns the delegation to `127.0.0.1:` on the CLI host. If the CLI runs in a remote sandbox while the user's browser is on a different machine, the sign-in never completes and later commands fail with authorization errors — no amount of re-running the link fixes it. With the ICP MCP tools, use the ICP MCP route instead. Without them, see Step 1.0: prefer a local session, where the browser and CLI share a loopback, or the ICP MCP connector, and use the delegation handoff (`icp identity delegation request` / `sign` / `use`) only when the user has neither option. Ask before you build in the sandbox, not after. 11. **Expecting the delegation handoff to fix a missing network.** The handoff moves signing authority, not connectivity — `icp deploy` still needs the network from the shell that runs it. If the CLI shell has no network at all (a sandboxed device bridge: DNS blocked, HTTPS fails), no `icp` network command can run there, link or deploy. Do not offer to "do the rest" from that shell and do not tunnel — hand the user one script for their real terminal (see "No-network CLI host" in Step 1.0), where the normal link flow works because terminal and browser share a loopback. 12. **Build timestamps in wasm metadata.** Metadata is baked into the wasm and must be deterministic — a build time (`$(date)`) changes every build even with identical source, breaking reproducibility and changing the module hash on every deploy. The deterministic alternative is the last commit's date, `service:git:updated_at` = `$(git log -1 --format=%cI)` — a property of the source tree, not the build. The deploy time itself comes from the canister history recorded by the network, never from metadata. 13. **Git metadata substitutions in a non-git project.** Outside a git repository, `$(git rev-parse HEAD)` does not fail the build — it silently bakes garbage: `service:git:sha` becomes the literal `+dirty` and `service:git:origin` comes out empty. Check for a git repo first (`git rev-parse HEAD` succeeds); if there is none, set only `service:version` with an explicit value (or `git init` and commit before deploying, if version control is wanted anyway). 14. **Letting an engine app collect sign-ins before pinning a derivation origin.** Internet Identity principals are per-origin, so adding a custom domain later turns every existing user into a stranger at the new address — and the fix cannot be applied retroactively without orphaning the accounts already made under the old origin. On the first deploy of any app that uses II, set `derivationOrigin` to the address of the canister that serves the frontend, built from its canister id (`https://.icp.net`), even when that is currently the app's only origin. Do **not** copy `__META_BASE_URL`: it is allowed to point at a custom domain, and a custom domain is exactly what must not become the derivation origin. See the `user-sign-in` skill for the `.well-known/ii-alternative-origins` half. 15. **Trying to deploy or fund the console proxy from the CLI or an API.** There is no `icp` command for it, and the console endpoints behind the buttons authenticate with a browser-session cookie from the Internet Identity login (no token auth), so an agent cannot drive them. Only the engine's owner can deploy one. Hand the user the console steps (engine → **Integrations** → **Proxy canisters** → **Deploy a proxy**) and wait for the proxy canister id. It needs no funding step: it is paid from the engine's balance. An agent *can* do the whole self-deployed-proxy path unattended, but that is a different canister with different authorization (Step 5). 16. **Deploying a self-deployed proxy onto the engine's subnet.** Reusing Step 3's `--subnet ` puts the proxy on the `CloudEngine` subnet, where it holds 0 cycles and may not send cycle-bearing messages either, so it cannot do the one thing a proxy is for. Omit `--subnet` so it lands on a normal Application subnet. 17. **Expecting a self-deployed proxy to accept calls from engine canisters.** It authorizes **controllers only**. An engine canister calling it gets `UnauthorizedUser` until that canister's principal is added with `icp canister settings update --add-controller -e ic`, and again for every canister added later. The console proxy authorizes every canister on the engine's subnet instead, which is why it is the right one for app code. 18. **Deleting a proxy that a signing app derives keys from.** The delete button sends the unspent cycles back to the engine's balance, which makes it look like a tidy-up. It is not: threshold keys are derived from the proxy's own principal, so deleting it (or repointing the app at another proxy) changes every Bitcoin/Ethereum address the app owns and strands any funds at the old ones. See `cloud-engine-canisters` for the derivation rules before touching a proxy that an app already signs with. 19. **Confusing the balances.** "The canister is out of cycles" means something different for each: an engine canister holds 0 cycles by design and cannot be topped up, the *engine's* balance running low is fixed with **Add funds** on its Billing page, and `InsufficientCycles` from a relayed call is the *proxy's* balance (for a console proxy, which refills from the engine's balance, that again means funding the engine). Establish which one before topping anything up, and note that the engine's balance running out deletes the engine. 20. **Deploying a proxy-dependent app without the proxy id.** An app that signs, derives vetKeys, reads exchange rates or calls the Bitcoin API or EVM/SOL RPC deploys fine with a placeholder, a guessed id or an id from another engine, then fails on its first proxied call (`UnauthorizedUser`, or keys and addresses that belong to someone else's proxy). Ask for the id before deploying (What You Need, item 3). If the engine has none, the owner deploys one from the console (Step 5); never stand in a self-deployed proxy for it. 21. **Picking the wrong route.** In a sandbox (a web or mobile chat, or a cloud coding session) that has the ICP MCP tools, asking the user to switch to a local session, or trying `icp identity link web` or the delegation handoff, wastes a round trip the connector makes unnecessary: use the ICP MCP route. The reverse holds too: in a local session, link the CLI and deploy with it even when the connector is also available, because the CLI can upload an asset canister's files and the connector cannot. 22. **Assuming the connector signs as the console principal.** Internet Identity principals are per-origin, and at the engine the connector signs as the principal derived for the engine's platform domain. It is not the user's console principal and not a CLI identity, so a `proxy` call answers `UnauthorizedUser` until that principal is an engine member, even for the engine's owner. Read it with `get_app_principal` and hand the user the invite link (M3); you cannot add it yourself. A `canister_update_call` without `derivation_origin` gets the same answer for a different reason: it runs anonymously, so pass the derivation origin `open_app` returned on every call. 23. **A Questions-only connector session.** With the **Questions only** access level, reads work and every state-changing call is rejected by the network, `create_canister` and `install_code` included. This is not an engine permission problem, so the invite link does not fix it. Ask the user to reconnect with **Actions & questions** (M0). 24. **Calling the management canister directly, or confusing the two proxies.** The connector refuses calls to `aaaaa-aa`; deploys go through the engine-operator's `proxy` method (M5). That method is not the chain-key proxy canister of Step 5, and the console proxy canister cannot create or install canisters: it relays only chain-key, Bitcoin and exchange-rate / RPC services. 25. **Creating a canister without listing the engine-operator as a controller.** `create_canister` through `proxy` always adds you, but the operator only when you list it in `settings.controllers`. Without it, `proxy` can no longer reach the canister (no install, no settings), and the owner cannot remove it with `deleteCanisters` either. List the operator in the create call (M5, step 1). 26. **Textual Candid in `proxy`'s `args`.** `args` is a `blob` holding the **binary** Candid encoding of the management method's argument (bytes starting with `DIDL`), and `result` comes back the same way. Passing the textual `(record { … })` as `args` makes the management canister fail to decode the argument. Encode it with a Candid library first (M5). 27. **Expecting the connector to finish a deploy that needs calls into the new canister.** The connector calls only canisters an app declares, and the engine's manifest declares only its operator. It can install your wasm through `proxy`, but it cannot call the canister you installed, so it cannot upload an asset canister's files. Ship configuration in the init argument or environment variables, or use the CLI route for such an app. 28. **Serving a custom domain from certified-assets older than 0.4.3.** For each app canister with a custom domain, the engine writes `/.well-known/ic-domains` (the HTTP gateway needs it to serve the domain) and `/.well-known/ii-alternative-origins` (Internet Identity needs it to accept the domain). It writes them with certified-assets' `upload_asset`, which arrived in 0.4.3. On an older canister the console warns that the engine can't write these files, and the domain does not work. Pin `@dfinity/static-site@v0.4.3` or newer. To fix an app that is already deployed, bump the recipe and run `icp deploy -e ic`. If the sync then stops with `assets canister version mismatch`, run `icp canister install --mode upgrade -e ic` (v0.4.x to v0.4.3 is a patch, so the state stays), then `icp deploy -e ic` again. From v0.3.x the bump is breaking: see the `static-site` skill, pitfall 11. The engine replaces whatever the app ships at these two paths, so do not build them into `dir`. List both in a `_preserve` file at the root of `dir`: without it, every deploy deletes them until the engine writes them again (within 10 minutes). ## Additional References - Load `cloud-engine-canisters` for the call rules for code that runs on the engine: never attach cycles, bounded-wait cross-subnet calls, direct HTTPS outcalls, and the console proxy for cycle-bearing cross-subnet targets (XRC, threshold signing, vetKD). Load it before writing or debugging engine canister code. - Load `icp-cli` for general icp CLI usage (`icp.yaml`, recipes, environments, bindings, identities). Load it for anything beyond this cloud-engine deploy flow — in particular when the project does not build or package yet. - Load `user-sign-in` for details of the Internet Identity sign-in that Step 1 triggers in the browser. - Load `service-discoverability` for the `/.well-known/ic-architecture` manifest that decides which canisters the ICP MCP connector may call, including how an app you deployed can declare its own canisters, and the operator terms that publishing it accepts. - ICP MCP connector setup (ChatGPT plugin, Claude, custom connector URL): https://mcp.internetcomputer.org/. - Load `vetkeys` for what vetKD is and how VetKeys are used, once a proxy is in place: its call code targets a normal subnet, so see `cloud-engine-canisters` for the proxied form an engine needs. - Load `cycles-management` for cycles on ordinary (non-engine) canisters: balances, freezing thresholds, and ICP-to-cycles conversion via the CMC. --- ## Encrypted Maps --- name: encrypted-maps description: "Add access-controlled, end-to-end encrypted key-value storage to a canister with the vetKeys EncryptedMaps library (ic-vetkeys for Rust and Motoko backends, @icp-sdk/vetkeys for the frontend). Values are encrypted client-side under vetKeys and shared between principals with per-user access rights (Read, ReadWrite, ReadWriteManage). Use when building a password manager, encrypted notes, a secure vault, or any app that stores and shares encrypted data on-chain. Start here for encrypted storage; escalate to the vetkeys skill only for BLS signatures, custom IBE, or timelock encryption." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2" metadata: title: Encrypted Maps category: Security --- # Encrypted Maps (vetKeys) `EncryptedMaps` is a ready-made vetKeys library for **access-controlled, end-to-end encrypted key-value storage**. Each map is owned by a principal and holds `mapKey → value` entries; **values are encrypted on the client** under a vetKey and the canister only ever stores ciphertext. Owners share maps with other principals at three access levels. This is the default starting point for any encrypted-storage app (password manager, encrypted notes, vault). Use the **`vetkeys` skill** instead when you need lower-level primitives: identity-based encryption (IBE), threshold BLS signatures, timelock encryption, or your own symmetric-key scheme. | Layer | Rust | Motoko | Frontend | |-------|------|--------|----------| | Package | `ic-vetkeys` **0.9** | `ic-vetkeys` **0.6** (moc ≥ 1.13.0, core ≥ 2.6.1) | `@icp-sdk/vetkeys` **0.7** | | Backend | `export_encrypted_maps_canister!` macro | `EncryptedMapsCanister` mixin | `@icp-sdk/vetkeys/encrypted_maps` | > Use `@icp-sdk/vetkeys` (≥0.7), not the legacy `@dfinity/vetkeys` (frozen at 0.4). 0.5 and 0.6 carried `@icp-sdk/core` as a plain dependency and could nest a second copy of it; 0.7 peers it as `^5 || ^6`, with an identical API. Frontend agent/identity come from `@icp-sdk/core`, not `@dfinity/agent`. ## Concepts - **Map** — identified by `(mapOwner: Principal, mapName: bytes)`. Contains `mapKey → encryptedValue` entries. `mapName` and `mapKey` are byte arrays, **max 32 bytes** each. - **Access rights** — `Read`, `ReadWrite`, `ReadWriteManage` (manage = may grant/revoke others). The owner always has full rights. - **Client-side encryption** — the frontend fetches a per-map vetKey and encrypts/decrypts locally; the canister enforces access control and stores ciphertext. Sharing a map re-encrypts the map key for the new user automatically. - **Key name & domain separator are immutable** once any value is encrypted — they feed key derivation, so changing them makes stored values undecryptable. See pitfalls. ## Backend — the whole canister in a few lines The generator emits the `#[init]`/`#[post_upgrade]`, the stable state, and every endpoint the `@icp-sdk/vetkeys` frontend expects — so the Candid matches the client by construction. Do not hand-write the ~200 lines of delegation. ### Rust — `export_encrypted_maps_canister!` ```rust use ic_stable_structures::memory_manager::{MemoryId, MemoryManager, VirtualMemory}; use ic_stable_structures::DefaultMemoryImpl; use std::cell::RefCell; type Memory = VirtualMemory; thread_local! { static MEMORY_MANAGER: RefCell> = RefCell::new(MemoryManager::init(DefaultMemoryImpl::default())); } fn memory(id: u8) -> Memory { MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(id))) } // Arg 1: the domain separator that isolates this app's derived keys (keep it // stable forever). Then four Memory instances, in order: domain-separator config, // access control, shared keys, encrypted values. ic_vetkeys::export_encrypted_maps_canister!( "password_manager_app", [memory(0), memory(1), memory(2), memory(3)], ); ic_cdk::export_candid!(); ``` The generated `#[init]` takes the vetKD key name (`test_key_1` / `key_1`) as a `String` argument — pass it via `init_args` in `icp.yaml`. ### Motoko — `EncryptedMapsCanister` mixin ```motoko import EncryptedMapsCanister "mo:ic-vetkeys/encrypted_maps/Canister"; import EncryptedMaps "mo:ic-vetkeys/encrypted_maps/EncryptedMaps"; import Types "mo:ic-vetkeys/Types"; import Runtime "mo:core/Runtime"; persistent actor PasswordManager { // `transient`: the key name is baked into `encryptedMapsState` at install and never re-read. transient let keyName = Runtime.envVar("VETKD_KEY_NAME") ?? "test_key_1"; // Arg 2 is the domain separator; like the key name it must stay stable for the life of the canister. let encryptedMapsState = EncryptedMaps.newEncryptedMapsState( { curve = #bls12_381_g2; name = keyName }, "password_manager_app", ); // The mixin contributes the full endpoint set (vetKD key, access control, map-name, value endpoints) // as snake_case methods, exactly what the frontend client calls. include EncryptedMapsCanister(encryptedMapsState); }; ``` In a `persistent actor` the `encryptedMapsState` binding is stable and persists across upgrades with no `stable` keyword; the actor owns it, so it stays a plain, migratable variable. Set `VETKD_KEY_NAME` at deploy time via canister settings (see the `icp-cli` skill). ## Frontend (TypeScript) ```typescript import { HttpAgent, type Identity } from "@icp-sdk/core/agent"; import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env"; import { DefaultEncryptedMapsClient, EncryptedMaps, IndexedDbDerivedKeyMaterialCache, type AccessRights, } from "@icp-sdk/vetkeys/encrypted_maps"; export async function createEncryptedMaps( identity: Identity, canisterId: string, host: string, ): Promise { // rootKey from the canister env (never fetchRootKey() in shipped code); undefined on mainnet const rootKey = safeGetCanisterEnv()?.IC_ROOT_KEY; const agent = await HttpAgent.create({ identity, host, rootKey }); // Since 0.5.0 derived key material is cached in memory only by default. // Opt into cross-reload persistence, namespaced by principal; clearCache() on logout. const cache = new IndexedDbDerivedKeyMaterialCache(`vetkeys-${identity.getPrincipal().toText()}`); return new EncryptedMaps(new DefaultEncryptedMapsClient(agent, canisterId), { cache }); } ``` ```typescript const owner = myPrincipal; // Principal from @icp-sdk/core/principal const mapName = new TextEncoder().encode("my-vault"); // ≤ 32 bytes const mapKey = new TextEncoder().encode("github.com"); // ≤ 32 bytes // Store / read / remove (encryption happens client-side) await encryptedMaps.setValue(owner, mapName, mapKey, new TextEncoder().encode("s3cr3t")); const value = await encryptedMaps.getValue(owner, mapName, mapKey); // Uint8Array (empty if absent) await encryptedMaps.removeEncryptedValue(owner, mapName, mapKey); // Share the map with another principal (AccessRights is a Candid variant, not a string) const rights: AccessRights = { ReadWrite: null }; // or { Read: null } / { ReadWriteManage: null } await encryptedMaps.setUserRights(owner, mapName, otherPrincipal, rights); const theirRights = await encryptedMaps.getUserRights(owner, mapName, otherPrincipal); // Everything the caller can access (owned + shared) const maps = await encryptedMaps.getAllAccessibleMaps(); await encryptedMaps.clearCache(); // on logout / identity switch ``` ## KeyManager — the layer beneath (use only when EncryptedMaps doesn't fit) `EncryptedMaps` is built on **`KeyManager`**, which derives and shares access-controlled vetKeys keyed by name. Reach for `KeyManager` directly only when you need access-controlled **key derivation** (e.g. handing each client a per-resource symmetric or IBE key to use themselves) rather than encrypted key-value **storage** — most apps want `EncryptedMaps`. Caveat: there is **no ready-made canister generator for KeyManager yet** ([dfinity/vetkeys#422](https://github.com/dfinity/vetkeys/issues/422)) — unlike EncryptedMaps, you wire the endpoints by hand. In Rust, `ic_vetkeys::key_manager::KeyManager::init` takes the domain separator, the `VetKDKeyId`, and three `Memory` instances (config, access control, shared keys), and exposes `get_vetkey_verification_key`, `get_encrypted_vetkey`, `get_user_rights`, `set_user_rights`, `remove_user`. Motoko mirrors this via `KeyManager.newKeyManagerState` + the `KeyManager` class; the frontend uses `@icp-sdk/vetkeys/key_manager` (`KeyManager` + `DefaultKeyManagerClient`). ## Pitfalls 1. **Use the generator, don't hand-write endpoints.** Rust `export_encrypted_maps_canister!`, Motoko `include EncryptedMapsCanister(state)`. Hand-written delegation drifts from the Candid the frontend client expects and breaks silently. 2. **Domain separator and vetKD key name are immutable once data exists.** Both feed key derivation; changing either makes every stored value undecryptable. In Motoko the `VETKD_KEY_NAME` env var is captured into stable state at first install — editing it on a later upgrade is silently ignored (only a `reinstall`, which drops all data, switches keys). Because `test_key_1` is also a valid mainnet key, a production deploy that forgets to set `VETKD_KEY_NAME` silently runs on it — assert the expected key at deploy time. 3. **Derived key material is in-memory by default since 0.5.0** (was IndexedDB). Pass `IndexedDbDerivedKeyMaterialCache` to persist it across reloads, and call `clearCache()` on logout / identity change. Old `@dfinity/vetkeys` 0.1–0.4 IndexedDB entries remain at rest after upgrading — clear them once. 4. **Client construction changed.** `DefaultEncryptedMapsClient` takes a ready `HttpAgent` (`await HttpAgent.create({ identity, host, rootKey })`), not `HttpAgentOptions`. Agent/identity come from `@icp-sdk/core`. 5. **`AccessRights` is a Candid variant, not a string** — `{ ReadWrite: null }`, not `"ReadWrite"`. Three levels: `Read`, `ReadWrite`, `ReadWriteManage`. 6. **`mapName` and `mapKey` are byte arrays, ≤ 32 bytes each** — encode strings with `TextEncoder`. 7. **Keep per-value app state consistent via the control-plane variant.** If you store metadata alongside each value, use `custom_value_endpoints` (Rust) / `EncryptedMapsControlPlaneCanister` (Motoko) and own the value endpoints — see `references/metadata.md`. Don't also expose the library's raw value mutators, or the two stores desync. 8. **Don't re-init state on upgrade.** The macro/mixin generate the lifecycle hooks; stable memory survives upgrades. Adding your own `post_upgrade` that rebuilds state corrupts it. 9. **Cycles.** `vetkd_derive_key` (used under the hood) costs cycles — `test_key_1` and `key_1` cost the same locally and on mainnet, and the library attaches the right amount (excess refunded). Keep the canister funded. (See the `vetkeys` skill for the cost table.) ## Additional References - Metadata / custom value endpoints: `references/metadata.md` - Lower-level vetKeys (IBE, BLS, timelock, symmetric, offline derivation): the **`vetkeys`** skill - Canonical examples: `motoko/vetkeys/password_manager`, `rust/vetkeys/password_manager` in [dfinity/examples](https://github.com/dfinity/examples/tree/master/rust/vetkeys) ## Deploy & verify Provisioning and generic deploy steps belong to the **`icp-cli`** skill. EncryptedMaps-specific checks: ```bash icp deploy backend # local replica provisions test_key_1 # From the frontend: setValue then getValue round-trips the plaintext for the owner; # a principal without rights gets an access-control error on getValue. ``` --- ## EVM RPC --- name: evm-rpc description: "Call Ethereum and EVM chains from IC canisters (Rust) via the EVM RPC canister using the evm_rpc_client crate. Covers typed API calls, raw JSON-RPC, multi-provider consensus, ERC-20 reads, and sending pre-signed transactions. Use when calling Ethereum, Arbitrum, Base, Optimism, or any EVM chain from a Rust canister. Do NOT use for generic HTTPS calls to non-EVM APIs — use https-outcalls instead." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2" metadata: title: EVM RPC category: Integration --- # EVM RPC Canister — Calling Ethereum from IC ## What This Is The EVM RPC canister is an IC system canister that proxies JSON-RPC calls to Ethereum and EVM-compatible chains via HTTPS outcalls. Your canister sends a request to the EVM RPC canister, which fans it out to multiple RPC providers, compares responses for consensus, and returns the result. No API keys required for default providers. No bridges or oracles needed. ## Prerequisites - `evm_rpc_client` crate (provides typed client API and re-exports `evm_rpc_types`) ## Canister IDs | Canister | ID | Subnet | |---|---|---| | EVM RPC (mainnet) | `7hfb6-caaaa-aaaar-qadga-cai` | 34-node fiduciary | Candid interface: `https://github.com/dfinity/evm-rpc-canister/releases/latest/download/evm_rpc.did` — or use the `canhelp` skill to fetch it directly from the mainnet canister. ## Supported Chains | Chain | Chain ID | Candid | Rust | |---|---|---|---| | Ethereum Mainnet | 1 | `variant { EthMainnet }` | `RpcServices::EthMainnet` | | Ethereum Sepolia | 11155111 | `variant { EthSepolia }` | `RpcServices::EthSepolia` | | Arbitrum One | 42161 | `variant { ArbitrumOne }` | `RpcServices::ArbitrumOne` | | Base Mainnet | 8453 | `variant { BaseMainnet }` | `RpcServices::BaseMainnet` | | Optimism Mainnet | 10 | `variant { OptimismMainnet }` | `RpcServices::OptimismMainnet` | | Custom EVM chain | any | `variant { Custom }` | `RpcServices::Custom` | ## RPC Providers Built-in providers (no API key needed for defaults): | Provider | Ethereum | Sepolia | Arbitrum | Base | Optimism | |---|---|---|---|---|---| | Alchemy | yes | yes | yes | yes | yes | | Ankr | yes | - | yes | yes | yes | | BlockPi | yes | yes | yes | yes | yes | | Cloudflare | yes | - | - | - | - | | LlamaNodes | yes | - | yes | yes | yes | | PublicNode | yes | yes | yes | yes | yes | ## Cycle Costs **Formula:** ``` (5_912_000 + 60_000 * nodes + 2400 * request_bytes + 800 * max_response_bytes) * nodes * rpc_count ``` Where `nodes` = 34 (fiduciary subnet), `rpc_count` = number of providers queried. **Practical guidance:** Send 10_000_000_000 cycles (10B) as a starting budget. Unused cycles are refunded. Typical calls cost 100M-1B cycles (~$0.0001-$0.001 USD). Use `requestCost` to get an exact estimate before calling. ## Pitfalls 1. **Not sending enough cycles.** Every EVM RPC call requires cycles attached. The `evm_rpc_client` defaults to 10B cycles per call, but if you override with `.with_cycles()`, sending too few causes silent failures or traps. 2. **Using default `Equality` consensus.** The default consensus strategy requires all providers to return identical responses. This fails for queries like `eth_getBlockByNumber(Latest)` where providers are often 1-2 blocks apart. Use `ConsensusStrategy::Threshold { total: Some(3), min: 2 }` (2-of-3 agreement) for most use cases. 3. **Ignoring the `Inconsistent` result variant.** Even with threshold consensus, providers can still disagree beyond the threshold. Multi-provider calls return `MultiRpcResult::Consistent(result)` or `MultiRpcResult::Inconsistent(results)`. Always handle both arms or your canister traps on provider disagreement. 4. **Using wrong chain variant.** `RpcServices::EthMainnet` is for Ethereum L1. For Arbitrum use `RpcServices::ArbitrumOne`, for Base use `RpcServices::BaseMainnet`. Using the wrong variant queries the wrong chain. 5. **Response size limits.** Large responses (e.g., `eth_getLogs` with broad filters) can exceed the max response size. Use `.with_response_size_estimate()` on the client builder or the call fails. 6. **Calling `eth_sendRawTransaction` without signing first.** The EVM RPC canister does not sign transactions. You must sign the transaction yourself (using threshold ECDSA via the IC management canister) and pass the raw signed bytes. 7. **Defining EVM RPC Candid types manually.** Use the `evm_rpc_client` crate which provides a typed client API and re-exports all Candid types from `evm_rpc_types`. Manual type definitions drift from the canister's actual interface and cause `IC0503` decode traps at runtime. ## Implementation ### icp.yaml Configuration The `evm_rpc` canister definition is only needed for local development — the local replica doesn't have the EVM RPC canister pre-installed, so you deploy your own copy from the pre-built WASM. On mainnet, the DFINITY-maintained canister is already deployed at `7hfb6-caaaa-aaaar-qadga-cai` — do NOT deploy your own instance. Use environments to control which canisters are deployed where: ```yaml canisters: - name: backend recipe: type: "@dfinity/rust@v3.3.0" - name: evm_rpc build: steps: - type: pre-built url: https://github.com/dfinity/evm-rpc-canister/releases/latest/download/evm_rpc.wasm.gz init_args: "(record {})" environments: - name: local network: local canisters: [backend, evm_rpc] - name: ic network: ic canisters: [backend] settings: backend: environment_variables: PUBLIC_CANISTER_ID:evm_rpc: "7hfb6-caaaa-aaaar-qadga-cai" ``` ### Rust The `evm_rpc_client` crate provides a typed client API for calling the EVM RPC canister. It handles cycle attachment, argument encoding, and response decoding. All Candid types are re-exported from `evm_rpc_types`. For projects using the Alloy ecosystem, enable the `alloy` Cargo feature to use Alloy-native request/response types. #### Cargo.toml ```toml [package] name = "evm_rpc_backend" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] evm_rpc_client = "0.4" evm_rpc_types = "3" ic-canister-runtime = "0.2" ic-cdk = "0.20" candid = "0.10" serde_json = "1" ``` #### src/lib.rs ```rust use candid::Principal; use evm_rpc_client::{CandidResponseConverter, EvmRpcClient, NoRetry}; use evm_rpc_types::{ Block, BlockTag, CallArgs, ConsensusStrategy, Hex, Hex20, Hex32, MultiRpcResult, RpcServices, SendRawTransactionStatus, }; use ic_canister_runtime::IcRuntime; use ic_cdk::update; use std::str::FromStr; // Resolve the EVM RPC canister ID from environment variable injected by icp-cli. // Locally: auto-injected with the locally deployed evm_rpc canister ID. // Mainnet: set explicitly in icp.yaml to the well-known canister ID. fn client() -> EvmRpcClient { let canister_id = Principal::from_text( ic_cdk::api::env_var_value("PUBLIC_CANISTER_ID:evm_rpc"), ) .expect("Invalid principal in PUBLIC_CANISTER_ID:evm_rpc"); EvmRpcClient::builder(IcRuntime::new(), canister_id) .with_rpc_sources(RpcServices::EthMainnet(None)) .with_consensus_strategy(ConsensusStrategy::Threshold { total: Some(3), min: 2, }) .build() } // -- Get ETH balance via raw JSON-RPC -- // Returns hex-encoded wei (e.g., "0xde0b6b3a7640000" = 1 ETH). // Parse hex to u128, divide by 10^18 to get ETH. #[update] async fn get_eth_balance(address: String) -> String { let json = serde_json::json!({ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [address, "latest"], "id": 1 }); client() .multi_request(json) .send() .await .expect_consistent() .unwrap_or_else(|err| ic_cdk::trap(&format!("RPC error: {:?}", err))) } // -- Get latest block via typed API -- #[update] async fn get_latest_block() -> Block { let result = client() .get_block_by_number(BlockTag::Latest) .send() .await; match result { MultiRpcResult::Consistent(Ok(block)) => block, MultiRpcResult::Consistent(Err(err)) => { ic_cdk::trap(&format!("RPC error: {:?}", err)) } MultiRpcResult::Inconsistent(_) => { ic_cdk::trap("Providers returned inconsistent results") } } } // -- Read ERC-20 balance via eth_call -- // Returns hex-encoded uint256. Divide by 10^decimals (e.g., 6 for USDC, 18 for DAI). // Function selector for balanceOf(address): 0x70a08231 // Pad address to 32 bytes (remove 0x prefix, left-pad with zeros) #[update] async fn get_erc20_balance(token_contract: String, wallet_address: String) -> String { let addr = wallet_address.trim_start_matches("0x"); let calldata = format!("0x70a08231{:0>64}", addr); let args = CallArgs { transaction: evm_rpc_types::TransactionRequest { to: Some(Hex20::from_str(&token_contract).unwrap()), input: Some(Hex::from_str(&calldata).unwrap()), ..Default::default() }, block: None, }; let result = client() .call(args) .send() .await .expect_consistent() .unwrap_or_else(|err| ic_cdk::trap(&format!("eth_call error: {:?}", err))); result.to_string() } // -- Send a signed raw transaction -- #[update] async fn send_raw_transaction(signed_tx_hex: String) -> SendRawTransactionStatus { client() .send_raw_transaction(Hex::from_str(&signed_tx_hex).unwrap()) .send() .await .expect_consistent() .unwrap_or_else(|err| ic_cdk::trap(&format!("RPC error: {:?}", err))) } // -- Get transaction receipt -- #[update] async fn get_transaction_receipt(tx_hash: String) -> evm_rpc_types::TransactionReceipt { client() .get_transaction_receipt(Hex32::from_str(&tx_hash).unwrap()) .send() .await .expect_consistent() .unwrap_or_else(|err| ic_cdk::trap(&format!("RPC error: {:?}", err))) .unwrap_or_else(|| ic_cdk::trap("Transaction receipt not found")) } // -- Override chain per request (e.g., Arbitrum instead of the client default) -- #[update] async fn get_arbitrum_block() -> Block { client() .get_block_by_number(BlockTag::Latest) .with_rpc_sources(RpcServices::ArbitrumOne(None)) .send() .await .expect_consistent() .unwrap_or_else(|err| ic_cdk::trap(&format!("RPC error: {:?}", err))) } ic_cdk::export_candid!(); ``` ## Deploy & Test ```bash # Local: deploys both backend and evm_rpc (as defined in the local environment) icp network start -d icp deploy -e local # Mainnet: deploys only backend (evm_rpc is excluded from the ic environment) icp deploy -e ic ``` ### Test via icp CLI ```bash # Set up variables export CYCLES=10000000000 # Get ETH balance (raw JSON-RPC via single provider) icp canister call evm_rpc request '( variant { EthMainnet = variant { PublicNode } }, "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBalance\",\"params\":[\"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\",\"latest\"],\"id\":1}", 1000 )' --with-cycles=$CYCLES # Get latest block (typed API, multi-provider) icp canister call evm_rpc eth_getBlockByNumber '( variant { EthMainnet = null }, null, variant { Latest } )' --with-cycles=$CYCLES # Get transaction receipt icp canister call evm_rpc eth_getTransactionReceipt '( variant { EthMainnet = null }, null, "0xdd5d4b18923d7aae953c7996d791118102e889bea37b48a651157a4890e4746f" )' --with-cycles=$CYCLES # Check available providers icp canister call evm_rpc getProviders # Estimate cost before calling icp canister call evm_rpc requestCost '( variant { EthMainnet = variant { PublicNode } }, "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBalance\",\"params\":[\"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\",\"latest\"],\"id\":1}", 1000 )' ``` --- ## HTTPS Outcalls --- name: https-outcalls description: "Make HTTPS requests from canisters to external web APIs. Covers replicated, non-replicated and flexible outcalls, transform functions for consensus, both cycle pricing versions (legacy and pay-as-you-go via ic0.cost_http_request_v2), response size limits, and idempotency patterns. Use when a canister needs to call an external API, fetch data from the web, make HTTP requests, choose a pricing_version, or use flexible_http_request. Do NOT use for EVM/Ethereum calls — use evm-rpc instead." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2; pricing version 2 and flexible outcalls need ic-cdk >= 0.20.3 with ic-cdk-management-canister >= 0.2.0 (Rust), or the ic mops package >= 6.0.0 with moc >= 2.1.0 (Motoko)" metadata: title: HTTPS Outcalls category: Integration --- # HTTPS Outcalls ## What This Is HTTPS outcalls allow canisters to make HTTP requests to external web services directly from on-chain code. In the default **replicated** mode, every node on the subnet makes the same request and all of them must agree on the response. A transform function strips non-deterministic fields (timestamps, request IDs, ordering) so that every replica sees an identical response and can reach consensus. Two other modes avoid that agreement step: **non-replicated** (`is_replicated = false`, one node makes the request) and **flexible** (`flexible_http_request`, a committee of nodes return their individual responses). See [Outcall modes](#outcall-modes). ## Support matrix | | Rust | Motoko | |---|---|---| | Package | `ic-cdk` **0.20.3+** with `ic-cdk-management-canister` **0.2+** | `ic` **6.x** (mops), which requires `core` **2.5.0+** and `moc` **2.1.0+** | | Entry point | `HttpRequest::new(url)` builder, `.send()` | `Call.httpRequest(url)` builder, `.send()` | | Pricing version 1 (legacy) | only by pinning `ic-cdk-management-canister` **0.1**, or calling `aaaaa-aa` directly with `ic_cdk::api::cost_http_request` | only by pinning `ic` **4.x** or **5.x**, or calling `aaaaa-aa` directly with `Prim.costHttpRequest` | | Pricing version 2 (pay-as-you-go) | **yes**, the builder always selects it | **yes**, the builder always selects it | | `flexible_http_request` | **yes**, `FlexibleHttpRequest::new(url)` | **yes**, `Call.flexibleHttpRequest(url)` | | `subnet_self_node_count` | `ic_cdk::api::subnet_self_node_count()` | `Prim.subnetSelfNodeCount()` (via `import Prim "mo:⛔"`) | Read this before writing code; what is available depends on the language and the dependency versions in the project. Both languages reach the same outcall surface, through a builder that selects version 2 and computes the cycles to attach, but only on recent dependencies. On `ic` **4.x** or **5.x** Motoko is still version 1: 4.x `HttpRequestArgs` has no `pricing_version` field at all, Candid omits the absent optional, and the replica reads it as version 1, which is exactly what that `Call.httpRequest` funds. The builder and `flexible_http_request` arrive in **6.0.0**, which requires `moc` **2.1.0** for the `costHttpRequestV2` primitive it calls. For Rust the right code depends on which of three worlds the project is in. `ic-cdk` 0.19 has `ic_cdk::management_canister::http_request(&args)` (version 1; the module was removed in 0.20). `ic-cdk` 0.20 with `ic-cdk-management-canister` 0.1 has `ic_cdk_management_canister::http_request(&args)` (version 1). `ic-cdk` 0.20.3+ with `ic-cdk-management-canister` 0.2 has the builders, and is **version 2 only**: 0.2.0 removed the free `http_request` and the builder hard-codes `pricing_version: Some(2)` with no opt-out, so upgrading the crate *is* the migration. Rust also needs `serde_json` for JSON parsing. **Which version to write.** Version 1 is deprecated and version 2 is the direction, so *new* Rust code should use the 0.2 builders. But do **not** bump a project's pinned versions in order to migrate it as a side effect of an unrelated task: 0.2 is a breaking change (it deletes the free `http_request` and `HttpRequestArgs` gains a required field), so the upgrade is the caller's decision. Write correct code for the line the project is actually on, and tell them the upgrade exists. ## Canister IDs HTTPS outcalls use the IC management canister: | Name | Canister ID | Used For | |------|-------------|----------| | Management canister | `aaaaa-aa` | The `http_request` and `flexible_http_request` management call targets | You do not deploy anything extra. The management canister is built into every subnet. ## Mistakes That Break Your Build 1. **Forgetting the transform function.** In **replicated** mode, without a transform the raw HTTP response often differs between replicas (different headers, different ordering in JSON fields, timestamps). Consensus fails and the call is rejected. ALWAYS provide one there. In **non-replicated** and **flexible** mode it is optional *for consensus*, because each node's own response is delivered. Whether to set one there is a tradeoff. **No transform reserves nothing for it** (the instruction term defaults to 0, not to the query limit), which is the cheapest configuration available. Adding one defaults that term to the full query limit, so you must also declare `with_expected_transform_instructions`. What it buys back is the delivery fee, charged per byte on the **transformed** size: every byte stripped lowers the bill, so what decides it is how much there is worth stripping (bulky headers yes, a response that is already mostly payload no). The reservation floors that term at about 1 KB, so `get_cost()` understates the saving on a small response. Two non-cycle reasons can decide it anyway: in flexible mode the combined 2 MiB budget is measured after the transform, so smaller responses mean fewer get dropped, and reconciling is impossible if per-node noise makes every response distinct. 2. **Not attaching cycles to the call.** On a normal Application subnet, HTTPS outcalls are not free — the calling canister must attach cycles to cover the cost, and attaching zero fails the call. Both Motoko and Rust have builders that compute and attach the required cycles automatically: in Motoko, `Call.httpRequest(url)....send()` from the `ic` mops package (`import Call "mo:ic/Call"`); in Rust, the `HttpRequest` builder's `.send()` from `ic-cdk-management-canister` 0.2. On current versions both price version 2 with `ic0.cost_http_request_v2`; an older `ic` (4.x or 5.x) prices version 1 with `ic0.cost_http_request` instead. Both are cost-schedule aware, so the same wrapper attaches the correct amount on any subnet type. **Under version 2 the up-front check is against the base fee only**, so an under-sized attachment is *not* rejected at call time: the call runs with tighter per-node limits and can fail partway, after the remote server was already contacted. See `references/pricing-version-2.md`. On a **cloud engine** (`CloudEngine` subnet), that amount is always 0 by design; do not "fix" a working outcall by attaching a hardcoded non-zero fee there — see the `cloud-engine-canisters` skill. 3. **Using HTTP instead of HTTPS.** The IC only supports HTTPS outcalls. Plain HTTP URLs are rejected. The target server must have a valid TLS certificate. 4. **Sizing `max_response_bytes` against the expected body — the limit is not body-only.** The spec defines the size of an HTTP request or response as *the total number of bytes representing the names and values of HTTP headers and the HTTP body*. Response **headers count against `max_response_bytes`**, and a real API commonly sends 1–2 KB of response headers (a unique request id, `Date`, the rate-limit family, CDN headers) before a single byte of body — against a tight cap that is a large share of the budget. Size the cap for **headers + body as they arrive from the server**, then add margin. The failure mode is total: the call fails every time rather than returning a truncated response. The maximum is 2MB = `2_000_000` bytes (decimal, not 2^21), and the same headers-plus-body definition caps the **request** you send at `2_000_000` bytes. 5. **Expecting the transform function to shrink an oversized response under the cap.** The cap is enforced **twice**: once on the raw response as it arrives from the server (headers first, then the body against what remains), and again on the transform's Candid-encoded **output**, which includes serialization overhead. Stripping headers in the transform cannot rescue a raw response that already exceeded the cap, because that first check fails before the transform ever runs. It *can* keep the transform's own output under the cap — worth doing when the transform would otherwise echo the headers back and its encoded output would exceed the limit. Both checks compare against the **same** `max_response_bytes` value, which is why a raw response that only just fits can still fail after the transform: the Candid overhead is added on top. So: size `max_response_bytes` for the raw response, and keep the transform's output small; never set a tight cap on the theory that stripping headers afterwards will make an oversized response fit. 6. **Ignoring the header limits.** Independent of `max_response_bytes`, the spec caps HTTP requests and responses at **64 headers**, **8 KiB** per header name or value, and **48 KiB** for all header names and values combined. The URL must not exceed **8192** bytes. On the request side these are enforced when the replica decodes your arguments, so an over-limit request never leaves the subnet and fails with `InvalidManagementPayload` — e.g. `Deserialize error: The number of elements exceeds maximum allowed 64` — rather than with any HTTP-looking error. If you send no `user-agent` header the IC adds `user-agent: ic/1.0`, and that added header does not count toward these limits. 7. **Omitting `max_response_bytes`.** Under **version 1**, if you do not set it the system assumes the maximum (2MB) and charges cycles accordingly — roughly 20.85 billion cycles on a 13-node subnet. Under **version 2** it no longer sets the price, but it is still the default for the `raw_response_bytes` expectation, so omitting it reserves for 2MB: 34.0 billion cycles rather than 5.3 billion for a 4,000-byte cap. Either way, always set it to a reasonable upper bound for your expected response (see pitfall 4 for what counts toward it). 8. **Non-idempotent POST requests without caution.** Because multiple replicas make the same request, a POST endpoint that is not idempotent (e.g., "create order") will be called N times (once per replica, typically 13 on a 13-node subnet). Use idempotency keys, or design endpoints to handle duplicate requests, or set `is_replicated = ?false` (Rust: `.non_replicated()`), which has a single node send the request and removes the rate-limit pressure entirely — at the cost of trusting that node not to observe or modify the response. 9. **Not handling outcall failures.** External servers can be down, slow, or return errors. Always handle the error case. There are **two distinct timeouts**, and neither traps — both come back as rejects (in Motoko the `await` raises a catchable `Error`; in Rust the wrapper returns `Err`): - The remote server does not respond within **30 seconds**: `SysFatal`, message `Timeout expired`. - The subnet does not produce a response within **60 seconds**: `SysTransient`, message `Canister http request timed out`. This one is normally the retryable one; the exception is a version 2 call that is under-funded *and* missing a node's report (see `references/pricing-version-2.md`). 10. **Calling localhost or private IPs.** HTTPS outcalls can only reach public internet endpoints. Localhost, 10.x.x.x, 192.168.x.x, and other private ranges are blocked. 11. **Forgetting the `Host` header.** Some API endpoints require the `Host` header to be explicitly set. The IC does not automatically set this from the URL. 12. **Leaving the version 2 expectations unset.** Anything you do not declare is *reserved* at its maximum: a 60-second round trip, and a transform running to the full query instruction limit. For a 4,000-byte cap that is around 5.3 billion cycles held, nearly all of it the transform reserve, against about 112 million once you declare `with_expected_transform_instructions` and `with_expected_roundtrip_time_ms`. Declare those two. Leave `raw_response_bytes` alone, because the server decides it; lower `max_response_bytes` instead if the byte terms dominate. Declare `with_expected_transformed_response_bytes` when your transform bounds its own output, which is the one case where the cap cannot be the lever. The *charge* is unaffected by any of this unless the smaller budget actually cuts the call short. `references/pricing-version-2.md` has the figures, the per-resource reasoning, and the failure modes. 13. **Expecting to reach version 1 through `ic-cdk-management-canister` 0.2.** You cannot. The builder is the only path the crate offers, it hard-codes `pricing_version: Some(2)`, and there is no `with_pricing_version`. `HttpRequest::from_args` looks like the escape hatch and is not: it is the documented way to migrate an existing call site, and it **silently overwrites `pricing_version` with 2**, so args that deliberately set 1 change version when you pass them through it. To stay on version 1, pin `ic-cdk-management-canister` 0.1, or call `aaaaa-aa` directly and price with `ic_cdk::api::cost_http_request`, which is still present in 0.20.3. 14. **Setting `pricing_version` by hand and funding it with the wrong cost function.** The field and the attachment have to agree. Set `pricing_version = 2` while attaching a `cost_http_request` (version 1) amount and the call is *accepted*, because the up-front check is only the base fee — it then runs on a smaller per-node allowance than version 2 intended and can fail partway. The reverse, a version 1 call funded with a `cost_http_request_v2` amount, is rejected outright with `http_request request sent with cycles, but cycles are required.`, because version 1 wants the whole `max_response_bytes` up front. Let the builder set both: in either language it pairs version 2 with `cost_http_request_v2`, and overwrites `pricing_version` even when you start from arguments you assembled yourself (`httpRequestFromArgs`, `HttpRequest::from_args`), so the field and the amount cannot drift apart. Note also that the replica *filters* an unrecognised version to version 1 with no error, so a bogus value fails as a funding mismatch rather than as a validation error. 15. **Hardcoding `total_requests` for a flexible outcall.** `total_requests` must not exceed the subnet size, which differs per subnet (13 or 34 on mainnet). Derive it: ```rust // WRONG, even when you want five nodes: 5 may exceed the subnet size. let replication = ReplicationCounts { total_requests: 5, min_responses: 3, max_responses: 5 }; // RIGHT: ask for five, but never more than the subnet has. let total_requests = subnet_self_node_count().min(5); let min_responses = total_requests / 2 + 1; ``` Also handle **any** count between `min_responses` and `max_responses` in the success arm — fewer than `max_responses` is a normal success, not a degraded one — and check each response's `status` separately, because no node had to agree with any other. See `references/flexible-outcalls.md`. ## Outcall modes Replicated and non-replicated are selected by `is_replicated`; flexible is a separate method. | | Replicated (default) | Non-replicated (`is_replicated = false`) | Flexible (`flexible_http_request`) | |---|---|---|---| | Who sends it | All N nodes | One node chosen by the system | A committee of `total_requests` nodes | | What you get | One agreed response | That node's response | Between `min_responses` and `max_responses` responses | | Transform | Required in practice | Optional, often still worth it | Optional, often still worth it | | Pricing | Version 1 or 2 | Version 1 or 2 | Always version 2 | | Extra methods | `GET`, `HEAD`, `POST` | plus `PUT`, `DELETE`, `PATCH` | plus those when `total_requests`, `min_responses` and `max_responses` are all equal | | Risk | N simultaneous requests trip API rate limits | That node could observe or modify the response | Reconciling the responses is your job | Use replicated when you need the integrity guarantee consensus gives, non-replicated for rate-limited APIs and non-idempotent POSTs, and flexible when the data changes faster than nodes could ever agree on it. ## Implementation ### Motoko Import both the builder and the types from the `ic` mops package: `import Call "mo:ic/Call"` and `import IC "mo:ic/Types"`. `Call.httpRequest(url)` starts a request and `.send()` computes and attaches the required cycles. **This is pricing version 2**, on `ic` 6.x. On `ic` 4.x or 5.x the entry point is `Call.httpRequest(args)` taking the whole record, and it prices version 1; see the support matrix. ```motoko import Blob "mo:core/Blob"; import Nat "mo:core/Nat"; import Text "mo:core/Text"; import Call "mo:ic/Call"; import IC "mo:ic/Types"; persistent actor { // Transform function: strips headers so all replicas see the same response for consensus. // MUST be a `shared query` function. public query func transform({ context : Blob; response : IC.HttpRequestResult; }) : async IC.HttpRequestResult { { response with headers = []; // Strip headers -- they often contain non-deterministic values }; }; // GET request: fetch a JSON API public func getIcpPriceUsd() : async Text { let url = "https://api.coingecko.com/api/v3/simple/price?ids=internet-computer&vs_currencies=usd"; // send() computes and attaches the cycles the call may need. let response = await Call.httpRequest(url) // Bounds the response; a larger one fails the call. The cap covers // headers and body together, and the transform cannot bring an // oversized response back under it. Under version 2 it no longer sets // the price, because only the bytes that arrive are charged. .withMaxResponseBytes(10_000) .withHeader("User-Agent", "ic-canister") .withTransform({ function = transform; context = Blob.fromArray([]) }) // Unset expectations reserve the worst case: 60 seconds of round trip, // and a transform running to the full query instruction limit. // Declaring what the call expects holds far fewer cycles while it runs; // the charge is unchanged, because only what is used is billed. .withExpectedRoundtripTimeMs(10_000) .withExpectedTransformInstructions(1_000_000) .send(); switch (Text.decodeUtf8(response.body)) { case (?text) { text }; case (null) { "Response is not valid UTF-8" }; }; }; // POST transform: also discards the body, because httpbin.org echoes the // sender's IP in "origin", which differs across replicas. public query func transformPost({ context : Blob; response : IC.HttpRequestResult; }) : async IC.HttpRequestResult { { response with headers = []; body = Blob.fromArray([]); }; }; // POST request: send JSON data public func postData(jsonPayload : Text) : async Text { let url = "https://httpbin.org/post"; // send() computes and attaches the cycles the call may need. let response = await Call.httpRequest(url) .withMethod(#post) .withMaxResponseBytes(50_000) .withHeader("Content-Type", "application/json") .withHeader("User-Agent", "ic-canister") // Idempotency key: prevents duplicate processing if multiple replicas hit the endpoint .withHeader("Idempotency-Key", "unique-request-id-12345") .withBody(Text.encodeUtf8(jsonPayload)) .withTransform({ function = transformPost; context = Blob.fromArray([]) }) .withExpectedRoundtripTimeMs(10_000) .withExpectedTransformInstructions(1_000_000) .send(); if (response.status == 200) { "POST successful (status 200)"; } else { "POST failed with status " # Nat.toText(response.status); }; }; }; ``` ### Rust ```toml # Cargo.toml [package] name = "https_outcalls_backend" version = "0.1.0" edition = "2024" [lib] crate-type = ["cdylib"] [dependencies] ic-cdk = "0.20" ic-cdk-management-canister = "0.2" candid = "0.10" serde = { version = "1", features = ["derive"] } serde_json = "1" ``` ```rust use ic_cdk_management_canister::{ transform_context_from_query, HttpMethod, HttpRequest, HttpRequestResult, TransformArgs, }; use ic_cdk::{query, update}; /// Transform function: strips non-deterministic headers so all replicas agree. /// MUST be a #[query] function. #[query(hidden = true)] fn transform(args: TransformArgs) -> HttpRequestResult { HttpRequestResult { status: args.response.status, body: args.response.body, headers: vec![], // Strip all headers for consensus // If you need specific headers, filter them here: // headers: args.response.headers.into_iter() // .filter(|h| h.name.to_lowercase() == "content-type") // .collect(), } } /// GET request: Fetch JSON from an external API #[update] async fn fetch_price() -> String { let url = "https://api.coingecko.com/api/v3/simple/price?ids=internet-computer&vs_currencies=usd"; // The builder always selects pricing version 2. `.send()` prices the call // with ic0.cost_http_request_v2 and attaches that amount. let request = HttpRequest::new(url) .with_method(HttpMethod::GET) // Budget for response headers + body: the cap covers both, and the // transform cannot bring an oversized response back under it. .with_max_response_bytes(10_000) .with_header("User-Agent", "ic-canister") .with_transform(transform_context_from_query("transform".to_string(), vec![])) // Unset expectations reserve the worst case: a 60s round trip and a // transform running to the full 5-billion-instruction query limit. // Declaring them holds far fewer cycles. See pitfall 12. .with_expected_roundtrip_time_ms(10_000) .with_expected_transform_instructions(1_000_000); match request.send().await { Ok(response) => { let body = String::from_utf8(response.body) .unwrap_or_else(|_| "Invalid UTF-8 in response".to_string()); if response.status != candid::Nat::from(200u64) { return format!("HTTP error: status {}", response.status); } body } Err(err) => { format!("HTTP outcall failed: {:?}", err) } } } /// POST transform: strips headers AND body, because httpbin.org echoes the /// sender's IP in "origin", which differs across replicas. #[query(hidden = true)] fn transform_post(args: TransformArgs) -> HttpRequestResult { HttpRequestResult { status: args.response.status, body: vec![], headers: vec![], } } /// POST request: Send JSON data to an external API #[update] async fn post_data(json_payload: String) -> String { let url = "https://httpbin.org/post"; let request = HttpRequest::new(url) .with_method(HttpMethod::POST) .with_max_response_bytes(50_000) .with_header("Content-Type", "application/json") .with_header("User-Agent", "ic-canister") // Idempotency key: prevents duplicate processing across replicas .with_header("Idempotency-Key", "unique-request-id-12345") .with_body(json_payload.into_bytes()) .with_transform(transform_context_from_query("transform_post".to_string(), vec![])) .with_expected_roundtrip_time_ms(10_000) .with_expected_transform_instructions(1_000_000); // Replicated, so every node POSTs: hence the idempotency key above, and // `transform_post`. `.non_replicated()` would send it once instead and make // both unnecessary, at the cost of trusting that one node (pitfall 8). match request.send().await { Ok(response) => { if response.status == candid::Nat::from(200u64) { "POST successful (status 200)".to_string() } else { format!("POST failed with status {}", response.status) } } Err(err) => { format!("HTTP outcall failed: {:?}", err) } } } ``` ### Cycle Cost Estimation There are two pricing versions. Version 1 is the replica default and is deprecated; version 2 ("pay-as-you-go") charges for the resources a call consumes instead of the bytes it reserves. **The current builders in both languages are version 2 only**, so a project on `ic-cdk-management-canister` 0.2 or `ic` 6.x is already on it. Version 1, which follows, is still the replica default and is what older dependencies attach; for version 2 in full, including the reservation mechanics and its distinct failure modes, read `references/pricing-version-2.md`. The `ic0.cost_http_request` system API computes the exact cycle cost at runtime, so canisters do not need to hard-code the formula. `Call.httpRequest` on `ic` 4.x or 5.x (Motoko) calls it internally and attaches the required cycles automatically; on the Rust side the same is true of the free `http_request` in `ic-cdk-management-canister` 0.1, or `ic_cdk::management_canister::http_request` on ic-cdk 0.19. For manual use: in Motoko, `Prim.costHttpRequest(requestSize, maxResponseBytes)` (via `import Prim "mo:⛔"`); in Rust, `ic_cdk::api::cost_http_request(request_size, max_res_bytes)`. `request_size` is the sum of byte lengths of the URL, all header names and values, the body, the transform function name, and the transform context. For reference, the underlying formula on a 13-node subnet (n = 13) is: ```text Base cost: 49_140_000 cycles (= (3_000_000 + 60_000*13) * 13) + per request byte: 5_200 cycles (= 400 * 13) + per max_response_bytes byte: 10_400 cycles (= 800 * 13) IMPORTANT: Under version 1 the charge is against max_response_bytes, NOT the actual response size. Under version 2 it is the reverse: the charge follows the bytes that arrive, the round-trip time and the transform instructions. Omitting max_response_bytes assumes the 2MB maximum (2_000_000 bytes) and costs 49_140_000 + 10_400 * 2_000_000 = 20_849_140_000 cycles (~20.85B), plus the per-request-byte term. ``` Under version 1, unused cycles are refunded when the call returns, so over-budgeting is **safe but not free**. Under version 2 it is not merely wasteful: the attachment beyond the base fee is the per-node allowance, which sets each node's response deadline and transform instruction limit, so a margin is permission to spend rather than idle reserve. Version 2 refunds also arrive asynchronously, with a node that never reported returning its allowance about a minute after the response. Attached cycles leave the canister's spendable balance for the *duration* of the call, so a hand-attached margin directly caps how many outcalls the canister can have in flight before it runs out of balance. For a canister making one outcall per user action, that margin is a concurrency limit. This is why both wrappers attach the exact computed amount rather than a round number — as the `ic` mops package puts it: *"Only minimal amount of cycles are added to the call. This helps the canister to make more calls in parallel without running out of cycles."* Do not hand-attach a buffer "to be safe". Call the wrapper, or compute the exact cost with `Prim.costHttpRequest` / `ic_cdk::api::cost_http_request` and attach that. Under version 1, the way to lower the cost of an outcall is a tighter `max_response_bytes`, never a larger attachment. Under version 2 the price follows what the call consumes; the round trip and the transform are governed by their `with_expected_*` setters, and size is still governed by `max_response_bytes`, which now sizes the reservation rather than the price. This formula applies on a normal **Application subnet**. It does not apply on a **cloud engine** (`CloudEngine` subnet): there, `ic0.cost_http_request` returns 0 regardless of `request_size` or `max_response_bytes`, because engines run under a free cost schedule. Load the `cloud-engine-canisters` skill for the engine's call rules before writing or debugging outcall code that will run there. ## Deploy & Test ### Local Deployment ```bash icp network start -d icp deploy backend ``` Note: HTTPS outcalls work on the local replica. icp-cli proxies the requests through the local HTTP gateway. Flexible outcalls run locally too, but every response comes from the same single node, so reconciliation never sees disagreement there. ### Mainnet Deployment ```bash icp canister status backend -e ic && icp deploy -e ic backend # check balance, then deploy ``` ## Verify It Works ```bash # 1. GET outcall. Expected: '("{\"internet-computer\":{\"usd\":12.34}}")', price varies. icp canister call backend getIcpPriceUsd '()' # Motoko example above icp canister call backend fetch_price '()' # Rust example above # 2. POST outcall. Expected: httpbin.org echoing your data back. icp canister call backend postData '("{\"test\": \"hello\"}")' # Motoko icp canister call backend post_data '("{\"test\": \"hello\"}")' # Rust # 4. Balance should have decreased. Under version 2 it keeps settling for about # a minute afterwards as per-node refunds arrive, so re-read before judging. icp canister status backend # 5. Error handling: add a function calling a non-existent domain and verify it # returns an error rather than trapping. ``` ### Debugging Outcall Failures If an outcall fails: ```bash # Check the replica log for detailed error messages # Local: icp output shows errors inline # Mainnet: check the canister logs # Exact reject messages from the replica (match on these, not on paraphrases): # # "Timeout expired" [SysFatal] # The remote server did not respond within 30s. # # "Canister http request timed out" [SysTransient] # The subnet did not produce a response within 60s. Normally retryable. # Under version 2 it can also mean under-funding, but only when a node went # silent AND the remaining contributors cannot fund delivery without it; # then a retry just times out again. See references/pricing-version-2.md. # # "Deadline Exceeded" [SysTransient] # The adapter did not answer the replica within its 60s deadline. Rarer # than the two above: the adapter's own 30s timeout usually fires first. # # "No consensus could be reached. Replicas had different responses. # Details: request_id: , hashes: <...>" [SysTransient] # Transform is missing or not stripping enough non-determinism. # # There are THREE distinct size-limit messages, all [SysFatal], because response # headers are counted against max_response_bytes BEFORE the body is read: # # "Header size exceeds specified response size limit " # The response headers ALONE exceeded max_response_bytes. # # "Http body exceeds size limit of bytes." # The body exceeded the allowance REMAINING after header bytes were # subtracted. Note the message prints the full cap , not the remainder, # so the body that failed can be well under . Do not read this message # as "my body is too big" -- it means headers + body are too big. # # "Transformed http response exceeds limit: " # The Candid-encoded output of your transform exceeded max_response_bytes. # # Raising max_response_bytes fixes all three. Stripping headers in the # transform fixes ONLY this last one: the first two are checked before # the transform runs. # # "http_request request sent with cycles, but cycles are required." # [CanisterReject] # Attached less than the computed cost. Use the wrapper rather than a # hand-picked number. Version 1 only: version 2 checks just the base fee up # front and fails later instead, as one of the next two. # # "Insufficient cycles" [CanisterReject] # Version 2: a node exhausted its own per-node allowance. Ordinary response # content, so it reaches the canister only if a quorum produce the same # reject; otherwise it becomes a divergence. # # "Out of cycles: of the assigned replicas reported a collective spend of # cycles, leaving cycles of the attached payment (after base fee # deduction). Delivering a response would cost at least cycles." # [CanisterReject] # Version 2 pooled shortfall: the nodes agreed, but what they left unspent # does not cover putting the response in a block. Raise the reservation. ``` ### Transform Debugging If you get "no consensus could be reached" errors, your transform function is not making responses identical. Common culprits: 1. **Response headers differ** -- strip ALL headers in the transform 2. **JSON field ordering differs** -- parse and re-serialize the JSON in the transform 3. **Timestamps in response body** -- extract only the fields you need For a typed JSON parser and a transform that normalizes field ordering, see `references/json-responses.md`. ## Additional References - **`references/pricing-version-2.md`** — the pay-as-you-go model: what it charges, the four expectations and their defaults, why they fund one pooled per-node budget, the reject messages for an under-funded call, and what to check before migrating. - **`references/json-responses.md`** — parsing a typed JSON body with `serde_json`, and a transform that re-serializes to normalize field ordering for consensus. - **`references/flexible-outcalls.md`** — `flexible_http_request` in full: replication counts derived from `subnet_self_node_count`, a compiling example, reconciliation strategies and their threat model, the four `global_error` values, the two separate size limits, why a local run never shows disagreement, and whether a transform pays for itself. - Load `cloud-engine-canisters` for canisters running on a cloud engine, including why outcall cost drops to 0 there and why outcalls must never be routed through the engine's console proxy. --- ## IC Dashboard APIs --- name: ic-dashboard description: "Query the public REST APIs that power dashboard.internetcomputer.org. Covers canister metadata, ICRC ledger data, SNS data, ICP ledger, and network metrics with cursor-based pagination. Use when fetching canister info, token data, SNS proposals, or network stats via HTTP from off-chain code. No canister deployment or cycles needed." license: Apache-2.0 metadata: title: IC Dashboard APIs category: Integration --- # IC Dashboard APIs ## What This Is These public REST APIs power **dashboard.internetcomputer.org**. They expose read-only access to canister metadata, ICRC ledgers, SNS data, the ICP ledger, and network metrics via OpenAPI specs and Swagger UI. Agents and scripts can call them over HTTPS from off-chain (no canister deployment or cycles required). **Prefer v2 or higher API versions** where available; they provide cursor-based pagination (`after`, `before`, `limit`) and are the same surface the dashboard uses. ## Prerequisites - Any HTTP client: `curl`, `fetch`, `axios`, or the language’s native HTTP library. - No `icp-cli` or canister deployment needed for read-only API access. - For OpenAPI-based codegen: optional use of the `openapi.json` URLs with your preferred OpenAPI tooling. ## API Base URLs and Docs | API | Base URL | OpenAPI spec | Swagger / Docs | Prefer | |-----|----------|--------------|----------------|--------| | IC API | `https://ic-api.internetcomputer.org` | `/api/v3/openapi.json` | `/api/v3/swagger` | v4 for canisters, subnets (cursor pagination) | | ICRC API | `https://icrc-api.internetcomputer.org` | `/openapi.json` | `/docs` | v2 for ledgers (TestICP and other ICRC tokens; **not** mainnet ICP) | | SNS API | `https://sns-api.internetcomputer.org` | `/openapi.json` | `/docs` | v2 for snses, proposals, neurons | | Ledger API (mainnet ICP) | `https://ledger-api.internetcomputer.org` | `/openapi.json` | `/swagger-ui/` | Use for **ICP token**; v2 for cursor pagination | | Metrics API | `https://metrics-api.internetcomputer.org` | `/api/v1/openapi.json` | `/api/v1/docs` | v1 (no newer version) | Full URLs for specs and UI: - IC API: https://ic-api.internetcomputer.org/api/v3/openapi.json — https://ic-api.internetcomputer.org/api/v3/swagger - ICRC API: https://icrc-api.internetcomputer.org/openapi.json — https://icrc-api.internetcomputer.org/docs - SNS API: https://sns-api.internetcomputer.org/openapi.json — https://sns-api.internetcomputer.org/docs - Ledger API: https://ledger-api.internetcomputer.org/openapi.json — https://ledger-api.internetcomputer.org/swagger-ui/ - Metrics API: https://metrics-api.internetcomputer.org/api/v1/openapi.json — https://metrics-api.internetcomputer.org/api/v1/docs ## How It Works 1. **Prefer v2+ APIs with cursor pagination.** IC API v4 (`/api/v4/canisters`, `/api/v4/subnets`), ICRC API v2 (`/api/v2/ledgers`, `/api/v2/ledgers/{id}/transactions`, etc.), and SNS API v2 (`/api/v2/snses`, `/api/v2/snses/{id}/proposals`, `/api/v2/snses/{id}/neurons`) use `after`, `before`, and `limit` for stable, efficient paging. Avoid v1/offset-based endpoints when a v2+ alternative exists. 2. **Choose the right API** for the data you need: IC API (canisters, subnets, NNS neurons/proposals), **Ledger API for mainnet ICP** (accounts, transactions, supply), ICRC API for **other** ICRC ledgers only (ckBTC, SNS tokens, testicp — ICRC API does not expose mainnet ICP), SNS API (SNS list, neurons, proposals), Metrics API (governance, cycles, Bitcoin, etc.). 3. **Use the OpenAPI spec** to get exact path, query, and body schemas and response shapes; prefer the spec over hand-written docs to avoid drift. 4. **Call over HTTPS** with `GET` (or documented method). Use the cursor fields from v2+ responses to request the next or previous page. The names are not uniform: IC, ICRC and SNS APIs return `next_cursor` / `previous_cursor`, but **Ledger API returns `next_cursor` / `prev_cursor`** and names the row array after the resource (`accounts`, `blocks`, …) rather than a uniform `data`. Read the field names from the response (or the OpenAPI spec) rather than assuming. ## Mistakes That Break Your Build 1. **Wrong base URL or API version.** IC API uses `/api/v3/` (and v4 for canisters/subnets); ICRC has `/api/v1/` and `/api/v2/` (ICRC API does not serve mainnet ICP — use Ledger API). Ledger API uses unversioned paths for some endpoints (e.g. `/accounts`, `/supply/total/latest`) and `/v2/` for cursor-paginated lists. Metrics API uses `/api/v1/`. Using the wrong prefix returns 404 or wrong schema. 2. **Canister ID format.** Canister IDs in paths and queries are principal text: lowercase Base32 of `CRC32(blob) · blob`, split into 5-character groups where only the last group may be shorter (1–5 characters). A mainnet canister ID is 27 characters — **four** groups of five plus a final three, e.g. `ryjl3-tyaaa-aaaaa-aaaba-cai`. Principals are not fixed-length: subnet IDs reach the 63-character maximum (ten groups of five plus a final three), and short ones such as the management canister `aaaaa-aa` are also valid principals. Sending a raw principal string in the wrong encoding or length causes 422 or 400. 3. **Using ICRC API for mainnet ICP.** ICRC API exposes **test ICP (TestICP) only**, not mainnet ICP. For mainnet ICP token data (accounts, transactions, supply) use **Ledger API** (`ledger-api.internetcomputer.org`). Use ICRC API for other ICRC ledgers (e.g. ckBTC, SNS tokens) and for TestICP. 4. **ICRC API: ledger_canister_id in path.** ICRC endpoints require `ledger_canister_id` in the path (e.g. `/api/v2/ledgers/{ledger_canister_id}/transactions`). Use the canister ID of the ledger you want (e.g. ckBTC `mxzaz-hqaaa-aaaar-qaada-cai`). Do not use ICRC API for mainnet ICP — use Ledger API instead. 5. **Using v1 or offset-based pagination when v2+ exists.** Always prefer v2 or higher endpoints that support cursor pagination (`after`, `before`, `limit`). IC API v4 (canisters, subnets), ICRC API v2 (ledgers, accounts, transactions), and SNS API v2 (snses, proposals, neurons) return `next_cursor`/`previous_cursor` and accept cursor query params — Ledger API v2 also paginates by cursor but names the field `prev_cursor`. Older v1/offset/`max_*_index` endpoints are legacy; using the wrong pagination model returns empty or incorrect pages. 6. **Timestamps.** Most time-range query params (`start`, `end`) expect Unix seconds (integer). Sending milliseconds or ISO strings causes validation errors (422). 7. **Account identifier format.** Ledger API and ICRC/ICP endpoints use **account identifiers** (hex hashes), not raw principals, for account-specific paths. Use the same encoding the API documents (e.g. 64-char hex for account_identifier where required). 8. **Assuming authentication.** These public dashboard APIs do not require API keys or auth for the documented read endpoints. If you get 401/403, confirm you are not hitting a different environment or a write endpoint that requires auth. ## Implementation ### IC API — Canisters and subnets (prefer v4 with cursor pagination) ```bash # List canisters (v4: cursor pagination, next_cursor/previous_cursor in response) curl -s "https://ic-api.internetcomputer.org/api/v4/canisters?limit=5" # Next page: use after= from previous response's next_cursor (see OpenAPI for cursor format) # curl -s "https://ic-api.internetcomputer.org/api/v4/canisters?limit=5&after=..." # Get one canister by ID (v3; no v4 single-canister endpoint) curl -s "https://ic-api.internetcomputer.org/api/v3/canisters/ryjl3-tyaaa-aaaaa-aaaba-cai" # List subnets (v4: cursor pagination) curl -s "https://ic-api.internetcomputer.org/api/v4/subnets?limit=10" # List NNS proposals (v3; use limit) curl -s "https://ic-api.internetcomputer.org/api/v3/proposals?limit=5" ``` ### ICRC API — Other ICRC ledgers only (v2 with cursor pagination) ICRC API exposes **TestICP and other ICRC ledgers (e.g. ckBTC, SNS tokens), not mainnet ICP.** For mainnet ICP use Ledger API. ```bash # List ledgers (v2: after/before/limit, next_cursor/previous_cursor in response) curl -s "https://icrc-api.internetcomputer.org/api/v2/ledgers?limit=10" # Get one ledger (e.g. ckBTC — mainnet ICP is not on ICRC API) curl -s "https://icrc-api.internetcomputer.org/api/v2/ledgers/mxzaz-hqaaa-aaaar-qaada-cai" # List transactions for a ledger (v2: cursor pagination) curl -s "https://icrc-api.internetcomputer.org/api/v2/ledgers/mxzaz-hqaaa-aaaar-qaada-cai/transactions?limit=5" # List accounts for a ledger (v2: after/before/limit) curl -s "https://icrc-api.internetcomputer.org/api/v2/ledgers/mxzaz-hqaaa-aaaar-qaada-cai/accounts?limit=10" ``` ### SNS API — SNS list and proposals (prefer v2 with cursor pagination) ```bash # List SNSes (v2: after/before/limit, next_cursor/previous_cursor) curl -s "https://sns-api.internetcomputer.org/api/v2/snses?limit=10" # List proposals for an SNS root canister (v2: cursor pagination) # Replace ROOT_CANISTER_ID with a real SNS root canister ID curl -s "https://sns-api.internetcomputer.org/api/v2/snses/ROOT_CANISTER_ID/proposals?limit=5" # List neurons for an SNS (v2: after/before/limit) curl -s "https://sns-api.internetcomputer.org/api/v2/snses/ROOT_CANISTER_ID/neurons?limit=10" ``` ### Ledger API — Mainnet ICP token (prefer v2 for cursor pagination) ```bash # List accounts (v2: after/before/limit). Note this API's own naming: # rows come back under `accounts` (not `data`), and the back-cursor is # `prev_cursor` (not `previous_cursor` as on the IC/ICRC/SNS APIs). curl -s "https://ledger-api.internetcomputer.org/v2/accounts?limit=10" # Get account by account_identifier (64-char hex) curl -s "https://ledger-api.internetcomputer.org/accounts/ACCOUNT_IDENTIFIER" # List transactions (v2: cursor pagination) curl -s "https://ledger-api.internetcomputer.org/v2/transactions?limit=10" # Total supply (latest) curl -s "https://ledger-api.internetcomputer.org/supply/total/latest" ``` ### Metrics API ```bash # Average cycle burn rate curl -s "https://metrics-api.internetcomputer.org/api/v1/average-cycle-burn-rate" # Governance metrics curl -s "https://metrics-api.internetcomputer.org/api/v1/governance-metrics" # ICP/XDR conversion rates (with optional start/end/step) curl -s "https://metrics-api.internetcomputer.org/api/v1/icp-xdr-conversion-rates?start=1700000000&end=1700086400&step=86400" ``` ### Fetching OpenAPI spec (for codegen or validation) ```bash # IC API v3 curl -s "https://ic-api.internetcomputer.org/api/v3/openapi.json" -o ic-api-v3.json # ICRC API curl -s "https://icrc-api.internetcomputer.org/openapi.json" -o icrc-api.json # SNS API curl -s "https://sns-api.internetcomputer.org/openapi.json" -o sns-api.json # Ledger API curl -s "https://ledger-api.internetcomputer.org/openapi.json" -o ledger-api.json # Metrics API v1 curl -s "https://metrics-api.internetcomputer.org/api/v1/openapi.json" -o metrics-api-v1.json ``` ## Deploy & Test No canister deployment is required. These are external HTTP APIs. Test from the shell or your app: ```bash # Smoke test: IC API root curl -s -o /dev/null -w "%{http_code}" "https://ic-api.internetcomputer.org/api/v3/" # Expected: 200 # Smoke test: ICRC ledgers list curl -s -o /dev/null -w "%{http_code}" "https://icrc-api.internetcomputer.org/api/v2/ledgers?limit=1" # Expected: 200 ``` ## Verify It Works ```bash # 1. IC API returns canister list with data array (v4 — the preferred list endpoint) curl -s "https://ic-api.internetcomputer.org/api/v4/canisters?limit=1" | head -c 200 # Expected: JSON with "data", "next_cursor" and "previous_cursor" keys, and one canister # 2. ICRC API returns ledger list curl -s "https://icrc-api.internetcomputer.org/api/v2/ledgers?limit=1" | head -c 200 # Expected: JSON with "data" and ledger entries # 3. Ledger API returns supply (array of [timestamp, value]) curl -s "https://ledger-api.internetcomputer.org/supply/total/latest" # Expected: JSON array with two elements (timestamp and supply string) # 4. OpenAPI specs are valid JSON curl -s "https://ic-api.internetcomputer.org/api/v3/openapi.json" | python3 -c "import sys,json; json.load(sys.stdin); print('OK')" # Expected: OK ``` --- ## ICP CLI --- name: icp-cli description: "Guides use of the icp command-line tool for building and deploying Internet Computer applications. Covers project configuration (icp.yaml), recipes, environments, canister lifecycle, identity management, and bundling a project into a self-contained .icp package (icp project bundle). Use when building, deploying, or managing any IC project. Use when the user mentions icp, dfx, canister deployment, local network, project setup, or bundling/packaging an app as an .icp file. Do NOT use for canister-level programming patterns like access control, inter-canister calls, or stable memory — use domain-specific skills instead." license: Apache-2.0 metadata: title: ICP CLI category: Infrastructure --- # ICP CLI ## What This Is The `icp` command-line tool builds and deploys applications on the Internet Computer. It replaces the legacy `dfx` tool with YAML configuration, a recipe system for reusable build templates, and an environment model that separates deployment targets from network connections. Never use `dfx` — always use `icp`. Before generating any `icp` command not explicitly documented here, run `icp --help` or `icp --help` to verify the command and its flags exist. Do not infer flags from `dfx` equivalents — the CLIs are not flag-compatible. ## Installation ```bash npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm ``` `ic-wasm` is required when using official recipes (`@dfinity/rust`, `@dfinity/motoko`, `@dfinity/static-site`, `@dfinity/asset-canister`) — they depend on it for optimization and metadata embedding. Requires [Node.js](https://nodejs.org/) >= 22. Also available via Homebrew and shell script installer — see the [icp-cli releases](https://github.com/dfinity/icp-cli/releases). **Linux note:** On minimal installs, you may need system libraries: `sudo apt-get install -y libdbus-1-3 libssl3 ca-certificates` (Ubuntu/Debian) or `sudo dnf install -y dbus-libs openssl ca-certificates` (Fedora/RHEL). ## Prerequisites - For Rust canisters: `rustup target add wasm32-unknown-unknown` - For Motoko canisters: `npm i -g ic-mops` and a `mops.toml` at the project root with the Motoko compiler version and a `[canisters]` entry: ```toml [toolchain] moc = "1.9.0" [canisters.backend] main = "src/backend/main.mo" ``` The `@dfinity/motoko@v5+` recipe compiles via `mops build `. The canister name in `icp.yaml` must exactly match a key in `[canisters]` — a missing or mismatched key causes `mops build` to fail with `No Motoko canisters found in mops.toml configuration` (see Pitfall 17). Without `mops.toml`, the recipe fails because `mops` is not found. Templates include `mops.toml` automatically; for manual projects, create it before running `icp build`. Load `mops-cli` for `[canisters]` configuration options, dependency management, and `mops build` details. ## Common Pitfalls 1. **Using `dfx` instead of `icp`.** The `dfx` tool is legacy. All commands have `icp` equivalents — see `references/dfx-migration.md` for the full command mapping. Never generate `dfx` commands or reference `dfx` documentation. Configuration uses `icp.yaml`, not `dfx.json` — and the structure differs: canisters are an array of objects, not a keyed object. 2. **Using `--network ic` to deploy to mainnet.** icp-cli uses environments, not direct network targeting. The correct flag is `-e ic` (short for `--environment ic`). ```bash # Wrong icp deploy --network ic # Correct icp deploy -e ic ``` Note: `-n` / `--network` targets a network directly and works with canister IDs (principals). Use `-e` / `--environment` when referencing canisters by name. For token and cycles operations, use `-n` since they don't reference project canisters. 3. **Using a recipe without a version pin.** icp-cli rejects unpinned recipe references. Always include an explicit version. Official recipes are hosted at [dfinity/icp-cli-recipes](https://github.com/dfinity/icp-cli-recipes). ```yaml # Wrong — rejected by icp-cli recipe: type: "@dfinity/rust" # Correct — pinned version recipe: type: "@dfinity/rust@v3.3.0" ``` 4. **Writing manual build steps when a recipe exists.** Official recipes handle Rust, Motoko, and asset canister builds. Use `recipe: { type: "@dfinity/rust@v3.3.0" }` instead of writing shell commands in `build.steps` — the Rust recipe defaults the Cargo `package` to the canister name, so no configuration is needed when they match (see Pitfall 21). 5. **Not committing `.icp/data/` to version control.** Mainnet canister IDs are stored in `.icp/data/mappings/.ids.json`. Losing this file means losing the mapping between canister names and on-chain IDs. Always commit `.icp/data/` — never delete it. Add `.icp/cache/` to `.gitignore` (it is ephemeral and rebuilt automatically). If you have environments using a connected network that gets reset frequently you can add those specific environment mapping files to .gitignore. **Never** add the entire `.icp` or `.icp/data` directory to gitignore. 6. **Using `icp identity use` instead of `icp identity default`.** The dfx command `dfx identity use ` became `icp identity default ` (setter). `icp identity default` with no argument is the getter — it prints the current default identity, equivalent to `dfx identity whoami`. The command `icp identity use` does not exist. Similarly, `dfx identity get-principal` became `icp identity principal`, and `dfx identity remove` became `icp identity delete`. 7. **Confusing networks and environments.** A network is a connection endpoint (URL). An environment combines a network + canisters + settings. You deploy to environments (`-e`), not networks. Multiple environments can target the same network with different settings (e.g., staging and production both on `ic`). 8. **Writing `networks` or `environments` as a YAML map instead of an array.** Both `networks` and `environments` are arrays of objects in `icp.yaml`, not maps: ```yaml # Wrong — map syntax networks: local: mode: managed environments: staging: network: ic # Correct — array syntax networks: - name: local mode: managed environments: - name: staging network: ic canisters: [backend, frontend] ``` 9. **Forgetting that local networks are project-local.** Unlike dfx which runs one shared global network, icp-cli runs a local network per project. You must run `icp network start -d` in your project directory before deploying locally. The local network auto-starts with system canisters and seeds accounts with ICP and cycles. Stop it when done: ```bash icp network start -d # start background network icp deploy # build + deploy + sync icp network stop # stop when done ``` 10. **Not specifying build commands for a frontend canister.** dfx automatically runs `npm run build` for asset canisters. icp-cli requires explicit build commands in the recipe configuration: ```yaml canisters: - name: frontend recipe: type: "@dfinity/static-site@v0.4.3" # recommended frontend recipe (certified-assets) configuration: dir: dist build: - npm install - npm run build ``` 11. **Expecting `output_env_file` or `.env` with canister IDs.** dfx writes canister IDs to a `.env` file (`CANISTER_ID_BACKEND=...`) via `output_env_file`. icp-cli does not generate `.env` files. Instead, it injects canister IDs as environment variables (`PUBLIC_CANISTER_ID:`) directly into canisters during `icp deploy`. Frontends read these from the `ic_env` cookie set by the frontend canister (static-site or the legacy asset canister). Remove `output_env_file` from your config and any code that reads `CANISTER_ID_*` from `.env` — frontends use the `ic_env` cookie, and canister code reads the same variables at runtime (see Canister Environment Variables below and Pitfall 22). 12. **Expecting `dfx generate` for TypeScript bindings.** icp-cli does not have a `dfx generate` equivalent. Use `@icp-sdk/bindgen` (>= 0.4.0) with `@icp-sdk/core` pinned to `^6` (the rest of the SDK peers `^6`, so a different major fails to install with `ERESOLVE`) to generate TypeScript bindings from `.did` files at build time. Use `outDir: "./src/bindings"` so imports are clean (e.g., `./bindings/backend`). The `.did` file must exist on disk — either commit it to the repo, or generate it with `icp build` first (recipes auto-generate it when `candid` is not specified). See `references/binding-generation.md` for the full Vite plugin setup. 13. **Porting the `@dfinity/agent` actor setup to `@icp-sdk/bindgen`.** The old `@dfinity/agent` pattern was `createActor(canisterId, { agent })` with `new HttpAgent({ identity, host })`. The `@icp-sdk/bindgen` pattern is `createActor(canisterId, { agentOptions: { identity, rootKey } })` — the binding creates the agent internally, and `host` stays unset in browser code. A pre-built `{ agent }` still works, but `new HttpAgent()` is deprecated. See `references/binding-generation.md` for the correct pattern and for when `host` must be set. 14. **Mixing canister-level fields across config styles.** When using a recipe, the only valid canister-level fields are `name`, `recipe`, `sync`, `settings`, and `init_args`. Fields like `candid`, `build`, or `wasm` are **not** valid at canister level alongside a recipe — recipe-specific options go inside `recipe.configuration`. When using bare `build` (no recipe), valid canister-level fields are `name`, `build`, `sync`, `settings`, and `init_args`. The field `init_arg_file` does not exist — use `init_args.path` instead (e.g., `init_args: { path: ./args.bin, format: bin }`). For the authoritative field reference, consult the [icp-cli configuration reference](https://cli.internetcomputer.org/1.2/reference/configuration.md). ```yaml # Wrong — candid is not a canister-level field when using a recipe canisters: - name: backend candid: backend/backend.did recipe: type: "@dfinity/rust@v3.3.0" # Correct — candid goes inside recipe.configuration canisters: - name: backend recipe: type: "@dfinity/rust@v3.3.0" configuration: candid: backend/backend.did ``` 15. **Placing `mops.toml` where `mops` cannot find it.** `mops` searches upward from the build working directory. Where to place `mops.toml` depends on how the canister is defined: - **Inline canisters** (defined directly in `icp.yaml`): build cwd is the project root. Place `mops.toml` at the project root next to `icp.yaml`. A `mops.toml` in `src/backend/` will not be found. - **Path-based canisters** (referenced via `canisters/*` or `./my-canister`, each with its own `canister.yaml`): build cwd is the canister directory. Place `mops.toml` in each canister's directory for per-canister dependencies and compiler versions, or omit it to fall back to a shared `mops.toml` in a parent directory. When `mops.toml` is not found, `mops build` fails because it cannot locate the project configuration. When `mops.toml` exists but is missing the matching `[canisters.]` entry, see Pitfall 17. 16. **Misunderstanding Candid file generation with recipes.** Binding generation tools (e.g. `@icp-sdk/bindgen`) require a `.did` file at a known path on disk. Where to configure it depends on the recipe: **Rust** — `candid` goes inside `recipe.configuration` in `icp.yaml`: - If **specified**: the file must already exist. The recipe uses it as-is and does not generate one. - If **omitted**: the recipe auto-generates the `.did` via `candid-extractor` into the build cache (no predictable project path). To generate and commit it, then add `candid: backend/backend.did` inside `recipe.configuration`: ```bash cargo install candid-extractor # one-time setup icp build backend candid-extractor target/wasm32-unknown-unknown/release/backend.wasm > backend/backend.did ``` **Motoko (v5 recipe)** — `mops build` auto-generates the `.did` to `.mops/.build/.did`. - **No binding generation needed** — nothing to do. The generated `.did` in `.mops/.build/` is sufficient; do not commit it. - **Binding generation needed** — generate a curated `.did` at a stable path with `mops generate candid`: ```bash mops generate candid backend ``` This extracts the Candid interface directly from Motoko source **without compiling WASM**. With `[canisters.backend].candid` set in `mops.toml`, it overwrites that file; otherwise it writes `.did` next to `main` (e.g. `main = "src/backend/main.mo"` → `src/backend/backend.did`) and records the path in `mops.toml`. Point the binding tool's config (e.g. `@icp-sdk/bindgen`'s `didFile`) at that `.did`. **Re-run after any interface change**, and commit the `.did` and `mops.toml` together. Load `mops-cli` for details. (The older `mops build backend` + `cp .mops/.build/backend.did …` two-step still works but builds the full WASM just to extract the interface.) 17. **Missing or mismatched `[canisters]` key in `mops.toml`.** The `@dfinity/motoko@v5+` recipe calls `mops build `, where the name comes from the `name` field in `icp.yaml`. `mops build` requires a matching `[canisters.]` entry in `mops.toml`. If the entry is absent or the key does not exactly match (including casing), the build fails with: ``` No Motoko canisters found in mops.toml configuration ``` Add the matching entry — the key must equal the `name:` value in `icp.yaml`: ```toml [canisters.backend] main = "src/backend/main.mo" ``` 18. **Port 8000 already in use when starting the local network.** Two scenarios: **Scenario A — another icp-cli project holds the port.** Stop that project's network using `--project-root-override` (a global flag available on all commands): ```bash icp network stop --project-root-override /path/to/other-project ``` To run both networks at once instead of stopping one — e.g. parallel git worktrees — set `gateway.port: 0` so each gets a free port. See "Parallel agents and worktrees" under How It Works. **Scenario B — a non-icp service holds the port.** Configure an alternate port in `icp.yaml` and read the actual URLs dynamically via `icp network status --json` rather than hardcoding localhost:8000: ```yaml networks: - name: local mode: managed gateway: port: 8001 ``` ```bash icp network status --json # returns gateway URL, replica URL, etc. ``` 19. **`icp new` hangs in CI without `--silent`.** Without `--define` flags, `icp new` launches an interactive prompt that blocks indefinitely in non-interactive environments. Always pass `--subfolder`, `--define`, and `--silent` for scripted use: ```bash icp new my-project --subfolder rust --define project_name=my-project --silent ``` 20. **Using the anonymous identity on mainnet.** The local network seeds all managed identities — including the anonymous identity, which is the default — with ICP and cycles on start, so local development works out of the box with no identity or cycles setup required. On mainnet this does not apply, and the anonymous identity should never be used: it is shared by anyone, meaning ICP sent to it is publicly accessible and canisters deployed under it are uncontrolled. Before deploying to mainnet, switch to a named identity: ```bash icp identity list # check available identities (`identity`, never `identities`) icp identity default my-identity # switch to an existing one # or: icp identity new my-identity && icp identity default my-identity ``` Then verify it has funds — a new identity will need to be funded with ICP or cycles before proceeding: ```bash icp token balance -n ic # check ICP balance on mainnet icp cycles balance -n ic # check cycles balance on mainnet icp identity account-id # get account ID to fund if needed ``` With a card and no ICP, `icp cycles buy --amount -n ic` (or `--cycles ` for the amount the deploy needs; see "Funding an identity for mainnet" below for the estimate) buys cycles for the identity itself through CyclePay's on-chain gateway: the agent creates the order, the human pays on the link it prints, and the cycles land on the identity's cycles-ledger account, where `icp deploy -e ic` spends from. Load the `buy-cycles` skill for the flow, the agent flags (`--yes --no-open --json`) and the order states. 21. **Over-specifying (or wrongly omitting) `package` in the Rust recipe.** As of `@dfinity/rust@v3.3.0` the `package` config is **optional** and defaults to the canister `name` in `icp.yaml`. By convention, keep the canister `name` equal to the `[package] name` in `Cargo.toml` and omit `package` entirely: ```yaml # Preferred — name matches the Cargo package, so no package config canisters: - name: backend # matches [package] name = "backend" in Cargo.toml recipe: type: "@dfinity/rust@v3.3.0" # Required only when the names differ (e.g. a workspace crate) canisters: - name: backend recipe: type: "@dfinity/rust@v3.3.0" configuration: package: my-project-backend # actual [package] name in Cargo.toml ``` Omitting `package` when the names **differ** causes `cargo build` to fail with a package-not-found error — set it to the exact `[package] name`. On recipe versions before `v3.3.0`, `package` was required in all cases. 22. **Hand-wiring canister IDs with setter methods or deploy scripts.** Controller-only setters (`setBridge(principal)`) called by a post-deploy script — or sibling IDs hardcoded in `settings.environment_variables` or init args — are unnecessary: `icp deploy` injects every canister's ID into every canister's settings as `PUBLIC_CANISTER_ID:`, readable by canister code at runtime with the correct per-environment value (see Canister Environment Variables). Setter wiring is also more fragile: a `--mode reinstall` silently wipes the stored pointer, while the automatic variables are re-stamped on every deploy. ## How It Works ### Project Creation `icp new` scaffolds projects from templates. Pass `--subfolder`, `--define`, and `--silent` for non-interactive use: ```bash icp new my-project --subfolder rust --define project_name=my-project --silent ``` Available templates and options: [dfinity/icp-cli-templates](https://github.com/dfinity/icp-cli-templates). ### Build → Deploy → Sync ```text Source Code → [Build] → WASM → [Deploy] → Running Canister → [Sync] → Configured State ``` `icp deploy` runs all three phases in sequence: 1. **Build** — Compile canisters to WASM (via recipes or explicit build steps) 2. **Deploy** — Create canisters (if new), apply settings, install WASM 3. **Sync** — Post-deployment operations via `script` or `plugin` steps (e.g., uploading assets). Asset uploading is not built into the CLI: a frontend recipe supplies a `plugin` sync step that uploads the `dir` contents — the recommended `@dfinity/static-site@v0.4.3` (certified-assets) or the legacy `@dfinity/asset-canister@v2.2.1`. The legacy built-in `type: assets` step is removed in icp-cli 0.3.0 — see the `static-site` skill. Run phases separately for more control: ```bash icp build # Build only icp deploy # Full pipeline (build + deploy + sync) icp sync my-canister # Sync only (e.g., re-upload assets) ``` ### Environments and Networks Two implicit environments are always available: | Environment | Network | Purpose | |-------------|---------|---------| | `local` | `local` (managed, localhost:8000) | Local development | | `ic` | `ic` (connected, https://icp-api.io) | Mainnet production | The `ic` network is protected and cannot be overridden. Custom environments enable multiple deployment targets on the same network: ```yaml environments: - name: staging network: ic canisters: [frontend, backend] settings: backend: compute_allocation: 5 - name: production network: ic canisters: [frontend, backend] settings: backend: compute_allocation: 20 freezing_threshold: 7776000 ``` ### Parallel agents and worktrees #### Isolating the gateway port Local networks are project-local — keyed by project root (Pitfall 9). Separate git worktrees of the same repo are separate project roots, so each worktree can run its own independent local network. This lets multiple agents or branches build and deploy in parallel without interfering. The only obstacle is the gateway port: every worktree defaults to `8000`, so the second `icp network start` fails with a port conflict. Set the managed network's gateway port to `0` so the OS assigns a free ephemeral port per worktree: ```yaml networks: - name: local mode: managed gateway: port: 0 # 0 = OS picks a free port — avoids collisions across worktrees ``` `icp network start -d` prints the chosen port (`Network started on port 58157`). To recover it afterward — for tests, scripts, or another agent — query the running network and read `gateway_url`: ```bash icp network start -d icp network status --json # -> { "managed": true, "api_url": "http://localhost:58157/", "gateway_url": "http://localhost:58157/", ... } icp network status --json | jq -r '.gateway_url' # http://localhost:58157/ ``` Never hardcode `localhost:8000` when using `port: 0` — the port changes on every start, so read `gateway_url` (or `api_url`) from `icp network status --json` each time. To target a specific worktree's network from outside its directory, pass the global `--project-root-override ` flag (e.g. `icp network status --json --project-root-override /path/to/worktree`). #### Isolating global CLI state (`ICP_HOME`) Project-local networks isolate *per-project* state only. Identities, settings, and the downloaded package cache are **global** — one directory per OS user, at `~/.local/share/icp-cli/` (Linux), `~/Library/Application Support/org.dfinity.icp-cli/` (macOS), or `%APPDATA%\icp-cli\data\` (Windows). Each of `identity/`, `settings/`, and `pkg/` inside it is guarded by a blocking advisory lock (`.lock`), so concurrent `icp` invocations touching the same one **serialize** — they wait for the lock, they do not fail. Several agents building at once contend on the package cache lock while recipes or the network launcher download. `ICP_HOME` overrides that directory, giving each agent its own copy: ```bash export ICP_HOME=/path/to/worktree/.icp-home icp identity new dev --storage plaintext icp deploy ``` Caveats, in the order they bite: - **The OS keyring is still shared.** Keyring entries are keyed by service `icp-cli` plus the identity name — `ICP_HOME` is not part of the key. Two isolated homes that each run `icp identity new dev` (keyring is the default storage) write the same entry and overwrite one another. Pass `--storage plaintext` so the key lands at `$ICP_HOME/identity/keys/.pem` and the isolation is real. The same applies to `icp identity import` and `icp identity link web`, whose session key also defaults to the keyring. Plaintext keys are for throwaway local and CI identities only — never for an identity that controls mainnet canisters or holds value (Pitfall 20). - **A fresh home is empty.** No identities, no settings, no cache. The default identity is anonymous, which managed local networks seed automatically but which is unusable on mainnet. - **The package cache is re-downloaded per home.** `pkg/` holds the network launcher and every recipe, and reaches hundreds of MB. Seed a new home by copying a warm `pkg/` into it, or point all homes at one shared launcher binary with `ICP_CLI_NETWORK_LAUNCHER_PATH=/path/to/icp-cli-network-launcher`. - **`ICP_HOME` must be set for every `icp` invocation** in that agent's session, not just the first. A command that misses it silently falls back to the shared default home and a different default identity. Reach for this only when agents actually contend. Separate worktrees that share one identity set and tolerate serialized cache access do not need it. ### Install Modes ```bash icp deploy # Auto: install new, upgrade existing (default) icp deploy --mode upgrade # Preserve state, run upgrade hooks icp deploy --mode reinstall # Clear all state (dangerous) ``` ### Bundling a project into an `.icp` package (experimental) `icp project bundle` packages a project into a self-contained deployable archive (icp-cli >= 0.3.0). **This is an experimental feature, intentionally hidden from help output** — `icp --help` and `icp project --help` do not list it, but the command exists and works. Do not conclude it doesn't exist because help omits it, and do not suggest it proactively — use it only when the user explicitly asks to bundle an app or produce an `.icp` package. ```bash icp project bundle --output my-app.icp # gzipped tar; --output accepts any path ``` For how to deploy from a bundle, what the archive contains, the conditions that make bundling fail, and uploading a package to a Caffeine cloud engine, see `references/bundling.md`. ## Configuration ### Rust canister ```yaml canisters: - name: backend recipe: type: "@dfinity/rust@v3.3.0" configuration: candid: backend.did # optional — if specified, file must exist (auto-generated when omitted) # package: my-crate # optional — only when the Cargo [package] name differs from the canister name ``` By convention the canister `name` must match the `[package] name` in `Cargo.toml`. When they match, `package` is optional (recipe >= v3.3.0 defaults it to the canister name). Set `package` explicitly only when the Cargo package name differs — e.g. a workspace with a differently named crate (see Pitfall 21). ### Motoko canister The v5 recipe delegates compilation to `mops build`. Canister configuration (`main`, `candid`, `args`) moves from `icp.yaml` to `mops.toml`: ```yaml # icp.yaml canisters: - name: backend recipe: type: "@dfinity/motoko@v5.0.0" ``` ```toml # mops.toml [toolchain] moc = "1.9.0" [canisters.backend] main = "src/backend/main.mo" candid = "backend.did" # optional — auto-generated to .mops/.build/ when omitted ``` The canister name (`backend`) must exactly match between `icp.yaml` and `mops.toml`. No `recipe.configuration` block is needed in `icp.yaml`. ### Static site (frontend) ```yaml canisters: - name: frontend recipe: type: "@dfinity/static-site@v0.4.3" configuration: dir: dist build: - npm install - npm run build ``` `@dfinity/static-site` (the certified-assets canister) is the recommended frontend recipe. The legacy `@dfinity/asset-canister@v2.2.1` recipe is still supported for existing projects — see the `static-site` skill for both and for migration. For multi-canister projects, list all canisters in the same `canisters` array. icp-cli builds them in parallel. There is no `dependencies` field — use Canister Environment Variables for inter-canister communication. ### Custom build steps (no recipe) When not using a recipe, only `name`, `build`, `sync`, `settings`, and `init_args` are valid canister-level fields. There are no `wasm`, `candid`, or `metadata` fields — handle these in the build script instead: - **WASM output**: copy the final WASM to `$ICP_WASM_OUTPUT_PATH` - **Candid metadata**: use `ic-wasm` to embed `candid:service` metadata - **Candid file**: the `.did` file is referenced only in the `ic-wasm` command, not as a YAML field ```yaml canisters: - name: backend build: steps: - type: script commands: - cargo build --target wasm32-unknown-unknown --release - cp target/wasm32-unknown-unknown/release/backend.wasm "$ICP_WASM_OUTPUT_PATH" - ic-wasm "$ICP_WASM_OUTPUT_PATH" -o "$ICP_WASM_OUTPUT_PATH" metadata candid:service -f backend/backend.did -v public --keep-name-section ``` ### Available recipes | Recipe | Type string | Required config | Optional config | |--------|------------|-----------------|-----------------| | Rust | `@dfinity/rust@v3.3.0` | — | `package` (defaults to canister name), `candid`, `locked`, `shrink`, `compress`, `metadata` | | Motoko | `@dfinity/motoko@v5.0.0` | — | `shrink`, `compress`, `metadata` | | Static site (frontend) | `@dfinity/static-site@v0.4.3` | `dir` | `build`, `presync`, `metadata` | | Asset (legacy frontend) | `@dfinity/asset-canister@v2.2.1` | `dir` | `build`, `version` | | Prebuilt | `@dfinity/prebuilt@v2.1.0` | `path` | `sha256`, `shrink`, `compress`, `metadata` | `@dfinity/static-site` is the recommended way to host a frontend; `@dfinity/asset-canister` is the legacy asset canister (see the `static-site` skill). Verify latest recipe versions at [dfinity/icp-cli-recipes releases](https://github.com/dfinity/icp-cli-recipes/releases). Use `icp project show` to see the effective configuration after recipe expansion. ### Canister Environment Variables During `icp deploy`, icp-cli injects the ID of **every canister in the environment** into **every canister's settings** as `PUBLIC_CANISTER_ID:` (the principal in text form). These are canister *settings* env vars, readable **at runtime by canister code**, with per-environment values refreshed on every deploy — the same code is correct on local, staging, and mainnet with zero configuration. **Use these for inter-canister wiring** instead of setter methods, init args, or post-deploy scripts (Pitfall 22). Read them lazily at call time — Motoko: `Runtime.envVar(...)` (motoko-core v2.1.0+), Rust: `ic_cdk::api::env_var_value(...)` — see `references/canister-env-vars.md` for code and the first-install/reinstall behavior. **Frontend** (JavaScript): the frontend canister (static-site or the legacy asset canister) exposes the variables through the `ic_env` cookie, set on all HTML responses. Read it with `@icp-sdk/core`: ```js import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env"; const backendId = safeGetCanisterEnv()?.["PUBLIC_CANISTER_ID:backend"]; ``` **Caveats:** - Variables are only updated at deploy time. After adding a canister, run `icp deploy` (without a canister name) so every canister gets the complete ID set. - User-defined variables (`settings.environment_variables` in `icp.yaml`) are static YAML strings shared across environments: a create-class install (first install or `--mode reinstall`) re-applies them, overwriting anything set with `icp canister settings update --add-environment-variable`. Re-assert environment-specific values (e.g. production origins) after such a deploy. - The replica caps an environment-variable *value* at 128 characters. Full reference: [icp-cli environment variables](https://cli.internetcomputer.org/1.2/reference/environment-variables/). ### Web identity flows Two specialized skills cover `icp identity link web`. Load the right one for the task — both document the stdin "Press Enter" block, the browser sign-in step, and their flag-specific pitfalls: - `deploy-to-cloud-engine` — link the CLI to a cloud engine console with `--app `, then deploy to the engine's subnet. It also covers deploying to an engine without the CLI, through the ICP MCP connector, which is the route for a sandboxed chat where this link cannot complete - `agent-web-identity` — obtain a delegation for an app-specific principal with `--app `, then make canister calls as the user ### Funding an identity for mainnet A new identity has neither ICP nor cycles. `icp deploy -e ic` then fails with `Insufficient cycles. Requested: cycles, available balance: 0 cycles.` (or `insufficient liquid cycles balance` from the cycles ledger): the deploying identity's cycles-ledger balance on mainnet is empty. The CLI does not estimate or warn beforehand, so do it yourself before the deploy, not after the failure: 1. **Count the canisters still to create.** `icp deploy` creates every canister of the environment that has no id in `.icp/data/mappings/.ids.json` (a `name: id` map; absent before the first deploy, so then it is all of them). `icp deploy --no-create -e ic` lists them without touching the network: it builds, then refuses with `the following canisters do not exist: ...`. 2. **Estimate.** Each creation takes the `--cycles` amount (default 2T; suffixes `k`/`m`/`b`/`t`) plus the cycles-ledger fee of 100M out of the identity's balance, so N canisters need `N × (2T + 100M)`. The network's creation fee (500B on a 13-node subnet) and the install itself come out of each canister's 2T, not the identity's balance; add a margin of about 10% so a top-up is possible afterwards. 3. **Compare** with `icp cycles balance -n ic --identity "$ID"` for the identity that will deploy (Pitfall 20; `-q` prints the bare number). 4. **If short, do not guess: tell the human the gap and offer both ways to close it.** - With ICP (`icp token balance -n ic` shows enough): `icp cycles mint --cycles -n ic` converts just that much (see `cycles-management`). - With a card and no ICP: `icp cycles buy --cycles -n ic --identity "$ID" --no-open --yes --json` pays the least that buys the gap; load the `buy-cycles` skill for the flow, the link hand-off and the order states. The human pays; the agent waits for `icp cycles balance -n ic` to reach the estimate. 5. **Deploy** as the same identity: `icp deploy -e ic --identity "$ID"`. ## Additional References For the complete CLI and configuration schema, consult the [icp-cli documentation index](https://cli.internetcomputer.org/llms.txt). For detailed guides on specific topics, consult these reference files when needed: - **`references/binding-generation.md`** — TypeScript binding generation with `@icp-sdk/bindgen` (Vite plugin, CLI, actor setup) - **`references/bundling.md`** — `icp project bundle` in full: archive contents, the four conditions that make bundling fail, and uploading an `.icp` package to a Caffeine cloud engine - **`references/canister-env-vars.md`** — reading `PUBLIC_CANISTER_ID:` from canister code at runtime (Motoko/Rust examples, lazy-read pattern) - **`references/dev-server.md`** — Vite dev server configuration to simulate the `ic_env` cookie locally. Important: wrap `getDevServerConfig()` in a `command === "serve"` guard so it only runs during `vite dev`, not `vite build`. - **`references/dfx-migration.md`** — Complete dfx → icp migration guide (command mapping, config mapping, identity/canister ID migration, frontend package migration, post-migration verification checklist) --- ## ICP Deploy Check --- name: icp-deploy-check description: Pre-deploy safety gate for an Internet Computer Rust canister (ic-cdk). A fast, read-only checklist for the five deploy-time footguns that brick a canister or let anyone drain it - anonymous-principal access, fetch_root_key in shipped code, unguarded admin methods, pre_upgrade traps, single controller - with grep signals, the tracing rules to confirm each hit, and a PASS/FAIL/REVIEW report. Use before `icp deploy -e ic` (or `dfx deploy --network ic`), in CI, or when asked whether a canister is ready or safe for mainnet. For the secure-coding patterns themselves, use canister-security. license: Apache-2.0 compatibility: "a local Rust canister repo (ic-cdk >= 0.18); ripgrep; no network, no mainnet action" metadata: title: ICP Deploy Check category: Security --- # ICP deploy check Run this static, read-only gate over a Rust canister repo **before** a mainnet deploy. It reads source and reports; it never deploys, never calls mainnet, never needs a key. The fix patterns behind each check live in the `canister-security` skill — this skill is the checklist, that one is the reference. Scope: every update entrypoint and the `init`/`pre_upgrade`/`post_upgrade` hooks in the Rust `ic-cdk` canister(s), plus any frontend or agent code in the same repo (check #2 only). Produce one row per check: `PASS` / `FAIL` / `REVIEW` / `N/A` with `file:line` evidence. ## Enumerating update entrypoints Checks #1 and #3 both start from the full list of update methods. Match the attribute with or without arguments — `#[update(guard = "...")]`, `#[update(name = "...")]` and `#[ic_cdk::update(manual_reply = true)]` are all entrypoints: ```bash rg -n -A4 '#\[(ic_cdk::)?update\b' ``` `\b` matches both `update]` and `update(`; a bare `'update\]'` pattern silently skips every parameterized entrypoint. Record each method's name, its attribute arguments (especially `guard = "..."`), and its body. Callers are read with `ic_cdk::api::msg_caller()` (ic-cdk >= 0.18). Older code uses `ic_cdk::caller()` / `ic_cdk::api::caller()` — treat them as equivalent when tracing. ## The five checks ### 1. Anonymous principal reaches a state change — FAIL if reachable Every state-changing update must reject `Principal::anonymous()` **before** its first mutation. - **Trace, don't pattern-match.** For each update that mutates state (writes a `thread_local!`/stable structure, credits/debits a balance, mints, sets config, makes a state-changing inter-canister call), confirm that on every path to the mutation the call is rejected (`trap`, `Err` return, or guard `Err`) when the caller is anonymous. Accept any of: - an explicit comparison against `Principal::anonymous()` (`==` with trap/return, or `!=` gating the mutation), on `msg_caller()` or a variable bound to it; - a `guard = "fn_name"` attribute — **open `fn_name`** and confirm its body returns `Err` for the anonymous principal; - a controller/owner/allowlist check that rejects the caller (anonymous can never be a controller). An owner-equality check counts only if the owner can never be anonymous — `RefCell::new(Principal::anonymous())` as the default owner with no `require_authenticated` first means anonymous **is** the owner until `init` runs. - **Not authentication** — FAIL if these are the only "guard": - `CallerGuard` / per-caller locks / `PENDING` sets: these are reentrancy locks, they accept the anonymous principal like any other; - a guard identified only by its name (`require_caller`, `check_access`, ...) without reading its body; - `is_controller(...)` or a comparison whose result is computed but never acted on, or that runs after the mutation. - An update that is deliberately open to anonymous callers (e.g. a public counter, an open sign-up whose cost is bounded) is `REVIEW`, not `FAIL` — state why it is intended. Query methods cannot persist state and are out of scope. ### 2. `fetch_root_key` in shipped code — FAIL if present `fetch_root_key()` (Rust `ic-agent`) / `fetchRootKey()` (JS agent) fetches the root public key **from the replica it is talking to** and trusts it. If that code runs against mainnet, a man-in-the-middle can substitute its own key and forge every certified response. This lives in frontend or agent/client code, not in the canister, so scan the whole repo: ```bash rg -n 'fetch_root_key|fetchRootKey|shouldFetchRootKey' ``` - **FAIL** on any occurrence in a shipped frontend or client path — **even behind an environment check** (`if network === "local"`, `process.env.DFX_NETWORK`, `#[cfg(feature = "local")]`): environment branching is how the call leaks into production builds. The fix is to stop fetching it: pass the root key from the `ic_env` cookie (`IC_ROOT_KEY`, via `safeGetCanisterEnv()`) as `rootKey` to `HttpAgent.create()`. See `canister-security` for the full pattern. - **Not a finding:** test-only code (`#[cfg(test)]`, `tests/`, PocketIC harnesses, scripts that only ever target a local replica) — mark `PASS` with a note. ### 3. Unguarded admin / privileged method — FAIL if not privileged-guarded Mint / burn / migrate / upgrade / config / `set_*` / withdraw updates must be restricted to a controller, owner or admin — not merely to authenticated users. - **Candidates:** from the enumerated update list (not a separate grep), take every method whose name contains — anywhere, not only as a prefix — `(?i)(mint|burn|admin|migrate|upgrade|config|set_|withdraw|transfer_from|owner|controller|pause|allowlist|whitelist)`. Name matching only finds candidates: an update whose visible body changes fees, ownership, other users' balances, or canister-wide settings is privileged regardless of its name. A user-facing method acting on the caller's own account (`deposit`, `transfer`, `claim`) is not privileged — it belongs to check #1. Do not speculate about helpers whose bodies you cannot see (`credit(...)`): judge the code shown and note what is out of view. - **PASS only if** the method (or the body of its `guard = "..."` function) rejects the call unless the caller is a controller (`is_controller(&caller)` acted on), the owner, or a member of an admin set. - **FAIL if** the only protection is anonymous rejection. `guard = "require_authenticated"`, or a body that only checks `!= Principal::anonymous()`, still lets **any** signed-in principal call `set_config`. A `guard =` attribute is evidence of nothing until you have read the guard function. ### 4. `pre_upgrade` trap risk — REVIEW A `pre_upgrade` that serializes a large or unbounded heap can exceed the instruction limit and **trap**, making the canister permanently un-upgradeable. - **Detect:** `rg -n '#\[(ic_cdk::)?pre_upgrade\b' -A10`. `REVIEW` any `pre_upgrade` that serializes (`stable_save`, `candid::encode_*`, `serde`) a collection (`Vec`/`HashMap`/`BTreeMap`/`String`) whose size users can grow. `PASS`/`N/A` when state lives in `ic-stable-structures` and there is no manual copy. - Recommend bounding the data or moving it into `ic-stable-structures`. ### 5. Single controller / no backup — REVIEW (operator, deploy-time) A canister controlled by one principal — especially a plaintext dev identity — is one lost or compromised key from being unrecoverable or silently re-coded. - **Detect:** this is not visible in source. Ask for, or have the operator run, `icp canister status -e ic` (legacy: `dfx canister info --network ic`) and read the controller list. Require a threshold/multisig controller (e.g. an orbit station or SNS) or a documented backup controller principal held offline. A single controller is `REVIEW`, not an automatic `FAIL`. ## Report format ``` Target: (Rust ic-cdk canister) — N update methods [FAIL ] #1 src/lib.rs:42 claim_bonus — credits balance, no anonymous rejection [FAIL ] #3 src/lib.rs:57 set_config — guard require_authenticated rejects only anonymous; needs controller/owner check [PASS ] #2 no fetch_root_key / fetchRootKey in shipped code [N/A ] #4 no pre_upgrade; state in ic-stable-structures [REVIEW] #5 controller set — operator to confirm a backup/multisig controller Verdict: NOT ready to deploy (2 FAIL) ``` A grep hit is a **candidate**: open the `file:line`, trace the guard, and only then mark `FAIL`. A `PASS` must also be traced — a guard attribute or a guard-like name proves nothing on its own. When no source is available, say so and list what you would check rather than inventing `file:line` evidence. ## Boundaries This is a fast pre-deploy gate, not a full audit. It does not cover TOCTOU across `await`, callback-trap ordering, cycle-drain economics, or unbounded storage growth — see the `canister-security` skill for those. It performs **no** network or mainnet action. --- ## ICRC Token Ledgers --- name: icrc-ledger description: "Deploy and interact with ICRC-1/ICRC-2 token ledgers (ICP, ckBTC, ckETH). Covers transfers, balances, approve/transferFrom allowances, fee handling, and ledger deployment. Use when working with ICP transfers, token transfers, balances, ICRC-1, ICRC-2, approve, allowance, or any fungible token on IC. Do NOT use for ckBTC minting or BTC deposit/withdrawal flows — use ckbtc instead." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2" metadata: title: ICRC Token Ledgers category: DeFi --- # ICRC Ledger Standards ## What This Is ICRC-1 is the fungible token standard on Internet Computer, defining transfer, balance, and metadata interfaces. ICRC-2 extends it with approve/transferFrom (allowance) mechanics, enabling third-party spending like ERC-20 on Ethereum. ## Prerequisites - For Motoko: mops with `core = "2.3.1"` in mops.toml - For Rust: `ic-cdk = "0.19"`, `candid = "0.10"`, `icrc-ledger-types = "0.1"` in Cargo.toml ## Canister IDs | Token | Ledger Canister ID | Decimals | |-------|-------------------|----------| | ICP | `ryjl3-tyaaa-aaaaa-aaaba-cai` | 8 | | ckBTC | `mxzaz-hqaaa-aaaar-qaada-cai` | 8 | | ckETH | `ss2fx-dyaaa-aaaar-qacoq-cai` | 18 | Index canisters (for transaction history): - ICP Index: `qhbym-qaaaa-aaaaa-aaafq-cai` - ckBTC Index: `n5wcd-faaaa-aaaar-qaaea-cai` - ckETH Index: `s3zol-vqaaa-aaaar-qacpa-cai` All ICRC-1 ledgers expose `icrc1_fee : () -> (nat) query` to return the current transfer fee. Fees are denominated in the token's smallest unit (e8s for ICP where 1 ICP = 10⁸ e8s, satoshis for ckBTC, wei for ckETH). Each ledger sets its own fee, and fees can change at runtime. ## Common Pitfalls 1. **Assuming all ledgers share the same fee** -- Each ledger sets its own fee (e.g., ICP = 10000 e8s, ckBTC = 10 satoshis). Never copy a fee value from one ledger and use it for another. Look up the fee via `icrc1_fee` (on-chain query or `icp canister call icrc1_fee '()'` via CLI). Fees can also change at runtime, so always handle `BadFee { expected_fee }` — the ledger tells you the correct fee in the error response. 2. **Forgetting approve before transferFrom** -- ICRC-2 transferFrom will reject with `InsufficientAllowance` if the token owner has not called `icrc2_approve` first. This is a two-step flow: owner approves, then spender calls transferFrom. 3. **Not handling Err variants** -- `icrc1_transfer` returns `Result`, not just `Nat`. The error variants are: `BadFee`, `BadBurn`, `InsufficientFunds`, `TooOld`, `CreatedInFuture`, `Duplicate`, `TemporarilyUnavailable`, `GenericError`. You must match on every variant or at minimum propagate the error. 4. **Using wrong Account format** -- An ICRC-1 Account is `{ owner: Principal; subaccount: ?Blob }`, NOT just a Principal. The subaccount is a 32-byte blob. Passing null/None for subaccount uses the default subaccount (all zeros). 5. **Omitting created_at_time** -- Without `created_at_time`, you lose deduplication protection. Two identical transfers submitted within 24h will both execute. Set `created_at_time` to `Time.now()` (Motoko) or `ic_cdk::api::time()` (Rust) for dedup. 6. **Hardcoding canister IDs as text** -- Always use `Principal.fromText("ryjl3-tyaaa-aaaaa-aaaba-cai")` (Motoko) or `Principal::from_text("ryjl3-tyaaa-aaaaa-aaaba-cai")` (Rust). Never pass raw strings where a Principal is expected. 7. **Calling ledger from frontend** -- ICRC-1 transfers should originate from a backend canister, not directly from the frontend. Frontend-initiated transfers expose the user to reentrancy and can bypass business logic. Use a backend canister as the intermediary. 8. **Shell substitution in `--argument-file` / `init_args.path`** -- Expressions like `$(icp identity principal)` do NOT expand inside files referenced by `init_args: { path: ... }` or `--argument-file`. The file is read as literal text. Either use `--argument` on the command line (where the shell expands variables), or pre-generate the file with `envsubst` / `sed` before deploying. 9. **Minting account cannot call `icrc2_approve`** -- If the ledger's `minting_account` and `initial_balances` use the same principal, that principal cannot call `icrc2_approve` — the ledger traps with "the minting account cannot delegate mints." Always use a **separate** principal for `minting_account` and different ones for `initial_balances`. In production, the minting account is typically a dedicated minter canister (e.g., the ckBTC minter); for local development, any principal that differs from your funded accounts works. 10. **Transfers to/from the minting account have zero fee** -- A transfer TO the minting account is a **burn**, and a transfer FROM the minting account is a **mint**. Both require `fee = null` (or `fee = ?0`). Passing the regular transfer fee (e.g., `fee = ?10000` for ICP) will fail with `BadFee { expected_fee = 0 }`. The error message gives no indication that burn/mint semantics are involved — it just says the expected fee is 0. ## Implementation ### Motoko #### Imports and Types ```motoko import Principal "mo:core/Principal"; import Nat "mo:core/Nat"; import Nat8 "mo:core/Nat8"; import Nat64 "mo:core/Nat64"; import Blob "mo:core/Blob"; import Time "mo:core/Time"; import Int "mo:core/Int"; import Runtime "mo:core/Runtime"; ``` #### Define the ICRC-1 Actor Interface ```motoko persistent actor { type Account = { owner : Principal; subaccount : ?Blob; }; type TransferArg = { from_subaccount : ?Blob; to : Account; amount : Nat; fee : ?Nat; memo : ?Blob; created_at_time : ?Nat64; }; type TransferError = { #BadFee : { expected_fee : Nat }; #BadBurn : { min_burn_amount : Nat }; #InsufficientFunds : { balance : Nat }; #TooOld; #CreatedInFuture : { ledger_time : Nat64 }; #Duplicate : { duplicate_of : Nat }; #TemporarilyUnavailable; #GenericError : { error_code : Nat; message : Text }; }; type ApproveArg = { from_subaccount : ?Blob; spender : Account; amount : Nat; expected_allowance : ?Nat; expires_at : ?Nat64; fee : ?Nat; memo : ?Blob; created_at_time : ?Nat64; }; type ApproveError = { #BadFee : { expected_fee : Nat }; #InsufficientFunds : { balance : Nat }; #AllowanceChanged : { current_allowance : Nat }; #Expired : { ledger_time : Nat64 }; #TooOld; #CreatedInFuture : { ledger_time : Nat64 }; #Duplicate : { duplicate_of : Nat }; #TemporarilyUnavailable; #GenericError : { error_code : Nat; message : Text }; }; type TransferFromArg = { spender_subaccount : ?Blob; from : Account; to : Account; amount : Nat; fee : ?Nat; memo : ?Blob; created_at_time : ?Nat64; }; type TransferFromError = { #BadFee : { expected_fee : Nat }; #BadBurn : { min_burn_amount : Nat }; #InsufficientFunds : { balance : Nat }; #InsufficientAllowance : { allowance : Nat }; #TooOld; #CreatedInFuture : { ledger_time : Nat64 }; #Duplicate : { duplicate_of : Nat }; #TemporarilyUnavailable; #GenericError : { error_code : Nat; message : Text }; }; type Value = { #Nat : Nat; #Int : Int; #Text : Text; #Blob : Blob; }; // Remote ledger actor reference (ICP ledger shown; swap canister ID for other tokens) transient let icpLedger = actor ("ryjl3-tyaaa-aaaaa-aaaba-cai") : actor { icrc1_balance_of : shared query (Account) -> async Nat; icrc1_transfer : shared (TransferArg) -> async { #Ok : Nat; #Err : TransferError }; icrc2_approve : shared (ApproveArg) -> async { #Ok : Nat; #Err : ApproveError }; icrc2_transfer_from : shared (TransferFromArg) -> async { #Ok : Nat; #Err : TransferFromError }; icrc1_fee : shared query () -> async Nat; icrc1_decimals : shared query () -> async Nat8; icrc1_metadata : shared query () -> async [(Text, Value)]; icrc1_supported_standards : shared query () -> async [{ name : Text; url : Text }]; }; // Fee for the ICP ledger — look up via icrc1_fee if targeting a different ledger transient let icpFee : Nat = 10000; // Check balance public func getBalance(who : Principal) : async Nat { await icpLedger.icrc1_balance_of({ owner = who; subaccount = null; }) }; // Transfer tokens (this canister sends from its own account) // WARNING: Add access control in production — this allows any caller to transfer tokens public func sendTokens(to : Principal, amount : Nat) : async Nat { let now = Nat64.fromNat(Int.abs(Time.now())); let result = await icpLedger.icrc1_transfer({ from_subaccount = null; to = { owner = to; subaccount = null }; amount = amount; fee = ?icpFee; memo = null; created_at_time = ?now; }); switch (result) { case (#Ok(blockIndex)) { blockIndex }; case (#Err(#InsufficientFunds({ balance }))) { Runtime.trap("Insufficient funds. Balance: " # Nat.toText(balance)) }; case (#Err(#BadFee({ expected_fee }))) { Runtime.trap("Wrong fee. Expected: " # Nat.toText(expected_fee)) }; case (#Err(_)) { Runtime.trap("Transfer failed") }; } }; // ICRC-2: Approve a spender public shared ({ caller }) func approveSpender(spender : Principal, amount : Nat) : async Nat { // caller is captured at function entry in Motoko -- safe across await let now = Nat64.fromNat(Int.abs(Time.now())); let result = await icpLedger.icrc2_approve({ from_subaccount = null; spender = { owner = spender; subaccount = null }; amount = amount; expected_allowance = null; expires_at = null; fee = ?icpFee; memo = null; created_at_time = ?now; }); switch (result) { case (#Ok(blockIndex)) { blockIndex }; case (#Err(_)) { Runtime.trap("Approve failed") }; } }; // ICRC-2: Transfer from another account (requires prior approval) // WARNING: Add access control in production — this allows any caller to transfer tokens public func transferFrom(from : Principal, to : Principal, amount : Nat) : async Nat { let now = Nat64.fromNat(Int.abs(Time.now())); let result = await icpLedger.icrc2_transfer_from({ spender_subaccount = null; from = { owner = from; subaccount = null }; to = { owner = to; subaccount = null }; amount = amount; fee = ?icpFee; memo = null; created_at_time = ?now; }); switch (result) { case (#Ok(blockIndex)) { blockIndex }; case (#Err(#InsufficientAllowance({ allowance }))) { Runtime.trap("Insufficient allowance: " # Nat.toText(allowance)) }; case (#Err(_)) { Runtime.trap("TransferFrom failed") }; } }; } ``` ### Rust #### Cargo.toml Dependencies ```toml [package] name = "icrc_ledger_backend" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] ic-cdk = "0.19" candid = "0.10" icrc-ledger-types = "0.1" serde = { version = "1", features = ["derive"] } ``` #### Complete Implementation ```rust use candid::{Nat, Principal}; use icrc_ledger_types::icrc1::account::Account; use icrc_ledger_types::icrc1::transfer::{TransferArg, TransferError}; use icrc_ledger_types::icrc2::approve::{ApproveArgs, ApproveError}; use icrc_ledger_types::icrc2::transfer_from::{TransferFromArgs, TransferFromError}; use ic_cdk::update; use ic_cdk::call::Call; const ICP_LEDGER: &str = "ryjl3-tyaaa-aaaaa-aaaba-cai"; // Fee for the ICP ledger — look up via icrc1_fee if targeting a different ledger const ICP_FEE: u64 = 10_000; fn ledger_id() -> Principal { Principal::from_text(ICP_LEDGER).unwrap() } // Check balance #[update] async fn get_balance(who: Principal) -> Nat { let account = Account { owner: who, subaccount: None, }; let (balance,): (Nat,) = Call::unbounded_wait(ledger_id(), "icrc1_balance_of") .with_arg(account) .await .expect("Failed to call icrc1_balance_of") .candid_tuple() .expect("Failed to decode response"); balance } // Transfer tokens from this canister's account // WARNING: Add access control in production — this allows any caller to transfer tokens #[update] async fn send_tokens(to: Principal, amount: Nat) -> Result { let fee = Nat::from(ICP_FEE); let transfer_arg = TransferArg { from_subaccount: None, to: Account { owner: to, subaccount: None, }, amount, fee: Some(fee), memo: None, created_at_time: Some(ic_cdk::api::time()), }; let (result,): (Result,) = Call::unbounded_wait(ledger_id(), "icrc1_transfer") .with_arg(transfer_arg) .await .map_err(|e| format!("Call failed: {:?}", e))? .candid_tuple() .map_err(|e| format!("Decode failed: {:?}", e))?; match result { Ok(block_index) => Ok(block_index), Err(TransferError::InsufficientFunds { balance }) => { Err(format!("Insufficient funds. Balance: {}", balance)) } Err(TransferError::BadFee { expected_fee }) => { Err(format!("Wrong fee. Expected: {}", expected_fee)) } Err(e) => Err(format!("Transfer error: {:?}", e)), } } // ICRC-2: Approve a spender #[update] async fn approve_spender(spender: Principal, amount: Nat) -> Result { let fee = Nat::from(ICP_FEE); let args = ApproveArgs { from_subaccount: None, spender: Account { owner: spender, subaccount: None, }, amount, expected_allowance: None, expires_at: None, fee: Some(fee), memo: None, created_at_time: Some(ic_cdk::api::time()), }; let (result,): (Result,) = Call::unbounded_wait(ledger_id(), "icrc2_approve") .with_arg(args) .await .map_err(|e| format!("Call failed: {:?}", e))? .candid_tuple() .map_err(|e| format!("Decode failed: {:?}", e))?; result.map_err(|e| format!("Approve error: {:?}", e)) } // ICRC-2: Transfer from another account (requires prior approval) // WARNING: Add access control in production — this allows any caller to transfer tokens #[update] async fn transfer_from(from: Principal, to: Principal, amount: Nat) -> Result { let fee = Nat::from(ICP_FEE); let args = TransferFromArgs { spender_subaccount: None, from: Account { owner: from, subaccount: None, }, to: Account { owner: to, subaccount: None, }, amount, fee: Some(fee), memo: None, created_at_time: Some(ic_cdk::api::time()), }; let (result,): (Result,) = Call::unbounded_wait(ledger_id(), "icrc2_transfer_from") .with_arg(args) .await .map_err(|e| format!("Call failed: {:?}", e))? .candid_tuple() .map_err(|e| format!("Decode failed: {:?}", e))?; result.map_err(|e| format!("TransferFrom error: {:?}", e)) } ``` ## Deploy Add to `icp.yaml`: Pin the release version before deploying: get the latest release tag from https://github.com/dfinity/ic/releases?q=%22ledger-suite-icrc%22&expanded=false, then substitute it for `` in the URL below. ```yaml canisters: - name: icrc1_ledger build: steps: - type: pre-built url: https://github.com/dfinity/ic/releases/download//ic-icrc1-ledger.wasm.gz init_args: path: icrc1_ledger_init.args format: candid ``` Create `icrc1_ledger_init.args`, replacing `YOUR_PRINCIPAL` with the output of `icp identity principal`. The `minting_account` **must** be a different principal than any principal in `initial_balances` (see pitfall #9). `initial_balances` accepts multiple entries to fund several accounts at genesis. > **Pitfall:** Shell substitutions like `$(icp identity principal)` will NOT expand inside this file. You must paste the literal principal strings. ``` (variant { Init = record { token_symbol = "TEST"; token_name = "Test Token"; minting_account = record { owner = principal "MINTER_PRINCIPAL" }; transfer_fee = 10_000 : nat; metadata = vec {}; initial_balances = vec { record { record { owner = principal "PRINCIPAL_A" }; 100_000_000_000 : nat; }; record { record { owner = principal "PRINCIPAL_B" }; 50_000_000_000 : nat; }; }; archive_options = record { num_blocks_to_archive = 1000 : nat64; trigger_threshold = 2000 : nat64; controller_id = principal "YOUR_PRINCIPAL"; }; feature_flags = opt record { icrc2 = true }; }}) ``` Deploy: ```bash icp network start -d icp deploy icrc1_ledger ``` --- ## Migrating to moc 2 --- name: migrating-to-moc-2 description: "Move a Motoko project from moc 1 to moc 2 — toolchain bump, removed compiler flags, and the fix for every new error. Load when bumping the moc toolchain to a 2.x release, when code that built on moc 1 fails on moc 2, or when one codebase must compile with both." license: Apache-2.0 compatibility: "moc >= 2.0.0, mops >= 3.0.0" metadata: title: Migrating to moc 2 category: Motoko --- # Migrating to moc 2 moc 2 is a major release of the Motoko compiler. It changes four things: - **Persistence.** Actors are persistent by default. Enhanced orthogonal persistence (EOP) is the only memory model and the incremental GC the only collector. - **Strictness.** Warnings for code that traps or silently does not do what it says are now errors, and a pattern must fit the type it matches. - **Syntax.** A few moc 1 forms no longer parse (`a ??b`, a branch glued to its condition, `flexible`). Several lighter forms are new and optional. - **Flags.** Every flag of a removed feature is rejected as an unknown option. Most projects need a handful of edits, and the compiler names each one. This skill maps every diagnostic to its fix. The upstream [moc 1 → 2 migration guide](https://github.com/caffeinelabs/motoko/blob/master/doc/md/moc-v2-migration.md) has longer explanations, and the [release notes](https://github.com/caffeinelabs/motoko/releases) list each change per release. ## First: is any canister still on classical persistence? moc 2 cannot build a canister on classical (32-bit) persistence, but it can upgrade one to EOP. A deployed canister is classical if it was built with `--legacy-persistence`, with a non-incremental GC flag (`--copying-gc`, `--compacting-gc`, `--generational-gc`), or with a moc older than 0.15, where classical was the default. - **Move it to EOP:** compile that **one** upgrade with `--enhanced-orthogonal-persistence` and **without** `--enhanced-migration`. The move is irreversible; later upgrades need neither flag. Without the flag the upgrade traps ("Detected implicit upgrade from classical orthogonal persistence to enhanced orthogonal persistence"); with `--enhanced-migration` it traps too ("Cannot upgrade from classical orthogonal persistence with --enhanced-migration"). - **Keep it classical:** stay on moc 1. A canister that moved to EOP with a moc older than 1.5.0 can trap on a later upgrade with `cannot upgrade from an actor using enhanced migration to an actor not using enhanced migration`. Run that one upgrade with graph-copy stabilization; the upstream [EOP migration path](https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/actors/orthogonal-persistence/enhanced.md#migration-path) has the steps. Every other canister already runs on EOP and needs no persistence work. ## Checklist 1. **Build cleanly on the latest moc 1 first.** The `.vals()` (M0269) and `preupgrade`/`postupgrade` (M0270) deprecations are identical in moc 2, so fix them before switching; on moc 2, `mops check --fix` rewrites `.vals()` to `.values()`. Fix every warning in the [diagnostics table](#diagnostics) too — most become errors. 2. **Bump the toolchain** to the latest 2.x release: `mops toolchain use moc ` (it rewrites `[toolchain] moc` in `mops.toml`), or wherever your build pins moc. 3. **Delete the [removed flags](#removed-flags)** from `[moc].args`, `[build].args`, `[canisters.].args`, `dfx.json` and build scripts. 4. **Run `mops check`** and fix what it reports in this order, because earlier errors hide later ones: 1. syntax errors (`??`, glued branches, `flexible`, record literals in block position); 2. errors that were warnings in moc 1; 3. M0277, redundant `async` on a function body; 4. M0142 and M0193 in libraries and actor classes; 5. M0131, only if you built with `--legacy-actors`. 5. **Check upgrade compatibility** against the deployed version before upgrading a live canister: `mops check-stable`, or `moc --stable-compatible old.most new.most`. Removing `persistent` and `stable` keywords does not change the stable signature. 6. **Optionally adopt the moc 2 forms** — only once nothing builds this code with moc 1 anymore. See [After the switch](#after-the-switch). ## Removed flags moc 2 exits with `unknown option ''` on each of these. | Flag | Replacement | | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `--default-persistent-actors`, `--require-persistent-actors` | none needed: actors are persistent by default | | `--legacy-actors` | mark every field that should reset on upgrade `transient` | | `--legacy-persistence`, `--copying-gc`, `--compacting-gc`, `--generational-gc` | none: stay on moc 1 for classical canisters | | `--incremental-gc`, `--rts-stack-pages`, `--skip-gc-deprecation-warning`, `--experimental-rtti` | none needed | | `--experimental-stable-memory` | use `Region` | | `--experimental-field-aliasing` | none: [record update copies `var` fields](#record-update-copies-var-fields) | | `--generate-view-queries` | write `public query func` getters. The generated `__` queries leave the canister's Candid interface on upgrade, so update any client that called them | | `--trap-on-call-error` | none: a failed call throws; handle it with `try`/`catch` | | `--experimental-multi-value`, `--no-experimental-multi-value` | none needed | | `-no-system-api` | `-wasi-system-api` to run outside the Internet Computer | | `-ref-system-api` | none needed: it selected the default | | `--print-source-on-error`, `-no-link`, `--profile`, `--profile-file`, `--profile-line-prefix`, `--profile-field` | none | `--enhanced-orthogonal-persistence` stays: it is a no-op on EOP canisters, and only the one-time classical upgrade needs it. `-A`, `-W` and `-E` no longer accept `M0135` and `M0142`. ## Diagnostics Each moc 1 warning that became an error can be downgraded again with `-W ` (e.g. `-W=M0145,M0215` in `[moc].args`). That is a stopgap: the code it lets through traps or silently misbehaves. Pattern errors M0116, M0050 and M0115 cannot be downgraded. | Code | In moc 1 | What it flags | Fix | | --- | --- | --- | --- | | M0001 at `??` | accepted | `a ??b` — `??` is whitespace-sensitive like `<` | `a ?? b` | | M0001 at `flexible` | accepted | `flexible` is no longer a keyword | `transient` | | M0273 | accepted | a block after `??` — `{` there now opens a record literal | `opt ?? do { ... }` | | M0275 | accepted | a branch glued to its condition (`if (c)-1 else 1`, `if c[0] else [1]`), or a bare branch after a compound condition (`if f(x) a else b`) | space before the branch (`if (c) -1 else 1`), or braced branches | | M0272 | M0001 | a record literal in block position — a `case` body, function body, or `if`/`switch`/`while` head | nest it as the block's result: `case null { { x = 0 } }`; parenthesize a head: `switch ({ x = 0 })` | | M0274 | M0001 | a reserved keyword (`query`, `implicit`, …) as an identifier | rename it | | M0277 | accepted | `= async { ... }` or `= ignore (async ...)` as a function body | drop the `async`; see [Async function bodies](#async-function-bodies) | | M0145 | warning | a pattern that does not cover every value, in `switch`, `let`, `catch`, `for` and parameters | `let ... else { ... }`, or a `case _` arm | | M0222 | warning | `ignore` of an `async*` value, which never runs | `await*` it | | M0210 | warning | a parenthetical on an `await*` call, where it has no effect | attach `(with cycles = n)` to an `async` call | | M0212 | warning | an unknown parenthetical attribute (`(with cycle = n)`) | fix the name: `cycles` | | M0215 | warning | a field the expected type drops, e.g. the typo in `{ u with emial = e }` | fix the name, or drop the field | | M0128 | warning | a function named like a system method (`heartbeat`, `inspect`, …) without `system` | `system func ...`, or rename it | | M0242 | warning | a `public func` without a return type, implicitly oneway | `: ()` if oneway is intended, else `: async ()` | | M0005 | warning | an import path whose letter case differs from the file name | match the file name | | M0276 | warning M0062 | a comparison whose result is constant, at a type with one value (`Any`, `{}`, records sharing no field) | compare the fields you mean: `user.id == order.userId` | | M0278 | warning M0251 | a file in the `--enhanced-migration` directory with no `public func migration`, so it never ran | rename the function to `migration`, or move the module out of the directory | | M0074, M0081, M0101 | warning | an array, `if` or `switch` whose only common type is `Any` | make the elements or branches agree, or annotate `: Any` if intended | | M0166, M0167 | warning | an intersection that is `None`, a union that is `Any` | write the intended type | | M0116 | warning M0146 | a variant tag the scrutinee's type lacks — usually a typo | fix the tag; to match a wider type on purpose, annotate the scrutinee: `switch (x : T)` | | M0050 | warning M0146 | a signed literal pattern (`case (-1)`) against `Nat` | annotate `switch (n : Int)`, or drop the case | | M0115 | warning M0146 | an option pattern against `Null` | fix the scrutinee's type | | M0142 | warning | an imported file that is a bare list of declarations | wrap it in `module { ... }` and mark exports `public` | | M0193 | warning M0135 | an actor class whose return type is not `async` | `actor class C() : async actor { ... }` | | M0131 | not reported: the field was transient | a function or object field that `--legacy-actors` left transient is now persistent | mark it `transient` | | M0057 | accepted | under `moc --check a.mo b.mo`, a file using another file's declaration without importing it | move the shared code into a module and import it | | M0072 | accepted | `mo:base/ExperimentalStableMemory` and the `Prim.stableMemory*` primitives are gone | use `Region` | New **warnings**, which only break a `-Werror` build: - M0217 / M0218 — the `persistent` keyword and `stable` modifier are redundant. `mops check --fix` deletes them, so hold off while moc 1 must still build the code: there, a bare `actor` needs `--default-persistent-actors`. - M0196 — an explicit `` on a primitive that no longer needs it (`Prim.getSelfPrincipal`, `Prim.envVar`, `Prim.envVarNames`, `Prim.callerInfoSigner`, `Prim.callerInfoData`, `Prim.getCandidLimits`, `Prim.getCandidTypeLimits`). Delete it; `query` methods can now call these. - M0236 — a module call that could use dot notation (`Map.size(m)` → `m.size()`), now on by default. `mops check --fix` applies it; `-A M0236` silences it. - M0146 — now also reported for an alternative that is never matched in `let ... else`. ## Persistence ### Actors are persistent by default Every `actor` and `actor class` is persistent: its `let` and `var` fields keep their values across upgrades unless declared `transient`. Code written as `persistent actor` with `stable` fields compiles unchanged, with warnings M0217 and M0218. If you built with `--legacy-actors`, unmarked fields used to be transient and are now persistent. Mark every field that should reset on upgrade `transient`; a field whose type cannot be persisted (a function, an object with methods) is error M0131 until you do. A field that turns from transient to persistent needs no migration: on the first upgrade it is new to the stable signature, so its initializer runs once. ### `preupgrade` and `postupgrade` They still work, with deprecation warning M0270. The usual reason for them is a structure that could not be persisted, such as `mo:base/HashMap`, copied into a stable array before an upgrade and rebuilt after it: ```motoko // moc 1, in the actor body var entries : [(Text, Nat)] = []; transient let users = HashMap.HashMap(16, Text.equal, Text.hash); system func preupgrade() { entries := Iter.toArray(users.entries()) }; system func postupgrade() { for ((k, v) in entries.vals()) { users.put(k, v) }; entries := []; }; ``` The `mo:core` collections are stable, so declare `users` as an ordinary field, `let users : Map.Map = Map.empty();`, delete both hooks and `entries`, and move the data once with a migration function on the actor: ```motoko // moc 2 import Map "mo:core/Map"; import Text "mo:core/Text"; (with migration = func(old : { var entries : [(Text, Nat)] }) : { users : Map.Map } { { users = Map.fromIter(old.entries.values()) } // `compare` is implicit, from the imported Text }) actor { /* ... */ }; ``` The upgrade that installs this version still runs the old `preupgrade`, so `entries` holds the data when the migration reads it. Warning M0207 on the dropped field is expected. Delete the `(with migration = ...)` clause once this version is deployed. With an enhanced migration chain (`--enhanced-migration`), declare the field without an initializer, `let users : Map.Map;`, and put the same function in the next chain file as `public func migration` instead. ## Syntax that no longer parses ### `??` needs spaces, and its right-hand side is an expression ```motoko let n = o ??0; // moc 2: syntax error let n = o ?? 0; // both let n = o ?? do { let k = f(); k + 1 }; // a block needs `do` (M0273 without it) let r = o ?? ({ x = 1 }); // a record literal; parentheses work in both ``` ### Branches glued to the condition A `(`, `[` or prefix operator directly after a condition now continues the condition, so a bare branch needs a space before it. A condition that is more than a name or a parenthesized expression needs braced branches (M0275): ```motoko if (c)-1 else 1; // moc 2: `(c)-1` is the condition — M0275 if (c) -1 else 1; // branch `-1` if (f(x)) a else b; // both if (f(x)) { a } else { b } // both, and never ambiguous ``` ## Async function bodies A function whose return type is `async T` has an asynchronous body whether it is written `{ ... }` or `= e`. Spelling the `async` out is now M0277, and the fix-it removes it: ```motoko func f() : async Nat = async { 1 }; // M0277 func f() : async Nat { 1 }; // both ``` The same applies to `= ignore (async ...)` in a oneway `shared` function. Two moc 1 forms have no direct replacement: a parenthetical on the body (`= (with cycles = n) async { ... }`) moves to each call site, `(with cycles = n) f()`; and a local function can no longer return a future created by its enclosing function — await it there instead. ## Record update copies `var` fields `{ base with ... }` on a record with `var` fields was error M0179 in moc 1, or aliased the base's fields under `--experimental-field-aliasing`. moc 2 copies them into new cells, like the equivalent record literal: ```motoko let base = { var count = 0; name = "a" }; let copy = { base with name = "b" }; copy.count += 1; // base.count is still 0 ``` Code that relied on aliasing compiles silently with different behavior. Keep the shared mutable state in one object that both records reference. ## Libraries, modules and primitives - **Imported files must be modules (M0142).** Wrap a bare list of declarations in `module { ... }` and mark the exports `public`. - **Actor classes return `async` (M0193):** `actor class C() : async actor { ... }`. - **`mo:base/ExperimentalStableMemory` no longer type-checks.** Use `Region` (`mo:core/Region` or `mo:base/Region`). The rest of `base` still compiles; new code should use `core`. - **`Prim.createActor` is gone.** Use actor classes, or the management canister's `create_canister` and `install_code`. - **Canisters no longer export `__motoko_stable_var_info`**, a query that always trapped under EOP. - **Implicit arguments and dot notation also search nested modules**, so importing a facade that re-exports its package's modules is enough. Every call that resolved in moc 1 resolves the same way; a call moc 1 rejected may now resolve, or be ambiguous (M0224, M0231). ## Tooling - **`moc --check a.mo b.mo` checks each file on its own**, seeing only its own imports. `-c`, `--idl` and `-r` take exactly one main file, and the REPL (`-i`) preloads at most one. Split programs with imports. - **`-g`** emits only the DWARF line table. - **`moc.js`:** `Motoko.run` takes `[]` as its first argument (use imports instead of preloads), and `gcFlags` accepts only `"force"` and `"scheduling"`. - **No Intel-Mac binary.** On an x86_64 Mac, build moc from source, use `moc.js`, or stay on moc 1. The `motoko-base-library.tar.gz` artifact is gone too; get `base` from mops. - **`mops bench`** cannot use `--legacy-persistence` or a non-incremental `--gc` under moc 2. ## Code that must compile with both moc 1 and moc 2 A library, or a codebase built by both majors during a transition, has to stay in the syntax both accept. Write moc 1 code with these rules and moc 2 compiles it with at most the warnings above: - Fix every warning moc 2 turns into an error (the [diagnostics table](#diagnostics)) — moc 1 only warns, so a clean moc 1 build is the bar. - Parenthesize `if`, `while`, `for` and `switch` heads: `if (c)`, `for (x in xs.values())`, `switch (e)`. - Write case patterns in parentheses and end every case with `;`: `case (#tag(p)) { ... };`. Always parenthesize a variant payload. - Put a space between a parenthesized condition and a bare branch, or brace the branches. - Space both sides of `??`; write a block on its right as `do { ... }` and a record literal as `({ ... })`. - Annotate a function passed where an `async` function is expected: `func(n : Nat) : async Nat { ... }`. moc 1 cannot infer it. - Write a function body as a block, never `= async { ... }`. - Never write `{ base with ... }` when `base` has `var` fields: moc 1 rejects it, moc 2 copies them. - Never write `flexible` or `stable`. - The read-only primitives listed above warn either way: moc 1 asks for `` (M0195) and moc 2 calls it unneeded (M0196). The `mo:core` wrappers, such as `Runtime.envVar(name)`, compile cleanly on both. - For actor persistence, either build with `--default-persistent-actors` on moc 1 only and write a bare `actor`, or write `persistent actor` and allow M0217 on moc 2 (`-A M0217`). ## After the switch Once no moc 1 build remains, these moc 2 forms are available. All are optional. - Delete `persistent` and `stable` (M0217, M0218) — `mops check --fix` does it. The stable signature does not change. - Heads without parentheses: `if f(x) { a } else { b }`, `while n > 0 { n -= 1 }`, `for x in xs.values() { ... }`, `switch p.x { ... }`. The branches or body must then be blocks. - Lighter `switch` cases: the `;` between cases is optional, and a pattern with a fixed extent needs no parentheses — `case null`, `case -1`, `case ?v`, `case #tag(p)`, combined with `or`, `and` and `: T`. A variant payload keeps its own parentheses: `case #tag(p)`, never `case #tag p`. - A function passed where an `async` function type is expected takes its parameter and return types from it: `run(func(n) { n + 1 })`. - `do { ... }` works as an operator operand: `1 + do { ... }`, `debug_show do { ... }`. --- ## Mops CLI --- name: mops-cli description: "Manage Motoko projects with the mops CLI — toolchain pinning, dependency management, type-checking, building, and linting. Use when working with mops.toml, mops.lock, running mops commands, adding/removing packages, pinning moc or lintoko versions, checking or building canisters, configuring moc flags, or setting up a new Motoko project." license: Apache-2.0 compatibility: "mops >= 3.3.0" metadata: title: Mops CLI category: Infrastructure --- # Mops CLI Opinionated guide for Motoko projects. Covers project config, dependency management, type-checking, building, and linting. ## Key Principles 1. **No dfx** — mops neither invokes nor supports `dfx`. There is no `mops toolchain init`, no `moc-wrapper`, and no `mops watch --generate` / `--deploy`. Always pin `moc` in `[toolchain]`; every command that compiles requires it. Use the newest `moc` version. Pin `pocket-ic` too if you have replica tests, benchmarks, or `--check-deploy` — with no pin those commands error, naming `mops toolchain use pocket-ic 15.0.0`. When `MOPS_POCKET_IC_URL` points at an already-running PocketIC server, no pin is needed and an existing pin is ignored with a warning — do not add one to silence it; unset the variable instead. 2. **No `mo:base`** — it is deprecated. Always use `mo:core` (`import Array "mo:core/Array"`). 3. **All config in `mops.toml`** — canisters, moc flags, toolchain versions, build settings. 4. **Canister-centric workflow** — define all canisters in `[canisters]`; never pass file paths to `mops check`. Exception: library packages (no `[canisters]`) use file paths directly: `mops check src/**/*.mo`. ## Project Setup ### Minimal `mops.toml` ```toml [toolchain] moc = "1.15.1" lintoko = "0.11.0" pocket-ic = "15.0.0" # required for replica tests / benchmarks / --check-deploy [dependencies] core = "2.6.1" [moc] args = ["--default-persistent-actors", "-W=M0223,M0236,M0237"] [canisters.backend] main = "src/backend/main.mo" [canisters.backend.migrations] chain = "src/backend/migrations" # check-limit = 10 # optional — speeds up `mops check` when the chain gets long [canisters.backend.check-stable] path = "deployed/backend.most" [build] outputDir = "src/backend/dist" args = ["--release"] # check-wasm = true # optional: analyze final Wasm complexity # check-deploy = true # optional: verify fresh PocketIC installation after build # Opt-in Wasm optimization (Binaryen wasm-opt) for build + bench [optimize] # level = "O3" # default # keep-names = true # default # wasm-opt pin: [toolchain] wasm-opt = "131" (required when [optimize] is set) ``` `check-stable` runs ICP's upgrade-time stable-variable compatibility check locally, so incompatible changes fail in `mops check` instead of being rejected when upgrading a live canister. It compares the current code against a `.most` from the deployed version. Bootstrap that `.most`: new project → `mops deployed init` (empty-actor baseline); already-deployed canister → build from the deployed commit, then `mops deployed`. After every deploy, run `mops deployed` to promote the just-built `.most` (see [`mops deployed`](#mops-deployed) below). Optional canister fields: `candid` (path to .did for compatibility checking), `initArg` (Candid-encoded init args). ### Warning Flags `-W=M0223,M0236,M0237` — redundant type instantiation (M0223), suggest contextual dot notation (M0236), suggest redundant explicit arguments (M0237). These are allowed (disabled) by default; `-W=` enables them as warnings. ### Moc Args Layering Flags are applied in this order (later overrides earlier): 1. `[moc].args` — global, all commands (check, build, test, bench, etc.) 2. `[build].args` — build only (e.g. `--release`) 3. `[canisters..migrations]` — auto-injected `--enhanced-migration` (managed by mops) 4. `[canisters.].args` — per-canister 5. CLI `-- ` — one-off overrides; supported by `mops check`, `mops build`, `mops check-stable`, `mops generate`, `mops migrate`, `mops test`, and `mops bench` ## Core Commands ### `mops install` ```bash mops install # dev flow: keeps mops.lock in sync, self-heals a broken one mops install --locked # CI flow: fail if mops.lock is missing or would change ``` Run after cloning or after manual `mops.toml` edits. `mops.lock` is always maintained — there is no flag to opt out, and no `--lock` flag (removed in v3). A missing, unparseable, legacy-format or `mops.toml`-inconsistent lock is regenerated by a plain `mops install`, including locks that still carry absolute local paths from older CLIs, and locks that lost a transitive dependency (a locked package declares a dependency that `deps` no longer lists — typically a botched merge). `--locked` requires an up-to-date lock and never writes it. It is also available on every implicitly-installing command (`mops build`, `mops check`, `mops check-stable`, `mops check-candid`, `mops test`, `mops bench`, `mops generate candid`), so CI can run `mops test --locked` with no prior install. `mops sources` has no `--locked` (a packtool caller parses its stdout mid-build) — put `mops install --locked` earlier in the pipeline instead. The `CI` env var no longer affects lockfile behavior (removed in v3). Commit `mops.lock` — for applications and libraries alike. A lock also goes stale when a local `path` dependency's own `mops.toml` changes — including one nested further down the chain. `mops install` regenerates it; `--locked` fails until the regenerated lock is committed. Note the first `mops install` after upgrading regenerates the lock of any project that has a `path` dependency, so commit it before running `--locked` in CI. Projects without `path` dependencies keep their existing lock. `{MOPS_ENV}` in a `path` dependency expands to `$MOPS_ENV` (default `local`), which makes the lock environment-specific. Switching `MOPS_ENV` makes it stale: `mops install` regenerates it, and `--locked` fails with a message naming `MOPS_ENV`. Keep one lock per environment, or drop `--locked` — a lock generated under one `MOPS_ENV` will not satisfy `--locked` under another. Integrity is verified at download time, so `mops install` no longer re-hashes `.mops/`: editing a dependency in place will not fail the next install. Use `mops verify` for the on-demand on-disk audit. Downloaded files are always checked before anything enters the cache — against `mops.lock` when it already records the package, otherwise against the registry. A committed lock therefore makes verification free, which is why a clean checkout installs without asking the registry about hashes. Two consequences worth knowing: a corrupt or hand-edited `mops.lock` now fails a _download_ (the error names `mops.lock` as a possible culprit — restore it from version control; already-cached packages are unaffected), and a package the registry publishes no hashes for still installs, unverified, with a warning. Packages download in parallel through a bounded pool. `mops install --concurrency ` or the `MOPS_CONCURRENCY` env var (works on every installing command) caps simultaneous registry requests; the default derives from the CPU count and the file-descriptor soft limit (4–16). Transient network errors (`fetch failed`, `ECONNRESET`, `EMFILE`) retry automatically with the concurrency halved, up to twice. Set `MOPS_CONCURRENCY=1` only if installs still fail after the retries (an egress proxy capping connections, for example). ### `mops verify` ```bash mops verify # re-hash .mops/ against mops.lock, and mops.lock against the registry ``` Covers GitHub dependencies as well as registry ones. Exits 1 with the offending files and a recovery hint. This is the replacement for anyone who relied on `mops install` failing when `.mops/` had been modified. ### `mops add ` ```bash mops add core # latest version mops add core@2.5.0 # specific version mops add --dev test # dev dependency mops add org/repo # GitHub shorthand (also accepts a full github.com url) mops add ./pkg # local package directory ``` Updates `mops.toml` and `mops.lock`. Adding a package that is already declared in the other section **moves** it rather than declaring it twice. `@` replaces the declared version and reports what it replaced; it leaves pinned aliases like `"core@1.0.0" = "1.0.0"` alone, and there is no flag to create one — write it by hand. ### `mops check` Primary correctness command — runs moc check, then check-stable (if configured), then lint (if lintoko is in toolchain). On moc 1.15.0+, canisters with `[migrations]` get stricter upgrade diagnostics: a field the initial actor requires that no migration produces fails as an `M0267` error instead of only warning (`M0254`), and compat errors carry a source location. Older moc pins and canisters without `[migrations]` are unaffected either way. The `check-stable` baseline is always a `.most` file — as `[canisters..check-stable].path` or as the `mops check-stable ` argument. A `.mo` source is rejected. See [`mops deployed`](#mops-deployed) for where the baseline comes from — that differs between a fresh project and an already-deployed canister. ```bash mops check # all canisters mops check backend # single canister mops check --fix # autofix + check + stable + lint mops check --no-lint # skip the lint step for one run mops check --verbose # show moc invocations mops check -- -Werror # treat warnings as errors ``` **Always use canister names, not file paths.** Per-canister args from `mops.toml` are applied automatically. `--fix` applies machine-applicable fixes from both moc and lintoko in one pass. Concurrent `--fix` runs (across processes) serialize automatically via an advisory lock at `.mops/fix.lock` — safe to invoke from multiple agents on the same project. Read-only files (e.g. frozen migrations) are skipped with a warning, not fixed. ### `mops build` ```bash mops build # all canisters mops build backend # single canister mops build --verbose # show compiler commands mops build --check-wasm # analyze final Wasm complexity without PocketIC mops build --no-check-wasm # skip configured [build].check-wasm once mops build --check-deploy # verify fresh installation on PocketIC mops build --no-check-deploy # skip configured [build].check-deploy once mops build -- --ai-errors # pass extra moc flags ``` Produces `.wasm`, `.did`, and `.most` files in `[build].outputDir` (default `.mops/.build`). With `[optimize]` in `mops.toml`, runs `wasm-opt` after candid metadata (default `-O3 -g`). Requires a Binaryen pin: `mops toolchain use wasm-opt 131`. Build commands never write the pin themselves, and a `wasm-opt` failure fails the build. Pass `--no-optimize` (on `build` or `bench`) to skip the pass for a single run without editing `mops.toml`. When `--check-wasm` or `[build].check-wasm = true` is enabled, Mops runs fast Walrus analysis on the final Wasm without starting PocketIC. Per-function IC0505 complexity below 750,000 is quiet, 750,000 through 899,999 emits an early warning, and 900,000 or more emits a critical warning. `MOPS-WASM-COMPLEXITY` output includes actionable function metrics, the three largest complexity contributors, and Motoko correction guidance. The estimate never fails the build. Use `--no-check-wasm` to skip configured analysis once. ### `mops deployed` Post-deploy hook — keeps the on-disk `.most` baseline used by `check-stable` in sync with what's actually deployed. ```bash mops deployed init backend # one-time bootstrap: empty-actor baseline + sets [check-stable].path mops deployed backend # post-deploy: promotes .mops/.build/backend.most → deployed/backend.most mops deployed # all canisters ``` Default destination is `deployed/.most`; override with `[deployed].dir` in `mops.toml` or `--dir`. It reads built `.most` files from `[build].outputDir` (default `.mops/.build`); override with `--build-dir`. `mops deployed` errors if the source `.most` is missing — it never regenerates. Run it from your deploy pipeline immediately after a successful deploy. ### `mops generate candid` ```bash mops generate candid # all canisters mops generate candid backend # single canister mops generate candid backend -o # single canister, ad-hoc path ``` (Re)generates the curated `.did` from current Motoko source. With `[canisters.].candid` set, overwrites that file. Without it, writes `.did` next to `main` (e.g. `main = "src/Backend.mo"` → `src/backend.did`) and sets `[canisters.].candid` in `mops.toml`. Run after every interface change; commit `.did` + `mops.toml` together. Same moc invocation as `mops build`, so the result always passes `mops build`'s subtype check. ### `mops toolchain` ```bash mops toolchain use moc 1.15.1 # pin specific version mops toolchain use moc latest # pin latest version (non-interactive) mops toolchain use lintoko 0.11.0 # pin specific version mops toolchain use pocket-ic 15.0.0 # pin for replica tests / benchmarks / --check-deploy mops toolchain use wasm-opt 131 # Binaryen for [optimize] (or `latest`) mops toolchain update moc # update to latest (requires existing [toolchain] entry) mops toolchain update # update all tools to latest mops toolchain info # show release info (latest, pinned, history) mops toolchain info --versions # list recent releases, newest first mops toolchain info --versions --all # full release history (cache warming) mops toolchain info --versions --prerelease # include prereleases mops toolchain bin moc # print path to binary ``` **`pocket-ic` versions**: pin anything from `9.0.0` up, `latest` included — mops keeps no list of blessed versions. Pins below `9.0.0` error with a migration message (they ran on the legacy client that mops 3.0.0 removed). With no pin, replica tests / `mops bench` / `--check-deploy` / `mops toolchain bin pocket-ic` error naming `mops toolchain use pocket-ic 15.0.0`. That version is a hint, not a fallback. **Agent note**: `toolchain use ` without a version opens an interactive picker — do not use in scripts or agents. Always pass a version or `latest`. The picker, `latest`, and `--versions` all default to stable releases; pass `--prerelease` to include prereleases. `toolchain update` only works when the tool already has a `[toolchain]` entry. `toolchain info --versions` works without `mops.toml` (first GitHub page by default; pass `--all` for full history). ### Enhanced migrations When `[canisters..migrations]` is configured, `mops check`, `mops build`, and `mops check-stable` automatically inject `--enhanced-migration`. Do not add `--enhanced-migration` to `[canisters.].args` — mops will error. Create migration files directly in the `chain` directory. After `mops check --fix` (or `mops check `) confirms the chain compiles, run `mops build` to produce the wasm artifact. Use `mops build --check-deploy`, or set `[build].check-deploy = true` for every build, to install each built Wasm on a fresh PocketIC canister and catch module validation, initialization, and installation failures. Requires `[toolchain] pocket-ic` (a version from `9.0.0` up, or a local binary path) — or set `MOPS_POCKET_IC_URL` to an already-running PocketIC server (the pin is then ignored). Unpinned with no URL, the build errors naming `mops toolchain use pocket-ic 15.0.0`. Use `--no-check-deploy` to skip configured validation once. The command uses each canister's `initArg`, or `()` when omitted. Set `wasmMemoryLimit` to a positive integer byte limit on a canister to check deployment under that limit. PocketIC errors are reported as provided by the client, and installation failures are collected across canisters. Before installation, Mops runs `moc --stable-compatible` from a temporary empty-actor `.most` to each generated `.most`. If moc reports incompatibility, Mops emits `MOPS-CHECK-DEPLOY-SKIPPED` with the compiler diagnostic and does not check that canister on fresh PocketIC. Eligible siblings are still checked; validate the skipped upgrade against representative baseline state. `check-limit` (optional) caps how many recent chain files `mops check` and `mops lint` consider — useful when the chain grows long and re-checking every old migration slows feedback down. `mops build` is unaffected by `check-limit`; it compiles the full chain, and when `[canisters..check-stable].path` is set it also folds the deployed baseline via `--stable-baseline`, so an applied migration edited, deleted, or backdated since deploy fails the build with `M0268` — the backstop for when `check-limit` trims that migration out of the folded `mops check`. When the limit kicks in, mops stages the included files into `.migrations-/` next to the `chain` directory (auto-`.gitignore`d). `moc` diagnostics may then print paths there — the real file lives in the `chain` directory with the same name. Override `check-limit` for a single run with `--no-check-limit` (`mops check`, `mops check-stable`, `mops lint`) — e.g. `mops check --fix --no-check-limit` to autofix older, normally-trimmed migrations. On `mops check` and `mops check-stable`, `--no-check-limit` also suppresses the pending-migration warning. When `check-limit` is set, `mops check-stable` (and the stable check inside `mops check`) reports if more migrations are pending than the limit allows — as an error if compat failed (replacing the misleading `moc` message), otherwise a warning. ### `mops remove ` ```bash mops remove core ``` Removes from whichever section declares the package; `--dev` limits it to `[dev-dependencies]`. A package declared in both sections is removed from both. ### Dependency Management ```bash mops outdated # list outdated deps (caret-bound); exit 1 if any, 2 if the check failed mops outdated core # check a single package mops update # rewrite mops.toml versions within caret bound (no major-version crossing) mops update core # update specific package within caret bound mops update --major # allow updates that cross major versions mops update --patch # restrict to patch bumps only (mutually exclusive with --major) mops update --verbose # verbose output mops sync # add missing / remove unused packages mops sync --dry-run # print what would change, write nothing ``` `mops update` rewrites `mops.toml` in place (like `cargo upgrade`, not `cargo update`) and re-pins GitHub dependencies to their branch head. Like `mops outdated`, it exits `2` when it cannot run or complete — no `mops.toml`, a package that is not declared, or a dependency that failed to update (the other dependencies are still updated). `mops sync` needs a pinned `[toolchain] moc` — it reads imports with `moc --print-deps`. Packages imported only from `test`/`tests`/`bench`/`benchmark` directories are added to `[dev-dependencies]`; already-declared packages are never moved between sections. ## Other Commands ### `mops self update` Updates a global install (npm/pnpm `-g`) only, and fails if the `mops` on PATH did not end up on the new version. For `ic-mops` as a project dependency, run `npm i -D ic-mops@` instead. ### `mops publish` ```bash mops publish # publish to the registry (runs tests/docs/bench by default) mops publish --dry-run # same local steps as publish; no registry contact / identity mops publish --dry-run --no-test --no-docs --no-bench # packaging checks only mops publish --no-test --no-docs --no-bench ``` `--dry-run` runs the same local publish pipeline (packaging checks, docs, changelog, tests, benchmarks) and prints the final file list, then stops before identity/upload. `--no-*` flags work as usual. It does **not** run canister config validation (SPDX/semver/name rules) or prove registry acceptance (already published, permissions, missing deps). ### `mops test` Tests live in `test/*.test.mo`: ```bash mops test # run all tests mops test my-test # filter by name mops test --mode wasi # use wasmtime (for to_candid/from_candid) mops test --reporter files # one line per file (default is verbose) mops test --watch # re-run on file changes mops test -- -Werror # pass extra moc flags ``` Replica tests (actor files or `// @testmode replica`) run on PocketIC — the `pocket-ic` version from `[toolchain]`, or an already-running server when `MOPS_POCKET_IC_URL` is set (no pin needed; canister log output is not streamed in attached mode). Unpinned with no URL, they error naming `mops toolchain use pocket-ic 15.0.0`. Same for `mops bench` and `mops watch --test`. There is no `--replica` flag and no dfx replica. ### `mops bench` Benchmarks live in `bench/*.bench.mo`: ```bash mops bench # run all benchmarks mops bench my-bench # filter by name mops bench --gc incremental # select GC mops bench --save # save results to .bench/.json mops bench --compare # compare with saved results mops bench -- -Werror # pass extra moc flags ``` ### `mops lint` Runs lintoko (also runs automatically as part of `mops check` when lintoko is in toolchain): ```bash mops lint # lint all .mo files mops lint --fix # autofix lint issues mops lint # filter to .mo files matching ``` When `[canisters..migrations].check-limit` is set, `mops lint` skips the trimmed chain migrations to match what `moc` sees during `mops check`. To lint a trimmed migration on demand, pass an explicit filter (e.g. `mops lint OldMigrationName`) or `--no-check-limit` to lint the full chain. ### `mops format` ```bash mops format # format all .mo files mops format --check # check formatting without modifying ``` ### `mops watch` ```bash mops watch # errors + warnings + format (the default set) mops watch --warning # errors + warnings only mops watch -t # errors + tests ``` Error checking is always on. Passing any flag selects only the named tasks, so add `-w` / `-f` when you want them alongside `-t`. Those four are the whole set — there is no `--generate` or `--deploy`. ## Common Patterns ### Warning suppression for a canister Use per-canister `args` (not global) for suppressions: ```toml [canisters.backend] main = "src/backend/main.mo" args = ["-A=M0198"] ``` ### New project ```bash mops init -y mops toolchain use moc latest # pin latest moc (non-interactive) mops toolchain use lintoko latest # pin latest lintoko mops add core ``` Then configure `[moc].args`, `[canisters]`, and `[build]` in `mops.toml`. To update tools later: `mops toolchain update moc` or `mops toolchain update` (all tools). --- ## Motoko Actor Migrations --- name: migrating-motoko-actors description: "Motoko actor state migration and schema evolution using the mops-managed migration chain (a migrations/ directory of timestamped files). Use when upgrading canisters, changing actor field types, renaming or adding stable fields, deciding implicit vs explicit migration, or writing migration files — including one-shot changes. For unexplained compatibility diagnostics, frozen migration files, a non-empty first OldActor, projects converted from legacy persistence, or requests to remove the chain or revert to inline (with migration = ...), use troubleshooting-motoko-migrations." license: Apache-2.0 compatibility: "moc >= 1.11.2, core >= 2.5.0" metadata: title: Motoko Actor Migrations category: Motoko --- # Motoko Actor Migrations Expert guidance for migrating actor state across canister upgrades with orthogonal persistence. ## Critical: Never use classical persistence or pre/post upgrade Do not use classical (legacy) persistence or `system func preupgrade` / `system func postupgrade`. They are error-prone, can leave canisters stuck if they trap, and do not scale. Also do not use the legacy `(with migration = ...)` actor-attached syntax. This skill covers **mops-managed migrations**. When a change requires an explicit migration, write it as a timestamped file in `src/backend/migrations/`; the chain replays automatically. ## How stable state is initialized Stable actor fields have no initializers in the actor body. The chain in `src/backend/migrations/` is what gives them values: the runtime walks it in lexicographic order, running every file on a fresh install and only the files not yet applied to the canister on an upgrade. ## When to Use This Skill - Planning or implementing a canister upgrade that changes actor state - Deciding between implicit vs explicit migration - Writing or refactoring a migration function - Introducing stable state for the first time (a migration with `OldActor = {}`, or fold it into the first one if that is still pending) ## Migration Folder Rules - **All migrations live in `src/backend/migrations/`.** The full chain replays in lexicographic filename order on fresh install; on upgrade, only entries newer than the deployed tail run. (The directory is declared as `chain = ...` under `[canisters..migrations]` in `mops.toml`; an imported project using a non-default canister name may place it elsewhere — read `mops.toml` rather than assuming.) - **At most one pending migration per build** (`check-limit = 1` in `mops.toml`). If a migration is already pending (not yet applied), **edit that file** to fold in further changes instead of adding another. `mops check` compares the deployed `.most` baseline and names the latest pending file to fold into when the limit is exceeded. Where a hosting platform owns the migrations section and `check-limit`, never edit them to clear an error. - **Name new files with just the UTC timestamp**, no suffix: `YYYYMMDD_HHMMSS.mo`. The timestamp must sort after every existing file. Do NOT encode the change in the name (no `AddPriority`, `AddTags`, `Init`, …) — any feature-ish name tempts you to add another file for the next change instead of editing the one pending file. - **Never modify, delete, or rename a migration that was already applied.** Applied migrations are tracked by module name, so a rename makes the runtime treat the file as never applied, and an edit to an already-applied file never executes. Some platforms enforce this by making applied migrations read-only, in which case writes to them simply fail. A migration that was not applied yet is pending: **edit** it rather than add a second migration for the same change. - **Migrations must be self-contained.** Inline BOTH old types AND new types in the migration file. Only `mo:core/...` and mops package imports are allowed — never `../types` or any project module. The chain replays forever; a frozen migration that imported `Types.Note` becomes wrong the moment `Note` changes in an incompatible way. Component-owned opaque state is the reason package imports are allowed: `AccessControl.initState()` from `mo:caffeineai-authorization/access-control` can only be constructed by importing the package. - `mops check --fix` automatically verifies upgrade compatibility. ## Two Kinds of Migration ### 1. Implicit migration (no code) The runtime allows the upgrade if the new program is compatible with the old. No migration function needed. > **Do NOT add a migration file for changes in the implicit list below.** Every migration file replays forever on fresh install; adding a no-op file bloats the chain, slows fresh installs, and creates a frozen artifact you can never delete. A long enough chain becomes undeployable in a way no retry recovers, and `mops check` will not warn you. **Fewer migrations are always better.** > > **Identity body = no migration.** If your `(old : OldActor) : NewActor` body would just be `old` (or rebuild the same record field-by-field with no transformation), the change is stable-compatible — delete the file. **Allowed without explicit migration (typical compatible changes):** - Changing mutability of a field (`var` to `let` or vice versa) - Adding variant constructors - Changing `Nat` to `Int` (and other safe supertypes) - Other changes that satisfy Motoko stable subtyping **Require explicit migration:** - Removing any actor field the previous version exposes — consume it in `OldActor`, omit from `NewActor` - Promoting to `Any` or other lossy supertypes - Renaming fields (map old to new in migration) - Non-trivial transformations (e.g. `Int` to `Float`, restructuring records) - Adding new stable fields (initial values must come from the migration; no inline initializers allowed) - Introducing stable state for the first time (the migration supplies the initial values; the actor declares stable fields with types only, no inline initializers) ### 2. Explicit migration (migration function) Use when the new state shape or types are not a simple compatible extension of the old. Extend the pending migration if there is one; otherwise add a new timestamped file to `src/backend/migrations/`. The chain replays automatically. **Rules:** - Migration function type: `(old : OldActor) : NewActor`. Both record types must be stable (no shared/local functions; use primitive types, records, variants, Option, Map, List, etc.). - **Domain** `OldActor`: record of old stable fields (names and types as in the previous version). If the retired actor is missing a field the domain expects, the upgrade traps and is aborted. - **Codomain** `NewActor`: record of new stable fields; each field must exist in the new actor with the same name and a supertype of the codomain type. Use `var x = ...` or `x = ...` in the output to match the actor's `var` vs `let`. - On fresh install, the entire chain replays in order starting from an empty actor (`OldActor = {}` for the first migration); on upgrade, only entries newer than the deployed tail run. Exception: in a project converted from legacy persistence the first file's `OldActor` is the pre-conversion stable shape, not `{}` — leave it alone (see `troubleshooting-motoko-migrations`). - Each `NewActor` field's value comes from the migration body. The actor body has no initializers in enhanced mode. - List every stable field in both `OldActor` and `NewActor` (including unchanged ones) is the canonical form for clarity. A partial `OldActor`/`NewActor` that lists only the fields being changed (subset form) is also supported: unchanged fields carry through automatically. Either way, a field in `OldActor` but not in `NewActor` is an explicit discard (possible data loss). - If the migration function traps, the upgrade is aborted and the canister remains on the old version. Keep the migration pure and free of operations that can trap unexpectedly. Multi-step upgrades (e.g. v1 to v2 to v3): Each upgrade step has one migration from the previously deployed version. The next version can use a new migration (or none if the change is stable-compatible). ## Authoring a migration Pick a bare UTC-timestamp filename (`YYYYMMDD_HHMMSS.mo`, no suffix) that sorts after every existing entry, then write the module: ```motoko module { type OldActor = { /* old stable fields, inlined */ }; type NewActor = { /* new stable fields */ }; public func migration(old : OldActor) : NewActor { { /* produce new fields from old */ }; }; }; ``` - Must be a `module` exporting `public func migration(old : OldActor) : NewActor` (the function name is required — the chain runner discovers it by name). - Both `OldActor` and `NewActor` must be inlined in the file — no project imports. ## Actor body: types only, no initializers Stable vars are declared with types, no initial values. Transient let/var fields use initializers as usual. > This no-initializer rule applies to enhanced-migration projects (this skill's subject), where the migration chain owns initial values. In a plain project without the enhanced-migration chain, stable fields are initialized with inline values in the actor body as usual (e.g. `actor { let m = Map.empty(); }`). ```motoko actor { let tasks : Map.Map; var nextId : Nat; transient var cache = List.empty(); }; ``` Initial values come from the migration chain. When you introduce stable state for the first time, write a migration whose `OldActor = {}` and `NewActor` enumerates **every** stable field declared in `main.mo`. The migration body must produce a value for each. Missing fields surface as compatibility warnings and break subsequent upgrades. > If an example anywhere shows inline initializers like `let accessControlState = AccessControl.initState();` or `let users = Map.empty();` directly in the actor body, it predates enhanced migration. Under enhanced migration that is a compile error (M0014, M0250). Treat such examples as state-shape hints only: copy the field name and type into your actor (without initializer), and **move the initializer expression into the migration function's `NewActor` output**. ## Stable-Compatible (definition) **Old** signature is **stable-compatible** with **new** if, for every stable field `id : T` in the old signature: - The new signature has a stable field `id : U` such that T is a stable subtype of U (the old value can be used as the new field's initial value without loss of data). - The new signature may include additional fields not present in the old one (each supplied by a migration). - Matching fields may differ in mutability (`var` vs non-`var`). So: you can widen types (e.g. `Nat` to `Int`) and change mutability without an explicit migration. You cannot remove fields, rename them, or narrow types. **Adding a stable field always requires a migration**: inline initializers are not allowed, so the new field's initial value must come from a migration file's `NewActor`. ## Patterns ### Add record field with default Use `record with newField = value` to add a field to every element: ```motoko // Add required field zipCode to each taxpayer old.taxPayers.map( func(_id, oldTaxPayer) { { oldTaxPayer with zipCode = "" } } ); ``` For a new optional field, set it to `null`: ```motoko { task with var status = task.status; var assignee = null : ?Principal } ``` ### Add or extend variant type Adding a variant tag -- cast the old value to the new variant type: ```motoko var status = bounty.status : NewTaskStatus // OldTaskStatus had #open;#claimed;#completed; New adds #expired ``` Replacing a Bool with a variant: ```motoko var status = if (task.completed) { #completed } else { #pending }; ``` ### Map over a collection Transform each value in a `Map` with `map(func(key, oldVal) { ... })`: ```motoko let todos = old.todos.map( func(_, task) { { task with due = 0; var status = if (task.completed) { #completed } else { #pending }; }; } ); { var todos; var nextTaskId = old.nextTaskId }; ``` ### Add new top-level stable field (computed from old state) Include the new field in the migration output and compute it from old fields: ```motoko let times = List.repeat(0, old.messages.size()); { var messages = old.messages; var times }; ``` ### Restructure: change shape of state When the new state has a different structure, provide a transformation function from the old field type to the new one and implement it according to the application's migration logic. Build the new value in the migration from the old state and return a record that matches NewActor. ### Change type of a field **Rename/conceptual change** -- e.g. `artist : Text` to `artists : Set.Set`: ```motoko { oldPainting with artists = Set.singleton(oldPainting.artist) } ``` ### Rename or change type of a single field Input record uses old name/type, output record uses new name/type: ```motoko project=rename-field filepath=src/backend/migrations/20260101_000000.mo // src/backend/migrations/YYYYMMDD_HHMMSS.mo import Int "mo:core/Int"; module { type OldActor = { var state : Int }; type NewActor = { var newState : Float }; public func migration(old : OldActor) : NewActor { { var newState = old.state.toFloat() }; }; }; ``` ### Drop a field intentionally Consume it in the migration input but do not include it in the output. Expect a compiler warning; ensure the loss is intentional. ### Add a new field Add the field to `main.mo` with type only (no initializer) AND add it to the next migration's `NewActor` with a value computed from old fields or a constant. The actor body cannot supply the initial value under enhanced migration. ## Migration-Time Semantics - The migration function runs once at upgrade time, in the upgrade context. Values like `Time.now()` in the migration body are the time of the upgrade, not of each original record creation. - Do not use constants or magic values in migrations; derive defaults from the migration input or from well-defined application types. ## Compatibility and Tooling The upgrade safety check compares the new actor body against the last deployed stable signature: a `.most` file (an encoded snapshot of the stable signature — field names and types) referenced from `mops.toml` under `[canisters..check-stable]`. When that is configured, `mops check --fix` picks it up automatically. Hosted platforms typically wire this up for you and keep the previous `.most` alongside the project. For the check to pass: the new migration's `OldActor` must match the previously deployed signature, and its `NewActor` must match (or be a stable supertype of) the new actor body. To derive `OldActor` deterministically: your `OldActor` equals the `NewActor` of the file that precedes yours in `src/backend/migrations/` (lex-order), or `{}` if yours is the first file in the chain. `{}` applies only when the chain starts from an empty canister — a project converted from legacy persistence starts from its pre-conversion stable shape instead, and its existing first file already reflects that. ## Checklist for Upgrades - [ ] Decide: implicit (compatible change) vs explicit (migration file) - [ ] **At most ONE pending migration file per build.** Before creating a file, check `src/backend/migrations/` — if a migration is already pending, edit it instead of adding a second - [ ] If explicit: pick a bare UTC-timestamp filename (`YYYYMMDD_HHMMSS.mo`, no suffix) that sorts after every existing file; do not encode the change in the name - [ ] Set `OldActor` to the `NewActor` of the file that precedes yours in `src/backend/migrations/` (lex-order), or `{}` if yours is the first file in a project that started out with a chain. Never from current `main.mo`. Never the file's own `NewActor`. - [ ] When the directory is empty (init migration), `NewActor` must list every stable field declared in `main.mo`, with a value for each - [ ] Inline both `OldActor` (with old types) and `NewActor` (with new types) — no project imports - [ ] Implement `public func migration(old : OldActor) : NewActor` - [ ] Never modify or delete a migration that was already applied; edit (don't duplicate) a pending one - [ ] Do not use preupgrade/postupgrade or `(with migration = ...)` for data migration - [ ] Iterate on `mops check --fix` (fast) until it passes — it verifies compilation and upgrade safety - [ ] Run `mops build` ONCE at the end (slow) to compile the backend and produce the updated IDL bindings ## Additional References - **Migration examples**: See [examples.md](references/examples.md) for minimal, self-contained examples (add field, map over collection, add optional field) - **When something does not add up**: Load `troubleshooting-motoko-migrations` for compatibility diagnostics you cannot explain, write failures on frozen files, projects converted from legacy persistence, and requests to remove the chain. Not needed on the normal path. - **General Motoko development**: Use `writing-motoko` for language fundamentals, core library reference, and architecture patterns - **mops tooling**: Load `mops-cli` for `mops.toml` configuration, `mops check`, `mops build`, and toolchain setup - [Motoko Docs: Data persistence](https://docs.internetcomputer.org/motoko/main/actors/stable-variables) - [Motoko Docs: Compatibility](https://docs.internetcomputer.org/motoko/main/actors/upgrades) --- ## Multi-Canister Architecture --- name: multi-canister description: "Design and deploy multi-canister dapps. Covers inter-canister calls, canister factory pattern, async messaging pitfalls, bounded vs unbounded wait, and 2MB payload limits. Use when splitting an app across canisters, making inter-canister or cross-canister calls, or designing canister-to-canister communication. Do NOT use for single-canister apps." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2" metadata: title: Multi-Canister Architecture category: Core --- # Multi-Canister Architecture ## What This Is Splitting an IC application across multiple canisters for scaling, separation of concerns, or independent upgrade cycles. Each canister has its own state, cycle balance, and upgrade path. Canisters communicate via async inter-canister calls. ## Prerequisites - For Motoko: `mops` package manager, `core = "2.1.0"` in mops.toml — `Runtime.envVar`, used below to discover a sibling canister's ID, was added in motoko-core 2.1.0 - For Rust: `ic-cdk >= 0.19`, `candid`, `serde`, `ic-stable-structures` ## How It Works A caller canister makes a call to a callee canister: the method name, arguments (payload) and attached cycles are packed into a canister request message, which is delivered to the callee after the caller blocks on `await`; the callee executes the request and produces a response; this is packed into a canister response message and delivered to the caller; the caller awakes fron the `await` and continues execution (executes the canister response message). The system may produce a reject response message if e.g. the callee is not found or some resource limit was reached. Calls may be unbounded wait (caller MUST wait until the callee produces a response) or bounded wait (caller MAY get a `SYS_UNKNOWN` response instead of the actual response after the call timeout expires or if the subnet runs low on resources). Request delivery is best-effort: the system may decide to reject any request instead of delivering it. Unbounded wait response (including reject response) delivery is guaranteed: the caller will always learn the outcome of the call. Bounded wait response delivery is best-effort: the caller may receive a system-generated `SYS_UNKNOWN` reject response (unknown outcome) instead of the actual response if the call timed out or some system resource was exhausted, whether or not the request was delivered to the callee. ## When to Use Multi-Canister | Reason | Threshold | |---|---| | Storage limits | Each canister: up to hundreds of GB stable memory + 4GB heap. If your data could exceed heap limits or benefit from partitioning, split storage across canisters. | | Scalable compute | Canisters are single-threaded actors. Sharding load across multiple canisters, potentially across multiple subnets, can significantly improve throughput. | | Separation of concerns | Auth service, content service, payment service as independent units. | | Independent upgrades | Upgrade the payments canister without touching the user canister. | | Access control | Different controllers for different canisters (e.g., DAO controls one, team controls another). | **When NOT to use:** Simple apps with <1GB data. Single-canister is simpler, faster, and avoids inter-canister call overhead. Do not over-architect. ## Issues that May Cause Functional Bugs For building a multi-canister application, take the perspective of an experienced senior software engineer and carefully read the following issues that may cause subtle functional bugs. Meticulously avoid bugs that could be caused by these issues. 1. **Request and response payloads are limited to 2 MB.** Because any canister call may be required to cross subnet boundaries; and cross-subnet (or XNet) messages (the request and response corresponding to each canister call) are inducted in (packaged into) 4 MB blocks; canister request and response payloads are limited to 2 MB. A call with a request payload above 2 MB will fail synchronously; and a response with a payload above 2 MB will trap. Chunk larger payloads into 1 MB chunks (to allow for any encoding overhead) and deliver them over multiple calls (e.g. chunked uploads or byte range queries). 2. **Update methods that make calls are NOT executed atomically.** When an update method makes a call, the code before the `await` is one atomic message execution (i.e. the ingress message or canister request that invoked the update method); and the code after the `await` is a separate atomic message execution (the response to the call). In particular, if the update method traps after the `await`, any mutations before the `await` have already been persisted; and any mutations after the `await` will be rolled back. Design for eventual consistency or use a saga pattern. If more context on this is needed, you can optionally refer to [properties of message executions on ICP](https://docs.internetcomputer.org/references/message-execution-properties). 3. **Use idempotent APIs. Or provide a separate endpoint to query the outcome of a non-idempotent call.** If a call to a non-idempotent API times out, there must be another way for the caller to learn the outcome of the call (e.g. by attaching a unique ID to the original call and querying for the outcome of the call with that unique ID). Without a way to learn the outcome, when the caller receives a `SYS_UNKNOWN` response it may be unable to decide whether to continue, retry the call or abort. 4. **Calls across subnet boundaries are slower than calls on the same subnet.** Under light subnet load, a call to a canister on the same subnet may complete and its response may be processed by the caller within a single round. The call latency only depends on how frequently the caller and callee are scheduled (which may be multiple times per round). A cross canister call requires 2-3 rounds either way (request delivery and response delivery), plus scheduler latency. 5. **Calls across subnet boundaries have relatively low bandwidth.** Cross-subnet (or XNet) messages are inducted in (packaged into) 4 MB blocks once per round, along with any ingress messages and other XNet messages. Expect multiple MBs of messages to take multiple rounds to deliver, on top of the XNet latency. (Subnet-local messages are routed within the subnet, so they don't suffer from this bandwidth limitation). 6. **Defensive practice: bind `msg_caller()` before `.await` in Rust.** The current ic-cdk executor preserves caller across `.await` points via protected tasks, but capturing it early guards against future executor changes. **Motoko is safe:** `public shared ({ caller }) func` captures `caller` as an immutable binding at function entry. ```rust // Recommended (Rust) — capture caller before await: #[update] async fn do_thing() { let original_caller = ic_cdk::api::msg_caller(); // Defensive: capture before await let _ = some_canister_call().await; let who = original_caller; // Safe } ``` 7. **Not handling rejected calls.** Inter-canister calls can fail (callee trapped, out of cycles, canister stopped). In Motoko use `try/catch`. In Rust, handle the `Result` from `ic_cdk::call`. Unhandled rejections trap your canister. 8. **Canister factory without enough cycles.** Creating a canister requires cycles. The management canister charges for creation and the initial cycle balance. If you do not attach enough cycles, creation fails. 9. **Not setting up `#[init]` and `#[post_upgrade]` in Rust.** Without a `post_upgrade` handler, canister upgrades may behave unexpectedly. Always define both. ## Issues that May Cause Security Bugs Take the perspective of an experienced senior security engineer and carefully read the following issues that may cause risky security issues. Meticulously avoid such security bugs. 1. **Avoid reentrancy issues.** The fact that calls are not atomic can cause reentrancy bugs such as double-spending vulnerabilities, see also "Update methods that make calls are NOT executed atomically" above. Avoid such issues, e.g. by employing locking patterns. If more context is needed, you can optionally refer to the [security best practices](https://docs.internetcomputer.org/building-apps/security/inter-canister-calls#be-aware-that-there-is-no-reliable-message-ordering) or the [paper](https://arxiv.org/pdf/2506.05932). 2. **Securely handle traps in callbacks.** A trap (a panic in Rust) in a callback causes the callback to not apply any state changes. For example, if a trap can be caused by a malicious entity, it could mean that security critical actions like debiting an account in a DeFi context can be skipped, leading to critical issues like double-spending. To avoid this, avoid traps in callbacks that could cause such bugs, consider using `call_on_cleanup`, and use "journaling". If more context is needed, optionally consider this [security best practice](https://docs.internetcomputer.org/building-apps/security/inter-canister-calls#securely-handle-traps-in-callbacks). 3. **Unbounded wait calls may prevent canister upgrades, indefinitely.** Unbounded wait calls may take arbitrarily long to complete: a malicious or incorrect callee may spin indefinitely without producing a response. Canisters cannot be stopped while awaiting responses to outstanding calls. Bounded wait calls avoid this issue by making sure that calls complete in a bounded time, independent of whether the callee responded or not. If more context is needed, optionally consider [this security best practice](https://docs.internetcomputer.org/building-apps/security/inter-canister-calls#be-aware-of-the-risks-involved-in-calling-untrustworthy-canisters). 4. **`canister_inspect_message` is not called for inter-canister calls.** It only runs for ingress messages (from external users). Do not rely on it for access control between canisters. Use explicit principal checks instead. If more context is needed, optionally consider [this security best practice](https://docs.internetcomputer.org/building-apps/security/iam#do-not-rely-on-ingress-message-inspection). ## Mistakes That Break Your Build 1. **Trying to order deployment with a `dependencies` field.** icp.yaml has a `dependencies` field but it is not used to order the deployment — icp-cli builds canisters in parallel, and `icp deploy` injects every canister's ID into every canister as a `PUBLIC_CANISTER_ID:` environment variable, so a canister can discover a sibling's ID at runtime regardless of deploy order. Read it with `Runtime.envVar("PUBLIC_CANISTER_ID:user_service")` in Motoko (motoko-core >= 2.1.0) or `ic_cdk::api::env_var_value("PUBLIC_CANISTER_ID:user_service")` in Rust. See the `icp-cli` skill's Canister Environment Variables section. 2. **Forgetting to generate type declarations for each backend canister.** Use language-specific tooling (e.g., `didc` for Candid bindings) to generate declarations for each backend canister individually. 3. **Shared types diverging between canisters.** If canister A expects `{ id: Nat; name: Text }` and canister B sends `{ id: Nat; title: Text }`, the call silently fails or traps. Use a shared types module imported by both canisters. ## Implementation ### Project Structure ``` my-project/ icp.yaml mops.toml src/ shared/ Types.mo # Shared type definitions user_service/ main.mo # User canister content_service/ main.mo # Content canister frontend/ ... # Frontend assets ``` ### icp.yaml ```yaml canisters: - name: user_service recipe: type: "@dfinity/motoko@v5.0.0" - name: content_service recipe: type: "@dfinity/motoko@v5.0.0" ``` ### mops.toml The `@dfinity/motoko@v5+` recipe compiles via `mops build `, so each canister's `main` lives in `mops.toml`, not in `recipe.configuration` in `icp.yaml`. Every canister `name` in `icp.yaml` must have an exactly matching `[canisters.]` key here, or the build fails with `No Motoko canisters found in mops.toml configuration`. ```toml [toolchain] moc = "1.9.0" [dependencies] core = "2.1.0" [canisters.user_service] main = "src/user_service/main.mo" [canisters.content_service] main = "src/content_service/main.mo" ``` ### Motoko #### src/shared/Types.mo — Shared Types ```motoko module { public type UserId = Principal; public type PostId = Nat; public type UserProfile = { id : UserId; username : Text; created : Int; }; public type Post = { id : PostId; author : UserId; title : Text; body : Text; created : Int; }; public type ServiceError = { #NotFound; #Unauthorized; #AlreadyExists; #InternalError : Text; }; }; ``` #### src/user_service/main.mo — User Canister ```motoko import Map "mo:core/Map"; import Principal "mo:core/Principal"; import Array "mo:core/Array"; import Time "mo:core/Time"; import Result "mo:core/Result"; import Runtime "mo:core/Runtime"; import Types "../shared/Types"; persistent actor { type UserProfile = Types.UserProfile; let users = Map.empty(); // Register a new user public shared ({ caller }) func register(username : Text) : async Result.Result { if (Principal.isAnonymous(caller)) { return #err(#Unauthorized); }; switch (Map.get(users, Principal.compare, caller)) { case (?_existing) { #err(#AlreadyExists) }; case null { let profile : UserProfile = { id = caller; username; created = Time.now(); }; Map.add(users, Principal.compare, caller, profile); #ok(profile) }; } }; // Check if a user exists (called by other canisters) public shared query func isValidUser(userId : Principal) : async Bool { switch (Map.get(users, Principal.compare, userId)) { case (?_) { true }; case null { false }; } }; // Get user profile public shared query func getUser(userId : Principal) : async ?UserProfile { Map.get(users, Principal.compare, userId) }; // Get all users public query func getUsers() : async [UserProfile] { Array.fromIter(Map.values(users)) }; }; ``` #### src/content_service/main.mo — Content Canister (calls User Service) ```motoko import Map "mo:core/Map"; import Nat "mo:core/Nat"; import Array "mo:core/Array"; import Time "mo:core/Time"; import Result "mo:core/Result"; import Runtime "mo:core/Runtime"; import Error "mo:core/Error"; import Principal "mo:core/Principal"; import Types "../shared/Types"; // Import the other canister — name must match icp.yaml canister key import UserService "canister:user_service"; persistent actor { type Post = Types.Post; let posts = Map.empty(); var postCounter : Nat = 0; // Create a post — validates user via inter-canister call public shared ({ caller }) func createPost(title : Text, body : Text) : async Result.Result { let originalCaller = caller; if (Principal.isAnonymous(originalCaller)) { return #err(#Unauthorized); }; // Inter-canister call to user_service let isValid = try { await UserService.isValidUser(originalCaller) } catch (e : Error.Error) { Runtime.trap("User service unavailable: " # Error.message(e)); }; if (not isValid) { return #err(#Unauthorized); }; let id = postCounter; let post : Post = { id; author = originalCaller; title; body; created = Time.now(); }; Map.add(posts, Nat.compare, id, post); postCounter += 1; #ok(post) }; // Get all posts public query func getPosts() : async [Post] { Array.fromIter(Map.values(posts)) }; // Get posts by author — with enriched user data public func getPostsWithAuthor(authorId : Principal) : async { user : ?Types.UserProfile; posts : [Post]; } { let userProfile = try { await UserService.getUser(authorId) } catch (_e : Error.Error) { null }; let authorPosts = Array.filter( Array.fromIter(Map.values(posts)), func(p : Post) : Bool { p.author == authorId } ); { user = userProfile; posts = authorPosts } }; // Delete a post — only the author can delete public shared ({ caller }) func deletePost(id : Nat) : async Result.Result<(), Types.ServiceError> { let originalCaller = caller; switch (Map.get(posts, Nat.compare, id)) { case (?post) { if (post.author != originalCaller) { return #err(#Unauthorized); }; ignore Map.delete(posts, Nat.compare, id); #ok(()) }; case null { #err(#NotFound) }; } }; }; ``` #### Production Readiness: Content Service The content service examples above are intentionally kept simple to demonstrate multi-canister communication patterns. They lack several things that would be needed for production use: - **Input validation.** The `username` parameter in `register` accepts any string — including empty strings or strings up to the 2MB message size limit. Validate length (e.g., 1–64 characters), enforce allowed character sets, and add a uniqueness constraint via a reverse lookup map to prevent impersonation. - **User enumeration and pagination on `getUsers`.** Using `getUsers`, it's possible for everyone to enumerate all users on the platform, which may not be desirable. Furthermore, the `getUsers` endpoint returns all user profiles in a single response. As the user base grows, this will hit the 2MB response size limit and trap, bricking the endpoint. Add pagination (offset/limit parameters). The same applies to `getPosts`. ### Rust #### Project Structure (Rust) ``` my-project/ icp.yaml Cargo.toml # workspace src/ user_service/ Cargo.toml src/lib.rs content_service/ Cargo.toml src/lib.rs ``` #### Cargo.toml (workspace root) ```toml [workspace] members = [ "src/user_service", "src/content_service", ] ``` #### icp.yaml (Rust) ```yaml canisters: - name: user_service recipe: type: "@dfinity/rust@v3.3.0" configuration: candid: src/user_service/user_service.did - name: content_service recipe: type: "@dfinity/rust@v3.3.0" configuration: candid: src/content_service/content_service.did ``` `package` is omitted: recipe >= v3.3.0 defaults it to the canister `name`, and each workspace member's `[package] name` already matches. Set `package` explicitly only when a crate name differs from its canister name. #### src/user_service/Cargo.toml ```toml [package] name = "user_service" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] ic-cdk = "0.19" candid = "0.10" serde = { version = "1", features = ["derive"] } ic-stable-structures = "0.7" ``` #### src/user_service/src/lib.rs ```rust use candid::{CandidType, Deserialize, Principal}; use ic_cdk::{init, post_upgrade, query, update}; use ic_stable_structures::memory_manager::{MemoryId, MemoryManager, VirtualMemory}; use ic_stable_structures::{DefaultMemoryImpl, StableBTreeMap}; use std::cell::RefCell; type Memory = VirtualMemory; #[derive(CandidType, Deserialize, Clone, Debug)] struct UserProfile { id: Principal, username: String, created: i64, } // Stable storage thread_local! { static MEMORY_MANAGER: RefCell> = RefCell::new(MemoryManager::init(DefaultMemoryImpl::default())); static USERS: RefCell, Vec, Memory>> = RefCell::new( StableBTreeMap::init( MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(0))) ) ); } fn principal_to_key(p: &Principal) -> Vec { p.as_slice().to_vec() } fn serialize_profile(profile: &UserProfile) -> Vec { candid::encode_one(profile).unwrap() } fn deserialize_profile(bytes: &[u8]) -> UserProfile { candid::decode_one(bytes).unwrap() } #[init] fn init() {} #[post_upgrade] fn post_upgrade() {} #[update] fn register(username: String) -> Result { let caller = ic_cdk::api::msg_caller(); if caller == Principal::anonymous() { return Err("Unauthorized".to_string()); } let key = principal_to_key(&caller); USERS.with(|users| { if users.borrow().contains_key(&key) { return Err("Already exists".to_string()); } let profile = UserProfile { id: caller, username, created: ic_cdk::api::time() as i64, }; let bytes = serialize_profile(&profile); users.borrow_mut().insert(key, bytes); Ok(profile) }) } #[query] fn is_valid_user(user_id: Principal) -> bool { let key = principal_to_key(&user_id); USERS.with(|users| users.borrow().contains_key(&key)) } #[query] fn get_user(user_id: Principal) -> Option { let key = principal_to_key(&user_id); USERS.with(|users| { users.borrow().get(&key).map(|bytes| deserialize_profile(&bytes)) }) } ic_cdk::export_candid!(); ``` #### src/content_service/Cargo.toml ```toml [package] name = "content_service" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] ic-cdk = "0.19" candid = "0.10" serde = { version = "1", features = ["derive"] } ic-stable-structures = "0.7" ``` #### src/content_service/src/lib.rs ```rust use candid::{CandidType, Deserialize, Principal}; use ic_cdk::call::Call; use ic_cdk::{init, post_upgrade, query, update}; use ic_stable_structures::memory_manager::{MemoryId, MemoryManager, VirtualMemory}; use ic_stable_structures::{DefaultMemoryImpl, StableBTreeMap, StableCell}; use std::cell::RefCell; type Memory = VirtualMemory; #[derive(CandidType, Deserialize, Clone, Debug)] struct Post { id: u64, author: Principal, title: String, body: String, created: i64, } #[derive(CandidType, Deserialize, Clone, Debug)] struct UserProfile { id: Principal, username: String, created: i64, } // Stable storage -- survives canister upgrades thread_local! { static MEMORY_MANAGER: RefCell> = RefCell::new(MemoryManager::init(DefaultMemoryImpl::default())); // Posts keyed by id (u64 as big-endian bytes) -> candid-encoded Post static POSTS: RefCell, Vec, Memory>> = RefCell::new( StableBTreeMap::init( MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(0))) ) ); // Post counter in stable memory static POST_COUNTER: RefCell> = RefCell::new( StableCell::init( MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(1))), 0u64, ) ); // Store the user_service canister ID (set during init, re-set on upgrade) static USER_SERVICE_ID: RefCell> = RefCell::new(None); } fn post_id_to_key(id: u64) -> Vec { id.to_be_bytes().to_vec() } fn serialize_post(post: &Post) -> Vec { candid::encode_one(post).unwrap() } fn deserialize_post(bytes: &[u8]) -> Post { candid::decode_one(bytes).unwrap() } #[init] fn init(user_service_id: Principal) { USER_SERVICE_ID.with(|id| *id.borrow_mut() = Some(user_service_id)); } #[post_upgrade] fn post_upgrade(user_service_id: Principal) { // Re-set the user_service ID (not stored in stable memory for simplicity, // since it is always passed as an init/upgrade argument) init(user_service_id); } fn get_user_service_id() -> Principal { USER_SERVICE_ID.with(|id| { id.borrow().expect("user_service canister ID not set") }) } // Defensive: capture caller before any await #[update] async fn create_post(title: String, body: String) -> Result { // Capture caller before the await as defensive practice let original_caller = ic_cdk::api::msg_caller(); if original_caller == Principal::anonymous() { return Err("Unauthorized".to_string()); } // Inter-canister call to user_service let user_service = get_user_service_id(); let (is_valid,): (bool,) = Call::unbounded_wait(user_service, "is_valid_user") .with_arg(original_caller) .await .map_err(|e| format!("User service call failed: {:?}", e))? .candid_tuple() .map_err(|e| format!("Failed to decode response: {:?}", e))?; if !is_valid { return Err("User not registered".to_string()); } let id = POST_COUNTER.with(|counter| { let mut counter = counter.borrow_mut(); let id = *counter.get(); counter.set(id + 1); id }); let post = Post { id, author: original_caller, // Use captured caller title, body, created: ic_cdk::api::time() as i64, }; POSTS.with(|posts| { posts.borrow_mut().insert(post_id_to_key(id), serialize_post(&post)); }); Ok(post) } #[query] fn get_posts() -> Vec { POSTS.with(|posts| { posts.borrow().iter() .map(|entry| deserialize_post(&entry.value())) .collect() }) } // Cross-canister enrichment: get posts with author profile #[update] async fn get_posts_with_author(author_id: Principal) -> (Option, Vec) { let user_service = get_user_service_id(); // Call user_service for profile data let user_profile: Option = match Call::unbounded_wait(user_service, "get_user") .with_arg(author_id) .await { Ok(response) => response.candid_tuple::<(Option,)>() .map(|(profile,)| profile) .unwrap_or(None), Err(_) => None, // Handle gracefully if user service is down }; let author_posts = POSTS.with(|posts| { posts.borrow().iter() .map(|entry| deserialize_post(&entry.value())) .filter(|p| p.author == author_id) .collect() }); (user_profile, author_posts) } #[update] async fn delete_post(id: u64) -> Result<(), String> { let original_caller = ic_cdk::api::msg_caller(); POSTS.with(|posts| { let mut posts = posts.borrow_mut(); let key = post_id_to_key(id); match posts.get(&key) { Some(bytes) => { let post = deserialize_post(&bytes); if post.author != original_caller { return Err("Unauthorized".to_string()); } posts.remove(&key); Ok(()) } None => Err("Not found".to_string()), } }) } ic_cdk::export_candid!(); ``` ### Canister Factory Pattern A canister that creates other canisters dynamically. Useful for per-user canisters, sharding, or dynamic scaling. #### Motoko Factory ```motoko import Principal "mo:core/Principal"; import Map "mo:core/Map"; import Array "mo:core/Array"; import Runtime "mo:core/Runtime"; persistent actor Self { type CanisterSettings = { controllers : ?[Principal]; compute_allocation : ?Nat; memory_allocation : ?Nat; freezing_threshold : ?Nat; }; type CreateCanisterResult = { canister_id : Principal; }; // IC Management canister transient let ic : actor { create_canister : shared ({ settings : ?CanisterSettings }) -> async CreateCanisterResult; install_code : shared ({ mode : { #install; #reinstall; #upgrade }; canister_id : Principal; wasm_module : Blob; arg : Blob; }) -> async (); deposit_cycles : shared ({ canister_id : Principal }) -> async (); } = actor "aaaaa-aa"; // Track created canisters let childCanisters = Map.empty(); // owner -> canister // Create a new canister for a user (one per caller) public shared ({ caller }) func createChildCanister(wasmModule : Blob) : async Principal { if (Principal.isAnonymous(caller)) { Runtime.trap("Auth required") }; if (Map.get(childCanisters, Principal.compare, caller) != null) { Runtime.trap("Child canister already exists for this caller"); }; // Create canister with cycles let createResult = await (with cycles = 1_000_000_000_000) ic.create_canister({ settings = ?{ controllers = ?[Principal.fromActor(Self), caller]; compute_allocation = null; memory_allocation = null; freezing_threshold = null; }; }); let canisterId = createResult.canister_id; // Install code await ic.install_code({ mode = #install; canister_id = canisterId; wasm_module = wasmModule; arg = to_candid (caller); // Pass owner as init arg }); Map.add(childCanisters, Principal.compare, caller, canisterId); canisterId }; // Get a user's canister public query func getChildCanister(owner : Principal) : async ?Principal { Map.get(childCanisters, Principal.compare, owner) }; }; ``` #### Rust Factory ```rust use candid::{CandidType, Deserialize, Nat, Principal, encode_one}; use ic_cdk::management_canister::{ create_canister_with_extra_cycles, install_code, CreateCanisterArgs, InstallCodeArgs, CanisterInstallMode, CanisterSettings, }; use ic_cdk::update; use ic_stable_structures::memory_manager::{MemoryId, MemoryManager, VirtualMemory}; use ic_stable_structures::{DefaultMemoryImpl, StableBTreeMap}; use std::cell::RefCell; type Memory = VirtualMemory; thread_local! { static MEMORY_MANAGER: RefCell> = RefCell::new(MemoryManager::init(DefaultMemoryImpl::default())); // Stable storage: owner principal -> child canister principal (survives upgrades) static CHILD_CANISTERS: RefCell, Vec, Memory>> = RefCell::new( StableBTreeMap::init( MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(0))) ) ); } #[update] async fn create_child_canister(wasm_module: Vec) -> Principal { let caller = ic_cdk::api::msg_caller(); assert_ne!(caller, Principal::anonymous(), "Auth required"); // One child canister per caller let already_exists = CHILD_CANISTERS.with(|c| c.borrow().contains_key(&caller.as_slice().to_vec())); if already_exists { ic_cdk::trap("Child canister already exists for this caller"); } // Create canister let create_args = CreateCanisterArgs { settings: Some(CanisterSettings { controllers: Some(vec![ic_cdk::api::canister_self(), caller]), compute_allocation: None, memory_allocation: None, freezing_threshold: None, reserved_cycles_limit: None, log_visibility: None, wasm_memory_limit: None, wasm_memory_threshold: None, environment_variables: None, }), }; // Attach 1T cycles for the new canister let create_result = create_canister_with_extra_cycles(&create_args, 1_000_000_000_000u128) .await .expect("Failed to create canister"); let canister_id = create_result.canister_id; // Install code let install_args = InstallCodeArgs { mode: CanisterInstallMode::Install, canister_id, wasm_module, arg: encode_one(&caller).unwrap(), // Pass owner as init arg }; install_code(&install_args) .await .expect("Failed to install code"); // Track the child canister CHILD_CANISTERS.with(|canisters| { canisters.borrow_mut().insert( caller.as_slice().to_vec(), canister_id.as_slice().to_vec(), ); }); canister_id } #[ic_cdk::query] fn get_child_canister(owner: Principal) -> Option { CHILD_CANISTERS.with(|canisters| { canisters.borrow().get(&owner.as_slice().to_vec()) .map(|bytes| Principal::from_slice(&bytes)) }) } ``` #### Production Readiness: Canister Factory The factory examples above are intentionally kept simple to demonstrate the canister creation pattern. They lack several things that would be needed for production use: - **Cycle-drain protection.** Any non-anonymous principal can call `createChildCanister` repeatedly, each call consuming 1T cycles from the factory. Add an allowlist of authorized callers, enforce a per-user creation limit, and check the factory's cycle balance before creating a canister (e.g., `Cycles.balance()` from `mo:core/Cycles` in Motoko, `ic_cdk::api::canister_cycle_balance()` in Rust). - **WASM module validation.** The WASM module is caller-supplied, meaning any authenticated user can deploy arbitrary code. Do not accept WASM from arbitrary callers in production. Instead, hardcode a known WASM module (or its hash) in the factory canister, or verify the module hash against an allowlist before installing. Whitelist principals that are allowed to deploy through the factory to avoid unauthorized use. - **Reentrancy protection.** The factory performs two sequential awaits (`create_canister`, then `install_code`) with no locking. Concurrent calls from the same caller can create orphaned canisters that the factory loses track of. Add a lock (e.g., a `Set` of principals with in-flight calls) that prevents concurrent creation for the same caller. - **Partial failure handling.** If `create_canister` succeeds but `install_code` fails, the canister exists and has cycles but is untracked by the factory. Track the canister ID immediately after creation (before attempting `install_code`) so the factory can retry installation or clean up on failure. ## Upgrade Strategy for Multi-Canister Systems ### Ordering 1. Deploy shared dependencies first (e.g., `user_service` before `content_service`). 2. Never change Candid interfaces in a breaking way. Add new fields as `opt` types. 3. Test upgrades locally before mainnet. ### Safe Upgrade Checklist - Never remove or rename fields in existing types shared across canisters. - Add new fields as optional (`?Type` in Motoko, `Option` in Rust). - If a canister's Candid interface changes, upgrade consumers after the provider. - Always have both `#[init]` and `#[post_upgrade]` in Rust canisters. - In Motoko, `persistent actor` handles stable storage automatically. ### Upgrade Commands ```bash # Upgrade canisters in dependency order icp deploy user_service # Rust content_service requires the user_service principal on every upgrade (post_upgrade arg) USER_SERVICE_ID=$(icp canister status user_service --id-only) icp deploy content_service --argument "(principal \"$USER_SERVICE_ID\")" npm run build icp deploy frontend ``` ## Deploy & Test ### Local Development ```bash # Start the local replica icp network start -d # Deploy in dependency order icp deploy user_service # content_service (Rust) requires the user_service canister ID as an init argument USER_SERVICE_ID=$(icp canister status user_service --id-only) icp deploy content_service --argument "(principal \"$USER_SERVICE_ID\")" # Build and deploy frontend npm run build icp deploy frontend ``` ### Test Inter-Canister Calls (Motoko) ```bash # Register a user PRINCIPAL=$(icp identity principal) icp canister call user_service register "(\"alice\")" # Verify user exists icp canister call user_service isValidUser "(principal \"$PRINCIPAL\")" # Expected: (true) # Create a post (triggers inter-canister call to user_service) icp canister call content_service createPost "(\"Hello World\", \"My first post\")" # Expected: (variant { ok = record { id = 0; author = principal "..."; ... } }) # Get all posts icp canister call content_service getPosts # Expected: (vec { record { id = 0; ... } }) ``` ### Test Inter-Canister Calls (Rust) Rust canisters use snake_case function names: ```bash PRINCIPAL=$(icp identity principal) icp canister call user_service register "(\"alice\")" icp canister call user_service is_valid_user "(principal \"$PRINCIPAL\")" # Expected: (true) # content_service must have been deployed with --argument "(principal \"\")" icp canister call content_service create_post "(\"Hello World\", \"My first post\")" # Expected: (variant { ok = record { id = 0 : nat64; author = principal "..."; ... } }) icp canister call content_service get_posts # Expected: (vec { record { id = 0 : nat64; ... } }) ``` ## Verify It Works ### Verify User Registration ```bash icp canister call user_service register '("testuser")' # Expected: (variant { ok = record { id = principal "..."; username = "testuser"; created = ... } }) ``` ### Verify Inter-Canister Call ```bash # This call should succeed (user is registered) # Motoko: createPost / Rust: create_post icp canister call content_service createPost '("Test Title", "Test Body")' # Expected: (variant { ok = record { ... } }) # Remember the identity you registered with. There is no identity named # `default` -- `icp identity default` names the *role*, and a fresh icp-cli # install has only `anonymous`. (Notices go to stderr, so this captures cleanly.) ORIGINAL_IDENTITY=$(icp identity default) # Create a new identity that is NOT registered icp identity new unregistered --storage plaintext icp identity default unregistered icp canister call content_service createPost '("Should Fail", "No user")' # Expected: (variant { err = "User not registered" }) # Switch back icp identity default "$ORIGINAL_IDENTITY" ``` ### Verify Cross-Canister Query ```bash PRINCIPAL=$(icp identity principal) # Motoko: getPostsWithAuthor / Rust: get_posts_with_author icp canister call content_service getPostsWithAuthor "(principal \"$PRINCIPAL\")" # Expected: (opt record { id = ...; username = "testuser"; ... }, vec { record { ... } }) ``` ### Verify Canister Factory ```bash # Read the wasm file for the child canister # (In practice you'd upload or reference a wasm blob) icp canister call factory createChildCanister '(blob "...")' # Expected: (principal "NEW-CANISTER-ID") icp canister call factory getChildCanister "(principal \"$PRINCIPAL\")" # Expected: (opt principal "NEW-CANISTER-ID") ``` --- ## Organization Sign-In --- name: organization-sign-in description: "Set up an organization's own single sign-on for Internet Identity, so staff sign in to II-powered apps against Okta, Entra ID, Google Workspace or Auth0. Nothing registers with II: it discovers the configuration from /.well-known/ii-openid-configuration on the organization's domain. Covers the OIDC client, the discovery file and every field, per-app clients including salted-hash keys, gate_all_apps, stable_identifier_claim, the limits that reject the whole file, and II's caching windows. Use when an organization wants its employees to sign in with its own identity provider, when II offers no SSO for a domain that has published the file, or when an edit to that file has not taken effect yet. This is the organization's side, done by whoever administers the domain. For an app sending users there with ssoDomain, load user-sign-in. Do NOT use for signing in to II with a personal Google, Apple or Microsoft account, which is ordinary OpenID and needs none of this." license: Apache-2.0 compatibility: "an OIDC provider (Okta, Entra ID, Google Workspace or Auth0), HTTPS hosting for the organization's domain" metadata: title: Organization Sign-In category: Auth --- # Organization Sign-In ## What this is, and who does it Internet Identity (II) authenticates an organization's staff against its own OpenID Connect provider (Okta, Entra ID, Google Workspace, Auth0). Nothing is registered with Internet Identity: it discovers the configuration from one file on the organization's domain. This is work an organization's IT administrator does once, on the organization's own domain and identity provider. It is not app code, and no app can do it. The app side is one constructor option, `new AuthClient({ ssoDomain: "acme.com" })`, documented in the `user-sign-in` skill along with the `getSsoStatus()` check that tells an app whether a domain has SSO at all. ## 1. Register an OIDC client In the identity provider, create an OIDC web application: | Setting | Value | |---|---| | Redirect URI | `https://id.ai/callback` | | Grant types | Authorization Code and Implicit (hybrid): II requests `response_type=code id_token` with `response_mode=form_post` | | ID token | Allowed with the implicit grant | | Access token | Not needed | | Scopes | `openid`, `profile`, `email` | ## 2. Publish the discovery file Serve it over HTTPS at exactly `https:///.well-known/ii-openid-configuration`: ```json { "client_id": "0oaDEFAULT", "openid_configuration": "https://acme.okta.com/.well-known/openid-configuration", "name": "Acme Corp", "session_max_age_seconds": 28800, "app_clients": { "https://payroll.acme.com": "0oaPAYROLL" }, "gate_all_apps": false, "stable_identifier_claim": "sub" } ``` | Field | Required | Default | Meaning | |---|---|---|---| | `client_id` | yes | | The client from step 1 | | `openid_configuration` | yes | | The provider's OIDC discovery URL | | `name` | no | the domain | Label on the sign-in screen, and `available.name` from `getSsoStatus()` | | `session_max_age_seconds` | no | `28800` (8 hours) | How long a sign-in through this domain stays valid; also caps an app's own session length | | `app_clients` | no | none | Maps an app's exact origin, or a salted hash of it, to that app's own client | | `gate_all_apps` | no | `false` | `true` refuses apps not listed in `app_clients` | | `stable_identifier_claim` | no | `sub` | A claim that is the same for one person across all the organization's clients (Entra ID: `oid`, since its `sub` differs per client) | No CORS header is required: Internet Identity fetches the file server-side, and `@icp-sdk/auth` 11.x checks a domain through II (`getSsoStatus()`), not from the browser. `isValidSsoDomain()` in 10.x and earlier fetched the file cross-origin, so keep `Access-Control-Allow-Origin: *` on it while any app on an older major still signs in through this domain. The domain users enter is a bare domain such as `acme.com`, not `https://acme.com`, `acme.com/`, or a path. ## Per-app access Give an app its own OIDC client, assign the allowed groups or users to that client in the provider (on Entra ID also set "Assignment required" to Yes), and add one `app_clients` line keyed by the app's exact origin. A trailing slash, a path, or a different scheme does not match, and the app then silently falls back to the organization's client. To list an app without naming it in the public file, key it by a salted hash: `sha256(origin || salt)` as hex, then `:`, then the salt as hex: ```bash origin=https://payroll.acme.com salt=$(openssl rand -hex 8) hash=$(printf %s "$origin$salt" | openssl dgst -sha256 -r | cut -d' ' -f1) echo "$hash:$salt" ``` Cleartext and hashed keys can be mixed in one file. Changing `stable_identifier_claim` on a live domain changes how identities key onto anchors: treat it as a migration, not a config tweak. ## Limits: one bad value rejects the whole file Internet Identity rejects the entire file, not just the offending field, when any of these is exceeded. SSO is then unavailable for the whole domain (`getSsoStatus()` reads `unavailable`): - the file larger than 64 KiB (the same limit applies to the provider's OIDC discovery document); - more than 100 `app_clients` entries; - an `app_clients` key or client id longer than 255 bytes; - `app_clients` keys and client ids together longer than 16 KiB; - `client_id`, `name`, or `stable_identifier_claim` longer than 255 bytes; - `session_max_age_seconds` of `0` or above `2592000` (30 days); it is rejected, not clamped; - in the OIDC discovery document: `issuer`, `jwks_uri`, or `authorization_endpoint` longer than 255 bytes. ## When changes take effect Internet Identity caches each domain's discovery result: - fresh for 1 hour; after that, the next sign-in through the domain starts a refresh and is served the cached result while it runs; - kept for 7 days past freshness, so a domain signed in through within the week starts from the cache; - a refresh that fails stops serving the old result 1 hour past freshness, then backs off (60 s, doubling) before retrying. So removing an `app_clients` entry or enabling `gate_all_apps` applies after the next refresh, normally within an hour of active use; the first sign-in after a quiet period is checked against the cached result while the refresh runs. The provider's signing keys (JWKS) are cached separately for at most 1 hour past freshness, so key rotation is picked up within that window. ## What an organization cannot assert **No `verified_email` under `sso:`.** An organization's SSO cannot produce a verified email. Its `sso::email` is asserted by the organization's own provider, so an app trusts it only for domains it lists. --- ## Reviewing Motoko --- name: reviewing-motoko description: "Design review for existing Motoko backends — judging whether code is well designed, not how to write it. Covers invariants encoded in types (variants over Text, correlated fields, case _ smells), stable vs transient state discipline under enhanced migration, file structure (types.mo/lib/mixins/main.mo), and severity-ranked findings (Blocker/Warning/Note). Use when reviewing, auditing, critiquing, or refactoring existing .mo files, or when asked for code-review feedback on a Motoko canister. Do NOT use for writing new Motoko code or fixing compiler errors (writing-motoko), authoring migration files (migrating-motoko-actors), or deployment." license: Apache-2.0 compatibility: "moc >= 1.12.0, core >= 2.6.0, mops >= 3.0.0" metadata: title: Reviewing Motoko category: Motoko --- # Reviewing Motoko This skill judges whether Motoko code is **well designed**. It does not teach the language — load `writing-motoko` for syntax, `mo:core` APIs, and mechanical rules, and `migrating-motoko-actors` before changing anything that is stable state. Four questions decide a review, in this order — the first three because each can invalidate the next, the fourth last because it is the least consequential: 1. **Is every invariant the code relies on encoded in a type?** Where the type system *can* rule out a bad state, leaving that to a runtime check or a comment is a defect, not a style preference. 2. **Is state declared with the right persistence?** Under enhanced migration, stable and transient are separate worlds. Blurring them produces state that silently stops updating. 3. **Does the code live in the right files?** `types.mo` / `lib/` / `mixins/` / `main.mo` is a contract about what may depend on what, not a folder convention. 4. **Does it read like Motoko?** Contextual dot notation, inferred implicits, no annotation the call already supplies, no classes. `mops check --fix` handles most of this; only what it cannot see is the reviewer's job. ## Procedure **Run the mechanical pass first** — do not spend review attention on what the compiler already reports. ```bash mops check --fix ``` Its style auto-fixes (M0236 dot notation, M0237 redundant implicits, M0223 redundant instantiation) only fire where they are enabled: M0236 is on by default from moc 2, and the rest need `-W` in `[moc] args`. `writing-motoko`'s `references/project-setup.md` has the setup. Where they are off, the **Conventions** findings below are all yours to make by hand. Then read in this order — outside in, because a misplaced file makes every type inside it suspect: 1. `mops.toml` — is there a `[canisters.*.migrations]` chain? If not, finding **B1** below outranks everything else. 2. **Structure** — the file layout, then each file's imports. 3. `types.mo` — every type declaration. This is where most findings are. 4. **State** — the actor fields in `main.mo`, and what each `include` passes. See [references/state-and-persistence.md](references/state-and-persistence.md). 5. **The API boundary** — every `public shared` / `public query` function: its parameter types, its return type, its authorization. 6. **Bodies** — last, and only for the smells under **Maintainability** below. ## Severity Report findings with one of three levels. Do not inflate: a reviewer who calls everything a blocker gets ignored. | Level | Meaning | | ------------ | --------------------------------------------------------------------------------------- | | **Blocker** | Can corrupt or silently lose state, or lets a caller reach an unauthorized action. | | **Warning** | An invariant the type system could enforce is left to runtime, a comment, or a convention. | | **Note** | Readability, duplication, or naming. Fix while you are in the file; do not gate on it. | State the concrete failure, not the rule. "`status : Text` accepts `"complete"`, and the three call sites spell it `"completed"`" beats "prefer variants over strings". ## Type encoding The rule: **if a value has a fixed set of shapes, the type must have that set of shapes.** Full recipes, including how to carry each change through a migration, are in [references/type-encoding.md](references/type-encoding.md). ### T1. `Text` for a closed set of values — **Warning**, **Blocker** if it gates authorization The most common defect in generated Motoko. Every producer and consumer agrees on spelling by convention and the compiler checks nothing — no exhaustiveness, no error on a typo, no error when a new state is added and half the call sites are not updated. ```motoko public type Task = { id : Nat; var status : Text }; // WRONG public type TaskStatus = { #open; #claimed : Principal; #done : { at : Time.Time } }; ``` Variants are shared, so this reaches the frontend as a discriminated union too. **Flag `Text` (or `Nat`, or `Bool`) whenever the code, a comment, or a doc lists the permitted values** — `== "..."` comparisons, a `switch` on a `Text` with a `case _`, role names held as `Text`. Keep `Text` for genuinely open sets, and for strings an external system owns. ### T2. Correlated fields — **Warning** Two fields that are only valid together belong in one variant. A `Bool` plus an optional payload has four representable combinations and two meaningful ones. ```motoko // WRONG — { hasDeadline = true; deadline = null } compiles and means nothing { hasDeadline : Bool; deadline : ?Time.Time } // RIGHT { deadline : { #none; #due : Time.Time } } // or simply `deadline : ?Time.Time` ``` If a `?T` already says it, drop the `Bool` — do not introduce a variant that only restates `?T`. ### T3. Wrong cardinality — **Note**, **Warning** when callers loop defensively Use the type that matches the real count. A `[T]` that is always empty-or-one makes every caller write a loop or an `if size == 1`; a `?T` tells them there is nothing to iterate. ### T4. Errors as `Text` — **Warning** `Result` forces every caller to string-match to tell one failure from another. Make `Err` a variant with the data each case needs. See the `Result` section of `writing-motoko` for the full rule, including when to return `?T` and when to trap instead. ### T5. `var` fields leaking into the API — **Blocker** (it does not compile) or **Warning** (it compiles but over-shares) A record with a `var` field is not shared, so it cannot be returned from a public function. Where a project already has the internal/view split (`Task` internal, `TaskView` shared), check that: - no public signature mentions the internal type; - the view is **narrower** than the internal record, not a mechanical field-for-field copy. A view that re-exports an internal `Principal` list, an audit trail, or another user's data is an information leak that compiles. ### T6. `case _` swallowing variants — **Warning** A catch-all arm is what turns "adding a variant tag is a compile error everywhere it matters" into "adding a variant tag silently takes the default branch". Keep `case _` only where the arms are genuinely uniform and the set is expected to grow (e.g. mapping many tags to one label). Anywhere a new tag would need new behaviour, enumerate the tags. ### T7. Transparent aliases sold as safety — **Note** `type UserId = Principal` is a documentation alias: any `Principal` still type-checks where a `UserId` is expected. That is fine, and usually the right trade. Just do not treat it as an enforced distinction — and if two different id types are genuinely being confused at call sites, a one-field record (`{ userId : Principal }`) or a variant tag (`#user(Principal)`) is what actually enforces it, at the cost of changing the Candid shape. ## State and persistence Under enhanced migration (EM) the actor's stable fields are declared **type-only** and every initial value comes from the migration chain. That separation is the point: it is what makes stable state impossible to initialize from something transient. Details in [references/state-and-persistence.md](references/state-and-persistence.md). ### B1. No enhanced migration — **Blocker** No `[canisters..migrations]` chain in `mops.toml` means pre-EM persistence, where stable fields carry inline initializers — so a stable field can be initialized from a transient one: ```motoko transient let defaultQuota = 100; let quota = defaultQuota; // stable; the initializer runs ONCE, on first install ``` Change `defaultQuota` to `250`, deploy, and `quota` is still `100` — forever, no warning. Point at `migrating-motoko-actors` for the conversion; everything below assumes EM. ### S1. Inline initializer on a stable field — **Blocker** Under EM this is M0250 / M0014, so it will not compile — but it appears constantly in code copied from pre-EM examples and in half-finished refactors. The fix is never to add `transient`: move the initial value into the pending migration's `NewActor`. ### S2. `transient` misused — **Warning** both ways Ask of every actor and mixin field: *if this is lost on upgrade, is the app still correct?* - **Missing `transient`**: caches, derived indexes, rate-limit counters, and anything rebuildable are being persisted. They then have to be migrated forever, and a stale cache survives the upgrade that was supposed to clear it. - **Wrongly `transient`**: durable domain data silently resets to its initializer on every upgrade. Look for `transient` on anything a user would expect to still be there after a deploy. ### S3. `var` actor field shared with a mixin — **Blocker** `var` parameters pass by value, so the mixin mutates a copy and the actor's field never changes. Wrap it in a record and pass the record. Also flag a fresh record literal at the `include` site (`include Api({ var n = state.n })`) — each mixin then gets its own copy. See `writing-motoko`. ### S4. Stable state inside a `mixin` block — **Blocker** Every bare `let`/`var` at the top of a `mixin` is implicitly stable and traps at runtime with `IC0503`. State comes in as a parameter; constants go in a module; only `transient` is allowed inline. ### S5. Migration hygiene — **Blocker** - A migration file importing anything other than `mo:core/...` — the chain replays forever, so a project import makes it wrong the moment that type changes. (`caffeineai-lints` catches this.) - More than one pending migration in a build, or an edit to a migration that was already applied. - A stable field in `main.mo` that no migration in the chain supplies (M0254 / M0267). An identity migration body is a **Warning** — the change was stable-compatible, so delete the file. [Full table](references/state-and-persistence.md#migration-hygiene). ## Structure Layers, with dependencies pointing one way only: `main.mo` → `mixins/` → `lib/` → `types.mo`. | File | Holds | Must not hold | | ------------- | ----------------------------------------------------------------------------- | -------------------------------- | | `types.mo` | Type declarations; small pure helpers on those types | State, endpoints, business rules | | `lib/*.mo` | Domain logic as stateless modules, state as parameters | Public endpoints, actor fields | | `mixins/*.mo` | Public endpoints: authorize, delegate, map to a view | Domain logic, stable state | | `main.mo` | State declarations and `include`s | **Any public method**, any logic | | `migrations/` | Applied (frozen) history plus at most one pending module, one module per file | Project imports | - **A1 — Blocker/Warning:** a public method in `main.mo`. Move it to a mixin. - **A2 — Warning:** a monolithic file. One `.mo` holding types, state, logic, and endpoints together. - **A3 — Warning:** domain logic in a mixin body. If an endpoint's body is more than authorize → delegate → map, the middle belongs in `lib/`. - **A4 — Warning:** wrong dependency direction — `lib/` importing a mixin, or `types.mo` importing either. - **A5 — Note:** a mixin that is not a feature. Mixins split by *feature* (`mixins/Bookings.mo`), not by verb (`mixins/Getters.mo`). - **A6 — Warning:** over-broad state injection. A mixin receiving state it never touches widens what a change can break; pass only the slices it uses. ## Maintainability Most of this is caught in the last, bodies pass. The exception is **M1**, the authorization blocker — it is found during the API-boundary pass (step 5), not with the body smells below. - **M1 — Blocker:** a `public shared` function that does not check `caller`. Every state change and every read of another user's data needs authorization on the backend. - **M2 — Warning:** `Nat` subtraction that is not provably non-negative at the operation. It traps. - **M3 — Warning:** a trap where the caller could have recovered. Traps roll back the message and reach the client as an opaque reject; caller-fixable failures belong in a `Result` error variant. - **M4 — Note:** duplicated internal→view mapping. One `toView` per type, in `lib/` or `types.mo`. - **M5 — Note:** magic values — bare literals for limits, quotas, or durations. Name them in a module. - **M6 — Note:** a comment asserting an invariant the type could carry. Every "must be non-empty" / "only set when …" comment is a type-encoding finding in disguise. Where Motoko cannot express the invariant, keep the comment but validate the value once at the boundary rather than re-checking it at every use. ## Conventions Least consequential of the four axes, and `mops check --fix` fixes most of it where the `-W` flags are on — so raise these only after the passes above, and only where the tooling cannot. `writing-motoko` has the rules; this is what to look for. - **C1 — Note:** a module-function call where the function takes `self` — `List.add(list, x)`, `Principal.toText(p)`. M0236, auto-fixed. - **C2 — Note:** an implicit passed explicitly (`map.add(Text.compare, k, v)`), or a type instantiation inference already resolved. M0237 / M0223, auto-fixed. - **C3 — Warning:** type annotations on an inline `func` passed as a **call argument** — `xs.filter(func(x : Nat) : Bool { x > 1 })`. No diagnostic catches this, so it is the reviewer's job: the call already fixes both types, and the annotation duplicates them so they can drift. Write `xs.filter(func x = x > 1)`. Instantiate the *call* (`map`) when M0098 demands it — never the lambda. One exception: `: async ()` on an async callback is load-bearing on moc 1, so keep it while the code must build on both majors. - **C4 — Blocker:** a `class`, or any object holding functions, used as actor state. Functions are not stable, so it fails with M0131 (`declared stable but has non-stable type`). Outside state a class still is not the idiom here — a module taking `self` plus dot notation gets the same call sites and stays stable. ## Refactoring Design fixes in Motoko are not free: **changing a type that is reachable from a stable actor field requires a migration**, and the chain is one-way. Before proposing a type change, establish whether that type is stable state. 1. `mops check --fix` first, so the mechanical noise is gone. 2. **Batch the stable-state type changes** — one pending migration per build, so they land together. 3. **Write the migration** (`migrating-motoko-actors`). For `Text` → variant, decide explicitly what an unrecognized string becomes rather than inventing an `#unknown` tag. 4. **Move code before changing it** — relocating, then editing, keeps each diff reviewable. 5. `mops check --fix` until clean, then `mops build` once. ## Reporting Group findings by severity, blockers first. Per finding: `file:line`, the level, the concrete failure it permits, and the change. Suppress findings the compiler already reports. ```text Blocker src/backend/mixins/Tasks.mo:34 (M1) `claimTask` never reads `caller` — any principal can claim any task. Warning src/backend/types.mo:12 (T1) `Task.status : Text` is a closed set, so the comparison at Tasks.mo:51 spells it "complete" and is never true. Stable state — needs a migration. ``` If nothing is wrong, say so plainly. Do not manufacture findings to fill a report. ## Additional References - [references/type-encoding.md](references/type-encoding.md) — recipes per invariant, and the migration each one needs - [references/state-and-persistence.md](references/state-and-persistence.md) — why EM matters, the stable/transient question, migration hygiene - `writing-motoko` — language mechanics, `mo:core` APIs, `Result`, dot notation - **mops tooling**: Load `mops-cli` for `mops.toml` configuration and `mops check`/`mops build` details - `migrating-motoko-actors` — writing the migration a type change requires - `troubleshooting-motoko-migrations` — compatibility diagnostics that do not match the source --- ## Service Discoverability --- name: service-discoverability description: "Make a canister app discoverable to an AI agent from just its URL, including through ICP MCP. Covers publishing a /.well-known/ic-architecture manifest of your canisters — generated at deploy time from real canister IDs via the static-site recipe's presync hook and envsubst — plus exposing candid:service (interface), a getApiDoc query method (behavior), an optional OQL schema/execute data surface, and a /.well-known/ii-derivation-origin file (identity). Publishing that manifest opts the app into ICP MCP and is itself the operator's acceptance of the ICP MCP App Operator Terms, so confirm with the app's operator before deploying it. Use when making an app agent-ready or available through ICP MCP, for agent/service discovery, the well-known ic-architecture manifest, or generating that manifest at deploy time. Do NOT use for the sign-in flows that consume the derivation origin: use agent-web-identity for the agent/CLI web-identity link, or user-sign-in for adding II login to a frontend." license: Apache-2.0 compatibility: "icp-cli >= 0.3.0 with the @dfinity/static-site recipe; envsubst (gettext) for templating" metadata: title: Service Discoverability category: Frontend --- # Service Discoverability ## What This Is When an AI agent is handed only your app's URL (e.g. `https://yourapp.com`), it should be able to work out the rest on its own: which canisters the app comprises, what each one does, how to call them, how to query their data, and how to act as the signed-in user. No human supplying canister IDs, no bespoke integration. This skill covers what a canister app **publishes** to make that possible, across five layers. Layer 1 is gated: it is what an app publishes to participate in [ICP MCP](https://internetcomputer.org/icp-mcp/), and publishing it accepts an agreement on the operator's behalf — read **Before Layer 1** before writing that file. Layers 2-5 are ungated and independently adoptable; each is useful on its own, and together they make an app agent-ready. | Layer | Question it answers | Mechanism | |-------|---------------------|-----------| | 1. Composition | Which canisters make up this app, and what is each for? | `/.well-known/ic-architecture` JSON manifest | | 2. Interface | What methods and types does a canister expose? | `candid:service` metadata | | 3. Behavior | How does it actually behave (units, lifecycle, gotchas)? | `getApiDoc` query method | | 4. Data | How do I query its data without a method per question? | OQL `schema` + `execute` query methods | | 5. Identity | How do I act as the signed-in user, under the right principal? | `/.well-known/ii-derivation-origin` file | The load-bearing move for Layers 1 and 5 is **generating the well-known files at deploy time**, because the canister IDs (and the mainnet origin) differ per network. This skill uses the [`@dfinity/static-site`](https://github.com/dfinity/icp-cli-recipes/blob/main/recipes/static-site/README.md) recipe's `presync` hook to do that — the same pattern demonstrated by the community example [`raymondk/demo-ic-architecture`](https://github.com/raymondk/demo-ic-architecture/tree/main/frontend/ic-architecture). ## Before Layer 1: The Operator Must Accept the ICP MCP App Operator Terms **Stop here before you create, generate, or deploy `/.well-known/ic-architecture`.** That file is not only configuration. Availability through [ICP MCP](https://internetcomputer.org/icp-mcp/) is governed by the [ICP MCP App Operator Terms](https://internetcomputer.org/icp-mcp/app-operator-terms/) — **version 1.1, effective 2026-09-02**, the version current when this skill was written — an agreement between DFINITY Stiftung (the "DFINITY Foundation") and the app's **operator** — and **publishing a valid manifest is, on its own, the act that accepts them** and opts the app in. No signature step, no checkbox, nothing further. An agent that adds the manifest to a build on its own initiative has entered its user into a contract without asking. Name that version to the user: it is what they are accepting. **Check the top of the terms page before you do** — the terms are versioned independently of this skill (section 14), so if the page shows a version later than the one above, the page is right and this skill is stale. Tell the user the version the page shows, and say the skill's copy is out of date so it gets fixed. **Do not publish until the user has confirmed both points below.** Put them in your own words, link the terms, and let the user read before they answer. **1. They are the operator, or authorized to bind it.** The operator is the person or entity legally authorized to operate the app and declare its canisters. Building the app is not the same as operating it — section 1: *"If you develop an application but do not operate it, these Terms are for its operator to accept, not you."* A contractor, agency, or employee on someone else's app routes the decision to the operator rather than publishing and moving on. **2. They accept what publishing permits.** Under section 2, participation lets the ICP MCP server, acting for users who have authorized their AI assistant through Internet Identity: - read the manifest, the `candid:service` metadata of the **canisters the manifest declares**, and what `getApiDoc` / `get_api_doc` returns; - index and cache that metadata, and describe the app and its API to assistants and their users, including in any public listing of participating apps; - submit **query calls and, for users who authorized actions, state-changing (update) calls** to those declared canisters, signed with the per-application Internet Identity identities of those users; and - fetch the app's published files from its origin to keep the above current. Participation is free in both directions: DFINITY charges nothing for it and owes nothing for it. ### The manifest is the switch, and it is the whole scope - **Only declared canisters are in scope.** ICP MCP retrieves canister metadata and submits query or update calls **only** to canisters listed in a valid manifest. Never list a canister the operator does not run or is not entitled to expose — section 5 is a standing representation, repeated every time the file is served, that every declared canister is operated by the operator or under their authority. - **Without a valid manifest, none of that happens.** ICP MCP may still fetch and describe the app's public website, but metadata retrieval and canister calls are refused. - **Removing the manifest is the off switch** — registered or not. Once ICP MCP observes the removal, new metadata reads and query/update calls stop; this is also the fastest mitigation if the origin or a declared canister is compromised (section 7). It does **not** stop ICP MCP fetching the public website or describing public information; for that, ask DFINITY to suspend participation at `mcp@dfinity.org`. - **Deactivating is not terminating.** Removing the manifest ends participation; ending the *agreement* is a separate act — notice to `mcp@dfinity.org` (section 11). Neither undoes calls already executed on the Internet Computer, and sections 8, 12, 13 and 15 (personal data, warranties, liability, governing law) survive termination. Tell an operator asking how to get out both halves, not just the file deletion. - **Keeping the manifest published is continuing acceptance**, including of an updated version of the terms. An operator who does not accept a new version ends participation before it takes effect. ### Registration is optional Registration is **not** a condition of participation and is **not** what opts the app in — the manifest already did that. It exists so DFINITY knows who the operator is: to reach them with the notices the terms provide for (sections 10, 11, 14), and to have a record of who accepted and of which version, which publication alone does not show. To register, the operator emails `mcp@dfinity.org` with: the operator's legal name and country; the name, role, and email of the accepting representative; the app's origin domain(s); the canister IDs the manifest declares; the URL of the app's own privacy policy, so ICP MCP can present it to users considering the app; and the version of the terms being accepted — read from the top of the terms page at that moment, which is where section 3 says it is shown. The version named in **Before Layer 1** is the one current when this skill was written; if the page disagrees, the page wins and its value is what goes in the email. Keep the registration current as any of those change. ### Obligations that outlive the deploy These bind for as long as the manifest is published, so raise them with the user while the app is being made discoverable, not after: - **Accuracy (section 6).** The manifest, the Candid interface, and the `getApiDoc` text must identify the app correctly, describe what each method actually does, and stay in sync as the app changes. Never present a state-changing method as read-only or harmless, and never conceal a fee or transfer it performs. - **No assistant manipulation (section 6).** Published metadata and API docs describe the API and nothing more — no instructions telling the assistant to ignore its user, change its safety behavior, exfiltrate data, or avoid or disparage other apps. A hard constraint on `getApiDoc` content. - **Security (section 7).** The operator is responsible for control of the origin, the canisters' security and upgrade paths, and the integrity of the discoverability files. - **Personal data (section 8).** Requests reaching the app carry personal data — call arguments, per-application identities, and whatever the canisters return. Each party is an independent controller; the operator handles that data lawfully and keeps an accurate privacy policy available to the app's users. The [ICP MCP Privacy Policy](https://internetcomputer.org/icp-mcp/privacy-policy/) covers what ICP MCP discloses to the app, not what the app then does with it. ## Prerequisites - `icp-cli` **and** `ic-wasm`, installed together: `npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm`. See the `icp-cli` skill. - The frontend deployed with the **`@dfinity/static-site`** recipe (the recommended way to host a frontend on the IC — see the `static-site` skill). This is what auto-serves `/.well-known/` files and runs the `presync` hook with deployed canister IDs available. - `envsubst` (from GNU gettext) for templating the manifest. Any other templating mechanism works too (a small Node/`jq` script); `envsubst` is just the simplest. ## Layer 1: Composition — the `ic-architecture` manifest > **Gated.** Publishing this file opts the app into ICP MCP and accepts the [ICP MCP App Operator Terms](https://internetcomputer.org/icp-mcp/app-operator-terms/) on the operator's behalf. Confirm with the operator first — see **Before Layer 1** above. Publish a JSON document at the origin's `/.well-known/ic-architecture` that lists every canister and its role: ```json { "version": "1.0.0", "canisters": [ { "id": "hcv4s-uaaaa-aaabq-qaaba-cai", "name": "frontend", "role": "the frontend" }, { "id": "hmxr2-pqaaa-aaabq-qaaaa-cai", "name": "backend", "role": "the backend", "description": "orders + inventory API; call getApiDoc() first" } ] } ``` Field rules: - `version` — the manifest schema version. - `id` — **required**, a canister principal. - `name`, `role` — human-readable labels; `description` is optional. These fields are untrusted, so a consumer sanitizes them before use. - Unknown fields must be ignored, so the format can grow (e.g. per-canister network hints, or an api-doc pointer) without breaking older readers. ### Generate it at deploy time (the `presync` pattern) Canister IDs differ per network (local, staging, mainnet), so **never commit hard-coded IDs**. Produce the file in the deploy pipeline, which already knows the IDs. With the `@dfinity/static-site` recipe this is the **`presync`** hook: it runs at sync time, *after* the canisters exist, so their IDs are resolvable. `frontend/canister.yaml` (the per-canister config referenced from your top-level `icp.yaml`; see the `static-site` skill for the project layout): ```yaml name: frontend recipe: type: "@dfinity/static-site@v0.4.3" configuration: build: # Runs BEFORE the canister exists — no canister IDs available here. - npm ci - npm run build presync: # Runs AFTER canisters exist, with each canister's ID exported as ICP_CLI_CID_. - mkdir -p dist/.well-known - envsubst < ic-architecture/tmpl."$ICP_CLI_ENVIRONMENT".json > dist/.well-known/ic-architecture dir: dist ``` - The static-site recipe exports each project canister's ID into `presync` as `ICP_CLI_CID_` (name upper-cased, non-alphanumerics → `_`; e.g. `backend` → `ICP_CLI_CID_BACKEND`). Other vars: `ICP_CLI_CID` (this canister), `ICP_CLI_NETWORK`. - `$ICP_CLI_ENVIRONMENT` is the environment being deployed (e.g. `local`, `ic`), exported into the `presync` shell. It selects the matching template, so the same hook serves every network. - **`presync` runs with the canister directory as its working directory.** The relative `ic-architecture/...` path therefore resolves *inside the frontend canister directory* — put the templates at `frontend/ic-architecture/`, alongside `canister.yaml` (as the example project does). A path resolved from the repo root instead would make `envsubst` read nothing and silently write an empty manifest (Pitfall 7). - Pin the recipe to the current release (`@dfinity/static-site@v0.4.3` here); check the static-site recipe releases and the `static-site` skill for the latest. Keep one template per environment under `frontend/ic-architecture/`, with `envsubst` placeholders for the IDs. `frontend/ic-architecture/tmpl.local.json`: ```json { "version": "1.0.0", "canisters": [ { "id": "${ICP_CLI_CID_FRONTEND}", "name": "frontend", "role": "the frontend" }, { "id": "${ICP_CLI_CID_BACKEND}", "name": "backend", "role": "the backend", "description": "orders + inventory API; call getApiDoc() first" } ] } ``` `frontend/ic-architecture/tmpl.ic.json` (mainnet) is the same shape; only fixed fields like a static external dependency would differ. **Alternative — the reference demo's form.** [`raymondk/demo-ic-architecture`](https://github.com/raymondk/demo-ic-architecture/tree/main/frontend/ic-architecture) resolves the IDs explicitly with `icp canister status` rather than the exported vars — useful if you need an ID the recipe does not export. Its `presync` is: ```yaml presync: - mkdir -p dist/.well-known - >- FRONTEND_ID=$(icp canister status frontend --id-only -e "$ICP_CLI_ENVIRONMENT") BACKEND_ID=$(icp canister status backend --id-only -e "$ICP_CLI_ENVIRONMENT") envsubst < ic-architecture/tmpl."$ICP_CLI_ENVIRONMENT".json > dist/.well-known/ic-architecture ``` with the template using `${FRONTEND_ID}` / `${BACKEND_ID}` instead. `icp canister status --id-only -e ` prints just the canister ID (there is no `icp canister id` command). ### Serve it correctly - **`.well-known/` is uploaded automatically** by the static-site recipe (it traverses `.well-known/` even though it skips other dotfiles). A file at `dist/.well-known/ic-architecture` is served at `/.well-known/ic-architecture` with **no extra config** — no `.ic-assets.json5`, no SPA-exemption rule. - **A real file beats the SPA fallback.** With the static-site `/* /index.html 200` rewrite, the manifest is a real file, so it is served directly; the rewrite only catches paths with no matching file. (The *legacy* `@dfinity/asset-canister` resolves the same way — its `index.html` fallback likewise fires only when no file matches — but there the manifest has to be uploaded in the first place: `.ic-assets.json5` needs `{ "match": ".well-known", "ignore": false }`, or the hidden directory never ships. On a non-IC host, check that host's own routing precedence; where rewrites shadow real files, exempt `/.well-known/*`.) - **Set the content type.** Extensionless files do not get `application/json` automatically. Add a `_headers` file (at the root of `dir`, e.g. via `public/_headers`) so the manifest is served as JSON: ```text /.well-known/ic-architecture Content-Type: application/json ``` See the `static-site` skill for `_headers`/`_redirects` details. ## Layer 2: Interface — `candid:service` Expose your Candid interface as the canister's public `candid:service` metadata — the standard IC mechanism, embedded by default by the `@dfinity/motoko` and `@dfinity/rust` recipes. It lets an agent fetch exact method signatures and types and encode/decode calls correctly. **Do not strip it** from the build. An agent (or you, to verify) fetches it with: ```bash # By raw canister ID against mainnet (the agent's case: no project context) — target the network. icp canister metadata candid:service --network ic # By canister name from inside a project — use the project environment instead. icp canister metadata backend candid:service -e ic ``` ## Layer 3: Behavior — `getApiDoc` Candid types describe shape, not behavior. Expose a query method returning a prose (markdown) guide to what an agent cannot infer from types. Name it so it appears in `candid:service` — an agent then finds it with zero out-of-band knowledge (no bootstrap hint or side channel). Motoko: ```motoko persistent actor { public query func getApiDoc() : async Text { "## Orders API\n\n" # "- **Units:** amounts are integers scaled by 10^8 (1 unit = 1e-8).\n" # "- **Auth:** `placeOrder` requires a signed principal; anonymous callers can only read.\n" # "- **Lifecycle:** `placeOrder` returns before settlement; poll `orderStatus` until `#done`.\n" # "- **Irreversible:** `cancelOrder` cannot be undone; `closeAccount` is a dead-man switch.\n" }; }; ``` Rust (`ic-cdk`): ```rust #[ic_cdk::query] fn get_api_doc() -> String { // Same content; the snake_case name get_api_doc is equally discoverable. "## Orders API\n\n- Units: amounts are integers scaled by 10^8 ...".to_string() } ``` Cover the non-obvious semantics: units and encoding (integer money scaled by `10^8`, fractions vs tenth-bps, timestamp units), which calls need a signed principal and how anonymous access differs, staged or asynchronous operations that return before completing and must be polled, what is irreversible and any dead-man switches, and the gotchas that routinely trip up new integrators. Once the app participates in ICP MCP, section 6 of the App Operator Terms constrains this text: it must not present a state-changing method as read-only or harmless or conceal a fee it charges, and it must describe the API only — never instructing the calling assistant to ignore its user, change its safety behavior, exfiltrate data, or disparage other apps. An agent acts on what `getApiDoc` returns, so prompt-injection-shaped content there is a breach, not a feature. ## Layer 4: Data — OQL (optional, for data-rich apps) For apps with a lot of queryable data, expose a self-describing query surface so an agent can answer open-ended questions without you writing a method per question. OQL is one such convention — two query methods that speak JSON-in-text: ```candid schema : () -> (text) query; // JSON catalogue: entities, fields, edges execute : (text) -> (Result) query; // one JSON query object -> paged rows ``` `schema` returns a JSON catalogue of entities, their fields (with types and roles), and the edges between them; an agent fetches it once. `execute` runs one JSON query object (filters, aggregation, ordering, projection, paging) and returns a paged `Result`: ```candid type Cell = record { name : text; value : variant { text : text; int : int; float : float64; bool : bool }; // representative scalar arms; a given canister may tag others }; type Result = record { hasMore : bool; rows : vec vec Cell }; // each row is a list of named cells ``` Agents read cells **by name, never by position**, and page while `hasMore` is true. Prefer server-side filtering and aggregation so only the needed data crosses into the agent's context. Any Candid interface works; OQL just makes open-ended questions more economical. ## Layer 5: Identity — `ii-derivation-origin` To let an agent act with the user's own principal and permissions, publish the Internet Identity **derivation origin** your frontends pin. An agent that already holds the user's II authorization derives a short-lived, per-app delegation for that origin, yielding the same principal the user has in a browser — so your existing access control applies unchanged. (The agent/CLI side that consumes this is the `agent-web-identity` skill: `icp identity link web --app `.) The principal a user gets is a function of three inputs: 1. The user's Internet Identity. 2. The account within that Internet Identity. 3. Your app's derivation origin. Only the third is under your app's control, which is why the app must declare it. The derivation origin defaults to the **visible** origin: the origin the user's agent was asked to act on (agentic flows) or the origin in the browser address bar (classical flows). Publishing the file matters when an app is reachable from more than one origin (e.g. a rebrand or a secondary frontend): the visible origin may then differ from the origin identities are derived for, and the file tells the agent which origin to request derivations for. Publish, at each supported frontend origin, `/.well-known/ii-derivation-origin` whose body is the canonical `https://host` origin on a single line: ```text https://hcv4s-uaaaa-aaabq-qaaba-cai.icp.net ``` - If the derivation origin is just the app's own visible origin, you may omit the file; its absence means "derive for the visible / requested origin itself." - Generate it at deploy time with the same `presync` pattern when the origin is a per-network canister URL; for a custom domain it is a one-line static file (e.g. `public/.well-known/ii-derivation-origin`). - **Do not confuse it with `ii-alternative-origins`.** A custom origin is enabled by two coupled files: the app pins `derivationOrigin` in its II configuration, and the derivation origin itself publishes `/.well-known/ii-alternative-origins` listing the origins allowed to derive against it. That list is the inverse relation — "who may point here," not "where does this app point" (Pitfall 8). On the default `*.icp0.io` / `ic0.app` canister origins, do **not** set a custom `derivationOrigin` at all (see "Your app's identity is its primary origin" in the `user-sign-in` skill); a custom one goes hand in hand with a custom domain — see the `custom-domains` skill. ## How an Agent Traverses This Published independently, the layers are consumed in one order — each step exists to let the agent skip work at the next: 1. `GET /.well-known/ic-architecture` → every canister ID, and which one to call, from whichever labels identify it (`name`, `role`, `description`). 2. `candid:service` on that canister → exact signatures and types, plus the names `getApiDoc` / `schema` / `execute`, which is why those must live in the interface and not a side channel. 3. `getApiDoc()` → the semantics the types cannot carry, including **which calls need a signed principal**. 4. `/.well-known/ii-derivation-origin`, or the visible origin when absent → derive the user's delegation and act as the signed-in user, so existing access control applies unchanged. 5. `schema()` once, then `execute(...)` per question, filtered and aggregated server-side. The identity step is numbered 5 as a layer but happens **before the first protected call**: step 3 is where the agent learns which methods require a signed principal, so anything gated — a protected `execute`, or any update call — has to wait for the delegation. Only unauthenticated reads can run ahead of it. Steps 1-3 take an agent from a bare URL to a correctly-encoded, correctly-understood call in three round trips. Each layer left unpublished replaces one of them with guessing — an unlabeled manifest alone costs a `candid:service` fetch per canister (Pitfall 10). ## Deployment Checklist - [ ] **Terms accepted:** the app's **operator** — not a developer or agent acting for them — has read the [ICP MCP App Operator Terms](https://internetcomputer.org/icp-mcp/app-operator-terms/) and confirmed, *before* the manifest ships. Publishing it is the acceptance; there is no separate step. - [ ] **Registration (optional):** if the operator wants notices and a record of who accepted which version, they email `mcp@dfinity.org` with the details in **Before Layer 1**, including the app's own privacy-policy URL. - [ ] **Composition:** the deploy pipeline emits `/.well-known/ic-architecture` (real JSON, extensionless path) with real per-environment canister IDs. - [ ] **Content type:** a `_headers` rule serves the manifest as `application/json`. - [ ] **Reachability (non-static-site hosts only):** `/.well-known/ic-architecture` actually resolves. Automatic on the static-site canister; on the legacy `@dfinity/asset-canister` the directory needs an `.ic-assets.json5` un-ignore rule to be uploaded at all; on a non-IC host, exempt `/.well-known/*` from the SPA catch-all if that host's rewrites shadow real files. - [ ] **Interface:** `candid:service` metadata is present (not stripped). - [ ] **Behavior:** the backend exposes `getApiDoc` / `get_api_doc` returning markdown. - [ ] **Data (if applicable):** data-rich canisters expose OQL `schema` + `execute`. - [ ] **Identity (if custom):** publish the effective origin in `/.well-known/ii-derivation-origin` (canonical `https://host`, one line). ## Verify (Acceptance Tests) Run against the deployed origin (`APP` = your frontend host): ```bash # 1. Manifest is real JSON listing the canisters (not the SPA shell). curl -s https://APP/.well-known/ic-architecture | jq '.canisters[].id' # 2. Backend exposes candid:service; fetch it against a canister ID from step 1 # (confirm it declares getApiDoc, plus schema/execute if data-rich). icp canister metadata candid:service --network ic # 3. If you pin a CUSTOM derivation origin, it is published as the canonical # https://host. Use -f so a 404 is an error and the fallback fires: curl -s # alone exits 0 on 404, so the "default" branch would never run. curl -sf https://APP/.well-known/ii-derivation-origin || echo "default (https://APP)" ``` Locally, the static-site recipe serves the same paths — e.g. `curl http://frontend.local.localhost:8000/.well-known/ic-architecture`. ## Pitfalls 1. **Hard-coding canister IDs.** IDs differ per network, so committing them ships a manifest that is wrong on every environment but the one it was written for. Generate at deploy time in `presync`. 2. **Putting ID resolution in `build` instead of `presync`.** `build` runs *before* the canisters exist, so no IDs are available (`ICP_CLI_CID_*` are unset and `icp canister status` has nothing to return). Only `presync` runs after creation with IDs available. 3. **Assuming the manifest is served, without setting its content type.** The extensionless file is served, but not as `application/json` unless a `_headers` rule says so. Add the `Content-Type: application/json` block above. 4. **Expecting `.ic-assets.json5` to matter.** That is the *legacy* asset canister's config; the static-site (certified-assets) canister ignores it. `.well-known/` is uploaded automatically and needs no un-ignore rule. The legacy canister is the reverse: it needs `{ "match": ".well-known", "ignore": false }` or the directory is never deployed — an upload problem, not a routing one. 5. **Writing the file with a `.json` extension.** The path is exactly `/.well-known/ic-architecture` (and `/.well-known/ii-derivation-origin`) — no extension, matching the IC `.well-known` convention (`ic-domains`, `ii-alternative-origins`). 6. **`envsubst` clobbering unintended `${...}`.** With no arguments `envsubst` substitutes *every* environment variable it finds. If a template contains a `${...}` you do not want replaced, restrict it: `envsubst '$ICP_CLI_CID_FRONTEND $ICP_CLI_CID_BACKEND'`. 7. **A missing `tmpl..json`, or templates in the wrong directory.** `$ICP_CLI_ENVIRONMENT` selects the template by name; if the file for the current environment is absent — or lives at the repo root while `presync` runs from the canister directory — `envsubst` reads nothing and writes an empty manifest. Keep one template per environment, under the frontend canister directory. 8. **Reading `ii-alternative-origins` to find the derivation origin.** It is the inverse relation (who may derive against this origin), not a pointer to it. There is no reverse lookup; using it backwards **silently** yields the wrong principal — a plausible wrong answer, not an error. Publish and read `ii-derivation-origin` for the forward fact. 9. **Naming the behavior method undiscoverably.** The name must appear in `candid:service`, so use `getApiDoc` / `get_api_doc`. A method reachable only via an out-of-band hint defeats zero-knowledge discovery. 10. **Listing canisters without labels that identify them.** `id` is the only required field, so a manifest of bare IDs is valid, and it still earns its keep: the agent gets the app's canisters without discovering them out of band. What it loses is the routing — with nothing to tell the backend from the frontend, the agent pays a `candid:service` fetch per entry and infers roles from method names. Label every entry with whatever identifies it (`name` is often enough; add `role`, and `description` where the purpose is not obvious from the name). 11. **Stripping `candid:service`.** Some minified/size-optimized builds drop wasm metadata. Keep it — it is what makes the interface fetchable. Verify with `icp canister metadata candid:service --network ic`. 12. **Publishing the manifest without asking the operator.** The likeliest agent failure here is treating `/.well-known/ic-architecture` as ordinary build config and adding it unprompted. It is the act that accepts the [ICP MCP App Operator Terms](https://internetcomputer.org/icp-mcp/app-operator-terms/) and opts the app into query and update calls from AI assistants. Confirm with the user first, and confirm they are the **operator** — section 1 says a developer who does not operate the app cannot accept for its operator. 13. **Mistaking registration for the opt-in, or for the opt-out.** Registration is optional and changes nothing about participation: an unregistered app whose manifest is published is fully participating and fully bound. Registration only tells DFINITY who accepted, which version, and where to send notices. Symmetrically, there is nothing to "unregister" to stop participating — **removing the manifest** is the off switch. Removing it deactivates participation; *terminating the agreement* is a separate act, a notice to `mcp@dfinity.org` (section 11). Neither undoes calls already executed on the Internet Computer, and sections 8, 12, 13 and 15 — personal data, warranties, liability and governing law — survive termination. "Delete the file and you are done" is wrong, not merely incomplete. 14. **Expecting manifest removal to delist the app entirely.** Deleting it stops new metadata reads and query/update calls once ICP MCP observes the removal, but ICP MCP may still fetch the app's public website and describe publicly available information. To be dropped from user-facing presentation, the operator asks DFINITY at `mcp@dfinity.org`. 15. **Declaring canisters the operator does not control.** It is tempting to list a third-party ledger or an ecosystem canister the app merely calls. Serving the manifest is a repeated representation (section 5) that **every** declared canister is operated by the operator or under their authority, and it makes those canisters eligible for update calls under the app's participation. List only your own. ## Additional References - Load `static-site` for the `@dfinity/static-site` recipe: `presync`/`build`, `_redirects`/`_headers`, `.well-known/` auto-upload, and canister-ID injection. - Load `agent-web-identity` for the agent/CLI side that *consumes* the derivation origin (`icp identity link web --app `). - Load `user-sign-in` for adding II sign-in to a frontend (it also explains when *not* to set `derivationOrigin`). - Load `custom-domains` for serving from your own domain, which then becomes your derivation origin. - Load `icp-cli` for `icp.yaml` / `canister.yaml`, environments, and the recipe system. - Load `canister-security` for access control on the methods agents call. - Authoritative human guide: [Service discoverability](https://docs.internetcomputer.org/guides/frontends/service-discoverability/). - The terms publishing the manifest accepts: [ICP MCP App Operator Terms](https://internetcomputer.org/icp-mcp/app-operator-terms/), and what ICP MCP is: [ICP MCP](https://internetcomputer.org/icp-mcp/). - What ICP MCP discloses to a participating app, and what it processes on registration: [ICP MCP Privacy Policy](https://internetcomputer.org/icp-mcp/privacy-policy/). - Candid interface reference for the typed interface agents read: [Candid interface](https://docs.internetcomputer.org/guides/canister-calls/candid/). - Community example of the Layer 1 generation (a personal repo — illustrative, not a stable dependency): [`raymondk/demo-ic-architecture`](https://github.com/raymondk/demo-ic-architecture/tree/main/frontend/ic-architecture). --- ## Single Sign-In --- name: single-sign-in description: "Let a user sign in once and be signed in across a whole suite of apps on sibling subdomains: opening a second app needs no second visit to Internet Identity, and signing out of one signs them out of all. Covers the shared record with CookieStateStorage, the /reauth route that silently acquires each app's own credential under transport: 'redirect' and prompt: 'none', the per-origin /.well-known/ii-auth-callbacks document, reading signed-in-elsewhere on load and offering it mid-session, and what ends the session. Use when a suite of apps under one domain should need a single sign-in, when moving between them asks the user to sign in again, or when /reauth bounces in a loop. Every app must already derive from one elected primary origin: load user-sign-in and settle that first. Do NOT use for a single app on one origin, which needs none of this, for apps on unrelated domains, which cannot share a cookie, or for staff signing in with their organization's identity provider (use organization-sign-in)." license: Apache-2.0 compatibility: "@icp-sdk/auth >= 11.0.0" metadata: title: Single Sign-In category: Auth --- # Single Sign-In ## Prerequisite Load the `user-sign-in` skill first and settle "Your app's identity is its primary origin". Everything here assumes one elected primary origin whose `ii-alternative-origins` already authorizes every sibling. That is not a courtesy link. Apps share a sign-in only when they share a principal, and a shared cookie does not produce one. Build this on top of separate principals and every app reads a record naming an account it can never hold, which is the `/reauth` loop in that skill's mistakes list. ## What this gets you A user of a suite of apps, say `chat.example.com`, `hr.example.com` and `docs.example.com`, signs in once. Every other app in the suite opens already signed in, with no second visit to Internet Identity, and signing out of any one signs them out of all. Principals are per origin, so every app must derive from **one** primary origin, listed in that origin's `/.well-known/ii-alternative-origins`. Without it each app sees a different user and there is nothing to share. ## 1. Share the record Every app builds its client with the same derivation origin and the same cookie domain, so a sign-in on one writes a record the others read: ```javascript import { AuthClient, CookieStateStorage, InteractionRequiredError } from "@icp-sdk/auth/client"; const clientOptions = { derivationOrigin: "https://.icp.net", stateStorage: new CookieStateStorage({ domain: "example.com" }), }; ``` Choosing that domain means trusting every origin under it. Do not do it on a domain whose subdomains you do not control. ## 2. Acquire the sign-in on a `/reauth` route An app that reads `signed-in-elsewhere` asks Internet Identity for its own credential for that account. It runs on page load with no user gesture, where a popup is blocked, so it uses `transport: "redirect"` on a route of its own, from a second client (`prompt` and `hint` are fixed when a client is built): ```javascript // Runs on the /reauth route. async function reauth() { const status = new AuthClient(clientOptions).getStatus(); if (status.state !== "signed-in-elsewhere") { location.replace("/"); return; } const authClient = new AuthClient({ ...clientOptions, transport: "redirect", prompt: "none", hint: status.principal, // answer for the account already signed in }); try { await authClient.signIn({ returnTo: new URLSearchParams(location.search).get("next") ?? "/", }); } catch (error) { if (error instanceof InteractionRequiredError) { // Nothing to resume, so the shared record is stale: clear it, or every // app on the domain keeps sending the user back here. await authClient.signOut().catch(() => {}); } location.replace("/"); } } reauth(); ``` Without `hint`, a provider holding more than one session refuses rather than guessing: `InteractionRequiredError` with `reason` `account_selection_required`. If what comes back is for a different account than `hint` asked for, the client refuses it and throws `AccountMismatchError`. ## 3. Declare the callback on every app origin A redirect sign-in is delivered only to a callback the returning origin itself declares, so every app serves `/.well-known/ii-auth-callbacks` on its own origin (not once on the derivation origin), listing its own `/reauth`: ```json { "callbacks": ["https://chat.example.com/reauth"] } ``` The entry is matched exactly (the full URL, no fragment), and II reads the document cross-origin. With `@dfinity/static-site`, add a `_headers` block: ``` /.well-known/ii-auth-callbacks Content-Type: application/json Access-Control-Allow-Origin: * ``` Validation fails closed: undeclared, unreadable, or not exactly matching, and the sign-in never comes back. The route must also terminate locally: the response arrives in the URL fragment, and a `3xx` carrying none re-attaches it to wherever it forwards. ## 4. Pick it up on load, on every page Every page, not only those requiring a sign-in, reads the status as it loads and hands `signed-in-elsewhere` to `/reauth` with the page to return to: ```javascript const authClient = new AuthClient(clientOptions); const status = authClient.getStatus(); // Only this state: signed-out and expired both mean a normal sign-in, and // sending them to /reauth just bounces the user back. if (status.state === "signed-in-elsewhere") { location.replace(`/reauth?next=${encodeURIComponent(location.pathname + location.search)}`); } ``` ## 5. Jump on load, ask afterwards Once a page is open, the status of that same client can still turn `signed-in-elsewhere` (someone signs in on a sibling in another tab). Redirecting a page the user is working on throws away their work, so subscribe and offer the same redirect behind a button: ```javascript authClient.subscribe(() => { if (authClient.getStatus().state === "signed-in-elsewhere") { showResumeDialog(() => location.replace(`/reauth?next=${encodeURIComponent(location.pathname + location.search)}`), ); } }); ``` ## What ends the session **Every state change travels the same way: through the shared record.** Whatever happens to the session, on this app or a sibling, the record is what carries it, each app's `subscribe()` fires, and `getStatus()` answers the new state. There is no second mechanism and no waiting period to account for, so the three cases below differ in what they mean, not in how they reach the other apps. - `signOut()` ends the session at Internet Identity, clears this app's credentials, and removes the shared record. Every sibling reads `signed-out`. - `maxTimeToIdle` on `signIn()` ends the session when nobody uses any of the apps; omitted, Internet Identity applies seven days. - Signing in to another account on any app replaces the session for the whole suite. The record now names a different account, so a sibling that has no credential for it reads `signed-in-elsewhere` and goes through `/reauth` silently, exactly as on a first sign-in. ### Render from the subscription, not from a value read at load A tab finds out as soon as its browser can tell it. Reading a cookie raises no event, so where the browser has the Cookie Store API that is immediate, and otherwise it is the next time that page is shown or its window regains focus. So there is a window where one tab knows and another does not, and it is the ordinary case rather than an edge case: - The user has `hr.example.com` open in one tab and `chat.example.com` in another. - They sign out in the HR tab. The shared record is gone immediately. - The chat tab is in the background and has not been told yet. It is still showing the signed-in screen, with the user's name in the corner and their chats on it. That tab fixes itself only if it re-reads the state when it hears. So call `getStatus()` inside the `subscribe()` callback and render from that, rather than from a status read once when the page loaded: ```javascript // Re-read on every change, including a sibling's sign-out. authClient.subscribe(() => render(authClient.getStatus())); render(authClient.getStatus()); // and once for the initial paint ``` A page that reads the status only at load keeps showing a signed-in screen to a user who is signed out, until something else happens to reload it. ### Service workers A service worker reads the single sign-in too (`@icp-sdk/auth` 11.2.0 or later; see "In a web or service worker" in the `user-sign-in` skill). With no page of its own origin open, it sees a sibling subdomain's sign-in or sign-out only once a page of its origin opens. --- ## SMTP Gateway (Inbound Email) --- name: smtp-gateway description: "Receive email in an Internet Computer canister through the SMTP Gateway Protocol. Covers implementing smtp_request and smtp_request_validate, addressing (user@.icp0.io, custom domains, handing mail to another canister with /.well-known/ic-smtp-canister-id), how the gateway turns reply codes into SMTP (5xx bounces, everything else retries, 550 rejects one recipient), what actually arrives (raw headers, raw MIME body, a per-attempt message_id, no sender authentication), the ic-smtp-gateway-protocol Rust crate, and the optional chunked upload for messages over 2 MiB. Use when a canister must receive or process inbound email, when implementing the SMTP gateway Candid interface, or when mail to a canister bounces, is retried, or never arrives. Do NOT use for sending email from a canister (the gateway is inbound only; call an email API with https-outcalls) or for serving HTTP from a canister." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2; Rust examples: ic-cdk 0.20 with ic-smtp-gateway-protocol 0.1 (plus sha2 0.11 for chunked upload); Motoko examples: moc >= 1.11.0 with core >= 2.5.0" metadata: title: SMTP Gateway (Inbound Email) category: Integration --- # SMTP Gateway (Inbound Email) ## What This Is An SMTP gateway is an off-chain mail server that accepts email addressed to a canister and delivers it by calling the canister's `smtp_request` method, the way the HTTP gateway calls `http_request`. DFINITY operates the gateways that mail for `.icp0.io` reaches, alongside its HTTP gateways; others can run their own, since the gateway is part of `ic-gateway`. The limits and sender checks in this skill are those of DFINITY's gateways. A canister opts in by implementing two methods. There is nothing to register for `.icp0.io` addresses. Mail flows **in** only: a canister cannot send email through the gateway, and it never receives bounce messages either, because the gateway rejects the null sender (`MAIL FROM:<>`). The protocol is specified in `candid/smtp_gateway.did` in `dfinity/ic-smtp-gateway-protocol`, and the gateway that implements it is the `smtp` module of `dfinity/ic-bn-lib`. ## Addressing | Address | Setup | |---|---| | `anything@.icp0.io` | None. Every `.icp0.io` already has MX records pointing at the gateway. | | `anything@` | The domain must be registered as an IC custom domain (`custom-domains` skill): the gateway resolves it in the same registry as the HTTP gateway. Its MX records must also point at the gateway. A subdomain set up the standard way (`CNAME` to `.icp1.io`) inherits the gateway's MX records through the CNAME. An apex domain cannot be a CNAME, and ALIAS or CNAME flattening only produces A/AAAA records, so publish the hosts that `dig +short MX boundary.dfinity.network` lists as your MX records, and keep them in sync. Do **not** publish `MX boundary.dfinity.network` itself: mail servers would connect to that name's own addresses, which do not accept mail. | How the gateway routes a recipient: - If the first DNS label of the recipient's domain parses as a principal, that is the canister. Otherwise the exact domain is looked up among registered custom domains. No match: `550 5.1.1 Unknown recipient domain.` - The domain arrives lowercased. The local part (`user`) arrives **verbatim**: case, `+tag` suffixes and quotes are kept. Match it case-insensitively unless you have a reason not to. The gateway rejects non-ASCII local parts itself. - **Handing mail to another canister.** Before calling the addressed canister, the gateway fetches `https://.icp0.io/.well-known/ic-smtp-canister-id`. If that returns a 2xx response whose body (whitespace-trimmed) is a principal, every SMTP call goes to that principal instead. Any failure falls back to the addressed canister, and either result is cached for 10 minutes. Use this when a frontend canister owns the domain and a backend canister handles mail: with the `static-site` recipe, add a file `.well-known/ic-smtp-canister-id` containing only the backend's canister ID to the uploaded directory (`.well-known/` is uploaded without extra configuration). ## The Protocol | Method | Required | When the gateway calls it | |---|---|---| | `smtp_request_validate : (SmtpRequest) -> (SmtpResponse) query` | **Yes** (see Pitfall 4) | Once per `RCPT TO`, before the message is transferred | | `smtp_request : (SmtpRequest) -> (SmtpResponse)` | Yes | After `DATA`, once per destination canister, listing all recipients that resolved to it | | `smtp_capabilities`, `smtp_upload_chunk`, `smtp_upload_commit`, `smtp_upload_status`, `smtp_upload_abort` | No | Chunked upload for messages over the ~2 MiB ingress limit. Read `references/chunked-upload.md` before implementing these. | What each call carries: | Field | `smtp_request_validate` | `smtp_request` | |---|---|---| | `envelope` | `MAIL FROM` address and exactly one recipient | `MAIL FROM` address and every recipient for this canister (at most 10 per session) | | `message` | `null` | Headers and raw body | | `message_id` | `null` | A new UUIDv7 for every SMTP transaction | The wire types are defined in `candid/smtp_gateway.did`. The Rust crate exports them, and the Motoko example below declares them field for field. `code` is `nat64` (a `nat32` does not decode), the variant labels are exactly `Ok` and `Err`, and `Ok` carries an empty record, not `null`. ## Reply Codes Are the Interface The gateway acts on the **class** of `SmtpRequestError.code`: 500–599 is permanent and anything else is temporary. Traps and call failures are temporary too, except two that are permanent: the method is not exported, or the request is too large for one ingress message. During `RCPT TO`, from `smtp_request_validate`: | Canister result | The sending server sees | |---|---| | `Ok` | `250 2.1.5 OK` | | `Err` with code 550 | `550 5.1.2 Mailbox does not exist.` for that recipient only (your `message` is dropped) | | `Err` with another 500–599 code | `550 5.1.3 Permanent error: ` | | `Err` with any other code | `451 4.4.3 Temporary error: ` | | Method not exported | `550 5.1.3 Permanent error: Canister does not support SMTP protocol` | | Trap or call failure | `451 4.4.3 Temporary error: ...` | After `DATA`, from `smtp_request`: | Canister result | The sending server sees | Then | |---|---|---| | `Ok` | `250` | Delivered | | `Err` with a 500–599 code | `550 5.5.0 Permanent delivery error: ` | The sender gets a bounce | | `Err` with any other code | `450 4.5.0 Temporary delivery error: ` | The sending server retries later | | Trap, call failure, or no reply within 90 s | `450 ...` | Retried | Codes to use. Permanent: **550** no such mailbox (reserved, never for anything else), **501** a required field is missing, **552** message, headers or recipient list too large, **554** content rejected, **530** caller not authorized. Temporary: **450** try again later, **452** out of storage. ## Mistakes That Break Mail Delivery 1. **Trapping instead of returning `Err`.** A trap is reported as a *temporary* failure, so the sending server retries for days before it gives up with an unhelpful error. Every rejection must be a returned `Err`. Traps hide in `unwrap()`, `expect()`, out-of-range slicing, `String::truncate` inside a multi-byte character, a nested `RefCell` borrow, and in Motoko in `Nat` underflow and array indexing. 2. **Reporting a permanent problem with a non-5xx code.** Only 500–599 bounces. A deterministic rejection sent as 4xx, or as any code outside 400–599, is retried until the sender's server gives up, and the sender never learns why. 3. **Using 550 for anything except "unknown mailbox".** From `smtp_request_validate`, 550 becomes `550 5.1.2 Mailbox does not exist.` and your text is dropped. Use another 5xx code (552, 554) for policy rejections so that your message reaches the sender. 4. **Skipping `smtp_request_validate`.** The gateway calls it on every `RCPT TO` and treats a missing method as a permanent "does not support SMTP protocol" rejection of every recipient. Implement both methods. (`smtp_capabilities` is genuinely optional: a missing method just means no chunked upload.) 5. **Requiring `message` or `message_id` in `smtp_request_validate`.** It receives only `envelope`, with exactly one recipient. Requiring the other fields rejects every recipient. 6. **Trusting Candid to validate the request.** Every `SmtpRequest` field is `opt`, so *any* record argument decodes into it, with all fields `null`. Check each field you need and return 501 when it is missing. 7. **Forgetting that anyone can call the SMTP methods.** They are public: any principal can call them directly with any envelope, headers and body, bypassing every check a gateway makes. To restrict who delivers mail, check the caller's principal. For example, to accept mail only through the DFINITY-operated gateway, allow only `ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae` (plus controllers, for testing), as both examples do. For another gateway, ask its operator for its principal, or don't restrict callers. Reject with 530, never by trapping, because the gateway would retry. Either way, bound every input (Internet Identity allows 100 headers, 8 KiB per header value, 64 bytes per local part) and cap stored mail. 8. **Trusting the sender's address.** DFINITY's gateways reject mail that fails SPF for the envelope sender's domain, and mail whose DKIM signatures all fail. They do accept senders without an SPF record and unsigned mail, they do not check that the signing domain matches `From` (no DMARC), and no result reaches the canister (`gateway_flags` is always `null`). So `From`, and `envelope.from` for domains without SPF, is still whatever the client claimed. If the sender's identity matters, verify DKIM inside the canister, as Internet Identity does: relaxed header canonicalization (names arrive normalized, so `simple` cannot be verified); the public key fetched with DNS-over-HTTPS outcalls (`https-outcalls` skill) and accepted only when several resolvers agree; the signing domain `d=` aligned with `From`; duplicate `From`, `Subject` or `DKIM-Signature` headers rejected, since a duplicate header can smuggle content past the signature. 9. **Expecting clean, decoded header values.** Each value is the raw text after the colon: the leading space, the trailing `\r\n` or `\n`, folded continuation lines and `=?UTF-8?B?...?=` encoded words are all left in. Trim before comparing, decode encoded words yourself if you display them, and match header names case-insensitively: names the gateway recognizes arrive in canonical case (`fRoM` as `From`). Order and duplicates are preserved; a header whose value is not valid UTF-8 is dropped. 10. **Expecting a parsed body.** `body` holds the raw bytes after the header block, with CRLF line endings, and no MIME processing. Mail from a normal client is usually `multipart/alternative` with base64 or quoted-printable parts: you receive the boundaries and encoded parts, not plain text. 11. **Deduplicating on `message_id`.** It identifies one SMTP transaction, not one email: when the sending server retries, the retry gets a new `message_id`. Delivery is at-least-once. A lost reply after you stored the mail, the 90-second delivery timeout, or a failure at *another* canister receiving the same message (the gateway fails the whole message and the sender retries for every recipient) all lead to redelivery. If duplicates matter, deduplicate on the RFC 5322 `Message-ID` header (chosen by the sender, so scope it per sender) or make processing idempotent. 12. **Awaiting inside `smtp_request`.** The gateway keeps the SMTP session open while it waits and gives up after 90 seconds. That is reported as temporary and retried, so if your call did finish, the mail arrives twice. Every `await` is also an interleaving point (`canister-security` skill). Accept synchronously and defer slow work, for example to a timer. Internet Identity stores the message and finishes its DKIM key lookups after it has replied. 13. **Long or multi-line error messages.** The `message` is copied into the SMTP reply line: on `RCPT TO` it is cut at about 224 bytes without stripping CR or LF, and a delivery reply over about 220 bytes can be dropped. Use short, single-line ASCII and never echo request content. 14. **Leaking secrets through error codes.** Every `Err` tells the caller something, and a 5xx also sends a bounce to the claimed sender. If mail carries secrets such as verification codes, return `Ok` for unknown or invalid content and record the outcome internally. Internet Identity returns `Err` only for malformed requests, more than one recipient, and unknown mailboxes. 15. **Keeping mail on the heap, or configuration in stable variables.** Heap state is lost on upgrade, so store mail in stable memory (`stable-memory` skill). In a Motoko `persistent actor` the opposite applies: a plain `let` is stable and keeps its first-install value, so a mailbox list or limit you change in code has no effect after an upgrade. Declare configuration `transient let`. ## Implementation Both examples accept mail for `support@` and `hello@` only through the DFINITY-operated gateway (and from controllers, for testing; this restriction is optional, see Pitfall 7), store each message, and apply the pitfalls above. `smtp_request_validate` and `smtp_request` share one envelope check because the query may be stale by the time the update runs. ### Rust The `ic-smtp-gateway-protocol` crate provides the protocol types. It builds for `wasm32-unknown-unknown`. ```toml [package] name = "backend" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] candid = "0.10" ic-cdk = "0.20" ic-smtp-gateway-protocol = "0.1" ``` Deploy it with the `@dfinity/rust@v3.3.0` recipe as canister `backend` (`icp-cli` skill). ```rust use std::{cell::RefCell, collections::BTreeMap}; use ic_cdk::{ api::{is_controller, msg_caller, time}, query, update, }; use ic_smtp_gateway_protocol::{ Envelope, Header, SmtpOk, SmtpRequest, SmtpRequestError, SmtpResponse, }; /// Principal of DFINITY's SMTP gateways; gateways run by others have their own. const SMTP_GATEWAY: &str = "ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae"; /// Local parts this canister accepts mail for. const MAILBOXES: &[&str] = &["support", "hello"]; // Bounds on what one request may cost this canister. const MAX_RECIPIENTS: usize = 10; const MAX_HEADERS: usize = 100; const MAX_BODY_BYTES: usize = 100_000; const MAX_STORED: usize = 10_000; #[allow(dead_code)] // read by your application logic struct Mail { envelope_from: String, // unauthenticated: see pitfalls subject: String, headers: Vec

, body: Vec, // raw RFC 5322 body bytes, MIME not decoded received_at: u64, } thread_local! { // Heap only for brevity: use stable structures in production. static INBOX: RefCell> = RefCell::default(); } /// Keep `message` short, single-line ASCII: the gateway copies it into the /// SMTP reply line. fn err(code: u64, message: &str) -> SmtpResponse { SmtpResponse::Err(SmtpRequestError { code, message: message.to_string(), }) } /// Optional: accept mail only through DFINITY's gateways (plus /// controllers, for testing). Drop this check to accept any gateway. Return /// 530 rather than trapping, which would read as a temporary failure. fn check_caller() -> Result<(), SmtpResponse> { let caller = msg_caller(); if caller.to_text() == SMTP_GATEWAY || is_controller(&caller) { Ok(()) } else { Err(err(530, "unauthorized caller")) } } /// Header names are case-insensitive. Values arrive as the raw text after the /// colon: leading space and line ending included, RFC 2047 not decoded. fn header<'a>(headers: &'a [Header], name: &str) -> Option<&'a str> { headers .iter() .find(|h| h.name.eq_ignore_ascii_case(name)) .map(|h| h.value.trim()) } fn is_mailbox(user: &str) -> bool { MAILBOXES.iter().any(|m| m.eq_ignore_ascii_case(user)) } /// Shared by both entry points: smtp_request must re-check everything /// smtp_request_validate checked, because the state may have changed since. fn check_envelope(env: &Envelope) -> Result<(), SmtpResponse> { if env.to.is_empty() { return Err(err(501, "no recipients")); } if env.to.len() > MAX_RECIPIENTS { return Err(err(552, "too many recipients")); } if env.to.iter().any(|rcpt| !is_mailbox(&rcpt.user)) { return Err(err(550, "no such mailbox")); } Ok(()) } /// Called once per RCPT TO, with only `envelope` set (exactly one recipient). /// Never require `message` or `message_id` here. #[query] fn smtp_request_validate(req: SmtpRequest) -> SmtpResponse { if let Err(rejected) = check_caller() { return rejected; } let Some(env) = req.envelope else { return err(501, "envelope is required"); }; match check_envelope(&env) { Ok(()) => SmtpResponse::Ok(SmtpOk {}), Err(rejected) => rejected, } } /// Delivery. Synchronous on purpose: no `.await`, so no interleaving and no /// risk of running into the gateway's delivery timeout. #[update] fn smtp_request(req: SmtpRequest) -> SmtpResponse { if let Err(rejected) = check_caller() { return rejected; } // Every SmtpRequest field is `opt`, so ANY record decodes into this type. // Check presence yourself and never unwrap: a trap reads as a temporary // failure, and the sending server retries it until it gives up. let (Some(env), Some(msg), Some(id)) = (req.envelope, req.message, req.message_id) else { return err(501, "envelope, message and message_id are required"); }; if let Err(rejected) = check_envelope(&env) { return rejected; } if msg.headers.len() > MAX_HEADERS { return err(552, "too many headers"); } if msg.body.len() > MAX_BODY_BYTES { return err(552, "message too large"); } INBOX.with_borrow_mut(|inbox| { if inbox.len() >= MAX_STORED { return err(452, "mailbox full"); // transient: the sender retries later } // `message_id` is unique per SMTP transaction, NOT per email: a retry // by the sending server arrives with a new one. Storing under it // avoids overwrites; it does not deduplicate. inbox.entry(id).or_insert_with(|| Mail { envelope_from: format!("{}@{}", env.from.user, env.from.domain), subject: header(&msg.headers, "Subject") .unwrap_or_default() .to_string(), headers: msg.headers, body: msg.body, received_at: time(), }); SmtpResponse::Ok(SmtpOk {}) }) } #[query] fn inbox_size() -> u64 { INBOX.with_borrow(|inbox| inbox.len() as u64) } ic_cdk::export_candid!(); ``` ### Motoko There is no Motoko package for the protocol: declare the types yourself, field for field, as below. `mops.toml` needs `core = "2.5.0"` under `[dependencies]`. ```motoko import Char "mo:core/Char"; import Map "mo:core/Map"; import Principal "mo:core/Principal"; import Text "mo:core/Text"; import Time "mo:core/Time"; persistent actor Inbox { // --- Protocol types: a field-for-field projection of candid/smtp_gateway.did --- // Names and labels are the wire format: keep `#Ok`/`#Err` capitalised, // `code : Nat64`, and `#Ok` carrying the empty record `{}`. public type Header = { name : Text; value : Text }; public type Message = { headers : [Header]; body : Blob }; public type Address = { user : Text; domain : Text }; public type Envelope = { from : Address; to : [Address] }; public type SmtpRequest = { message : ?Message; envelope : ?Envelope; gateway_flags : ?[Text]; message_id : ?Text; }; public type SmtpRequestError = { code : Nat64; message : Text }; public type SmtpResponse = { #Ok : {}; #Err : SmtpRequestError }; // --- Application state --- type Mail = { envelopeFrom : Address; // unauthenticated: see pitfalls subject : Text; headers : [Header]; body : Blob; // raw RFC 5322 body bytes, MIME not decoded receivedAt : Int; }; // Configuration is `transient`: a plain `let` in a persistent actor is // stable and would keep its first-install value across upgrades. // Principal of DFINITY's SMTP gateways; gateways run by others have their own. transient let smtpGateway = Principal.fromText("ttvgm-eefjs-h2pqz-huxqk-ld2c3-rcwbm-a2tik-35hex-pm2jn-l6glo-oae"); // Local parts this canister accepts mail for. transient let mailboxes : [Text] = ["support", "hello"]; // Bounds on what one request may cost this canister. transient let maxRecipients = 10; transient let maxHeaders = 100; transient let maxBodyBytes = 100_000; transient let maxStored = 10_000; let inbox = Map.empty(); // stable: survives upgrades // Keep `message` short, single-line ASCII: the gateway copies it into the // SMTP reply line. func err(code : Nat64, message : Text) : SmtpResponse { #Err({ code; message }); }; // Optional: accept mail only through DFINITY's gateways (plus // controllers, for testing). Drop this check to accept any gateway. Return // 530 rather than trapping, which would read as a temporary failure. func checkCaller(caller : Principal) : ?SmtpResponse { if (caller == smtpGateway or Principal.isController(caller)) null else ?err(530, "unauthorized caller"); }; // Header names are case-insensitive. Values arrive as the raw text after the // colon: leading space and line ending included, RFC 2047 not decoded. func header(headers : [Header], name : Text) : ?Text { let wanted = name.toLower(); for (h in headers.vals()) { if (h.name.toLower() == wanted) return ?h.value.trim(#predicate(Char.isWhitespace)); }; null; }; func isMailbox(user : Text) : Bool { let u = user.toLower(); for (m in mailboxes.vals()) { if (m == u) return true }; false; }; // Shared by both entry points: smtp_request must re-check everything // smtp_request_validate checked, because the state may have changed since. func checkEnvelope(env : Envelope) : ?SmtpResponse { if (env.to.size() == 0) return ?err(501, "no recipients"); if (env.to.size() > maxRecipients) return ?err(552, "too many recipients"); for (rcpt in env.to.vals()) { if (not isMailbox(rcpt.user)) return ?err(550, "no such mailbox"); }; null; }; // Called once per RCPT TO, with only `envelope` set (exactly one recipient). // Never require `message` or `message_id` here. public shared query ({ caller }) func smtp_request_validate(req : SmtpRequest) : async SmtpResponse { switch (checkCaller(caller)) { case (?rejected) return rejected; case null {} }; let ?env = req.envelope else return err(501, "envelope is required"); switch (checkEnvelope(env)) { case (?rejected) rejected; case null #Ok({}); }; }; // Delivery. No `await` in here: no interleaving, and no risk of running // into the gateway's delivery timeout. public shared ({ caller }) func smtp_request(req : SmtpRequest) : async SmtpResponse { switch (checkCaller(caller)) { case (?rejected) return rejected; case null {} }; // Every SmtpRequest field is `opt`, so ANY record decodes into this type. // Check presence yourself and never trap: a trap reads as a temporary // failure, and the sending server retries it until it gives up. let (?env, ?msg, ?id) = (req.envelope, req.message, req.message_id) else { return err(501, "envelope, message and message_id are required"); }; switch (checkEnvelope(env)) { case (?rejected) return rejected; case null {}; }; if (msg.headers.size() > maxHeaders) return err(552, "too many headers"); if (msg.body.size() > maxBodyBytes) return err(552, "message too large"); if (Map.size(inbox) >= maxStored) return err(452, "mailbox full"); // transient // `message_id` is unique per SMTP transaction, NOT per email: a retry by // the sending server arrives with a new one. Storing under it avoids // overwrites; it does not deduplicate. if (not Map.containsKey(inbox, Text.compare, id)) { Map.add( inbox, Text.compare, id, { envelopeFrom = env.from; subject = switch (header(msg.headers, "Subject")) { case (?s) s; case null ""; }; headers = msg.headers; body = msg.body; receivedAt = Time.now(); }, ); }; #Ok({}); }; public query func inboxSize() : async Nat { Map.size(inbox) }; }; ``` ## Chunked Upload (Optional) A message whose encoded `SmtpRequest` exceeds 2 MiB cannot be delivered with one ingress call. The gateway then uploads it with `smtp_upload_chunk` and finalizes it with `smtp_upload_commit`, but **only** when `smtp_capabilities` returns both `upload_protocol_version >= 1` and `max_message_size > 0`. Otherwise the sender gets a permanent `550 5.5.0 ... does not support chunked upload` error, and your canister is unaffected. DFINITY's gateways accept at most 1,996,800 bytes per message (header block and body) and rejects larger mail with `552 5.3.4`, so nearly everything it accepts fits one `smtp_request`: implement chunked upload only if you need it. The obligations are strict: verify each chunk's SHA-256 before storing it, bound the layout before allocating, derive the commit digest from the bytes you stored (SHA-256 over the concatenated per-chunk SHA-256 digests in index order, not over the body: the crate's `body_sha256()`; a mismatch is 554), and keep the commit verdict so a repeated commit or a status query returns it. Read `references/chunked-upload.md` for the checklist, the gateway's behavior, and where to find the reference implementation. ## Deploy & Test There is no local SMTP gateway. Test by making the gateway's two calls yourself. Your identity deployed the canister, so it is a controller and passes the caller check: ```bash icp network start -d icp deploy backend # 1. RCPT TO for a known mailbox. Expected: (variant { Ok = record {} }) icp canister call backend smtp_request_validate '(record { envelope = opt record { from = record { user = "alice"; domain = "example.com" }; to = vec { record { user = "support"; domain = "example.icp0.io" } } } })' # 2. RCPT TO for an unknown mailbox. Expected: Err with code = 550 : nat64 icp canister call backend smtp_request_validate '(record { envelope = opt record { from = record { user = "alice"; domain = "example.com" }; to = vec { record { user = "nobody"; domain = "example.icp0.io" } } } })' # 3. Delivery, with header values as raw as the gateway sends them. # Expected: (variant { Ok = record {} }) icp canister call backend smtp_request '(record { envelope = opt record { from = record { user = "alice"; domain = "example.com" }; to = vec { record { user = "support"; domain = "example.icp0.io" } } }; message = opt record { headers = vec { record { name = "From"; value = " Alice \r\n" }; record { name = "Subject"; value = " Hello\r\n" } }; body = blob "Hi there!\r\n"; }; message_id = opt "0193f0a1-2b3c-7d4e-8f90-a1b2c3d4e5f6"; })' # 4. Delivery without message_id. Expected: Err with code = 501 : nat64, not a trap icp canister call backend smtp_request '(record { envelope = opt record { from = record { user = "a"; domain = "b.c" }; to = vec { record { user = "support"; domain = "x" } } }; message = opt record { headers = vec {}; body = blob "" } })' # 5. Expected: (1 : nat64). The Motoko example names this inboxSize and returns nat. icp canister call backend inbox_size '()' # 6. A caller that is neither the gateway nor a controller. Expected: Err with code = 530 : nat64 icp canister call --identity anonymous backend smtp_request_validate '(record {})' ``` ## Verify It Works on Mainnet ```bash icp deploy -e ic backend CANISTER_ID=$(icp canister status backend -e ic --id-only) # 1. Mail for the canister routes to the gateway. Expected: one or more MX hosts. dig +short MX "$CANISTER_ID.icp0.io" # 2. Send a mail to support@.icp0.io from any mail account, then: icp canister call -e ic backend inbox_size '()' ``` | Symptom at the sender | Cause | |---|---| | `550 5.1.3 Permanent error: Canister does not support SMTP protocol` | `smtp_request_validate` is not exported, misnamed, or not a query, or the `.well-known/ic-smtp-canister-id` handoff names a canister without it | | `550 5.1.2 Mailbox does not exist.` | `smtp_request_validate` returned 550. Check the local-part match, including case. | | `550 5.1.3 Permanent error: unauthorized caller` | The caller check does not accept the gateway principal (Pitfall 7) | | `550 5.1.1 Unknown recipient domain.` | The custom domain is not registered, or the address is not `.icp0.io` | | Delivery delayed, then a bounce after days | The canister traps, or returns a code outside 500–599, or takes longer than 90 s. Call it directly to see which. | | `552 5.3.4 Message too big` | The message exceeds the gateway's size limit (see Chunked Upload) | --- ## SNS DAO Launch --- name: sns-launch description: "Configure and launch an SNS DAO to decentralize a dapp. Covers token economics, governance parameters, testflight validation, NNS proposal submission, and decentralization swap. Use when launching an SNS, configuring tokenomics, or setting up DAO governance for a dapp. Do NOT use for NNS governance or general canister management." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2, dfx with sns extension" metadata: title: SNS DAO Launch category: Governance --- # SNS DAO Launch ## What This Is Service Nervous System (SNS) is the DAO framework for decentralizing individual Internet Computer dapps. Like the NNS governs the IC network itself, an SNS governs a specific dapp -- token holders vote on proposals to upgrade code, manage treasury funds, and set parameters. Launching an SNS transfers canister control from developers to a community-owned governance system through a decentralization swap. ## Prerequisites - An NNS neuron with sufficient stake to submit proposals (mainnet) - Dapp canisters already deployed and working on mainnet - `sns_init.yaml` configuration file with all parameters defined ## Canister IDs | Canister | Mainnet ID | Purpose | |----------|-----------|---------| | NNS Governance | `rrkah-fqaaa-aaaaa-aaaaq-cai` | Votes on SNS creation proposals | | SNS-W (Wasm Modules) | `qaa6y-5yaaa-aaaaa-aaafa-cai` | Deploys and initializes SNS canisters | | NNS Root | `r7inp-6aaaa-aaaaa-aaabq-cai` | Must be co-controller of dapp before launch | | ICP Ledger | `ryjl3-tyaaa-aaaaa-aaaba-cai` | Handles ICP token transfers during swap | ## SNS Canisters Deployed When an SNS launch succeeds, SNS-W deploys these canisters on an SNS subnet: | Canister | Purpose | |----------|---------| | **Governance** | Proposal submission, voting, neuron management | | **Ledger** | SNS token transfers (ICRC-1 standard) | | **Root** | Sole controller of all dapp canisters post-launch | | **Swap** | Runs the decentralization swap (ICP for SNS tokens) | | **Index** | Transaction indexing for the SNS ledger | | **Archive** | Historical transaction storage | ## Mistakes That Break Your Build 1. **Setting `min_participants` too high.** If you require 500 participants but only 200 show up, the entire swap fails and all ICP is refunded. Start conservative -- most successful SNS launches use 100-200 minimum participants. 2. **Forgetting to add NNS Root as co-controller before proposing.** The launch process requires NNS Root to take over your canisters. If you submit the proposal without adding it first, the launch will fail at stage 6 when SNS Root tries to become sole controller. 3. **Not testing on SNS testflight first.** Going straight to mainnet means discovering configuration issues after your NNS proposal is live. Always deploy a testflight mock SNS on mainnet first to verify governance and upgrade flows. 4. **Token economics that fail NNS review.** The NNS community votes on your proposal. Unreasonable tokenomics (excessive developer allocation, zero vesting, absurd swap caps) will get rejected. Study successful SNS launches (OpenChat, Hot or Not, Kinic) for parameter ranges the community accepts. 5. **Not defining fallback controllers.** If the swap fails, the dapp needs controllers to return control to. Without `fallback_controller_principals`, your dapp could become uncontrollable. 6. **Setting swap duration too short.** Users across time zones need time to participate. Less than 24 hours is risky -- 3-7 days is standard. 7. **Forgetting restricted proposal types during swap.** Six governance proposal types are blocked while the swap runs: `ManageNervousSystemParameters`, `TransferSnsTreasuryFunds`, `MintSnsTokens`, `UpgradeSnsControlledCanister`, `RegisterDappCanisters`, `DeregisterDappCanisters`. Do not plan operations that require these during the swap window. 8. **Developer neurons with zero dissolve delay.** Developers can immediately dump tokens post-launch. Set dissolve delays and vesting periods (12-48 months is typical) to signal long-term commitment. ## Implementation ### SNS Configuration File (sns_init.yaml) This is the single source of truth for all launch parameters. Copy the template from the `dfinity/sns-testing` repo and customize: ```yaml # Units: token-valued fields (transaction_fee, rejection_fee, stake, treasury, the swap # *_icp limits) carry an explicit suffix -- "tokens", "token", or "e8s" # (1 token = 100_000_000 e8s). Duration fields (initial_voting_period, dissolve_delay, # vesting_period, ...) carry a time suffix and may be concatenated: seconds, minutes, # hours, days, weeks, months (30.44 days), years (365.25 days) -- e.g. "4 days", "1w 2d 3h". # Plain counts such as minimum_participants take no suffix. # An e8s-only, seconds-only config is the older format; do not mix the two conventions. # === PROJECT METADATA === name: MyProject description: > A decentralized application for [purpose]. This proposal requests the NNS to create an SNS for MyProject. logo: logo.png url: https://myproject.com # === NNS PROPOSAL TEXT === NnsProposal: title: "Proposal to create an SNS for MyProject" url: "https://forum.dfinity.org/t/myproject-sns-proposal/XXXXX" summary: > This proposal creates an SNS DAO to govern MyProject. Token holders will control upgrades, treasury, and parameters. # === FALLBACK (if swap fails, these principals regain control) === fallback_controller_principals: - YOUR_PRINCIPAL_ID_HERE # === CANISTER IDS TO DECENTRALIZE === dapp_canisters: - BACKEND_CANISTER_ID - FRONTEND_CANISTER_ID # === TOKEN CONFIGURATION === Token: name: MyToken symbol: MYT transaction_fee: 0.0001 tokens logo: token_logo.png # === GOVERNANCE PARAMETERS === Proposals: rejection_fee: 1 token initial_voting_period: 4 days maximum_wait_for_quiet_deadline_extension: 1 day Neurons: minimum_creation_stake: 1 token Voting: minimum_dissolve_delay: 1 month MaximumVotingPowerBonuses: DissolveDelay: duration: 8 years bonus: 100% # 2x voting power at max dissolve Age: duration: 4 years bonus: 25% RewardRate: initial: 2.5% final: 2.5% transition_duration: 0 seconds # === TOKEN DISTRIBUTION === Distribution: Neurons: # Developer allocation (with vesting) - principal: DEVELOPER_PRINCIPAL stake: 2_000_000 tokens memo: 0 dissolve_delay: 6 months vesting_period: 24 months # Seed investors - principal: INVESTOR_PRINCIPAL stake: 500_000 tokens memo: 1 dissolve_delay: 3 months vesting_period: 12 months InitialBalances: treasury: 5_000_000 tokens # Treasury (controlled by DAO) swap: 2_500_000 tokens # Sold during decentralization swap total: 10_000_000 tokens # Must equal sum of all allocations # === DECENTRALIZATION SWAP === Swap: minimum_participants: 100 minimum_direct_participation_icp: 50_000 tokens maximum_direct_participation_icp: 500_000 tokens minimum_participant_icp: 1 token maximum_participant_icp: 25_000 tokens duration: 7 days neurons_fund_participation: true VestingSchedule: events: 5 # Neurons unlock in 5 stages interval: 3 months confirmation_text: > I confirm that I am not a resident of a restricted jurisdiction and I understand the risks of participating in this token swap. restricted_countries: - US - CN ``` ### Launch Process (11 Stages) ``` Stage 1: Developer defines parameters in sns_init.yaml Stage 2: Developer adds NNS Root as co-controller of dapp canisters Stage 3: Developer submits NNS proposal using `dfx sns propose` Stage 4: NNS community votes on the proposal Stage 5: (If adopted) SNS-W deploys uninitialized SNS canisters Stage 6: SNS Root becomes sole controller of dapp canisters Stage 7: SNS-W initializes canisters in pre-decentralization-swap mode Stage 8: 24-hour minimum wait before swap opens Stage 9: Decentralization swap opens (users send ICP, receive SNS neurons) Stage 10: Swap closes (time expires or maximum ICP reached) Stage 11: Finalization (exchange rate set, neurons created, normal mode) ``` ### Motoko Prepare your canister for SNS control. The key requirement is that your canister accepts upgrade proposals from SNS governance: ```motoko import Principal "mo:core/Principal"; import Runtime "mo:core/Runtime"; persistent actor { // SNS Root will be set as sole controller after launch. // Your canister code does not need to change -- SNS governance // controls upgrades via the standard canister management API. // If your canister has admin functions, transition them to // accept SNS governance proposals instead of direct principal checks: var snsGovernanceId : ?Principal = null; // ⚠ SECURITY: This setter MUST be access-controlled. Without a check, any caller // can front-run you and set themselves as governance, permanently locking you out. // Replace DEPLOYER_PRINCIPAL with your actual principal or use an admin list. public shared ({ caller }) func setSnsGovernance(id : Principal) : async () { // Only the deployer (or canister controllers) should call this. assert (Principal.isController(caller)); switch (snsGovernanceId) { case (null) { snsGovernanceId := ?id }; case (?_) { Runtime.trap("SNS governance already set") }; }; }; func requireGovernance(caller : Principal) { switch (snsGovernanceId) { case (?gov) { if (caller != gov) { Runtime.trap("Only SNS governance can call this") }; }; case (null) { Runtime.trap("SNS governance not configured") }; }; }; // Admin functions become governance-gated: public shared ({ caller }) func updateConfig(newFee : Nat) : async () { requireGovernance(caller); // ... apply config change }; }; ``` ### Rust ```rust use candid::{CandidType, Deserialize, Principal}; use ic_cdk::{init, post_upgrade, query, update}; use std::cell::RefCell; #[derive(CandidType, Deserialize, Clone)] struct Config { sns_governance: Option, } thread_local! { // ⚠ STATE LOSS: RefCell in thread_local! is HEAP storage — it is wiped on every // canister upgrade. In production, use ic-stable-structures (StableCell or StableBTreeMap) // to persist this across upgrades. At minimum, implement #[pre_upgrade]/#[post_upgrade] // hooks to serialize/deserialize this data. Without that, an upgrade erases your // governance config and locks out SNS control. static CONFIG: RefCell = RefCell::new(Config { sns_governance: None, }); } fn require_governance(caller: Principal) { CONFIG.with(|c| { let config = c.borrow(); match config.sns_governance { Some(gov) if gov == caller => (), Some(_) => ic_cdk::trap("Only SNS governance can call this"), None => ic_cdk::trap("SNS governance not configured"), } }); } // ⚠ SECURITY: This setter MUST be access-controlled. Without a check, any caller // can front-run you and set themselves as governance, permanently locking you out. #[update] fn set_sns_governance(id: Principal) { // Only canister controllers should call this. if !ic_cdk::api::is_controller(&ic_cdk::api::msg_caller()) { ic_cdk::trap("Only canister controllers can set governance"); } CONFIG.with(|c| { let mut config = c.borrow_mut(); if config.sns_governance.is_some() { ic_cdk::trap("SNS governance already set"); } config.sns_governance = Some(id); }); } #[update] fn update_config(new_fee: u64) { let caller = ic_cdk::api::msg_caller(); require_governance(caller); // ... apply config change } ``` **Cargo.toml dependencies:** ```toml [package] name = "sns_dapp_backend" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] candid = "0.10" ic-cdk = "0.19" serde = { version = "1", features = ["derive"] } ``` ## Deploy & Test ### Local Testing with sns-testing ```bash # Clone the SNS testing repository git clone https://github.com/dfinity/sns-testing.git cd sns-testing # WARNING: starting a fresh network wipes all local canister data. Only use for fresh setup. icp network start -d # Deploy NNS canisters locally (includes governance, ledger, SNS-W) # Note: Use the sns-testing repo's setup scripts for NNS + SNS-W canister installation. # See https://github.com/dfinity/sns-testing for current instructions. # Deploy your dapp canisters icp deploy my_backend icp deploy my_frontend # Deploy a testflight SNS locally using your config # Use the sns-testing repo tooling to deploy a local testflight SNS. # See sns-testing README for the current testflight workflow. ``` ### Mainnet Testflight (Mock SNS) ```bash # Deploy a mock SNS on mainnet to test governance flows # This does NOT do a real swap -- it creates a mock SNS you control # Use the sns-testing repo tooling for mainnet testflight deployment. # See https://github.com/dfinity/sns-testing for the current testflight workflow. # Test submitting proposals, voting, and upgrading via SNS governance ``` ### Mainnet Launch (Real) ```bash # Step 1: Add NNS Root as co-controller of each dapp canister # Requires dfx sns extension: `dfx extension install sns` dfx sns prepare-canisters add-nns-root BACKEND_CANISTER_ID --network ic dfx sns prepare-canisters add-nns-root FRONTEND_CANISTER_ID --network ic # Step 2: Validate your config locally before submitting dfx sns init-config-file validate # Or review the rendered proposal by inspecting the yaml output carefully. # You can also test the full flow on a local replica first (see Local Testing above). # Step 3: Submit the proposal (THIS IS IRREVERSIBLE — double-check your config) dfx sns propose --network ic --neuron $NEURON_ID sns_init.yaml ``` ## Verify It Works ### After local testflight deployment: ```bash # List deployed SNS canisters icp canister status sns_governance --id-only icp canister status sns_ledger --id-only icp canister status sns_root --id-only icp canister status sns_swap --id-only # Verify SNS governance is operational icp canister call sns_governance get_nervous_system_parameters '()' # Expected: returns the governance parameters you configured # Verify token distribution icp canister call sns_ledger icrc1_total_supply '()' # Expected: matches your total token supply # Verify dapp canister controllers changed icp canister status BACKEND_CANISTER_ID # Expected: controller is the SNS Root canister, NOT your principal # Test an SNS proposal (upgrade your canister via governance) icp canister call sns_governance manage_neuron '(record { ... })' # Expected: proposal created, can be voted on ``` ### After mainnet launch: ```bash # Check swap status icp canister call SNS_SWAP_ID get_state '()' -e ic # Expected: shows swap status, participation count, ICP raised # Check SNS governance icp canister call SNS_GOVERNANCE_ID get_nervous_system_parameters '()' -e ic # Expected: returns your configured parameters # Verify dapp controller is SNS Root icp canister status BACKEND_CANISTER_ID -e ic # Expected: single controller = SNS Root canister ID ``` --- ## Stable Memory & Upgrades --- name: stable-memory description: "Persist canister state across upgrades. Covers StableBTreeMap and MemoryManager in Rust, persistent actor in Motoko, and upgrade hook patterns. Use when dealing with canister upgrades, data persistence, data lost after upgrade, stable storage, StableBTreeMap, pre_upgrade traps, or heap vs stable memory. Do NOT use for inter-canister calls or access control — use multi-canister or canister-security instead." license: Apache-2.0 compatibility: "icp-cli >= 0.2.2, moc >= 1.7.0 for the Motoko examples (dot notation)" metadata: title: "Stable Memory & Upgrades" category: Core --- # Stable Memory & Canister Upgrades ## What This Is Stable memory is persistent storage on Internet Computer that survives canister upgrades. Whether ordinary variables survive depends on the language: - **Rust** -- heap data (`thread_local! { RefCell }`, plain `static`s) is wiped on every upgrade. Any data you care about must live in stable memory, either through `ic-stable-structures` or by serializing it yourself in `pre_upgrade`/`post_upgrade`. - **Motoko** -- enhanced orthogonal persistence is on by default, so `let` and `var` in a `persistent actor` already survive upgrades with no `stable` keyword and no upgrade hooks. Only `transient` declarations are wiped. ## Prerequisites - For Motoko: mops with `core = "2.0.0"` in mops.toml, and `moc >= 1.7.0` (dot notation on `Map`/`List` needs it) - For Rust: `ic-stable-structures = "0.7"` in Cargo.toml ## Canister IDs No external canister dependencies. Stable memory is a local canister feature. ## Mistakes That Break Your Build 1. **Using `thread_local! { RefCell }` for user data (Rust)** -- This is heap memory. It is wiped on every canister upgrade. All user data, balances, settings stored this way will vanish after `icp deploy`. Use `StableBTreeMap` instead. 2. **Forgetting `#[post_upgrade]` handler (Rust)** -- Without a `post_upgrade` function, the canister may silently reset state or behave unexpectedly after upgrade. Always define both `#[init]` and `#[post_upgrade]`. 3. **Using `stable` keyword in persistent actors (Motoko)** -- In mo:core `persistent actor`, all `let` and `var` declarations are automatically stable. Writing `stable let` produces warning M0218 and `stable var` is redundant. Just use `let` and `var`. 4. **Confusing heap memory limits with stable memory limits (Rust)** -- Heap (Wasm linear) memory is limited to 4GB for wasm32 and 6GB for wasm64. Stable memory can grow up to hundreds of GB (the subnet storage limit). The real danger: if you use `pre_upgrade`/`post_upgrade` hooks to serialize heap data to stable memory and deserialize it back, you are limited by the heap memory size AND by the instruction limit for upgrade hooks. Large datasets will trap during upgrade, bricking the canister. The solution is to use stable structures (`StableBTreeMap`, `StableCell`, etc.) that read/write directly to stable memory, bypassing the heap entirely. Use `MemoryManager` to partition stable memory into virtual memories so multiple structures can coexist without overwriting each other. 5. **Treating a rejected upgrade as data loss (Motoko)** -- Enhanced orthogonal persistence checks the new program against the existing state and either accepts the upgrade or rejects it *before* it takes effect. A rejected upgrade is **not** data loss: the canister keeps running the previous version with its state intact, so you fix the code and redeploy. Which schema changes need a migration, and how to write one, are owned by `migrating-motoko-actors` (the mops-managed migration chain); load it for the rules and syntax. The one thing to know here is the common surprise: **changing a record type that an existing persistent variable holds is an incompatible change and needs a migration**, even for an *optional* added field, and regardless of where the record lives (a top-level `var`, a `Map` value, etc.). Whether adding a *new* stable field itself needs a migration depends on the project's setup — under the enhanced migration chain a stable field is declared type-only, so a new one needs a migration; a plain `persistent actor` with an initializer on the new field does not — which is exactly why the rules live in that skill rather than as a table here. An incompatible upgrade is rejected at runtime with `RTS error: Memory-incompatible program upgrade` (the old state stays intact — it is not data loss). Don't discover this at deploy time. Configure `[canisters..check-stable]` in `mops.toml` so `mops check` runs the stable-compatibility check against the previous version's `.most` (load `mops-cli`): it tells you at check time whether a change is compatible or needs a migration, instead of surfacing the `RTS error` on the upgrade call. 6. **Serializing large data in pre_upgrade (Rust)** -- `pre_upgrade` has a fixed instruction limit. If you serialize a large HashMap to stable memory in pre_upgrade, it will hit the limit and trap, bricking the canister. Use `StableBTreeMap` which writes directly to stable memory and needs no serialization step. 7. **Mismatching the actor form and the `--default-persistent-actors` flag (Motoko)** -- Both plain `actor` and `persistent actor` are correct; which one compiles depends on that compiler flag. Enabling it is the recommended setup, because it keeps the code less verbose: ```toml # mops.toml — recommended; see `mops-cli` [moc] args = ["--default-persistent-actors"] ``` With the flag, every actor is persistent, so write plain `actor { }`; the `persistent` keyword still compiles but is redundant (warning M0217). Without the flag, `persistent actor { }` is required, and plain `actor` fails with `[M0220] this actor or actor class should be declared persistent`. No annotation rescues it — `stable`, `transient`, and `pre_upgrade`/`post_upgrade` hooks all still fail, because the error is on the actor itself: ```motoko // without --default-persistent-actors actor { stable var users = Map.empty(); // M0220 — `stable` does not help }; persistent actor { let users = Map.empty(); // compiles; persisted automatically }; ``` The examples below use `persistent actor`, which compiles either way. One trap when the flag is off: if the actor body has un-annotated `let`/`var`, moc reports `[M0219] this declaration is currently implicitly transient, please declare it explicitly transient` on those lines and M0220 never appears. Do not follow that suggestion — `transient` discards the data on upgrade, and the actor still fails M0220. The fix is `persistent` on the actor, or the flag. ## Implementation ### Motoko With mo:core 2.0, `persistent actor` makes stable storage trivial. All `let` and `var` declarations inside the actor body are automatically persisted across upgrades. ```motoko import Map "mo:core/Map"; import List "mo:core/List"; import Nat "mo:core/Nat"; // required: the compiler derives Map's implicit `compare` from this module import Text "mo:core/Text"; import Time "mo:core/Time"; persistent actor { // Types: in the actor body (as here) or in an imported module -- but never // between the imports and the actor, which is M0141. See the `writing-motoko` skill. type User = { id : Nat; name : Text; created : Int; }; // These survive upgrades automatically -- no "stable" keyword needed let users = Map.empty(); var userCounter : Nat = 0; let tags = List.empty(); // Transient data -- reset to initial value on every upgrade transient var requestCount : Nat = 0; public func addUser(name : Text) : async Nat { let id = userCounter; users.add(id, { id; name; created = Time.now(); }); userCounter += 1; requestCount += 1; id }; public query func getUser(id : Nat) : async ?User { users.get(id) }; public query func getUserCount() : async Nat { users.size() }; // requestCount resets to 0 after every upgrade public query func getRequestCount() : async Nat { requestCount }; } ``` Key rules for Motoko persistent actors: - `let` for Map, List, Set, Queue -- auto-persisted, no serialization - `var` for simple values (Nat, Text, Bool) -- auto-persisted - `transient var` for caches, counters that should reset on upgrade - NO `pre_upgrade` / `post_upgrade` needed -- the runtime handles it - NO `stable` keyword -- it is redundant and produces warnings #### mops.toml ```toml [package] name = "my-project" version = "0.1.0" [dependencies] core = "2.0.0" # Required. Without a [toolchain] moc pin, mops falls back to the dfx cache and # the build dies with `dfx: not found` (see `mops-cli`). [toolchain] moc = "1.9.0" ``` ### Rust Rust canisters use `ic-stable-structures` for persistent storage. The `MemoryManager` partitions stable memory (up to hundreds of GB, limited by subnet storage) into virtual memories, each backing a different data structure. #### Cargo.toml ```toml [package] name = "stable_memory_backend" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] [dependencies] ic-cdk = "0.19" ic-stable-structures = "0.7" candid = "0.10" serde = { version = "1", features = ["derive"] } ciborium = "0.2" ``` #### Single Stable Structure (Simple Case) ```rust use ic_stable_structures::{ memory_manager::{MemoryId, MemoryManager, VirtualMemory}, storable::{Bound, Storable}, DefaultMemoryImpl, StableBTreeMap, }; use ic_cdk::{init, post_upgrade, query, update}; use candid::CandidType; use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::cell::RefCell; type Memory = VirtualMemory; // -- Implement Storable for custom types -- // StableBTreeMap keys need Storable + Ord, values need Storable. // Storable defines how a type is serialized to/from bytes in stable memory. // Use CBOR (via ciborium) for serialization -- compact binary format, faster than candid. #[derive(CandidType, Serialize, Deserialize, Clone)] struct User { id: u64, name: String, created: u64, } impl Storable for User { // Recommended: prefer Unbounded to avoid backwards compatibility issues when adding new fields. // Bounded requires a fixed max_size -- adding a field that increases the size will break existing data. const BOUND: Bound = Bound::Unbounded; fn to_bytes(&self) -> Cow<'_, [u8]> { let mut buf = vec![]; ciborium::into_writer(self, &mut buf).expect("Failed to encode User"); Cow::Owned(buf) } fn into_bytes(self) -> Vec { let mut buf = vec![]; ciborium::into_writer(&self, &mut buf).expect("Failed to encode User"); buf } fn from_bytes(bytes: Cow<'_, [u8]>) -> Self { ciborium::from_reader(bytes.as_ref()).expect("Failed to decode User") } } // Bound::Bounded { max_size, is_fixed_size: true } exists for fixed-size types but is NOT // recommended -- adding a new field later will exceed max_size and break deserialization. // Stable storage -- survives upgrades thread_local! { static MEMORY_MANAGER: RefCell> = RefCell::new(MemoryManager::init(DefaultMemoryImpl::default())); static USERS: RefCell> = RefCell::new(StableBTreeMap::init( MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(0))) )); // Counter stored in stable memory via StableCell static COUNTER: RefCell> = RefCell::new(ic_stable_structures::StableCell::init( MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(1))), 0u64, )); } #[init] fn init() { // Any one-time initialization } #[post_upgrade] fn post_upgrade() { // Stable structures auto-restore -- no deserialization needed // Re-init timers or other transient state here } #[update] fn add_user(name: String) -> u64 { let id = COUNTER.with(|c| { let mut cell = c.borrow_mut(); let current = *cell.get(); cell.set(current + 1); current }); let user = User { id, name, created: ic_cdk::api::time(), }; USERS.with(|users| { users.borrow_mut().insert(id, user); }); id } #[query] fn get_user(id: u64) -> Option { USERS.with(|users| users.borrow().get(&id)) } #[query] fn get_user_count() -> u64 { USERS.with(|users| users.borrow().len()) } ic_cdk::export_candid!(); ``` #### Multiple Stable Structures with MemoryManager ```rust use ic_stable_structures::{ memory_manager::{MemoryId, MemoryManager, VirtualMemory}, DefaultMemoryImpl, StableBTreeMap, StableCell, StableLog, }; use std::cell::RefCell; type Memory = VirtualMemory; // Each structure gets its own MemoryId -- NEVER reuse IDs const USERS_MEM_ID: MemoryId = MemoryId::new(0); const POSTS_MEM_ID: MemoryId = MemoryId::new(1); const COUNTER_MEM_ID: MemoryId = MemoryId::new(2); const LOG_INDEX_MEM_ID: MemoryId = MemoryId::new(3); const LOG_DATA_MEM_ID: MemoryId = MemoryId::new(4); thread_local! { static MEMORY_MANAGER: RefCell> = RefCell::new(MemoryManager::init(DefaultMemoryImpl::default())); static USERS: RefCell, Memory>> = RefCell::new(StableBTreeMap::init( MEMORY_MANAGER.with(|m| m.borrow().get(USERS_MEM_ID)) )); static POSTS: RefCell, Memory>> = RefCell::new(StableBTreeMap::init( MEMORY_MANAGER.with(|m| m.borrow().get(POSTS_MEM_ID)) )); static COUNTER: RefCell> = RefCell::new(StableCell::init( MEMORY_MANAGER.with(|m| m.borrow().get(COUNTER_MEM_ID)), 0u64, )); static AUDIT_LOG: RefCell, Memory, Memory>> = RefCell::new(StableLog::init( MEMORY_MANAGER.with(|m| m.borrow().get(LOG_INDEX_MEM_ID)), MEMORY_MANAGER.with(|m| m.borrow().get(LOG_DATA_MEM_ID)), )); } ``` Key rules for Rust stable structures: - `MemoryManager` partitions stable memory -- each structure gets a unique `MemoryId` - NEVER reuse a `MemoryId` for two different structures -- they will corrupt each other - `StableBTreeMap` keys must implement `Storable` + `Ord`, values must implement `Storable` - Implement `Storable` for custom types: define `BOUND`, `to_bytes`, `into_bytes`, and `from_bytes`. Use `ciborium::into_writer`/`ciborium::from_reader` for CBOR serialization (compact, fast). Prefer `Bound::Unbounded` -- it avoids backwards compatibility breakage when adding new fields. `Bound::Bounded` exists but is not recommended because exceeding `max_size` after a schema change breaks deserialization - Primitive types (`u64`, `bool`, `f64`, etc.), `String`, `Vec`, and `Principal` already implement `Storable` -- no manual impl needed - `StableCell` for single values (counters, config) - `StableLog` for append-only logs (needs two memory regions: index + data) - `thread_local! { RefCell> }` is the correct pattern -- the RefCell wraps the stable structure, not a heap HashMap - No `pre_upgrade`/`post_upgrade` serialization needed -- data is already in stable memory ## Deploy & Test ### Motoko: Verify Persistence Across Upgrades ```bash # Start local replica icp network start -d # Deploy icp deploy backend # Add data icp canister call backend addUser '("Alice")' # Expected: (0 : nat) icp canister call backend addUser '("Bob")' # Expected: (1 : nat) # Verify data exists icp canister call backend getUserCount '()' # Expected: (2 : nat) icp canister call backend getUser '(0)' # Expected: (opt record { id = 0 : nat; name = "Alice"; created = ... }) # Now upgrade the canister (simulates code change + redeploy) icp deploy backend # Verify data survived the upgrade icp canister call backend getUserCount '()' # Expected: (2 : nat) -- STILL 2, not 0 icp canister call backend getUser '(1)' # Expected: (opt record { id = 1 : nat; name = "Bob"; created = ... }) ``` ### Rust: Verify Persistence Across Upgrades ```bash icp network start -d icp deploy backend icp canister call backend add_user '("Alice")' # Expected: (0 : nat64) icp canister call backend get_user_count '()' # Expected: (1 : nat64) # Upgrade icp deploy backend # Verify persistence icp canister call backend get_user_count '()' # Expected: (1 : nat64) -- data survived icp canister call backend get_user '(0)' # Expected: (opt record { id = 0 : nat64; name = "Alice"; created = ... }) ``` ## Verify It Works The definitive test for stable memory: data survives upgrade. ```bash # 1. Deploy and add data icp deploy backend icp canister call backend addUser '("TestUser")' # 2. Record the count icp canister call backend getUserCount '()' # Note the number # 3. Upgrade (redeploy) icp deploy backend # 4. Check count again -- must be identical icp canister call backend getUserCount '()' # Must match step 2 # 5. Verify transient data DID reset icp canister call backend getRequestCount '()' # Expected: (0 : nat) -- transient var resets on upgrade ``` If the count drops to 0 after step 3, your data is NOT in stable memory. Review your storage declarations. --- ## Static Site (Certified Assets) --- name: static-site description: "Deploy a frontend or any static site to the IC with the @dfinity/static-site recipe (the certified-assets canister). Covers icp.yaml recipe config, SPA routing with _redirects, custom headers/CSP with _headers, clean URLs, access protection for private apps, custom domains, and building against canister IDs. This is the recommended way to host frontends and static files on the IC. Also the entry point for the legacy @dfinity/asset-canister recipe and .ic-assets.json5 (see the legacy reference) and for migrating an existing asset canister to certified-assets. Use when hosting a frontend, deploying static files, an asset canister, or setting up SPA routing on the IC. Do NOT use for canister-level HTTP code patterns or custom domain DNS setup — use custom-domains for DNS." license: Apache-2.0 compatibility: "icp-cli >= 1.0.0, Node.js >= 22" metadata: title: Static Site (Certified Assets) category: Frontend --- # Static Site (Certified Assets) ## What This Is The **`@dfinity/static-site` recipe** deploys a static site — a built frontend, docs, or any folder of files — to the **certified-assets canister** on the Internet Computer, which serves it over HTTP with **response certification**. The canister certifies **every** response (certification v2 only, never the `no_certification` escape hatch, no way to turn it off), and a **verifying** HTTP gateway checks that proof before handing the response to the browser: visitors get content the canister provably committed to, not something altered in transit. Whether the proof is *checked* depends on the gateway the visitor goes through: `https://.icp.net` verifies, `https://.raw.icp.net` does not (Pitfall 14). **This is the recommended way to host a frontend on the IC going forward.** The recipe bundles a matched pair — the canister and its sync plugin — pinned together by one version. You point it at your build directory; `icp deploy` uploads, certifies, and serves. > The older **`@dfinity/asset-canister` recipe** (the SDK asset canister, configured with `.ic-assets.json5`) is still supported for existing projects but is no longer the recommended path. It is a *different canister* with a different config format and API — see [`references/legacy-asset-canister.md`](references/legacy-asset-canister.md). To move an existing project over, see [`references/migrating-from-asset-canister.md`](references/migrating-from-asset-canister.md). ## Prerequisites - `icp-cli` — `npm install -g @icp-sdk/icp-cli`. The recipe pins the canister + sync-plugin pair, both pre-built, so a plain `dir`/`build`/`presync` deploy needs nothing else. - `ic-wasm` — `npm install -g @icp-sdk/ic-wasm`. A **separate** binary, not bundled with `icp-cli`. This recipe shells out to it *only* when you set the `metadata` field (the generated build guards on `command -v ic-wasm` and fails with "ic-wasm not found"); other official recipes need it unconditionally, so installing both up front is the safe default — see the `icp-cli` skill. - Your frontend's build toolchain (e.g. Node.js >= 22 for a Vite/React app). ## Canister IDs and URLs Static-site canisters are created per-project — there is no global canister ID. After deployment the canister ID is stored in `.icp//mappings/.ids.json`. Managed networks (the local replica) are **cache** — `.icp/cache/mappings/local.ids.json`; connected networks (mainnet `ic`) are **data** — `.icp/data/mappings/ic.ids.json`. | Environment | Browser URL | |-------------|-------------| | Local | `http://..localhost:8000` — the middle label is the **environment name**, `local` by default, so `http://frontend.local.localhost:8000` (this is the URL `icp deploy` prints; `http://.localhost:8000` also works — `.localhost` with no environment label does not) | | Mainnet | `https://.icp.net` | | Custom domain | `https://yourdomain.com` (with DNS configuration) | ## icp.yaml Configuration ```yaml canisters: - name: frontend recipe: type: "@dfinity/static-site@v0.4.3" configuration: build: - npm ci - npm run build dir: dist ``` Check the [static-site releases](https://github.com/dfinity/icp-cli-recipes/releases?q=static-site) for the latest version and pin it in the `type` field. Because the recipe pins a matched canister + plugin pair, there is **no separate canister version to choose** — the recipe version *is* the canister version. The recipe takes four configuration fields: | Field | Required | Description | |-------|----------|-------------| | `dir` | **Yes** | The single directory of built files to serve. The canister owns its whole URL space, so this is one directory, not a list. Vite → `dist`, Next.js export → `out`. | | `build` | No | Shell commands run *before the canister exists* to produce `dir` (e.g. `npm run build`). No canister IDs are available yet. | | `presync` | No | Shell commands run *at sync time, after the canister exists*, with deployed canister IDs exported as env vars. Use this to bake a canister ID into a frontend build (see [below](#building-against-canister-ids-presync-vs-build)). | | `metadata` | No | `name`/`value`/`visibility` entries baked into the canister wasm via `ic-wasm`. `visibility` is optional, `public` or `private`; omitted means `private` (ic-wasm's default), and only `public` sections are readable by anyone via `icp canister metadata`. Values are interpolated in a shell at build time, so `$(…)` works. | ## Pitfalls 1. **Using `.ic-assets.json5` with the static-site recipe.** `.ic-assets.json5` is the **legacy asset canister's** config file. The certified-assets canister does not read it — and because the plugin skips every dotfile and dot-directory (only `.well-known/` is exempt, Pitfall 12), a `.ic-assets.json5` in your `dir` is not even uploaded. It is silently absent, so SPA fallback, headers, and security policy do nothing. Configure this canister with `_redirects` and `_headers` instead (below). 2. **Wrong SPA fallback rule.** For client-side routing, the fallback is a **rewrite** in `_redirects`: `/* /index.html 200`. The `200` status is what makes it a rewrite (serve the shell's contents at the requested URL, no visible redirect) so deep links work on fresh load and reload. Do **not** use a `301`/`302` redirect, and do **not** reach for `enable_aliasing` — that is a legacy asset-canister setting and has no effect here. 3. **Relative asset paths in a SPA.** Link assets with **absolute** paths (`/assets/app.js`), never relative (`assets/app.js`). Under a `/*` rewrite, a relative URL resolves against the *client route*: at `/dashboard/settings` the browser requests `/dashboard/settings/assets/app.js`, which `/*` answers with the HTML shell — producing a confusing MIME-type error instead of loading your script. 4. **Expecting `AssetManager` / `@icp-sdk/canisters` to work.** The certified-assets canister's upload API is `upload_chunks` + `execute_operations`, **not** the SDK asset canister's `store`/`create_batch`/`commit_batch`. `AssetManager` from `@icp-sdk/canisters/assets` targets the *legacy* canister and does **not** work against static-site. Uploads happen through the recipe's sync plugin on `icp deploy`; there is no drop-in JS `AssetManager` equivalent for this canister. (If you need programmatic uploads, you are almost certainly on the legacy canister — see the legacy reference.) 5. **`_headers` / `_redirects` in the wrong place.** These two files must sit at the **root of your `dir`** (e.g. `dist/_redirects`). They are read as configuration and never served as assets. Put them in your `public/` (Vite) or `static/` folder so the build copies them into `dir` automatically — a file left at the project root but not copied into `dir` is simply absent at deploy time. 6. **Setting a reserved header in `_headers`.** The sync plugin **rejects** these at deploy time with an explanatory error: `Content-Length`, `Content-Encoding`, `ETag`, `Transfer-Encoding`, `Accept-Ranges`, `Content-Range`, `IC-Certificate`, `IC-CertificateExpression`, `Location`. To set an asset's media type use the bare `Content-Type:` form (it routes to asset metadata, not a response header). To redirect, use `_redirects` — a `Location` header in `_headers` would not redirect (status stays `200`). 7. **Assuming default security headers.** Unlike the legacy canister's `security_policy: "standard"`, the certified-assets canister adds **no default headers** — no `Cache-Control`, no CSP, no `X-Frame-Options`. If you want them, declare them in `_headers` (baseline below). The only headers it manages itself are the certification/serving ones and its `ic_env` cookie. 8. **A `404`/`410` rule pointing at a large file.** An error-page target must be a **small, single-chunk file** (under ~1.9 MB). Large files are served as certified `206` range responses that can't carry a 4xx status, so the plugin rejects such a rule at deploy time, naming it. (A `200` rewrite to a large file is fine.) 9. **Expecting dynamic redirect captures.** There is no `:splat` or `:placeholder` — you can't forward a captured segment (`/old/:rest → /new/:rest`). Every certifiable response must be enumerable ahead of time, so `_redirects`/`_headers` support only exact paths, a trailing `/*` subtree wildcard, and fixed destinations. 10. **Switching an existing project from the legacy asset canister to static-site.** Repointing `recipe:` at `@dfinity/static-site` and running a plain `icp deploy` **fails before anything is installed**: these are two unrelated canisters with unrelated Candid interfaces, so icp-cli's pre-install check aborts with `Candid interface compatibility check failed: '' … You are making a BREAKING change`. Run **`icp deploy --mode reinstall`** instead. That replaces the wasm with the certified-assets canister, **discards the old stable memory** — every legacy asset, permission, and `.ic-assets.json5`-derived setting is gone — and leaves the canister with empty state, after which the sync plugin uploads your whole `dir` from scratch. Deploying static-site as a brand-new canister avoids the question entirely. Do **not** silence the check with `--yes`: that pushes the in-place upgrade through onto stable memory certified-assets cannot read, leaving a live canister that serves nothing. See the migration reference. 11. **Assuming a recipe version bump re-installs itself.** Moving between certified-assets' **own** releases is gentler than the legacy switch above — the Candid interface is stable across a release series, so nothing blocks the deploy — but a breaking bump still needs a reinstall **you run yourself**. The canister and plugin are version-locked, so after bumping the recipe `icp deploy` upgrades in place and the sync plugin then refuses, reporting `assets canister version mismatch: canister is X, this plugin is Y` plus the fix: `icp canister install --mode upgrade` for a **patch** bump (state preserved) or `icp canister install --mode reinstall` for a **breaking** (pre-1.0 minor, post-1.0 major) bump, which wipes state so the next sync re-uploads every asset and redirect rule. (**`v0.3.x` → `v0.4.0` is breaking**: reinstall, then `icp deploy`. `v0.4.x` → `v0.4.3` is a patch: upgrade, then `icp deploy`.) A failed sync right after a version bump is expected — this, not a bug. 12. **`.well-known/` is uploaded automatically — no config needed.** The plugin skips dotfiles and dot-directories *except* `.well-known/`, which it traverses normally. So `dir/.well-known/ic-domains` is served at `/.well-known/ic-domains` with no extra setting. (This is the opposite of the legacy canister, which needed an explicit `.ic-assets.json5` un-ignore rule.) 13. **Access protection ordering.** The recipe's `icp deploy` installs the canister **and** syncs assets together, so a plain deploy-then-`enable_protection` briefly serves your content publicly. For a brand-new *private* app, enable protection **before your real assets are synced** — deploy a `dir` containing only `login.html`, `enable_protection`, then deploy the full site — so assets are never world-readable. The login page must be **fully self-contained** (inline CSS/JS, `data:` URIs) — it is the only gate-exempt path, and any external subresource it references would itself be gated. See [Access protection](#access-protection-private-apps). 14. **Sharing or linking a `raw.icp.net` URL.** `.raw.icp.net` serves the same site as `.icp.net`, but the gateway forwards responses **without checking the certificate**, so the visitor gets no more assurance than from an ordinary web host. There is no canister setting to refuse `raw` requests (unlike the legacy canister's `allow_raw_access`): the only clue is the unauthenticated `Host` header, and which hostnames verify is a gateway deployment detail, not protocol. Link to `https://.icp.net` (or a custom domain on a verifying gateway) and treat `raw` as a debugging tool only. With access protection on, a `raw` URL is actively dangerous: the redirect and login page arrive unverified, so a non-verifying gateway could serve a fake login form and harvest tokens. The access cookie is host-only, so a session on the certified host does not carry over to `raw`. ## SPA Routing and Redirects: `_redirects` Add a `_redirects` file to the root of your `dir`. Syntax follows [Netlify's `_redirects`](https://docs.netlify.com/manage/routing/redirects/overview/) — one rule per line, three whitespace-separated fields (`from`, `to`, `status`); blank lines and `#` comments are ignored. ``` # Single-page-app fallback: serve the shell for any unmatched path (a rewrite, status 200) /* /index.html 200 # Permanent redirect to a new internal path /old-blog /blog 301 # Redirect to an external site /discord https://discord.gg/example 302 # Rewrite: serve /content/article.html at a pretty URL, no visible redirect /article /content/article.html 200 # Subtree redirect: everything under /docs/v1/ moves to /docs/v2/ /docs/v1/* /docs/v2/ 301 # Custom error pages (target must be a small single-chunk file) /secret /403.html 404 /retired-feature /sunset.html 410 ``` Status codes: `301`/`302`/`307`/`308` redirect; `200` is a **rewrite**; `404`/`410` serve an error page. `from` is always absolute and its only wildcard is a trailing `/*`. Precedence, first match wins: **real files** > automatic **clean-URL** rules > your `_redirects` (in file order) > the 404 fallback. Because a real file always wins, a `/*` SPA rule only catches paths nothing else claimed. **SPA caveat — missing assets return HTML.** With `/* /index.html 200`, a typo'd `/assets/app-old.js` also matches `/*` and serves the shell as `text/html`. To give real 404s under a build-output folder, scope a narrower rule *above* the catch-all (rules match in file order): ``` /assets/* /404.html 404 /* /index.html 200 ``` This needs a `404.html` in your `dir`; declaring `/*` means the built-in default 404 is not added. ## Custom Headers: `_headers` Add a `_headers` file to the root of your `dir`. Syntax follows [Netlify's `_headers`](https://docs.netlify.com/manage/routing/headers/): a path pattern on its own line, followed by indented `Name: value` lines; a blank line or `#` ends a block. Patterns are absolute paths with an optional single `*` wildcard (which matches `/` too; there is no `**` or `?`). A useful baseline — act like a senior security engineer and tighten the CSP for your app: ``` /* X-Frame-Options: DENY X-Content-Type-Options: nosniff Referrer-Policy: strict-origin-when-cross-origin Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline' # Fingerprinted build assets never change — cache them hard /assets/* Cache-Control: public, max-age=31536000, immutable # HTML should revalidate so deploys are picked up /*.html Cache-Control: public, max-age=0, must-revalidate ``` Key rules: - **Patterns match the file (asset key), not the visitor's URL.** Write `/index.html`, not `/`. For a SPA, a `Cache-Control` on `/index.html` (or `/*.html`) is what every `/*`-rewritten client route gets; a block written against a route like `/dashboard/*` matches no file and does nothing. - **All matching blocks contribute** — a file matching several blocks gets every block's headers (same-name values are combined comma-separated; `Set-Cookie` stays separate). - **`Content-Type` is special** — the bare `Content-Type: ` form overrides the stored media type of the matching file (use it for extension-less files like `/llms.txt`); it is single-valued, first-match-wins, and is *not* emitted as an ordinary header. - **`Set-Cookie` is allowed, but don't use the name `ic_env`.** The canister adds its own `ic_env` cookie to HTML responses as **two** `Set-Cookie` headers with the same name and value: one `SameSite=Lax`, one `SameSite=None; Partitioned` (so it survives in a cross-site iframe). Seeing two `ic_env` headers is expected, not a duplicate-header bug. - Reserved headers are rejected at deploy time — see Pitfall 6. ## Clean URLs and the 404 Page You don't link to `.html` files — the canister maps each HTML file to a clean, extension-less canonical URL and `307`-redirects the other forms to it: | Your file | Canonical URL | Also handled (→ `307`) | |-----------|---------------|------------------------| | `dist/index.html` | `/` | `/index` | | `dist/about.html` | `/about` | `/about/`, `/about/index` | | `dist/blog/index.html` | `/blog/` | `/blog`, `/blog/index` | Requesting the underlying `/about.html` directly currently serves it `200` (a file always beats a routing rule). For a custom 404, put a `404.html` at the root of your `dir`; otherwise a certified default is served. A SPA `/*` rule takes over the whole path space, so it replaces the default 404 with your shell. ## Custom Domains To serve from your own domain, add a `.well-known/ic-domains` file to your `dir`, one domain per line: ``` example.com www.example.com ``` `.well-known/` is uploaded automatically (Pitfall 12), so the file is served where the IC boundary nodes look. Registering the domain itself (DNS records, ACME challenge, TLS provisioning) is a separate IC platform step — see the `custom-domains` skill. ## Access Protection (private apps) Put a login gate in front of an in-progress or preview app. Unauthenticated visitors get a certified `307 → ` (HTML) or `401` (other assets). Configure it through controller-only canister methods: ```sh # 1. Add a self-contained /login.html to your dir and deploy. icp deploy # 2. Turn the gate on, naming your login page. icp canister call frontend enable_protection '("/login.html")' # 3. Mint a credential (here: a chosen passphrase valid ~1 year). Pass value = null for a random token. # issue_token takes a record (IssueTokenArgs), not positional args. icp canister call frontend issue_token '(record { label = "owner"; ttl_secs = 31536000 : nat32; value = opt "my-passphrase" })' ``` > **Ordering & the public window.** The `static-site` recipe's `icp deploy` **installs the canister and syncs your assets in one step**, so the sequence above serves your content publicly for the brief window between that first deploy and `enable_protection` — fine when gating an existing or preview app. To avoid *any* public exposure for a **brand-new private app**, enable protection **before your real assets are synced**: run the first `icp deploy` with a `dir` containing only `login.html`, then `enable_protection '("/login.html")'`, then `icp deploy` again with the full site. The login page is gate-exempt, so nothing private is ever served unauthenticated (Pitfall 13). (Enabling on a truly empty canister also works — the canister reports `EnabledLoginPageMissing` and self-heals to `Enabled` once `login.html` is synced.) | Method | Effect | |--------|--------| | `issue_token '(record { label = "