# Cloud Engine Canisters

> 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).

- Skill: `jiayaoqijia/cloud-engine-canisters-2` (Agent Skill, multi-file: 4 files)
- Install (CLI): `npx get-skill add jiayaoqijia/cloud-engine-canisters-2`
- Raw SKILL.md: https://api.skillmd.com/api/skills/jiayaoqijia/cloud-engine-canisters-2/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: DevOps & Infra
- License: Apache-2.0
- Author: jiayaoqijia (https://skillmd.com/u/jiayaoqijia)
- Updated: 2026-11-18
- Page: https://skillmd.com/skills/jiayaoqijia/cloud-engine-canisters-2

---


# 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 <id> 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 <proxy-id> 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 <operator-id> listInferenceProviders '()' -n ic --query
```

```candid
(record { providers = opt vec {
  record { id = opt "iig"; name = opt "IIG"; base_url = opt "https://<iig-router>/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<Nat>` 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 <provider> 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 

…(truncated)
