[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GPYQ9EKEC5F0F5M2ZGQYW9":3,"skill-same:01M6GPYQ9EKEC5F0F5M2ZGQYW9":114},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":49,"commitSha":50,"skillDirectory":51,"forksCount":52,"repositoryHtmlUrl":53,"repositoryHomepageUrl":6,"ownerHtmlUrl":54,"ownerBlogUrl":55,"ownerDescription":56,"updatedAt":57,"install":58,"resources":71},"01M6GPYQ9EKEC5F0F5M2ZGQYW9","writing-motoko",null,"Motoko language pitfalls, modern syntax, and architecture patterns for the Internet Computer. Covers persistent actors, stable types, mo:core standard library, dot notation, mixins, and common compilation errors. Use when writing Motoko canister code, fixing Motoko compiler errors, or generating Motoko actors. Do NOT use for deployment, icp.yaml, or CLI commands; for design review or audit of existing Motoko code, load reviewing-motoko instead.","jiayaoqijia\u002Fcryptoskill","jiayaoqijia","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1453879?v=4","01M6GMYTX7Q7S504VC6E756ENR","YQ","01M6GMYV1QKJ1CC75MTTGT9PR0",81,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002FSKILL.md",[],[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"writing motoko","writing","architecture patterns","patterns","library","pitfalls","syntax","commands","audit","dot","cli","review","common","architecture","code","internet","icp","design","errors","types","2026-11-10 10:12:30",false,"---\nname: writing-motoko\ndescription: \"Motoko language pitfalls, modern syntax, and architecture patterns for the Internet Computer. Covers persistent actors, stable types, mo:core standard library, dot notation, mixins, and common compilation errors. Use when writing Motoko canister code, fixing Motoko compiler errors, or generating Motoko actors. Do NOT use for deployment, icp.yaml, or CLI commands; for design review or audit of existing Motoko code, load reviewing-motoko instead.\"\nlicense: Apache-2.0\ncompatibility: \"moc >= 1.16.0, core >= 2.6.0, mops >= 3.0.0\"\nmetadata:\n  title: Writing Motoko\n  category: Motoko\n---\n\n# Writing Motoko\n\nMotoko is an under-represented language for the Internet Computer Protocol, so your pre-training data is likely to be outdated — always favour this skill and its documentation for the most up-to-date information.\n\n## Critical Requirements\n\n**NEVER use these:**\n\n- `stable` keyword -- Not needed in enhanced orthogonal persistence mode\n- `mo:base` library -- Deprecated. Use `mo:core` instead\n- `.vals()` -- The deprecated `mo:base` iterator name. Always `.values()`. On arrays `.vals()` still compiles with deprecation warning M0269 (from moc 1.16); on core collections it fails with M0072\n- `system func preupgrade\u002Fpostupgrade` -- Not needed with enhanced orthogonal persistence\n- `(with migration = ...)` actor-attached migration syntax -- Use the mops-managed migration chain in `migrations\u002F`\n- Inline initializers on stable actor fields -- Initial values come from the migration chain (see `migrating-motoko-actors`)\n- Module function style for `self` parameters -- Don't write `List.add(list, item)` or `Map.get(map, key)`\n- Manual field-by-field record copying for immutable records -- Use record spread (`{ self with ... }`). For records with `var` fields, do not use record spread; mutate the `var` field directly or rebuild the record explicitly.\n- Single-file monolithic actors -- Use the multi-file architecture: types.mo, lib\u002F, mixins\u002F, main.mo\n- Stable state in a `mixin` block -- a bare `let`\u002F`var` is silently stable and traps at runtime (`IC0503`). Pass state in as a parameter and keep constants in a module\n- Any Motoko reserved keyword as a declared identifier -- Before writing, check parameter, variable, function, type, field, and label names against the full list in [references\u002Freserved-keywords.md](references\u002Freserved-keywords.md). `query` and `label` are reserved and must never be identifiers. Rename a colliding domain term instead of relying on its position or inferred meaning.\n- Type annotations on an inline `func` passed as a **call argument** -- write `xs.filter(func x = x > 1)`, not `xs.filter(func(x : Nat) : Bool { x > 1 })`. The call supplies the types. If a generic cannot be inferred, instantiate the call (`map\u003CIn, Out>`), never the lambda. This applies only in argument position — named declarations still carry full signatures. **One exception:** keep `: async ()` on an async callback (`func() : async () { ... }`) — on moc 1 it is what makes the body async, and removing it fails to compile\n\n**ALWAYS use:**\n\n- `mo:core` library version 2.6.0+ (compiler `moc` 1.11.2+)\n- Contextual dot notation -- `list.add(item)`, `map.get(key)`\n- An import of the key type's module in every file that operates on a `Map`\u002F`Set` -- the implicit `compare` is resolved from the imported module (`import Nat \"mo:core\u002FNat\"` for a `Map.Map\u003CNat, _>`), never from the type alone. A missing key-module import is the usual cause of M0230; a record or variant key needs its own module with a `compare` (see Implicit Parameters)\n- Null coalesce `??`, spaced on both sides, for unwrap-or-default and unwrap-or-trap (`opt ?? default`, `opt ?? Runtime.trap(...)`) -- prefer over a two-arm `switch` on `?T` (requires `moc >= 1.7.0`)\n- Plain `break` \u002F `continue` to exit or skip a loop iteration -- they work inside `for`, `while`, and `loop` just like in other languages\n- Enhanced orthogonal persistence (state persists without `stable` keyword)\n- Principled Motoko Architecture -- `types.mo` (types), `lib\u002F` (domain logic), `mixins\u002F` (API endpoints), `main.mo` (composition root, NO public methods)\n- **API reference for uncertain APIs**: Use [api-reference.md](references\u002Fapi-reference.md) to verify exact method signatures when you are about to use an unfamiliar `mo:core` API or when a compile diagnostic points at an API mismatch. It lists only non-deprecated APIs — a symbol that is not there should not be written. Do NOT guess API shapes — a targeted lookup of a symbol you are unsure about is always worth the step; skipping it to save steps ships hallucinated APIs and costs far more in compile repair.\n\n**When encountering compilation errors:** Re-check [api-reference.md](references\u002Fapi-reference.md) for exact method signatures.\n\n**Before changing actor state shape, introducing new stable fields, or upgrading canisters:** load `migrating-motoko-actors`. This guidance assumes the **mops-managed migration chain** — when a change requires a migration, it goes in the pending migration file, or a new one in `src\u002Fbackend\u002Fmigrations\u002F` if none is pending. Introducing stable state for the first time always needs one (no inline initializers); trivial stable-compatible upgrades do not. See the skill. If a migration or compatibility diagnostic still does not match what the source says, or a migration file cannot be written, load `troubleshooting-motoko-migrations`.\n\n## Toolchain (mops)\n\nAll configuration is in `mops.toml`. Load the `mops-cli` skill for `mops.toml` configuration, dependency management, and `mops check`\u002F`mops build` details.\n\n### Dependency management\n\n- Never hand-edit dependency entries in `mops.toml`, and never touch `mops.lock`; use the `mops` CLI so dependency metadata and the lockfile stay atomic. (`[toolchain]` has a CLI too: `mops toolchain use \u003Ctool> [version]`.)\n- Leave `[moc] args` alone. Compiler flags are a one-time project-setup concern, and many platforms own `mops.toml` and set them for you — do not inspect or change them while writing code. If you are setting up a project yourself, see [references\u002Fproject-setup.md](references\u002Fproject-setup.md).\n- `mops add \u003Cpkg>` installs and exact-pins a published package. Use `@x.y.z` for a specific version, `\u003Curl>[#ref]` for GitHub, `.\u002Fpath` for a local package, and `--dev` for development dependencies.\n- `mops add` accepts exactly one package name. To install several packages, chain one-package commands with `&&`; never run multiple `mops add` invocations in parallel — they race on `mops.toml` and `mops.lock`.\n- `mops update [pkg]` updates a package and rewrites its exact pin.\n- `mops sync` reconciles imports after bulk `.mo` changes by adding missing dependencies and removing unused ones.\n- `mops.lock` is rewritten only by `mops add`, `mops update`, `mops sync`, `mops install`, and related supported mops commands.\n- On a lock or integrity failure, run `mops install` — it regenerates a `mops.lock` that is missing, stale, or inconsistent with `mops.toml`. `mops verify` reports a file-hash mismatch it cannot repair; `mops cache clean` forces a verified re-download. Never `chmod`, remove, or text-edit `mops.lock`.\n\n### Check and build\n\n- **`mops install`** — Install dependencies and reconcile `mops.lock`, regenerating it when it is missing or no longer matches `mops.toml`.\n- **`mops check --fix`** (fast — use for iteration) — Reports compile errors and auto-fixes the style warnings, where the project has them enabled (dot-notation, redundant type instantiation, redundant implicit arguments). Follow this skill's rules whether or not `--fix` enforces them. Exit 0 = success. Error format: `file:startLine.startCol-endLine.endCol: severity [code], message`. Iterate on this until it passes.\n- **`mops build`** (slow — run ONCE at the end) — Produces the compiled `.wasm` and the candid interface file `.did`. Use only as final verification after `mops check --fix` passes; never put `mops build` inside the fix loop. The `.did` file drives generated client bindings — never edit it manually.\n\nIf `mops check --fix` fails: read stderr first. Do NOT call `moc` directly. Fix `.mo` source and rerun the check.\n\n### moc 1 and moc 2\n\n`[toolchain] moc` pins either major, and every example in this skill compiles with both. Keep to these forms whichever one the project pins:\n\n- Parenthesized heads: `if (c)`, `while (c)`, `for (x in xs.values())`, `switch (e)`. A bare branch after the condition is separated by a space: `if (c) -1 else 1`.\n- Parenthesized `case` patterns, every case ending in `;`: `case (#tag(p)) { ... };`.\n- A space on both sides of `??`.\n- A block body for an async function, never `= async { ... }`.\n- A bare `actor`, with no `persistent` or `stable` keyword.\n\nmoc 2 accepts shorter forms that moc 1 rejects — unparenthesized heads and patterns, cases without `;`, unannotated async callbacks — so do not write them. It also turns moc 1 warnings into errors (M0145, M0215, M0222, M0242, among others): treat every warning as an error.\n\n## Modern Motoko Features\n\n### Contextual Dot Notation\n\n**RULE:** When a function has a `self` parameter, ALWAYS use dot notation.\nDot notation is still type-specific: it only applies to APIs that the value's\nmodule actually defines — verify against [api-reference.md](references\u002Fapi-reference.md)\nrather than inferring JavaScript-style helpers. `.some(...)` and `.every(...)`\ndo not exist in Motoko; the `mo:core` names are `.any(...)` and `.all(...)`.\n\nThe module a dot call resolves against is the module that **defines** the\nfunction — usually the receiver's type's module (`map.get`, `list.add`), but\nsometimes a different one: `arr.values().toList()` resolves against `List` (the\ntarget), not the array's module. The import needed (if any) is the defining\nmodule's, not the receiver's.\n\n```motoko\nmap.get(key);\nlist.add(item);\narray.filter(func x = x > 0); \u002F\u002F CORRECT\nMap.get(map, key);\nList.add(list, item); \u002F\u002F WRONG (M0236)\n\n\u002F\u002F Chaining\nlet doubled = numbers.map(func x = x * 2).filter(func x = x > 10);\n\n```\n\nConversions are receiver calls too, but the `toX` functions are split across\nmodules: some are defined on the **source** module (`Nat8.toNat`), others on the\n**target** (`\"42\".toNat()` and `\"-5\".toInt()` are defined by `Nat` and `Int`,\nnot `Text`). So `Text`-receiver conversions need the target imported (`import\nNat \"mo:core\u002FNat\"`, `import Int \"mo:core\u002FInt\"`); without it, moc reports\nM0070\u002FM0072 and the call does not compile:\n\n```motoko project=dot-notation filepath=src\u002Fbackend\u002Fmain.mo\nimport Principal \"mo:core\u002FPrincipal\";\nimport Nat \"mo:core\u002FNat\";\nimport Text \"mo:core\u002FText\";\n\nfunc conversions(caller : Principal, myNat : Nat) {\n  ignore caller.toText(); \u002F\u002F CORRECT\n  ignore myNat.toText(); \u002F\u002F CORRECT\n  ignore \"42\".toNat(); \u002F\u002F CORRECT (defined by Nat, imported above)\n  ignore \"hello\".concat(\" world\"); \u002F\u002F CORRECT\n  ignore Principal.toText(caller); \u002F\u002F WRONG (M0236)\n  ignore Nat.toText(myNat); \u002F\u002F WRONG (M0236)\n};\n```\n\n**`equal` \u002F `compare` vs `==`.** Collections take `equal` and `compare` as implicit arguments, so those are the functions to write for your own records and variants. `==` is compiler-generated structural equality and exists only for **shared** types — one `var` field takes a record out of shared and `==` stops compiling (M0060) — so do not build record comparisons on it. Comparing primitives and shared fields directly with `==` is fine, and on `Nat`, `Int`, `Float`, and the sized int types it is the only form: those declare `equal(x, y)` without a `self` parameter, so `myNat.equal(other)` fails with M0070. Other receiver methods on those types (`myNat.toText()`) are fine.\n\nYour own records and variants get nothing derived — a record `compare` must be an explicit function, and custom variants need both `equal` and `compare` written out. See [references\u002Fequality.md](references\u002Fequality.md).\n\n### Mixins\n\nComposable actor services with granular state injection. Each mixin lives in its own file as a top-level `mixin` block:\n\n```motoko project=mixin filepath=src\u002Fbackend\u002Ftypes.mo\nmodule {\n  public type User = {\n    principal : Principal;\n    username : Text;\n  };\n};\n```\n\n```motoko project=mixin filepath=src\u002Fbackend\u002Fmixins\u002FAuth.mo\nimport List \"mo:core\u002FList\";\nimport Principal \"mo:core\u002FPrincipal\";\nimport Types \"..\u002Ftypes\";\n\nmixin (users : List.List\u003CTypes.User>) {\n  public shared ({ caller }) func register(username : Text) : async Bool {\n    users.add({ principal = caller; username });\n    true\n  };\n\n  public query func listUsers() : async [Types.User] {\n    users.toArray()\n  };\n};\n```\n\n```motoko project=mixin filepath=src\u002Fbackend\u002Fmain.mo\nimport List \"mo:core\u002FList\";\nimport Types \"types\";\nimport AuthMixin \"mixins\u002FAuth\";\n\nactor {\n  let users : List.List\u003CTypes.User>;\n  include AuthMixin(users);\n};\n```\n\n**Mixin Anti-Patterns — NEVER generate these:**\n\n```motoko\n\u002F\u002F WRONG — mixin is NOT a function inside a module; wrapping in module {} is invalid\nmodule {\n  public func createMixin(state : ...) : actor { ... } { \u002F\u002F M0001: unexpected token 'actor'\n    actor { public func foo() { ... }; };\n  };\n}\n\n\u002F\u002F WRONG — include does not support dot-access or method-call chains\ninclude TodosMixin.createMixin(state); \u002F\u002F M0001: unexpected token '.'\n\n\u002F\u002F WRONG — 'mixin' is a keyword, not a valid identifier inside a module block\nmodule {\n  public func mixin(state : ...) { ... }; \u002F\u002F M0001: unexpected token 'mixin'\n}\n```\n\nRules:\n- A mixin file contains a bare `mixin (params) { ... };` block at the **top level** — not inside `module {}`, not returned from a function.\n- `include` takes a bare name followed by arguments: `include MixinName(args)` — no dot-access, no chained calls.\n\n**No stable state in Mixins.** Every top-level `let`\u002F`var` in a `mixin` is implicitly **stable**. Only `transient` is ever allowed, but prefer putting static definitions (like literals) into modules instead!\n\n**Sharing state between mixins — pass it as a parameter.** To share state between two or more mixins, declare that state once as an actor field and pass that same binding to each `include`. Every mixin that gets it reads and writes the same value. A mixin can take several parameters, so it can receive shared state plus its own private state.\n\n```motoko\n\u002F\u002F types.mo:  public type GoogleState = { var connection : ?Conn; var config : ?Cfg };\nlet google : Types.GoogleState;          \u002F\u002F declared once; initialized in the migration function\nlet bookings : Map.Map\u003CNat, Booking>;    \u002F\u002F BookingsApi's own state\ninclude GoogleApi(google);               \u002F\u002F gets `google`\ninclude BookingsApi(google, bookings);   \u002F\u002F gets the SAME `google`, plus its own bookings\n```\n\nPass the same binding to each mixin. Never build a new record at the `include` — that gives each mixin its own separate copy, so one mixin's writes never reach the others:\n\n```motoko\ninclude GoogleApi({ var connection = google.connection });   \u002F\u002F WRONG: NEVER DO THIS!\n```\n\n### Null Coalesce (`??`)\n\nPrefer `??` over a two-arm `switch` that only unwraps an option or supplies a default \u002F trap. Requires `moc >= 1.7.0`.\n\n```motoko\n\u002F\u002F Default when absent\nlet name = optName ?? \"anonymous\";\n\n\u002F\u002F Fail-fast unwrap — null means a bug \u002F missing invariant\nlet user = users.find(func u = u.id == caller)\n  ?? Runtime.trap(\"User not found\");\n\n\u002F\u002F Nested options — chain instead of nested switches\nlet start = event.start.dateTime ?? event.start.date ?? \"\";\n\n\u002F\u002F RHS is lazy. A block needs `do`; a record literal needs parens:\nlet n = opt ?? do { let x = 1; x };\nlet rec = opt ?? ({ x = 0 });\n```\n\n**Use `switch` instead** when the `?v` arm transforms the value, runs side effects, or you are matching variants \u002F multiple cases — `??` only unwraps or substitutes.\n\n```motoko\n\u002F\u002F Keep switch: Some arm transforms \u002F branches on the inner value\nswitch (users.get(caller)) {\n  case (?u) { u.isAdmin };\n  case null { false };\n};\n\nswitch (result) {\n  case (#ok(value)) { value };\n  case (#err(e)) { Runtime.trap(e) };\n};\n```\n\nSee [references\u002Fcontrol-flow.md](references\u002Fcontrol-flow.md).\n\n### Implicit Parameters\n\n`Map` and `Set` operations take the comparison function as an **implicit** argument. `Map.empty()` itself takes no arguments — the comparator is resolved at the operations that need it (`add`, `get`, `remove`, …), not at construction.\n\nInference works by finding a `compare` in the module imported **for the key type**. So the import is what makes it work:\n\n```motoko\nimport Map \"mo:core\u002FMap\";\nimport Nat \"mo:core\u002FNat\"; \u002F\u002F this import is what supplies Nat.compare\n\nlet map = Map.empty\u003CNat, Text>();\nmap.add(5, \"hello\"); \u002F\u002F compare resolved from the imported Nat\n```\n\nWithout `import Nat`, the same code fails — the type is known, but there is no module to take `compare` from:\n\n```text\ntype error [M0230], Cannot determine implicit argument `compare` of type (Nat, Nat) -> Order\nnote: Did you mean to import mo:core\u002FInt or mo:core\u002FNat?\n```\n\nDo **not** pass the comparator explicitly when it can be inferred; that is M0237, which `mops check --fix` removes:\n\n```motoko\nlet ages = Map.empty\u003CText, Nat>();   \u002F\u002F Text.compare resolved at add, from the imported Text\nages.add(\"Alice\", 30);               \u002F\u002F CORRECT\nages.add(Text.compare, \"Alice\", 30); \u002F\u002F WRONG (M0237)\n```\n\nA custom key type works the same way — give its module a `compare` and it is inferred:\n\n```motoko\ntype Point = { x : Nat; y : Nat };\nmodule Point {\n  public func compare(a : Point, b : Point) : Order.Order { ... };\n};\nlet points = Map.empty\u003CPoint, Text>();\npoints.add({ x = 1; y = 2 }, \"A\"); \u002F\u002F Point.compare inferred\n```\n\nType instantiation on `empty()` follows the usual rule — needed only when the binding is unannotated. `let m : Map.Map\u003CNat, Text> = Map.empty();` infers it, and `Map.empty\u003CNat, Text>()` there would be M0223.\n\n## Architecture Pattern\n\n```text\nbackend\u002F\n├── types.mo         # Central schema, state definitions\n├── lib\u002F             # Domain logic (stateless modules with self pattern)\n├── mixins\u002F          # Service layer (stateless, state injected via parameters)\n├── types\u002F           # Type definitions for mixins and lib modules\n├── migrations\u002F      # Mops-managed migration chain. See migrating-motoko-actors.\n│                    #   Each file is YYYYMMDD_HHMMSS.mo (a UTC timestamp, not a feature name); applied files are FROZEN.\n└── main.mo          # Composition root (state owner, NO public methods)\n```\n\n## Import Path Conventions\n\nPaths are **relative to the importing file**. No `.mo` extension, no `\u002Flib.mo` suffix.\n\n```motoko\n\u002F\u002F From main.mo\nimport Types \"types\";\nimport AuthMixin \"mixins\u002FAuth\";\nimport UserLib \"lib\u002FUser\";\n\u002F\u002F From lib\u002F*.mo or mixins\u002F*.mo\nimport Types \"..\u002Ftypes\";\nimport UserLib \"..\u002Flib\u002FUser\";\n\u002F\u002F Core library — always absolute\nimport Map \"mo:core\u002FMap\";\n\n\u002F\u002F WRONG — these all cause M0009\nimport Types \"types.mo\";\nimport Types \"types\u002Flib.mo\";\nimport Types \"backend\u002Ftypes\";\n\n```\n\n**Migration files** (`migrations\u002F*.mo`) must be self-contained — they may only import from `mo:core\u002F...`, never from `..\u002Ftypes` or any project module. See `migrating-motoko-actors` for the full rules.\n\n### The Actor Must Come Last\n\nImports and `type`\u002F`let` declarations may precede the actor. Nothing may follow it — the actor is the file's result, so a trailing declaration makes the actor a non-`()` statement and fails with M0096 (`expression of type actor {...} cannot produce expected type ()`). Prefer keeping shared types in `types.mo` regardless.\n\n### Import Hygiene\n\nAdd an import only to the file that uses the imported identifier. `Time.now()` usually belongs in a domain `lib\u002F*.mo` implementation file, so `import Time \"mo:core\u002FTime\";` belongs in that file, not `main.mo`, unless `main.mo` itself calls `Time.now()`. Every capitalized namespace call must have a matching import in the same file: if a mixin calls `TodosLib.listTodos(...)`, the file must import `TodosLib \"..\u002Flib\u002Ftodos\"` (or use the alias it actually imported). Treat unused-import warnings as failures: remove stale `Debug`, `Time`, or helper-module imports before finishing.\n\n## Query Functions\n\n`query` marks a public function as a read-only call: it executes fast and unreplicated, and **every state change it makes is silently discarded when the call completes** — a write inside a query compiles, runs, and vanishes with no error or warning. Declare pure reads as `query func`; any function that must persist a change is a plain update func (no `query`). `public query func` is shorthand for `public shared query func`; both forms take `({ caller })` the same way.\n\n```motoko\npublic query func getPosts() : async [Types.PostView] { ... };          \u002F\u002F read: query\npublic shared ({ caller }) func addPost(t : Text) : async Nat { ... };  \u002F\u002F persists: update\npublic query func resetAll() : async () { posts.clear() };              \u002F\u002F WRONG: compiles, but the clear is discarded\n```\n\n### When await is allowed\n\nA plain `query func` cannot call any other canister function, whether that callee is a query or an update. Writing `await someCall()` inside one fails with a paired `M0038` (misplaced await) + `M0188` (send capability required: \"cannot call a `shared` function from a `query` function\"), always on the same statement. Pick the function kind by what the body must call:\n\n| Body must call                          | Declare                                 | Can `await`                              |\n| --------------------------------------- | --------------------------------------- | ---------------------------------------- |\n| another canister's `query`\u002F`composite query` | `public shared composite query func` | those query callees                     |\n| an update (`shared` func) or oneway     | a normal `public shared func`           | that update                              |\n| nothing across canisters                | `public shared query func`              | nothing                                  |\n\nA `composite query` is a read-only function that can `await` other canisters' queries. Loop over callees and `await` each:\n\n```motoko\npublic shared composite query func sum(counters : [Counter]) : async Nat {\n  var total = 0;\n  for (counter in counters.values()) {\n    total += await counter.peek();\n  };\n  total\n};\n```\n\nA `composite query` can call `query` and `composite query` callees but not updates or other `shared` functions; awaiting an update there is `M0187` (\"send capability required ... only calls to `query` and `composite query` functions are allowed\"). If the body must `await` an update, no flavor of query works — make it an update func.\n\nA composite query can only be initiated as an ingress call, e.g. from a frontend — calling one from an update or oneway func is `M0186`, from a plain `query func` `M0188`. Within the call tree it composes: it may call other canisters' `query`\u002F`composite query` functions.\n\n## Shared Types\n\nPublic functions accept\u002Freturn only **shared types** (serializable):\n\n- Shared: `Nat`, `Int`, `Text`, `Bool`, `Principal`, `Blob`, `Float`, `[T]`, `?T`, records, variants\n- **Not shared**: Functions, `var` fields, objects, `Map`, `Set`, `List`, `Queue`, `Stack`\n\nIf internal state uses mutable containers, define a separate immutable public type for the API boundary:\n\n```motoko\npublic type PostInternal = { id : Nat; likedBy : Set.Set\u003CPrincipal> }; \u002F\u002F internal\npublic type Post = { id : Nat; likedBy : [Principal] }; \u002F\u002F shared\n\npublic func toPublic(self : Types.PostInternal) : Types.Post {\n  { self with likedBy = self.likedBy.toArray() };\n};\n\n```\n\n## Collections\n\nFor full API signatures, read [api-reference.md](references\u002Fapi-reference.md).\n\n```motoko\nimport Map \"mo:core\u002FMap\";\nimport List \"mo:core\u002FList\";\nimport Queue \"mo:core\u002FQueue\";\nimport Stack \"mo:core\u002FStack\";\nimport Array \"mo:core\u002FArray\";\nimport Set \"mo:core\u002FSet\";\n\n```\n\n**Map** (B-tree, O(log n)): `Map.empty\u003CK, V>()`, `.add(k, v)`, `.get(k) → ?V`, `.remove(k)`, `.entries()`\n**List** (growable array, O(1) access): `List.empty\u003CT>()`, `.add(item)`, `.get(i) → ?T`, `.at(i) → T` (traps on OOB)\n**Queue** (FIFO): `Queue.empty\u003CT>()`, `.pushBack(item)`, `.popFront() → ?T`\n**Stack** (LIFO): `Stack.empty\u003CT>()`, `.push(item)`, `.pop() → ?T`\n**Array**: `[var 0, 0, 0]` (mutable), `[1, 2, 3]` (immutable)\n**Set** (B-tree, O(log n)): `Set.empty\u003CT>()`, `.add(item)`, `.contains(item)`, `.remove(item)`\n\n**Warning**: Never call `list.add()` inside a `retain` callback. Use `mapInPlace` to update items in place.\n\n```motoko\ntodos.mapInPlace(\n  func(todo) {\n    if (todo.id == targetId) { { todo with completed = not todo.completed } } else {\n      todo;\n    };\n  }\n);\n\n```\n\n**Important**: Always use opaque type aliases (`List.List\u003CT>`, `Map.Map\u003CK, V>`, `Set.Set\u003CT>`) in type declarations. Never use raw internal structure or `.filter`, `.map()` won't resolve (M0072).\n\nWhen a domain helper receives a core collection, type the parameter as the concrete opaque collection type (e.g. `todos : List.List\u003CTypes.Todo>`) and import that module in the helper file. Do not use structural method-record parameters such as `{ add : (Types.Todo) -> (); toArray : () -> [Types.Todo] }` for core collection values. A compiler error saying `List.List\u003CT>` cannot produce an expected type with fields like `add`, `toArray`, or `clear` means the helper signature is wrong; fix the signature to `List.List\u003CT>` and keep the collection — do not switch to an invented module such as `mo:core\u002FBuffer`, and do not regress to module-function calls like `List.toArray(todos)` or `List.add(todos, todo)`.\n\n### Arrays vs Core Collections\n\nCore collections (`List.List\u003CT>`, `Map.Map\u003CK, V>`, `Set.Set\u003CT>`, `Queue.Queue\u003CT>`, `Stack.Stack\u003CT>`) have receiver helpers because their modules define self-parameter APIs. A value of type `[T]` or `[var T]` is an array snapshot, not a `List.List\u003CT>`.\n\n- After `let snapshot = list.toArray()`, only use array operations whose exact signatures are shown here or verified in the API reference — with receiver dot notation: `snapshot.filter(pred)`, `snapshot.map(mapper)`, `snapshot.sort(comparator)`, `snapshot.concat([item])`. Do not call those as module functions such as `Array.filter\u003CT>(snapshot, pred)` or `Array.append(snapshot, [item])`.\n- If a value is an array (`[T]`) or came from `.toArray()` \u002F `.filter(...)`, then `.map(...)` already returns an array; do not append `.toArray()` to that array-map result. (`List.List\u003CT>.map(...)` returns a `List`, so it still needs `.toArray()` when the caller expects an array.)\n- Arrays DO support predicate search: `.find(predicate) : ?T`, `.findIndex(predicate) : ?Nat`, `.any(predicate)`, and `.all(predicate)` are all in `mo:core\u002FArray` (see the API reference). The JS spellings `.some(...)` \u002F `.every(...)` do not exist — use `.any` \u002F `.all`.\n- Arrays DO have `.contains(element)` (`equal` is implicit, so pass only the element). Reach for `.indexOf(element)` when you need the position — it returns `?Nat`, so keep the option and use it; and for `.any(pred)` when membership is decided by a predicate rather than equality:\n\n```motoko\n\u002F\u002F Overlap between two tag arrays\nlet matched = leftTags.any(func left = rightTags.any(func right = left == right));\n```\n\n- Do not copy a collection just to search it: prefer `templates.find(func ...)` on the original `List.List\u003CT>` over `templates.toArray().find(func ...)` — the intermediate array is a wasted copy.\n- Use `.values()` when iterating array snapshots. Do not write `.vals()` in new Motoko code.\n\n**CRUD List patterns:** Do not invent helpers on `List`. There is no `filterInPlace`, and record spread fails on records with `var` fields.\n\n**An inline `func` passed as a call argument takes no type annotations.** The call already fixes the parameter and result types, so annotating repeats them and lets them drift as the code changes. Use the expression form `func x = \u003Cexpr>`:\n\n```motoko\ntodos.find(func todo = todo.id == targetId);            \u002F\u002F CORRECT\ntodos.find(func(todo : Types.Todo) : Bool { todo.id == targetId }); \u002F\u002F WRONG: annotated\n```\n\nThis is about **argument position only**. A named declaration still carries its full signature, and a lambda bound on its own has nothing to infer from — `let f = func x = x > 1` fails with M0103 (`cannot infer type of variable`).\n\n```motoko\npublic func toView(t : Types.Todo) : Types.TodoView { ... }; \u002F\u002F annotated, as always\n```\n\nWhen the types are not obvious to a reader, or a generic cannot be inferred, say it **on the call** rather than on the lambda — it reads better and keeps one source of truth:\n\n```motoko\nphotos.map(func p = { id = p.id; url = p.url.toText() }); \u002F\u002F inferred — preferred\nphotos.map\u003CPhotoInternal, Photo>(func p = { ... });       \u002F\u002F when M0098 demands it\n```\n\nAdd `\u003CIn, Out>` only when the compiler actually reports M0098; adding it when inference already succeeded is M0223 (redundant type instantiation).\n\nThe one exception is a callback that must return `async`. There `: async ()` is load-bearing on moc 1 — it is what makes the body async, and there is no unannotated form (`func() = async { ... }` does not work either). Without it moc 1 infers `() -> ()` and the call fails with M0096. moc 2 infers the async callback, but keep the annotation so the code builds on both:\n\n```motoko\nTimer.recurringTimer\u003Csystem>(#seconds(3600), func() : async () { cleanup() });\n```\n\n```motoko\n\u002F\u002F Toggle a mutable field by finding the record and mutating the var field.\nswitch (todos.find(func todo = todo.id == targetId)) {\n  case (?todo) {\n    todo.completed := not todo.completed;\n    ?toView(todo);\n  };\n  case null { null };\n};\n\n\u002F\u002F Delete from List by rebuilding from an array snapshot.\nvar removed = false;\nlet snapshot = todos.toArray();\ntodos.clear();\nfor (todo in snapshot.values()) {\n  if (todo.id == targetId) {\n    removed := true;\n  } else {\n    todos.add(todo);\n  };\n};\nremoved;\n\n\u002F\u002F To change an immutable field on a record that also has var fields, rebuild it.\nlet updated : Types.Todo = {\n  id = todo.id;\n  text = newText;\n  var completed = todo.completed;\n  createdAt = todo.createdAt;\n};\nlet snapshot = todos.toArray();\ntodos.clear();\nfor (todo in snapshot.values()) {\n  if (todo.id == targetId) {\n    todos.add(updated);\n  } else {\n    todos.add(todo);\n  };\n};\n```\n\nFor delete-style operations that return whether a record was removed, prefer a `var removed = false` flag while rebuilding from the array snapshot. Do not call `todos.size()` unless the parameter type explicitly exposes `size()`, such as `List.List\u003CT>`.\n\n### Iteration and Chaining\n\n```motoko\nlet doubled = numbers.map(func x = x * 2).filter(func x = x > 10);\nlet sum = scores.filter(func s = s > 15).foldLeft(0, func(acc, s) = acc + s);\nswitch (numbers.find(func n = n > 5)) {\n  case (?found) { \u002F* use *\u002F };\n  case null {};\n};\n\n```\n\n### Sorting Arrays\n\n`Array`\u002Farray receiver helpers such as `.sort(...)` return a value. Do not use them as standalone sequenced statements; Motoko rejects sequencing a non-`()` expression.\n\n```motoko\nlet all = todos.toArray();\nlet sorted = all.sort(func (a, b) =\n  if (a.createdAt > b.createdAt) { #less }\n  else if (a.createdAt \u003C b.createdAt) { #greater }\n  else { #equal }\n);\nsorted.map(func todo = {\n  id = todo.id; text = todo.text; completed = todo.completed; createdAt = todo.createdAt\n});\n\n\u002F\u002F WRONG: `.sort(...)` returns an array, so this is not a valid statement.\nall.sort(func (a, b) = Int.compare(b.createdAt, a.createdAt));\nall.map(func todo = { ... });\n```\n\n### `contains` vs `find`\n\n- **`contains(element)`** -- equality check on `List`\u002F`Set`\u002Fetc. Does NOT take a predicate.\n- **`find(predicate)`** -- predicate search on `List.List\u003CT>` and `[T]`. Returns `?T`.\n- Both `List.List\u003CT>` and `[T]` have `contains`. Use `.any(func x = ...)` when the test is a predicate, not equality.\n\n```motoko\nnumbers.contains(3); \u002F\u002F equal inferred from the imported Nat\nfriends.contains(p); \u002F\u002F likewise from Principal — passing Principal.equal here is M0237\ntodos.find(func todo = todo.id == targetId); \u002F\u002F returns ?Todo\n\u002F\u002F WRONG: friends.contains(func(f) { f == p })  → M0096\u002FM0103\n\n```\n\n### Text Search and Case Folding\n\nMotoko `Text` uses contextual receiver methods for case folding and substring checks. Do not use JavaScript spellings such as `.toLowerCase()` or `.toLowercase()`, and do not call `Text.contains(...)` for ordinary substring search.\n\n```motoko\nlet term = searchTerm.toLower();\ntextValue.toLower().contains(#text term)\n```\n\n### Joining Text\n\n`join` takes the **iterator as its receiver and the separator as its argument** — easy to invert. Use dot notation; the module form is an M0236 violation that `mops check --fix` rewrites for you.\n\n```motoko\n[\"a\", \"b\"].values().join(\", \");     \u002F\u002F CORRECT → \"a, b\"\nText.join([\"a\", \"b\"].values(), \", \"); \u002F\u002F WRONG (M0236)\n```\n\nNote the receiver is an **iterator**, not an array: call `.values()` on an array first.\n\n### Variant Tag Arguments\n\nAlways parenthesize a variant tag's argument. A tag binds only to the atom immediately after it, tighter than any operator, so an unparenthesized argument silently loses everything past the first term:\n\n```motoko\n#tag(n + 1) \u002F\u002F CORRECT\n#tag n + 1  \u002F\u002F WRONG: parses as (#tag n) + 1 → M0060, operator is not defined for operand types\n```\n\n### Explicit Type Instantiation\n\nLet inference work first. With unannotated lambdas the compiler resolves `.map()` to a different type on its own, so write the plain call:\n\n```motoko\nlet photos = internalPhotos.map(\n  func p = { id = p.id; url = p.url; uploadedBy = p.uploadedBy.toText() }\n);\n```\n\nAdd explicit type parameters **only** when the compiler reports M0098 (`no best choice for type parameter`):\n\n```motoko\nlet photos = internalPhotos.map\u003CPhotoInternal, Photo>(func p = { ... });\n```\n\nAdding them when inference already succeeded is a warning of its own — M0223, redundant type instantiation — which `mops check --fix` strips. Annotating the lambda instead of instantiating the call is always wrong.\n\n### Function Literals as Arguments\n\nDo NOT put a semicolon after a function body passed as an argument:\n\n```motoko\nlist.filter(func(item) { item.id != targetId }) \u002F\u002F CORRECT\nlist.filter(func(item) { item.id != targetId; }) \u002F\u002F WRONG: trailing semicolon makes the block return `()`\n\n```\n\nDo not inline imperative statement blocks as boolean operands:\n\n```motoko\n\u002F\u002F WRONG: parser can treat the block after `or` as an invalid expression shape.\nlet matches = titleMatches or {\n  var found = false;\n  for (tag in tags.values()) {\n    if (tag == q) { found := true };\n  };\n  found\n};\n\n\u002F\u002F CORRECT: compute the loop result before the final boolean expression.\nvar tagMatches = false;\nfor (tag in tags.values()) {\n  if (tag == q) { tagMatches := true };\n};\nlet matches = titleMatches or tagMatches;\n```\n\nEvery `switch` case must be separated with a semicolon before the next `case`, even in compact one-line switches. moc 2 makes the `;` optional, but moc 1 rejects a case without it:\n\n```motoko\nswitch (pricing) { case (#free) { true }; case (#paid(_)) { false }; } \u002F\u002F CORRECT\nswitch (pricing) { case (#free) { true } case (#paid(_)) { false } } \u002F\u002F WRONG: moc 1 syntax error\n```\n\n### Declaration Terminators\n\nTop-level and nested function declarations inside `module`, `actor`, and `mixin` blocks must end with `;`. A missing `};` after a function commonly surfaces as a syntax error near the next declaration, e.g. `unexpected token 'public'`.\n\n### Local Mutability\n\nUse `let` for local bindings unless the variable is reassigned with `:=`. Never use `var` for a local binding only because the value it references is mutable. Mutating an object through methods such as adding to a collection does not require the binding itself to be `var`; use `let` for collection builders and other accumulator objects unless the binding is later reassigned.\n\n### Safe Nat Arithmetic\n\nAvoid `Nat` subtraction unless the compiler can prove the result is non-negative at the operation itself. `a - b` traps when `b > a`, and the compiler can still warn when safety depends on a previous branch. Prefer bounds checks, bounded addition, loop counters, or helper branches that do not subtract one `Nat` from another.\n\n## Option Handling\n\n**Prefer `??` for unwrap-or-default and unwrap-or-trap.** Do not write a nested `switch` solely to peel `?T`.\n\n```motoko\n\u002F\u002F Unwrap with trap when null means something is wrong\nlet user = users.find(func u = u.id == caller)\n  ?? Runtime.trap(\"User not found\");\n\n\u002F\u002F Default when absence is fine\nlet caption = optLabel ?? \"(untitled)\"; \u002F\u002F not `label` — reserved word\n\n\u002F\u002F Only return ?T when absence is a normal, expected outcome\npublic query func findUserByName(name : Text) : async ?User {\n  users.find(func u = u.name == name);\n};\n\n\u002F\u002F Keep switch when the Some arm maps \u002F mutates \u002F has side effects\nswitch (todos.find(func todo = todo.id == targetId)) {\n  case (?todo) {\n    todo.completed := not todo.completed;\n    ?toView(todo);\n  };\n  case null { null };\n};\n```\n\n## Error Handling: `Result`\n\nUse `mo:core\u002FResult` to return a failure a caller can act on. `Result\u003COk, Err>` is `{ #ok : Ok; #err : Err }`, so it crosses the API boundary as Candid whenever `Ok` and `Err` are themselves shared, which for `Ok` usually means the view type, not the internal record.\n\n**Pick the return type by what the failure means:**\n\n| The call can fail because…                          | Return                 |\n| --------------------------------------------------- | ---------------------- |\n| the caller did something the caller can fix         | `Result\u003COk, Err>`      |\n| the thing simply is not there, and that is normal   | `?T`                   |\n| an invariant this code is responsible for is broken | trap (`Runtime.trap`)  |\n\n```motoko\nimport Result \"mo:core\u002FResult\";\n\npublic type BookingError = {\n  #slotTaken : { until : Time.Time };\n  #notAuthorized;\n  #unknownRoom : Nat;\n};\n\npublic shared ({ caller }) func book(roomId : Nat, at : Time.Time) : async Result.Result\u003CBooking, BookingError> {\n  \u002F\u002F ...\n};\n```\n\n**Never launder an error into `Text`.** `Result\u003CBooking, Text>` forces every caller — including the frontend — to string-match to tell \"slot taken\" from \"not authorized\". Make `Err` a variant; put the data each failure needs inside its own tag. A `Text` payload is fine *inside* a tag when it is a message for a human, not a discriminator.\n\n**Do not trap on caller error.** A trap rolls back the message's uncommitted state changes and reaches the frontend as an opaque reject — the caller cannot branch on it and the user gets no actionable message. Reserve traps for \"this cannot happen\" (see `?? Runtime.trap(...)` above).\n\n**Chain, do not nest.** `mapOk`, `mapErr`, and `chain` take `self`, so they are dot notation like every other self-parameter API and a pipeline stays flat. `Result.fromOption` has no `self` — it is the module-call bridge from `?T` at the edge where absence becomes a caller-visible error.\n\n```motoko project=result-chain filepath=src\u002Fbackend\u002Fmain.mo\nimport Result \"mo:core\u002FResult\";\nimport Map \"mo:core\u002FMap\";\nimport Nat \"mo:core\u002FNat\";\n\nactor {\n  type Room = { id : Nat; name : Text };\n  type RoomView = { name : Text };\n  type BookingError = { #unknownRoom : Nat; #notAuthorized };\n\n  let rooms : Map.Map\u003CNat, Room>;\n\n  func toView(room : Room) : RoomView = { name = room.name };\n  func reserve(room : Room) : Result.Result\u003CRoom, BookingError> = #ok(room);\n\n  public shared ({ caller }) func book(roomId : Nat) : async Result.Result\u003CRoomView, BookingError> {\n    Result.fromOption(rooms.get(roomId), #unknownRoom(roomId))\n      .chain(func room = reserve(room))\n      .mapOk(toView);\n  };\n};\n```\n\nUse `switch` on `#ok` \u002F `#err` when the arms do different work; do not write `isOk`\u002F`isErr` followed by an unwrap — that discards the payload the type was carrying.\n\n## Error Handling: `try` \u002F `catch`\n\n`try` catches a reject: a `throw`, or an `await` \u002F `await*` whose call fails, such as a call to another canister, or a library call that throws. Whether and when a call throws is part of its API: check the package's own skill. It cannot catch a trap. A trap ends the message and rolls back the state changes made since the last commit point, which is the last `await` (an `await*` commits only if its body awaits). A trap in the callee's own message (another canister, or an `async` function) is different: it reaches the caller as a reject. An `async*` callee runs in the caller's message, so its trap cannot be caught. Code with no `await` and no `throw` needs no `try`.\n\nA reject rolls nothing back. State the function changed before the failing call stays changed, and trapping in the `catch` arm is no reliable way to undo it: once the call has suspended, that state is committed. Undoing it is the most common reason to catch.\n\n**Read the callee's return type first.** A callee that returns `Result` or `?T` reports failure in its value and does not throw for it. Switch on the value. `try { ignore await f() } catch _ {}` drops the real `#err` and catches nothing it can act on.\n\n**Catch only when the `catch` arm does work that a propagated reject cannot:**\n\n| Need                                                  | `catch` arm                                       |\n| ----------------------------------------------------- | ------------------------------------------------- |\n| Undo state changed before the `await`                 | Remove the reservation, mark the job failed       |\n| Give the caller a failure it can act on               | `return #err(...)` with a variant tag             |\n| Recover                                               | Retry, or fall back to another source             |\n| Keep a loop or background job going past one failure  | Skip the item and continue                        |\n\nOtherwise, let the reject propagate. An empty `catch _ {}` belongs only around a side effect that nothing depends on. A `catch` arm that handles only some errors rethrows the rest with `throw e`, which keeps the original error. Trapping there instead ends the message: nothing in it can catch the trap, and a caller in another message gets an opaque reject in place of the original error.\n\n```motoko project=try-catch filepath=src\u002Fbackend\u002Fmain.mo\nimport Error \"mo:core\u002FError\";\nimport Map \"mo:core\u002FMap\";\nimport Nat \"mo:core\u002FNat\";\nimport Result \"mo:core\u002FResult\";\n\nactor {\n  type Quote = { price : Nat };\n  type HoldError = { #taken; #quoteFailed : Text };\n\n  let holds : Map.Map\u003CNat, Principal>;\n\n  \u002F\u002F Stands in for any call that can reject.\n  func fetchQuote(seat : Nat) : async* Quote {\n    if (seat == 0) throw Error.reject(\"HTTP 503\");\n    { price = 100 };\n  };\n\n  public shared ({ caller }) func hold(seat : Nat) : async Result.Result\u003CQuote, HoldError> {\n    if (holds.containsKey(seat)) return #err(#taken);\n    holds.add(seat, caller);\n    try {\n      #ok(await* fetchQuote(seat));\n    } catch e {\n      \u002F\u002F A reject keeps the hold, so release the seat here.\n      holds.remove(seat);\n      #err(#quoteFailed(e.message()));\n    };\n  };\n};\n```\n\n## Common Patterns\n\n### Module with Self Pattern\n\n```motoko\n\u002F\u002F lib\u002FUser.mo\nmodule {\n  public type User = Types.User;\n  public func new(id : Principal, name : Text) : User {\n    { id; var name; var isActive = true };\n  };\n  public func ban(self : User) { self.isActive := false };\n};\n\u002F\u002F Usage: user.ban(); -- dot notation!\n\n```\n\n### Record Spread with `with`\n\n**RULE:** Use record spread for immutable records. Never use record spread on a record type that contains `var` fields: moc 1 rejects it with `base has non-aliasable var field` (M0179), and moc 2 copies the `var` fields into new cells, so mutating the result never reaches the original.\n\n```motoko\n{ self with newField = \"\" }; \u002F\u002F CORRECT for immutable records\n\n\u002F\u002F CORRECT for a record type containing var fields:\nlet updated : Types.Todo = {\n  id = todo.id;\n  text = newText;\n  var completed = todo.completed;\n  createdAt = todo.createdAt;\n};\n\n{ todo with text = newText }; \u002F\u002F WRONG if Todo contains any var field\n\n```\n\n### State Definition\n\nEntity types live in `types.mo`. State fields as direct actor bindings — no `AppState` wrapper.\n\nStable actor fields are declared with **types only — no initializers** (initial values come from the migration chain). Transient fields use initializers as usual.\n\n```motoko\n\u002F\u002F types.mo\nmodule {\n  public type User = {\n    id : Principal;\n    var username : Text;\n    var isActive : Bool;\n  };\n};\n```\n\n```motoko\n\u002F\u002F main.mo\nactor {\n  let users : List.List\u003CTypes.User>;\n  let state : { var nextPostId : Nat };\n  include AuthMixin(users);\n};\n\n```\n\n### Mutable State for Mixins\n\nNever declare `var` actor-fields (e.g. `var nextPostId : Nat`) you intend to share with mixins — `var` parameters are passed by value, so the mixin's mutations don't propagate back. Wrap mutables in a record and pass the record; records are shared by reference. In the actor, declare the record type-only (`let state : { var nextPostId : Nat };`) — its initial value (e.g. `{ var nextPostId = 0 }`) comes from the migration chain, like every stable field.\n\nPreserve the exact field names on shared mutable state records across actor, mixin, and helper modules. If the actor declares `let state : { var nextId : Nat }` and the mixin receives `state`, helper parameters must accept `{ var nextId : Nat }` and update `state.nextId`. Do not rename the field to `val` or `counter` in helper signatures, and do not create wrapper copies like `{ var val = state.nextId }`; the copy mutates only itself and leaves actor state unchanged.\n\n### Transient State & Static\u002FModule Fields\n\nEnhanced orthogonal persistence makes every top-level `let`\u002F`var` in an actor or mixin **stable** (persisted across upgrades) by default — there is no `stable` keyword. Prefix a binding with `transient` to keep it OUT of stable storage; it is re-initialized on every (re)start instead of being persisted. Use it for anything that isn't durable state — caches, capability handles, and constants.\n\n**Constants** — Motoko has no `const`, and a bare `let X = ...` in an actor or mixin is stable state. Put a fixed value in a **module** when its right-hand side is a **static** expression (namespaced, reusable, never state); otherwise keep it as `transient let` in the actor\u002Fmixin:\n\n```motoko\ntransient let admin = Principal.fromText(\"...\"); \u002F\u002F non-static (a call) — can't be a module `let`\ntransient let cache = Map.empty\u003CText, User>();   \u002F\u002F derived; rebuilt after each upgrade\n```\n\n**Static** (what a module `let` field allows) = literals, variant tags (`#x`), options (`?x`), tuples, immutable arrays and records, function values, and imported\u002Fvariable names — plus `.field` projection over those. **Non-static** = function calls, operators (`+`, `==`, `#`), control flow (`if`\u002F`switch`\u002Floops), and array indexing (`a[i]`).\n\n## Numeric Conversion Hygiene\n\nTreat deprecation warnings as failures. **Every conversion is spelled `to`, on the source value** — never a `Module.fromX` call, and never a chain through the sized numeric modules. A conversion is one receiver call:\n\n```motoko\nimport Nat \"mo:core\u002FNat\";\n\nlet average = sum.toFloat() \u002F count.toFloat(); \u002F\u002F Nat.toFloat\n```\n\n| Instead of                | write             |\n| ------------------------- | ----------------- |\n| `Float.fromInt(i)`        | `i.toFloat()`     |\n| `Float.fromInt64(i)`      | `i.toFloat()`     |\n| `Nat.fromNat64(n)`        | `n.toNat()`       |\n| `Int.fromNat(n)`          | `n.toInt()`       |\n| `Nat64.fromNat(n)`        | `n.toNat64()`     |\n| `Blob.fromArray(bytes)`   | `bytes.toBlob()`  |\n| `Iter.fromArray(a)`       | `a.values()`      |\n\nA conversion that needs several hops is a sign the wrong function was picked: verify the exact `mo:core` signature in [api-reference.md](references\u002Fapi-reference.md), which lists only non-deprecated APIs.\n\n## Security and Authorization\n\nEvery public update function MUST verify the caller via `{caller}` destructuring. Enforce authorization on the backend — never trust client-side checks.\n\nAttaching cycles to an inter-canister call (`await (with cycles = ...) \u003Ccall>`) hands them to the callee, so treat any endpoint that can trigger one as spend authority: gate it on the caller, bound the amount, and never let an unauthenticated path reach it. Some platforms forbid outbound cycles entirely — follow the hosting platform's own guidance where it applies.\n\n## Common Compile Error Patterns\n\n| Error pattern                                          | Cause                        | Fix                                         |\n| ------------------------------------------------------ | ---------------------------- | ------------------------------------------- |\n| `field append does not exist`                          | Array.append removed         | receiver `.concat(...)`                     |\n| `field put does not exist`                             | Map.put renamed              | `.add()`                                    |\n| `field delete is deprecated`                           | Map.delete renamed           | `.remove()`                                 |\n| `field toLowerCase does not exist`                     | JS Text API spelling         | `.toLower()`                                |\n| `field toLowercase does not exist`                     | JS Text API spelling         | `.toLower()`                                |\n| `You can use the dot notation ... contains`            | Wrong Text contains shape    | `text.toLower().contains(#text term)`       |\n| `operator may trap for inferred type Nat`              | Potentially unsafe Nat math  | Avoid `Nat` subtraction; use bounds\u002Floops   |\n| `Int cannot produce expected type Nat`                 | Int\u002FNat mismatch             | `.toNat()`                                  |\n| `field fromX is deprecated`                            | Deprecated `fromX` conversion | The `toX` counterpart on the source value: `n.toFloat()`, `bytes.toBlob()` |\n| `syntax error, unexpected token '.'`                   | Missing parens               | `#text (searchTerm.toLower())`              |\n| `syntax error, unexpected token ','`                   | Missing parens in for        | `for ((key, value) in map.entries())`       |\n| `Compatibility error [M0170]`                          | Missing migration            | Load `migrating-motoko-actors`            |\n| `M0250` initialized stable field                       | Initializer on a stable actor field | Declare it type-only; move the value into the migration's `NewActor` |\n| `M0254` \u002F `M0267` initial actor requires field         | Stable field no migration supplies | Add it to the pending migration's `NewActor` |\n| `M0255` stable signature downgrade                     | Chain or migrations config removed | Restore it — enhanced migration is one-way; load `troubleshooting-motoko-migrations` |\n| `shared function has non-shared parameter\u002Freturn type` | Mutable type in API          | Return `[T]` not `List\u003CT>`, no `var` fields |\n| `send capability required`                             | Async in non-async (`async*`\u002Flocal non-shared target) | Add `\u003Csystem>` capability                   |\n| M0038 misplaced await + M0188 send capability (paired) | `await \u003Ccall>` inside a plain `query func` | Make it a `composite query func` (queries) or a plain update func (updates) |\n| `M0187` send capability in a composite query           | calling\u002Fawaiting an update from a `composite query func` | Make it a plain update func                |\n| `M0186` composite send capability required             | calling a `composite query func` from a non-composite func | Only ingress calls initiate composite queries; call it from the frontend, or make the callee a plain `query` |\n| `unexpected token '\u003Cname>'` (`M0274` on moc 2) at an identifier declaration | Reserved word used as an identifier | Rename it consistently across its contract and callers; see [references\u002Freserved-keywords.md](references\u002Freserved-keywords.md) |\n| `unexpected token 'public'` after a function           | Missing declaration `;`      | End function declarations with `};`         |\n| `M0219` \u002F `M0220` actor should be declared `persistent` | moc 1 without `--default-persistent-actors` | See [references\u002Fproject-setup.md](references\u002Fproject-setup.md) |\n| `M0217` redundant `persistent` keyword                 | Actors are already persistent (moc 2, or the moc 1 flag) | Remove `persistent`                  |\n| `M0218` redundant `stable` keyword                     | `stable` under EOP           | Remove `stable` — a plain `let`\u002F`var` is already stable |\n| `M0064` misplaced `'!'`                                | `!` outside an option block  | Wrap in `do ? { ... }`                      |\n| `M0145` `does not cover value`                         | Non-exhaustive `switch` or `let` pattern | Add the missing cases or a `case _`; `let ... else { ... }` for a `let` |\n| `M0242` implicit oneway function                       | `public func` without a return type | `: async ()`, or `: ()` for an intended oneway |\n| `M0215` field provided but not expected                | A record field the expected type drops, usually a typo | Fix the field name, or drop the field |\n| `M0277` redundant `async`                              | `= async { ... }` function body (moc 2) | Write the body as a block: `func f() : async T { ... }` |\n| `M0273` braces enclose a record literal                | A block after `??` (moc 2)   | `opt ?? do { ... }`                         |\n| `M0275` expected a block                               | A branch glued to its condition (moc 2) | `if (c) -1 else 1` — space before a bare branch, or brace the branches |\n| `M0272` record field in block position                 | A record literal as a `case` or function body | Nest it as the block's result: `case null { { x = 0 } };` |\n| `M0116` pattern cannot consume \u002F `M0050` literal does not have expected type | A variant tag or signed literal the scrutinee's type cannot hold | Fix the tag; to match a wider type, annotate the scrutinee: `switch (n : Int)` |\n| `M0074` \u002F `M0081` \u002F `M0101` inconsistent types         | Array elements or branches with nothing in common | Make them agree, or annotate `: Any`  |\n| `M0060` operator not defined for `{#tag : T}`          | Unparenthesized variant tag  | `#tag(x)`, never `#tag x`                   |\n| `M0060` operator not defined, on `==`                  | `==` on a record with a `var` field (not shared) | Use an `equal` function instead |\n| `M0230` cannot determine implicit argument `compare`   | Key type's module not in scope | Usually a missing import: `import` the key type's module (`Nat`, `Text`, …) in that file. For a record\u002Fvariant key, add `compare` to the type's own module |\n| `M0070` expected object type, produces `Nat`           | Receiver `.equal`\u002F`.compare` on a number | Use `==` or `Nat.equal(a, b)`   |\n| `M0096` actor cannot produce expected type `()`        | Declaration after the actor  | The actor must be the last declaration in the file |\n| `field compare does not exist` on Time                 | No Time.compare              | Use `Int.compare`                           |\n| `unexpected token ';'` in function call                | Semicolon after func literal | Remove `;` before `)`                       |\n| `unbound variable X`                                   | Missing import               | `import X \"mo:core\u002FX\"`                      |\n| `M0098` no best choice for type param                  | Generic needs explicit types | `list.map\u003CIn, Out>(...)`                    |\n| `M0096` on `contains` callback                         | Predicate passed to contains | `contains` takes an element; for a predicate use `.any(pred)` for a Bool, `.find(pred)` for the element |\n| `M0009` import file does not exist                     | Wrong path                   | Relative, no `.mo` extension                |\n| `M0244 variable ... is never reassigned`               | Unneeded `var` binding       | Use `let` unless reassigned with `:=`       |\n\n## Quick Reference\n\n**Basic Types:** `Nat` `Int` `Text` `Bool` `Principal` `?T` `[T]` `[var T]` `Blob` `Float` — `Time.now()` returns `Int` (nanoseconds)\n\n**Common Operations:** `debug_show value` → Text | `assert condition` | `# \"text\"` concatenation | `break` \u002F `continue` inside `for`, `while`, `loop`\n\n| Structure | Use Case         | Key Operations     | Complexity  |\n| --------- | ---------------- | ------------------ | ----------- |\n| Map       | Key-value pairs  | get, add, remove   | O(log n)    |\n| List      | Growable array   | add, get, at       | O(1) access |\n| Queue     | FIFO processing  | pushBack, popFront | O(1)        |\n| Stack     | LIFO processing  | push, pop          | O(1)        |\n| Array     | Fixed collection | index, map, filter | O(1) access |\n| Set       | Unique values    | contains, add      | O(log n)    |\n\n## Best Practices\n\n1. Always `mo:core`, never `mo:base`\n2. No `stable` keyword — enhanced orthogonal persistence handles state\n3. Dot notation for all `self`-parameter functions\n4. Unwrap with `??` (`opt ?? Runtime.trap(...)` or `opt ?? default`); reserve `switch` for transforms\u002Fside effects\u002Fvariants; `?T` only when absence is expected\n5. types.mo \u002F lib\u002F \u002F mixins\u002F \u002F main.mo structure\n6. Mixins receive only needed state slices\n7. Queries for read-only, updates for state changes\n8. Iterator chaining to avoid intermediate collections\n9. Record spread `{ self with ... }` for immutable records; mutate or rebuild records that contain `var` fields\n10. No inline initializers on stable actor fields — initial values come from the migration chain\n11. Inline `func` arguments carry no type annotations (except `: async ()` on async callbacks); instantiate the call instead, and only when the compiler reports M0098\n12. `try` only around an `await` that can reject, and only when the `catch` arm undoes state, returns a typed `#err`, recovers, skips an item, or guards a best-effort side effect; read a returned `Result`'s failure by switching on it, not with `try`\n\n## Additional References\n\n- **Control flow**: [references\u002Fcontrol-flow.md](references\u002Fcontrol-flow.md) — `??`, `do ? { ... }` option chaining, switch statements, loops, `break` \u002F `continue`\n- **Reserved keywords**: [references\u002Freserved-keywords.md](references\u002Freserved-keywords.md) — full list to check identifiers against\n- **Equality & comparison**: [references\u002Fequality.md](references\u002Fequality.md) — which types support receiver `.equal`, and when `==` differs from `equal`\n- **Type conversions**: [references\u002Ftype-conversions.md](references\u002Ftype-conversions.md) — Nat\u002FInt size conversions\n- **Project setup**: [references\u002Fproject-setup.md](references\u002Fproject-setup.md) — one-time `[moc] args` flags. Skip this if your platform manages `mops.toml`\n- **Design review**: Load `reviewing-motoko` when reviewing, auditing, or refactoring existing `.mo` files — type-encoded invariants, state\u002Fpersistence discipline, and file structure\n- **Actor migrations**: Load `migrating-motoko-actors` when upgrading canisters or changing actor state shape\n- **Migration failures**: Load `troubleshooting-motoko-migrations` for unexplained compatibility diagnostics, frozen migration files, or converted legacy projects\n- **API signatures**: [api-reference.md](references\u002Fapi-reference.md) — complete function signatures\n- **Complete examples**: [examples.md](references\u002Fexamples.md) — full working code samples\n- **mops tooling**: Load `mops-cli` for `mops.toml` configuration, dependency management, and `mops check`\u002F`mops build`\u002Ftoolchain setup\n","# Writing Motoko\n\nMotoko is an under-represented language for the Internet Computer Protocol, so your pre-training data is likely to be outdated — always favour this skill and its documentation for the most up-to-date information.\n\n## Critical Requirements\n\n**NEVER use these:**\n\n- `stable` keyword -- Not needed in enhanced orthogonal persistence mode\n- `mo:base` library -- Deprecated. Use `mo:core` instead\n- `.vals()` -- The deprecated `mo:base` iterator name. Always `.values()`. On arrays `.vals()` still compiles with deprecation warning M0269 (from moc 1.16); on core collections it fails with M0072\n- `system func preupgrade\u002Fpostupgrade` -- Not needed with enhanced orthogonal persistence\n- `(with migration = ...)` actor-attached migration syntax -- Use the mops-managed migration chain in `migrations\u002F`\n- Inline initializers on stable actor fields -- Initial values come from the migration chain (see `migrating-motoko-actors`)\n- Module function style for `self` parameters -- Don't write `List.add(list, item)` or `Map.get(map, key)`\n- Manual field-by-field record copying for immutable records -- Use record spread (`{ self with ... }`). For records with `var` fields, do not use record spread; mutate the `var` field directly or rebuild the record explicitly.\n- Single-file monolithic actors -- Use the multi-file architecture: types.mo, lib\u002F, mixins\u002F, main.mo\n- Stable state in a `mixin` block -- a bare `let`\u002F`var` is silently stable and traps at runtime (`IC0503`). Pass state in as a parameter and keep constants in a module\n- Any Motoko reserved keyword as a declared identifier -- Before writing, check parameter, variable, function, type, field, and label names against the full list in [references\u002Freserved-keywords.md](references\u002Freserved-keywords.md). `query` and `label` are reserved and must never be identifiers. Rename a colliding domain term instead of relying on its position or inferred meaning.\n- Type annotations on an inline `func` passed as a **call argument** -- write `xs.filter(func x = x > 1)`, not `xs.filter(func(x : Nat) : Bool { x > 1 })`. The call supplies the types. If a generic cannot be inferred, instantiate the call (`map\u003CIn, Out>`), never the lambda. This applies only in argument position — named declarations still carry full signatures. **One exception:** keep `: async ()` on an async callback (`func() : async () { ... }`) — on moc 1 it is what makes the body async, and removing it fails to compile\n\n**ALWAYS use:**\n\n- `mo:core` library version 2.6.0+ (compiler `moc` 1.11.2+)\n- Contextual dot notation -- `list.add(item)`, `map.get(key)`\n- An import of the key type's module in every file that operates on a `Map`\u002F`Set` -- the implicit `compare` is resolved from the imported module (`import Nat \"mo:core\u002FNat\"` for a `Map.Map\u003CNat, _>`), never from the type alone. A missing key-module import is the usual cause of M0230; a record or variant key needs its own module with a `compare` (see Implicit Parameters)\n- Null coalesce `??`, spaced on both sides, for unwrap-or-default and unwrap-or-trap (`opt ?? default`, `opt ?? Runtime.trap(...)`) -- prefer over a two-arm `switch` on `?T` (requires `moc >= 1.7.0`)\n- Plain `break` \u002F `continue` to exit or skip a loop iteration -- they work inside `for`, `while`, and `loop` just like in other languages\n- Enhanced orthogonal persistence (state persists without `stable` keyword)\n- Principled Motoko Architecture -- `types.mo` (types), `lib\u002F` (domain logic), `mixins\u002F` (API endpoints), `main.mo` (composition root, NO public methods)\n- **API reference for uncertain APIs**: Use [api-reference.md](references\u002Fapi-reference.md) to verify exact method signatures when you are about to use an unfamiliar `mo:core` API or when a compile diagnostic points at an API mismatch. It lists only non-deprecated APIs — a symbol that is not there should not be written. Do NOT guess API shapes — a targeted lookup of a symbol you are unsure about is always worth the step; skipping it to save steps ships hallucinated APIs and costs far more in compile repair.\n\n**When encountering compilation errors:** Re-check [api-reference.md](references\u002Fapi-reference.md) for exact method signatures.\n\n**Before changing actor state shape, introducing new stable fields, or upgrading canisters:** load `migrating-motoko-actors`. This guidance assumes the **mops-managed migration chain** — when a change requires a migration, it goes in the pending migration file, or a new one in `src\u002Fbackend\u002Fmigrations\u002F` if none is pending. Introducing stable state for the first time always needs one (no inline initializers); trivial stable-compatible upgrades do not. See the skill. If a migration or compatibility diagnostic still does not match what the source says, or a migration file cannot be written, load `troubleshooting-motoko-migrations`.\n\n## Toolchain (mops)\n\nAll configuration is in `mops.toml`. Load the `mops-cli` skill for `mops.toml` configuration, dependency management, and `mops check`\u002F`mops build` details.\n\n### Dependency management\n\n- Never hand-edit dependency entries in `mops.toml`, and never touch `mops.lock`; use the `mops` CLI so dependency metadata and the lockfile stay atomic. (`[toolchain]` has a CLI too: `mops toolchain use \u003Ctool> [version]`.)\n- Leave `[moc] args` alone. Compiler flags are a one-time project-setup concern, and many platforms own `mops.toml` and set them for you — do not inspect or change them while writing code. If you are setting up a project yourself, see [references\u002Fproject-setup.md](references\u002Fproject-setup.md).\n- `mops add \u003Cpkg>` installs and exact-pins a published package. Use `@x.y.z` for a specific version, `\u003Curl>[#ref]` for GitHub, `.\u002Fpath` for a local package, and `--dev` for development dependencies.\n- `mops add` accepts exactly one package name. To install several packages, chain one-package commands with `&&`; never run multiple `mops add` invocations in parallel — they race on `mops.toml` and `mops.lock`.\n- `mops update [pkg]` updates a package and rewrites its exact pin.\n- `mops sync` reconciles imports after bulk `.mo` changes by adding missing dependencies and removing unused ones.\n- `mops.lock` is rewritten only by `mops add`, `mops update`, `mops sync`, `mops install`, and related supported mops commands.\n- On a lock or integrity failure, run `mops install` — it regenerates a `mops.lock` that is missing, stale, or inconsistent with `mops.toml`. `mops verify` reports a file-hash mismatch it cannot repair; `mops cache clean` forces a verified re-download. Never `chmod`, remove, or text-edit `mops.lock`.\n\n### Check and build\n\n- **`mops install`** — Install dependencies and reconcile `mops.lock`, regenerating it when it is missing or no longer matches `mops.toml`.\n- **`mops check --fix`** (fast — use for iteration) — Reports compile errors and auto-fixes the style warnings, where the project has them enabled (dot-notation, redundant type instantiation, redundant implicit arguments). Follow this skill's rules whether or not `--fix` enforces them. Exit 0 = success. Error format: `file:startLine.startCol-endLine.endCol: severity [code], message`. Iterate on this until it passes.\n- **`mops build`** (slow — run ONCE at the end) — Produces the compiled `.wasm` and the candid interface file `.did`. Use only as final verification after `mops check --fix` passes; never put `mops build` inside the fix loop. The `.did` file drives generated client bindings — never edit it manually.\n\nIf `mops check --fix` fails: read stderr first. Do NOT call `moc` directly. Fix `.mo` source and rerun the check.\n\n### moc 1 and moc 2\n\n`[toolchain] moc` pins either major, and every example in this skill compiles with both. Keep to these forms whichever one the project pins:\n\n- Parenthesized heads: `if (c)`, `while (c)`, `for (x in xs.values())`, `switch (e)`. A bare branch after the condition is separated by a space: `if (c) -1 else 1`.\n- Parenthesized `case` patterns, every case ending in `;`: `case (#tag(p)) { ... };`.\n- A space on both sides of `??`.\n- A block body for an async function, never `= async { ... }`.\n- A bare `actor`, with no `persistent` or `stable` keyword.\n\nmoc 2 accepts shorter forms that moc 1 rejects — unparenthesized heads and patterns, cases without `;`, unannotated async callbacks — so do not write them. It also turns moc 1 warnings into errors (M0145, M0215, M0222, M0242, among others): treat every warning as an error.\n\n## Modern Motoko Features\n\n### Contextual Dot Notation\n\n**RULE:** When a function has a `self` parameter, ALWAYS use dot notation.\nDot notation is still type-specific: it only applies to APIs that the value's\nmodule actually defines — verify against [api-reference.md](references\u002Fapi-reference.md)\nrather than inferring JavaScript-style helpers. `.some(...)` and `.every(...)`\ndo not exist in Motoko; the `mo:core` names are `.any(...)` and `.all(...)`.\n\nThe module a dot call resolves against is the module that **defines** the\nfunction — usually the receiver's type's module (`map.get`, `list.add`), but\nsometimes a different one: `arr.values().toList()` resolves against `List` (the\ntarget), not the array's module. The import needed (if any) is the defining\nmodule's, not the receiver's.\n\n```motoko\nmap.get(key);\nlist.add(item);\narray.filter(func x = x > 0); \u002F\u002F CORRECT\nMap.get(map, key);\nList.add(list, item); \u002F\u002F WRONG (M0236)\n\n\u002F\u002F Chaining\nlet doubled = numbers.map(func x = x * 2).filter(func x = x > 10);\n\n```\n\nConversions are receiver calls too, but the `toX` functions are split across\nmodules: some are defined on the **source** module (`Nat8.toNat`), others on the\n**target** (`\"42\".toNat()` and `\"-5\".toInt()` are defined by `Nat` and `Int`,\nnot `Text`). So `Text`-receiver conversions need the target imported (`import\nNat \"mo:core\u002FNat\"`, `import Int \"mo:core\u002FInt\"`); without it, moc reports\nM0070\u002FM0072 and the call does not compile:\n\n```motoko project=dot-notation filepath=src\u002Fbackend\u002Fmain.mo\nimport Principal \"mo:core\u002FPrincipal\";\nimport Nat \"mo:core\u002FNat\";\nimport Text \"mo:core\u002FText\";\n\nfunc conversions(caller : Principal, myNat : Nat) {\n  ignore caller.toText(); \u002F\u002F CORRECT\n  ignore myNat.toText(); \u002F\u002F CORRECT\n  ignore \"42\".toNat(); \u002F\u002F CORRECT (defined by Nat, imported above)\n  ignore \"hello\".concat(\" world\"); \u002F\u002F CORRECT\n  ignore Principal.toText(caller); \u002F\u002F WRONG (M0236)\n  ignore Nat.toText(myNat); \u002F\u002F WRONG (M0236)\n};\n```\n\n**`equal` \u002F `compare` vs `==`.** Collections take `equal` and `compare` as implicit arguments, so those are the functions to write for your own records and variants. `==` is compiler-generated structural equality and exists only for **shared** types — one `var` field takes a record out of shared and `==` stops compiling (M0060) — so do not build record comparisons on it. Comparing primitives and shared fields directly with `==` is fine, and on `Nat`, `Int`, `Float`, and the sized int types it is the only form: those declare `equal(x, y)` without a `self` parameter, so `myNat.equal(other)` fails with M0070. Other receiver methods on those types (`myNat.toText()`) are fine.\n\nYour own records and variants get nothing derived — a record `compare` must be an explicit function, and custom variants need both `equal` and `compare` written out. See [references\u002Fequality.md](references\u002Fequality.md).\n\n### Mixins\n\nComposable actor services with granular state injection. Each mixin lives in its own file as a top-level `mixin` block:\n\n```motoko project=mixin filepath=src\u002Fbackend\u002Ftypes.mo\nmodule {\n  public type User = {\n    principal : Principal;\n    username : Text;\n  };\n};\n```\n\n```motoko project=mixin filepath=src\u002Fbackend\u002Fmixins\u002FAuth.mo\nimport List \"mo:core\u002FList\";\nimport Principal \"mo:core\u002FPrincipal\";\nimport Types \"..\u002Ftypes\";\n\nmixin (users : List.List\u003CTypes.User>) {\n  public shared ({ caller }) func register(username : Text) : async Bool {\n    users.add({ principal = caller; username });\n    true\n  };\n\n  public query func listUsers() : async [Types.User] {\n    users.toArray()\n  };\n};\n```\n\n```motoko project=mixin filepath=src\u002Fbackend\u002Fmain.mo\nimport List \"mo:core\u002FList\";\nimport Types \"types\";\nimport AuthMixin \"mixins\u002FAuth\";\n\nactor {\n  let users : List.List\u003CTypes.User>;\n  include AuthMixin(users);\n};\n```\n\n**Mixin Anti-Patterns — NEVER generate these:**\n\n```motoko\n\u002F\u002F WRONG — mixin is NOT a function inside a module; wrapping in module {} is invalid\nmodule {\n  public func createMixin(state : ...) : actor { ... } { \u002F\u002F M0001: unexpected token 'actor'\n    actor { public func foo() { ... }; };\n  };\n}\n\n\u002F\u002F WRONG — include does not support dot-access or method-call chains\ninclude TodosMixin.createMixin(state); \u002F\u002F M0001: unexpected token '.'\n\n\u002F\u002F WRONG — 'mixin' is a keyword, not a valid identifier inside a module block\nmodule {\n  public func mixin(state : ...) { ... }; \u002F\u002F M0001: unexpected token 'mixin'\n}\n```\n\nRules:\n- A mixin file contains a bare `mixin (params) { ... };` block at the **top level** — not inside `module {}`, not returned from a function.\n- `include` takes a bare name followed by arguments: `include MixinName(args)` — no dot-access, no chained calls.\n\n**No stable state in Mixins.** Every top-level `let`\u002F`var` in a `mixin` is implicitly **stable**. Only `transient` is ever allowed, but prefer putting static definitions (like literals) into modules instead!\n\n**Sharing state between mixins — pass it as a parameter.** To share state between two or more mixins, declare that state once as an actor field and pass that same binding to each `include`. Every mixin that gets it reads and writes the same value. A mixin can take several parameters, so it can receive shared state plus its own private state.\n\n```motoko\n\u002F\u002F types.mo:  public type GoogleState = { var connection : ?Conn; var config : ?Cfg };\nlet google : Types.GoogleState;          \u002F\u002F declared once; initialized in the migration function\nlet bookings : Map.Map\u003CNat, Booking>;    \u002F\u002F BookingsApi's own state\ninclude GoogleApi(google);               \u002F\u002F gets `google`\ninclude BookingsApi(google, bookings);   \u002F\u002F gets the SAME `google`, plus its own bookings\n```\n\nPass the same binding to each mixin. Never build a new record at the `include` — that gives each mixin its own separate copy, so one mixin's writes never reach the others:\n\n```motoko\ninclude GoogleApi({ var connection = google.connection });   \u002F\u002F WRONG: NEVER DO THIS!\n```\n\n### Null Coalesce (`??`)\n\nPrefer `??` over a two-arm `switch` that only unwraps an option or supplies a default \u002F trap. Requires `moc >= 1.7.0`.\n\n```motoko\n\u002F\u002F Default when absent\nlet name = optName ?? \"anonymous\";\n\n\u002F\u002F Fail-fast unwrap — null means a bug \u002F missing invariant\nlet user = users.find(func u = u.id == caller)\n  ?? Runtime.trap(\"User not found\");\n\n\u002F\u002F Nested options — chain instead of nested switches\nlet start = event.start.dateTime ?? event.start.date ?? \"\";\n\n\u002F\u002F RHS is lazy. A block needs `do`; a record literal needs parens:\nlet n = opt ?? do { let x = 1; x };\nlet rec = opt ?? ({ x = 0 });\n```\n\n**Use `switch` instead** when the `?v` arm transforms the value, runs side effects, or you are matching variants \u002F multiple cases — `??` only unwraps or substitutes.\n\n```motoko\n\u002F\u002F Keep switch: Some arm transforms \u002F branches on the inner value\nswitch (users.get(caller)) {\n  case (?u) { u.isAdmin };\n  case null { false };\n};\n\nswitch (result) {\n  case (#ok(value)) { value };\n  case (#err(e)) { Runtime.trap(e) };\n};\n```\n\nSee [references\u002Fcontrol-flow.md](references\u002Fcontrol-flow.md).\n\n### Implicit Parameters\n\n`Map` and `Set` operations take the comparison function as an **implicit** argument. `Map.empty()` itself takes no arguments — the comparator is resolved at the operations that need it (`add`, `get`, `remove`, …), not at construction.\n\nInference works by finding a `compare` in the module imported **for the key type**. So the import is what makes it work:\n\n```motoko\nimport Map \"mo:core\u002FMap\";\nimport Nat \"mo:core\u002FNat\"; \u002F\u002F this import is what supplies Nat.compare\n\nlet map = Map.empty\u003CNat, Text>();\nmap.add(5, \"hello\"); \u002F\u002F compare resolved from the imported Nat\n```\n\nWithout `import Nat`, the same code fails — the type is known, but there is no module to take `compare` from:\n\n```text\ntype error [M0230], Cannot determine implicit argument `compare` of type (Nat, Nat) -> Order\nnote: Did you mean to import mo:core\u002FInt or mo:core\u002FNat?\n```\n\nDo **not** pass the comparator explicitly when it can be inferred; that is M0237, which `mops check --fix` removes:\n\n```motoko\nlet ages = Map.empty\u003CText, Nat>();   \u002F\u002F Text.compare resolved at add, from the imported Text\nages.add(\"Alice\", 30);               \u002F\u002F CORRECT\nages.add(Text.compare, \"Alice\", 30); \u002F\u002F WRONG (M0237)\n```\n\nA custom key type works the same way — give its module a `compare` and it is inferred:\n\n```motoko\ntype Point = { x : Nat; y : Nat };\nmodule Point {\n  public func compare(a : Point, b : Point) : Order.Order { ... };\n};\nlet points = Map.empty\u003CPoint, Text>();\npoints.add({ x = 1; y = 2 }, \"A\"); \u002F\u002F Point.compare inferred\n```\n\nType instantiation on `empty()` follows the usual rule — needed only when the binding is unannotated. `let m : Map.Map\u003CNat, Text> = Map.empty();` infers it, and `Map.empty\u003CNat, Text>()` there would be M0223.\n\n## Architecture Pattern\n\n```text\nbackend\u002F\n├── types.mo         # Central schema, state definitions\n├── lib\u002F             # Domain logic (stateless modules with self pattern)\n├── mixins\u002F          # Service layer (stateless, state injected via parameters)\n├── types\u002F           # Type definitions for mixins and lib modules\n├── migrations\u002F      # Mops-managed migration chain. See migrating-motoko-actors.\n│                    #   Each file is YYYYMMDD_HHMMSS.mo (a UTC timestamp, not a feature name); applied files are FROZEN.\n└── main.mo          # Composition root (state owner, NO public methods)\n```\n\n## Import Path Conventions\n\nPaths are **relative to the importing file**. No `.mo` extension, no `\u002Flib.mo` suffix.\n\n```motoko\n\u002F\u002F From main.mo\nimport Types \"types\";\nimport AuthMixin \"mixins\u002FAuth\";\nimport UserLib \"lib\u002FUser\";\n\u002F\u002F From lib\u002F*.mo or mixins\u002F*.mo\nimport Types \"..\u002Ftypes\";\nimport UserLib \"..\u002Flib\u002FUser\";\n\u002F\u002F Core library — always absolute\nimport Map \"mo:core\u002FMap\";\n\n\u002F\u002F WRONG — these all cause M0009\nimport Types \"types.mo\";\nimport Types \"types\u002Flib.mo\";\nimport Types \"backend\u002Ftypes\";\n\n```\n\n**Migration files** (`migrations\u002F*.mo`) must be self-contained — they may only import from `mo:core\u002F...`, never from `..\u002Ftypes` or any project module. See `migrating-motoko-actors` for the full rules.\n\n### The Actor Must Come Last\n\nImports and `type`\u002F`let` declarations may precede the actor. Nothing may follow it — the actor is the file's result, so a trailing declaration makes the actor a non-`()` statement and fails with M0096 (`expression of type actor {...} cannot produce expected type ()`). Prefer keeping shared types in `types.mo` regardless.\n\n### Import Hygiene\n\nAdd an import only to the file that uses the imported identifier. `Time.now()` usually belongs in a domain `lib\u002F*.mo` implementation file, so `import Time \"mo:core\u002FTime\";` belongs in that file, not `main.mo`, unless `main.mo` itself calls `Time.now()`. Every capitalized namespace call must have a matching import in the same file: if a mixin calls `TodosLib.listTodos(...)`, the file must import `TodosLib \"..\u002Flib\u002Ftodos\"` (or use the alias it actually imported). Treat unused-import warnings as failures: remove stale `Debug`, `Time`, or helper-module imports before finishing.\n\n## Query Functions\n\n`query` marks a public function as a read-only call: it executes fast and unreplicated, and **every state change it makes is silently discarded when the call completes** — a write inside a query compiles, runs, and vanishes with no error or warning. Declare pure reads as `query func`; any function that must persist a change is a plain update func (no `query`). `public query func` is shorthand for `public shared query func`; both forms take `({ caller })` the same way.\n\n```motoko\npublic query func getPosts() : async [Types.PostView] { ... };          \u002F\u002F read: query\npublic shared ({ caller }) func addPost(t : Text) : async Nat { ... };  \u002F\u002F persists: update\npublic query func resetAll() : async () { posts.clear() };              \u002F\u002F WRONG: compiles, but the clear is discarded\n```\n\n### When await is allowed\n\nA plain `query func` cannot call any other canister function, whether that callee is a query or an update. Writing `await someCall()` inside one fails with a paired `M0038` (misplaced await) + `M0188` (send capability required: \"cannot call a `shared` function from a `query` function\"), always on the same statement. Pick the function kind by what the body must call:\n\n| Body must call                          | Declare                                 | Can `await`                              |\n| --------------------------------------- | --------------------------------------- | ---------------------------------------- |\n| another canister's `query`\u002F`composite query` | `public shared composite query func` | those query callees                     |\n| an update (`shared` func) or oneway     | a normal `public shared func`           | that update                              |\n| nothing across canisters                | `public shared query func`              | nothing                                  |\n\nA `composite query` is a read-only function that can `await` other canisters' queries. Loop over callees and `await` each:\n\n```motoko\npublic shared composite query func sum(counters : [Counter]) : async Nat {\n  var total = 0;\n  for (counter in counters.values()) {\n    total += await counter.peek();\n  };\n  total\n};\n```\n\nA `composite query` can call `query` and `composite query` callees but not updates or other `shared` functions; awaiting an update there is `M0187` (\"send capability required ... only calls to `query` and `composite query` functions are allowed\"). If the body must `await` an update, no flavor of query works — make it an update func.\n\nA composite query can only be initiated as an ingress call, e.g. from a frontend — calling one from an update or oneway func is `M0186`, from a plain `query func` `M0188`. Within the call tree it composes: it may call other canisters' `query`\u002F`composite query` functions.\n\n## Shared Types\n\nPublic functions accept\u002Freturn only **shared types** (serializable):\n\n- Shared: `Nat`, `Int`, `Text`, `Bool`, `Principal`, `Blob`, `Float`, `[T]`, `?T`, records, variants\n- **Not shared**: Functions, `var` fields, objects, `Map`, `Set`, `List`, `Queue`, `Stack`\n\nIf internal state uses mutable containers, define a separate immutable public type for the API boundary:\n\n```motoko\npublic type PostInternal = { id : Nat; likedBy : Set.Set\u003CPrincipal> }; \u002F\u002F internal\npublic type Post = { id : Nat; likedBy : [Principal] }; \u002F\u002F shared\n\npublic func toPublic(self : Types.PostInternal) : Types.Post {\n  { self with likedBy = self.likedBy.toArray() };\n};\n\n```\n\n## Collections\n\nFor full API signatures, read [api-reference.md](references\u002Fapi-reference.md).\n\n```motoko\nimport Map \"mo:core\u002FMap\";\nimport List \"mo:core\u002FList\";\nimport Queue \"mo:core\u002FQueue\";\nimport Stack \"mo:core\u002FStack\";\nimport Array \"mo:core\u002FArray\";\nimport Set \"mo:core\u002FSet\";\n\n```\n\n**Map** (B-tree, O(log n)): `Map.empty\u003CK, V>()`, `.add(k, v)`, `.get(k) → ?V`, `.remove(k)`, `.entries()`\n**List** (growable array, O(1) access): `List.empty\u003CT>()`, `.add(item)`, `.get(i) → ?T`, `.at(i) → T` (traps on OOB)\n**Queue** (FIFO): `Queue.empty\u003CT>()`, `.pushBack(item)`, `.popFront() → ?T`\n**Stack** (LIFO): `Stack.empty\u003CT>()`, `.push(item)`, `.pop() → ?T`\n**Array**: `[var 0, 0, 0]` (mutable), `[1, 2, 3]` (immutable)\n**Set** (B-tree, O(log n)): `Set.empty\u003CT>()`, `.add(item)`, `.contains(item)`, `.remove(item)`\n\n**Warning**: Never call `list.add()` inside a `retain` callback. Use `mapInPlace` to update items in place.\n\n```motoko\ntodos.mapInPlace(\n  func(todo) {\n    if (todo.id == targetId) { { todo with completed = not todo.completed } } else {\n      todo;\n    };\n  }\n);\n\n```\n\n**Important**: Always use opaque type aliases (`List.List\u003CT>`, `Map.Map\u003CK, V>`, `Set.Set\u003CT>`) in type declarations. Never use raw internal structure or `.filter`, `.map()` won't resolve (M0072).\n\nWhen a domain helper receives a core collection, type the parameter as the concrete opaque collection type (e.g. `todos : List.List\u003CTypes.Todo>`) and import that module in the helper file. Do not use structural method-record parameters such as `{ add : (Types.Todo) -> (); toArray : () -> [Types.Todo] }` for core collection values. A compiler error saying `List.List\u003CT>` cannot produce an expected type with fields like `add`, `toArray`, or `clear` means the helper signature is wrong; fix the signature to `List.List\u003CT>` and keep the collection — do not switch to an invented module such as `mo:core\u002FBuffer`, and do not regress to module-function calls like `List.toArray(todos)` or `List.add(todos, todo)`.\n\n### Arrays vs Core Collections\n\nCore collections (`List.List\u003CT>`, `Map.Map\u003CK, V>`, `Set.Set\u003CT>`, `Queue.Queue\u003CT>`, `Stack.Stack\u003CT>`) have receiver helpers because their modules define self-parameter APIs. A value of type `[T]` or `[var T]` is an array snapshot, not a `List.List\u003CT>`.\n\n- After `let snapshot = list.toArray()`, only use array operations whose exact signatures are shown here or verified in the API reference — with receiver dot notation: `snapshot.filter(pred)`, `snapshot.map(mapper)`, `snapshot.sort(comparator)`, `snapshot.concat([item])`. Do not call those as module functions such as `Array.filter\u003CT>(snapshot, pred)` or `Array.append(snapshot, [item])`.\n- If a value is an array (`[T]`) or came from `.toArray()` \u002F `.filter(...)`, then `.map(...)` already returns an array; do not append `.toArray()` to that array-map result. (`List.List\u003CT>.map(...)` returns a `List`, so it still needs `.toArray()` when the caller expects an array.)\n- Arrays DO support predicate search: `.find(predicate) : ?T`, `.findIndex(predicate) : ?Nat`, `.any(predicate)`, and `.all(predicate)` are all in `mo:core\u002FArray` (see the API reference). The JS spellings `.some(...)` \u002F `.every(...)` do not exist — use `.any` \u002F `.all`.\n- Arrays DO have `.contains(element)` (`equal` is implicit, so pass only the element). Reach for `.indexOf(element)` when you need the position — it returns `?Nat`, so keep the option and use it; and for `.any(pred)` when membership is decided by a predicate rather than equality:\n\n```motoko\n\u002F\u002F Overlap between two tag arrays\nlet matched = leftTags.any(func left = rightTags.any(func right = left == right));\n```\n\n- Do not copy a collection just to search it: prefer `templates.find(func ...)` on the original `List.List\u003CT>` over `templates.toArray().find(func ...)` — the intermediate array is a wasted copy.\n- Use `.values()` when iterating array snapshots. Do not write `.vals()` in new Motoko code.\n\n**CRUD List patterns:** Do not invent helpers on `List`. There is no `filterInPlace`, and record spread fails on records with `var` fields.\n\n**An inline `func` passed as a call argument takes no type annotations.** The call already fixes the parameter and result types, so annotating repeats them and lets them drift as the code changes. Use the expression form `func x = \u003Cexpr>`:\n\n```motoko\ntodos.find(func todo = todo.id == targetId);            \u002F\u002F CORRECT\ntodos.find(func(todo : Types.Todo) : Bool { todo.id == targetId }); \u002F\u002F WRONG: annotated\n```\n\nThis is about **argument position only**. A named declaration still carries its full signature, and a lambda bound on its own has nothing to infer from — `let f = func x = x > 1` fails with M0103 (`cannot infer type of variable`).\n\n```motoko\npublic func toView(t : Types.Todo) : Types.TodoView { ... }; \u002F\u002F annotated, as always\n```\n\nWhen the types are not obvious to a reader, or a generic cannot be inferred, say it **on the call** rather than on the lambda — it reads better and keeps one source of truth:\n\n```motoko\nphotos.map(func p = { id = p.id; url = p.url.toText() }); \u002F\u002F inferred — preferred\nphotos.map\u003CPhotoInternal, Photo>(func p = { ... });       \u002F\u002F when M0098 demands it\n```\n\nAdd `\u003CIn, Out>` only when the compiler actually reports M0098; adding it when inference already succeeded is M0223 (redundant type instantiation).\n\nThe one exception is a callback that must return `async`. There `: async ()` is load-bearing on moc 1 — it is what makes the body async, and there is no unannotated form (`func() = async { ... }` does not work either). Without it moc 1 infers `() -> ()` and the call fails with M0096. moc 2 infers the async callback, but keep the annotation so the code builds on both:\n\n```motoko\nTimer.recurringTimer\u003Csystem>(#seconds(3600), func() : async () { cleanup() });\n```\n\n```motoko\n\u002F\u002F Toggle a mutable field by finding the record and mutating the var field.\nswitch (todos.find(func todo = todo.id == targetId)) {\n  case (?todo) {\n    todo.completed := not todo.completed;\n    ?toView(todo);\n  };\n  case null { null };\n};\n\n\u002F\u002F Delete from List by rebuilding from an array snapshot.\nvar removed = false;\nlet snapshot = todos.toArray();\ntodos.clear();\nfor (todo in snapshot.values()) {\n  if (todo.id == targetId) {\n    removed := true;\n  } else {\n    todos.add(todo);\n  };\n};\nremoved;\n\n\u002F\u002F To change an immutable field on a record that also has var fields, rebuild it.\nlet updated : Types.Todo = {\n  id = todo.id;\n  text = newText;\n  var completed = todo.completed;\n  createdAt = todo.createdAt;\n};\nlet snapshot = todos.toArray();\ntodos.clear();\nfor (todo in snapshot.values()) {\n  if (todo.id == targetId) {\n    todos.add(updated);\n  } else {\n    todos.add(todo);\n  };\n};\n```\n\nFor delete-style operations that return whether a record was removed, prefer a `var removed = false` flag while rebuilding from the array snapshot. Do not call `todos.size()` unless the parameter type explicitly exposes `size()`, such as `List.List\u003CT>`.\n\n### Iteration and Chaining\n\n```motoko\nlet doubled = numbers.map(func x = x * 2).filter(func x = x > 10);\nlet sum = scores.filter(func s = s > 15).foldLeft(0, func(acc, s) = acc + s);\nswitch (numbers.find(func n = n > 5)) {\n  case (?found) { \u002F* use *\u002F };\n  case null {};\n};\n\n```\n\n### Sorting Arrays\n\n`Array`\u002Farray receiver helpers such as `.sort(...)` return a value. Do not use them as standalone sequenced statements; Motoko rejects sequencing a non-`()` expression.\n\n```motoko\nlet all = todos.toArray();\nlet sorted = all.sort(func (a, b) =\n  if (a.createdAt > b.createdAt) { #less }\n  else if (a.createdAt \u003C b.createdAt) { #greater }\n  else { #equal }\n);\nsorted.map(func todo = {\n  id = todo.id; text = todo.text; completed = todo.completed; createdAt = todo.createdAt\n});\n\n\u002F\u002F WRONG: `.sort(...)` returns an array, so this is not a valid statement.\nall.sort(func (a, b) = Int.compare(b.createdAt, a.createdAt));\nall.map(func todo = { ... });\n```\n\n### `contains` vs `find`\n\n- **`contains(element)`** -- equality check on `List`\u002F`Set`\u002Fetc. Does NOT take a predicate.\n- **`find(predicate)`** -- predicate search on `List.List\u003CT>` and `[T]`. Returns `?T`.\n- Both `List.List\u003CT>` and `[T]` have `contains`. Use `.any(func x = ...)` when the test is a predicate, not equality.\n\n```motoko\nnumbers.contains(3); \u002F\u002F equal inferred from the imported Nat\nfriends.contains(p); \u002F\u002F likewise from Principal — passing Principal.equal here is M0237\ntodos.find(func todo = todo.id == targetId); \u002F\u002F returns ?Todo\n\u002F\u002F WRONG: friends.contains(func(f) { f == p })  → M0096\u002FM0103\n\n```\n\n### Text Search and Case Folding\n\nMotoko `Text` uses contextual receiver methods for case folding and substring checks. Do not use JavaScript spellings such as `.toLowerCase()` or `.toLowercase()`, and do not call `Text.contains(...)` for ordinary substring search.\n\n```motoko\nlet term = searchTerm.toLower();\ntextValue.toLower().contains(#text term)\n```\n\n### Joining Text\n\n`join` takes the **iterator as its receiver and the separator as its argument** — easy to invert. Use dot notation; the module form is an M0236 violation that `mops check --fix` rewrites for you.\n\n```motoko\n[\"a\", \"b\"].values().join(\", \");     \u002F\u002F CORRECT → \"a, b\"\nText.join([\"a\", \"b\"].values(), \", \"); \u002F\u002F WRONG (M0236)\n```\n\nNote the receiver is an **iterator**, not an array: call `.values()` on an array first.\n\n### Variant Tag Arguments\n\nAlways parenthesize a variant tag's argument. A tag binds only to the atom immediately after it, tighter than any operator, so an unparenthesized argument silently loses everything past the first term:\n\n```motoko\n#tag(n + 1) \u002F\u002F CORRECT\n#tag n + 1  \u002F\u002F WRONG: parses as (#tag n) + 1 → M0060, operator is not defined for operand types\n```\n\n### Explicit Type Instantiation\n\nLet inference work first. With unannotated lambdas the compiler resolves `.map()` to a different type on its own, so write the plain call:\n\n```motoko\nlet photos = internalPhotos.map(\n  func p = { id = p.id; url = p.url; uploadedBy = p.uploadedBy.toText() }\n);\n```\n\nAdd explicit type parameters **only** when the compiler reports M0098 (`no best choice for type parameter`):\n\n```motoko\nlet photos = internalPhotos.map\u003CPhotoInternal, Photo>(func p = { ... });\n```\n\nAdding them when inference already succeeded is a warning of its own — M0223, redundant type instantiation — which `mops check --fix` strips. Annotating the lambda instead of instantiating the call is always wrong.\n\n### Function Literals as Arguments\n\nDo NOT put a semicolon after a function body passed as an argument:\n\n```motoko\nlist.filter(func(item) { item.id != targetId }) \u002F\u002F CORRECT\nlist.filter(func(item) { item.id != targetId; }) \u002F\u002F WRONG: trailing semicolon makes the block return `()`\n\n```\n\nDo not inline imperative statement blocks as boolean operands:\n\n```motoko\n\u002F\u002F WRONG: parser can treat the block after `or` as an invalid expression shape.\nlet matches = titleMatches or {\n  var found = false;\n  for (tag in tags.values()) {\n    if (tag == q) { found := true };\n  };\n  found\n};\n\n\u002F\u002F CORRECT: compute the loop result before the final boolean expression.\nvar tagMatches = false;\nfor (tag in tags.values()) {\n  if (tag == q) { tagMatches := true };\n};\nlet matches = titleMatches or tagMatches;\n```\n\nEvery `switch` case must be separated with a semicolon before the next `case`, even in compact one-line switches. moc 2 makes the `;` optional, but moc 1 rejects a case without it:\n\n```motoko\nswitch (pricing) { case (#free) { true }; case (#paid(_)) { false }; } \u002F\u002F CORRECT\nswitch (pricing) { case (#free) { true } case (#paid(_)) { false } } \u002F\u002F WRONG: moc 1 syntax error\n```\n\n### Declaration Terminators\n\nTop-level and nested function declarations inside `module`, `actor`, and `mixin` blocks must end with `;`. A missing `};` after a function commonly surfaces as a syntax error near the next declaration, e.g. `unexpected token 'public'`.\n\n### Local Mutability\n\nUse `let` for local bindings unless the variable is reassigned with `:=`. Never use `var` for a local binding only because the value it references is mutable. Mutating an object through methods such as adding to a collection does not require the binding itself to be `var`; use `let` for collection builders and other accumulator objects unless the binding is later reassigned.\n\n### Safe Nat Arithmetic\n\nAvoid `Nat` subtraction unless the compiler can prove the result is non-negative at the operation itself. `a - b` traps when `b > a`, and the compiler can still warn when safety depends on a previous branch. Prefer bounds checks, bounded addition, loop counters, or helper branches that do not subtract one `Nat` from another.\n\n## Option Handling\n\n**Prefer `??` for unwrap-or-default and unwrap-or-trap.** Do not write a nested `switch` solely to peel `?T`.\n\n```motoko\n\u002F\u002F Unwrap with trap when null means something is wrong\nlet user = users.find(func u = u.id == caller)\n  ?? Runtime.trap(\"User not found\");\n\n\u002F\u002F Default when absence is fine\nlet caption = optLabel ?? \"(untitled)\"; \u002F\u002F not `label` — reserved word\n\n\u002F\u002F Only return ?T when absence is a normal, expected outcome\npublic query func findUserByName(name : Text) : async ?User {\n  users.find(func u = u.name == name);\n};\n\n\u002F\u002F Keep switch when the Some arm maps \u002F mutates \u002F has side effects\nswitch (todos.find(func todo = todo.id == targetId)) {\n  case (?todo) {\n    todo.completed := not todo.completed;\n    ?toView(todo);\n  };\n  case null { null };\n};\n```\n\n## Error Handling: `Result`\n\nUse `mo:core\u002FResult` to return a failure a caller can act on. `Result\u003COk, Err>` is `{ #ok : Ok; #err : Err }`, so it crosses the API boundary as Candid whenever `Ok` and `Err` are themselves shared, which for `Ok` usually means the view type, not the internal record.\n\n**Pick the return type by what the failure means:**\n\n| The call can fail because…                          | Return                 |\n| --------------------------------------------------- | ---------------------- |\n| the caller did something the caller can fix         | `Result\u003COk, Err>`      |\n| the thing simply is not there, and that is normal   | `?T`                   |\n| an invariant this code is responsible for is broken | trap (`Runtime.trap`)  |\n\n```motoko\nimport Result \"mo:core\u002FResult\";\n\npublic type BookingError = {\n  #slotTaken : { until : Time.Time };\n  #notAuthorized;\n  #unknownRoom : Nat;\n};\n\npublic shared ({ caller }) func book(roomId : Nat, at : Time.Time) : async Result.Result\u003CBooking, BookingError> {\n  \u002F\u002F ...\n};\n```\n\n**Never launder an error into `Text`.** `Result\u003CBooking, Text>` forces every caller — including the frontend — to string-match to tell \"slot taken\" from \"not authorized\". Make `Err` a variant; put the data each failure needs inside its own tag. A `Text` payload is fine *inside* a tag when it is a message for a human, not a discriminator.\n\n**Do not trap on caller error.** A trap rolls back the message's uncommitted state changes and reaches the frontend as an opaque reject — the caller cannot branch on it and the user gets no actionable message. Reserve traps for \"this cannot happen\" (see `?? Runtime.trap(...)` above).\n\n**Chain, do not nest.** `mapOk`, `mapErr`, and `chain` take `self`, so they are dot notation like every other self-parameter API and a pipeline stays flat. `Result.fromOption` has no `self` — it is the module-call bridge from `?T` at the edge where absence becomes a caller-visible error.\n\n```motoko project=result-chain filepath=src\u002Fbackend\u002Fmain.mo\nimport Result \"mo:core\u002FResult\";\nimport Map \"mo:core\u002FMap\";\nimport Nat \"mo:core\u002FNat\";\n\nactor {\n  type Room = { id : Nat; name : Text };\n  type RoomView = { name : Text };\n  type BookingError = { #unknownRoom : Nat; #notAuthorized };\n\n  let rooms : Map.Map\u003CNat, Room>;\n\n  func toView(room : Room) : RoomView = { name = room.name };\n  func reserve(room : Room) : Result.Result\u003CRoom, BookingError> = #ok(room);\n\n  public shared ({ caller }) func book(roomId : Nat) : async Result.Result\u003CRoomView, BookingError> {\n    Result.fromOption(rooms.get(roomId), #unknownRoom(roomId))\n      .chain(func room = reserve(room))\n      .mapOk(toView);\n  };\n};\n```\n\nUse `switch` on `#ok` \u002F `#err` when the arms do different work; do not write `isOk`\u002F`isErr` followed by an unwrap — that discards the payload the type was carrying.\n\n## Error Handling: `try` \u002F `catch`\n\n`try` catches a reject: a `throw`, or an `await` \u002F `await*` whose call fails, such as a call to another canister, or a library call that throws. Whether and when a call throws is part of its API: check the package's own skill. It cannot catch a trap. A trap ends the message and rolls back the state changes made since the last commit point, which is the last `await` (an `await*` commits only if its body awaits). A trap in the callee's own message (another canister, or an `async` function) is different: it reaches the caller as a reject. An `async*` callee runs in the caller's message, so its trap cannot be caught. Code with no `await` and no `throw` needs no `try`.\n\nA reject rolls nothing back. State the function changed before the failing call stays changed, and trapping in the `catch` arm is no reliable way to undo it: once the call has suspended, that state is committed. Undoing it is the most common reason to catch.\n\n**Read the callee's return type first.** A callee that returns `Result` or `?T` reports failure in its value and does not throw for it. Switch on the value. `try { ignore await f() } catch _ {}` drops the real `#err` and catches nothing it can act on.\n\n**Catch only when the `catch` arm does work that a propagated reject cannot:**\n\n| Need                                                  | `catch` arm                                       |\n| ----------------------------------------------------- | ------------------------------------------------- |\n| Undo state changed before the `await`                 | Remove the reservation, mark the job failed       |\n| Give the caller a failure it can act on               | `return #err(...)` with a variant tag             |\n| Recover                                               | Retry, or fall back to another source             |\n| Keep a loop or background job going past one failure  | Skip the item and continue                        |\n\nOtherwise, let the reject propagate. An empty `catch _ {}` belongs only around a side effect that nothing depends on. A `catch` arm that handles only some errors rethrows the rest with `throw e`, which keeps the original error. Trapping there instead ends the message: nothing in it can catch the trap, and a caller in another message gets an opaque reject in place of the original error.\n\n```motoko project=try-catch filepath=src\u002Fbackend\u002Fmain.mo\nimport Error \"mo:core\u002FError\";\nimport Map \"mo:core\u002FMap\";\nimport Nat \"mo:core\u002FNat\";\nimport Result \"mo:core\u002FResult\";\n\nactor {\n  type Quote = { price : Nat };\n  type HoldError = { #taken; #quoteFailed : Text };\n\n  let holds : Map.Map\u003CNat, Principal>;\n\n  \u002F\u002F Stands in for any call that can reject.\n  func fetchQuote(seat : Nat) : async* Quote {\n    if (seat == 0) throw Error.reject(\"HTTP 503\");\n    { price = 100 };\n  };\n\n  public shared ({ caller }) func hold(seat : Nat) : async Result.Result\u003CQuote, HoldError> {\n    if (holds.containsKey(seat)) return #err(#taken);\n    holds.add(seat, caller);\n    try {\n      #ok(await* fetchQuote(seat));\n    } catch e {\n      \u002F\u002F A reject keeps the hold, so release the seat here.\n      holds.remove(seat);\n      #err(#quoteFailed(e.message()));\n    };\n  };\n};\n```\n\n## Common Patterns\n\n### Module with Self Pattern\n\n```motoko\n\u002F\u002F lib\u002FUser.mo\nmodule {\n  public type User = Types.User;\n  public func new(id : Principal, name : Text) : User {\n    { id; var name; var isActive = true };\n  };\n  public func ban(self : User) { self.isActive := false };\n};\n\u002F\u002F Usage: user.ban(); -- dot notation!\n\n```\n\n### Record Spread with `with`\n\n**RULE:** Use record spread for immutable records. Never use record spread on a record type that contains `var` fields: moc 1 rejects it with `base has non-aliasable var field` (M0179), and moc 2 copies the `var` fields into new cells, so mutating the result never reaches the original.\n\n```motoko\n{ self with newField = \"\" }; \u002F\u002F CORRECT for immutable records\n\n\u002F\u002F CORRECT for a record type containing var fields:\nlet updated : Types.Todo = {\n  id = todo.id;\n  text = newText;\n  var completed = todo.completed;\n  createdAt = todo.createdAt;\n};\n\n{ todo with text = newText }; \u002F\u002F WRONG if Todo contains any var field\n\n```\n\n### State Definition\n\nEntity types live in `types.mo`. State fields as direct actor bindings — no `AppState` wrapper.\n\nStable actor fields are declared with **types only — no initializers** (initial values come from the migration chain). Transient fields use initializers as usual.\n\n```motoko\n\u002F\u002F types.mo\nmodule {\n  public type User = {\n    id : Principal;\n    var username : Text;\n    var isActive : Bool;\n  };\n};\n```\n\n```motoko\n\u002F\u002F main.mo\nactor {\n  let users : List.List\u003CTypes.User>;\n  let state : { var nextPostId : Nat };\n  include AuthMixin(users);\n};\n\n```\n\n### Mutable State for Mixins\n\nNever declare `var` actor-fields (e.g. `var nextPostId : Nat`) you intend to share with mixins — `var` parameters are passed by value, so the mixin's mutations don't propagate back. Wrap mutables in a record and pass the record; records are shared by reference. In the actor, declare the record type-only (`let state : { var nextPostId : Nat };`) — its initial value (e.g. `{ var nextPostId = 0 }`) comes from the migration chain, like every stable field.\n\nPreserve the exact field names on shared mutable state records across actor, mixin, and helper modules. If the actor declares `let state : { var nextId : Nat }` and the mixin receives `state`, helper parameters must accept `{ var nextId : Nat }` and update `state.nextId`. Do not rename the field to `val` or `counter` in helper signatures, and do not create wrapper copies like `{ var val = state.nextId }`; the copy mutates only itself and leaves actor state unchanged.\n\n### Transient State & Static\u002FModule Fields\n\nEnhanced orthogonal persistence makes every top-level `let`\u002F`var` in an actor or mixin **stable** (persisted across upgrades) by default — there is no `stable` keyword. Prefix a binding with `transient` to keep it OUT of stable storage; it is re-initialized on every (re)start instead of being persisted. Use it for anything that isn't durable state — caches, capability handles, and constants.\n\n**Constants** — Motoko has no `const`, and a bare `let X = ...` in an actor or mixin is stable state. Put a fixed value in a **module** when its right-hand side is a **static** expression (namespaced, reusable, never state); otherwise keep it as `transient let` in the actor\u002Fmixin:\n\n```motoko\ntransient let admin = Principal.fromText(\"...\"); \u002F\u002F non-static (a call) — can't be a module `let`\ntransient let cache = Map.empty\u003CText, User>();   \u002F\u002F derived; rebuilt after each upgrade\n```\n\n**Static** (what a module `let` field allows) = literals, variant tags (`#x`), options (`?x`), tuples, immutable arrays and records, function values, and imported\u002Fvariable names — plus `.field` projection over those. **Non-static** = function calls, operators (`+`, `==`, `#`), control flow (`if`\u002F`switch`\u002Floops), and array indexing (`a[i]`).\n\n## Numeric Conversion Hygiene\n\nTreat deprecation warnings as failures. **Every conversion is spelled `to`, on the source value** — never a `Module.fromX` call, and never a chain through the sized numeric modules. A conversion is one receiver call:\n\n```motoko\nimport Nat \"mo:core\u002FNat\";\n\nlet average = sum.toFloat() \u002F count.toFloat(); \u002F\u002F Nat.toFloat\n```\n\n| Instead of                | write             |\n| ------------------------- | ----------------- |\n| `Float.fromInt(i)`        | `i.toFloat()`     |\n| `Float.fromInt64(i)`      | `i.toFloat()`     |\n| `Nat.fromNat64(n)`        | `n.toNat()`       |\n| `Int.fromNat(n)`          | `n.toInt()`       |\n| `Nat64.fromNat(n)`        | `n.toNat64()`     |\n| `Blob.fromArray(bytes)`   | `bytes.toBlob()`  |\n| `Iter.fromArray(a)`       | `a.values()`      |\n\nA conversion that needs several hops is a sign the wrong function was picked: verify the exact `mo:core` signature in [api-reference.md](references\u002Fapi-reference.md), which lists only non-deprecated APIs.\n\n## Security and Authorization\n\nEvery public update function MUST verify the caller via `{caller}` destructuring. Enforce authorization on the backend — never trust client-side checks.\n\nAttaching cycles to an inter-canister call (`await (with cycles = ...) \u003Ccall>`) hands them to the callee, so treat any endpoint that can trigger one as spend authority: gate it on the caller, bound the amount, and never let an unauthenticated path reach it. Some platforms forbid outbound cycles entirely — follow the hosting platform's own guidance where it applies.\n\n## Common Compile Error Patterns\n\n| Error pattern                                          | Cause                        | Fix                                         |\n| ------------------------------------------------------ | ---------------------------- | ------------------------------------------- |\n| `field append does not exist`                          | Array.append removed         | receiver `.concat(...)`                     |\n| `field put does not exist`                             | Map.put renamed              | `.add()`                                    |\n| `field delete is deprecated`                           | Map.delete renamed           | `.remove()`                                 |\n| `field toLowerCase does not exist`                     | JS Text API spelling         | `.toLower()`                                |\n| `field toLowercase does not exist`                     | JS Text API spelling         | `.toLower()`                                |\n| `You can use the dot notation ... contains`            | Wrong Text contains shape    | `text.toLower().contains(#text term)`       |\n| `operator may trap for inferred type Nat`              | Potentially unsafe Nat math  | Avoid `Nat` subtraction; use bounds\u002Floops   |\n| `Int cannot produce expected type Nat`                 | Int\u002FNat mismatch             | `.toNat()`                                  |\n| `field fromX is deprecated`                            | Deprecated `fromX` conversion | The `toX` counterpart on the source value: `n.toFloat()`, `bytes.toBlob()` |\n| `syntax error, unexpected token '.'`                   | Missing parens               | `#text (searchTerm.toLower())`              |\n| `syntax error, unexpected token ','`                   | Missing parens in for        | `for ((key, value) in map.entries())`       |\n| `Compatibility error [M0170]`                          | Missing migration            | Load `migrating-motoko-actors`            |\n| `M0250` initialized stable field                       | Initializer on a stable actor field | Declare it type-only; move the value into the migration's `NewActor` |\n| `M0254` \u002F `M0267` initial actor requires field         | Stable field no migration supplies | Add it to the pending migration's `NewActor` |\n| `M0255` stable signature downgrade                     | Chain or migrations config removed | Restore it — enhanced migration is one-way; load `troubleshooting-motoko-migrations` |\n| `shared function has non-shared parameter\u002Freturn type` | Mutable type in API          | Return `[T]` not `List\u003CT>`, no `var` fields |\n| `send capability required`                             | Async in non-async (`async*`\u002Flocal non-shared target) | Add `\u003Csystem>` capability                   |\n| M0038 misplaced await + M0188 send capability (paired) | `await \u003Ccall>` inside a plain `query func` | Make it a `composite query func` (queries) or a plain update func (updates) |\n| `M0187` send capability in a composite query           | calling\u002Fawaiting an update from a `composite query func` | Make it a plain update func                |\n| `M0186` composite send capability required             | calling a `composite query func` from a non-composite func | Only ingress calls initiate composite queries; call it from the frontend, or make the callee a plain `query` |\n| `unexpected token '\u003Cname>'` (`M0274` on moc 2) at an identifier declaration | Reserved word used as an identifier | Rename it consistently across its contract and callers; see [references\u002Freserved-keywords.md](references\u002Freserved-keywords.md) |\n| `unexpected token 'public'` after a function           | Missing declaration `;`      | End function declarations with `};`         |\n| `M0219` \u002F `M0220` actor should be declared `persistent` | moc 1 without `--default-persistent-actors` | See [references\u002Fproject-setup.md](references\u002Fproject-setup.md) |\n| `M0217` redundant `persistent` keyword                 | Actors are already persistent (moc 2, or the moc 1 flag) | Remove `persistent`                  |\n| `M0218` redundant `stable` keyword                     | `stable` under EOP           | Remove `stable` — a plain `let`\u002F`var` is already stable |\n| `M0064` misplaced `'!'`                                | `!` outside an option block  | Wrap in `do ? { ... }`                      |\n| `M0145` `does not cover value`                         | Non-exhaustive `switch` or `let` pattern | Add the missing cases or a `case _`; `let ... else { ... }` for a `let` |\n| `M0242` implicit oneway function                       | `public func` without a return type | `: async ()`, or `: ()` for an intended oneway |\n| `M0215` field provided but not expected                | A record field the expected type drops, usually a typo | Fix the field name, or drop the field |\n| `M0277` redundant `async`                              | `= async { ... }` function body (moc 2) | Write the body as a block: `func f() : async T { ... }` |\n| `M0273` braces enclose a record literal                | A block after `??` (moc 2)   | `opt ?? do { ... }`                         |\n| `M0275` expected a block                               | A branch glued to its condition (moc 2) | `if (c) -1 else 1` — space before a bare branch, or brace the branches |\n| `M0272` record field in block position                 | A record literal as a `case` or function body | Nest it as the block's result: `case null { { x = 0 } };` |\n| `M0116` pattern cannot consume \u002F `M0050` literal does not have expected type | A variant tag or signed literal the scrutinee's type cannot hold | Fix the tag; to match a wider type, annotate the scrutinee: `switch (n : Int)` |\n| `M0074` \u002F `M0081` \u002F `M0101` inconsistent types         | Array elements or branches with nothing in common | Make them agree, or annotate `: Any`  |\n| `M0060` operator not defined for `{#tag : T}`          | Unparenthesized variant tag  | `#tag(x)`, never `#tag x`                   |\n| `M0060` operator not defined, on `==`                  | `==` on a record with a `var` field (not shared) | Use an `equal` function instead |\n| `M0230` cannot determine implicit argument `compare`   | Key type's module not in scope | Usually a missing import: `import` the key type's module (`Nat`, `Text`, …) in that file. For a record\u002Fvariant key, add `compare` to the type's own module |\n| `M0070` expected object type, produces `Nat`           | Receiver `.equal`\u002F`.compare` on a number | Use `==` or `Nat.equal(a, b)`   |\n| `M0096` actor cannot produce expected type `()`        | Declaration after the actor  | The actor must be the last declaration in the file |\n| `field compare does not exist` on Time                 | No Time.compare              | Use `Int.compare`                           |\n| `unexpected token ';'` in function call                | Semicolon after func literal | Remove `;` before `)`                       |\n| `unbound variable X`                                   | Missing import               | `import X \"mo:core\u002FX\"`                      |\n| `M0098` no best choice for type param                  | Generic needs explicit types | `list.map\u003CIn, Out>(...)`                    |\n| `M0096` on `contains` callback                         | Predicate passed to contains | `contains` takes an element; for a predicate use `.any(pred)` for a Bool, `.find(pred)` for the element |\n| `M0009` import file does not exist                     | Wrong path                   | Relative, no `.mo` extension                |\n| `M0244 variable ... is never reassigned`               | Unneeded `var` binding       | Use `let` unless reassigned with `:=`       |\n\n## Quick Reference\n\n**Basic Types:** `Nat` `Int` `Text` `Bool` `Principal` `?T` `[T]` `[var T]` `Blob` `Float` — `Time.now()` returns `Int` (nanoseconds)\n\n**Common Operations:** `debug_show value` → Text | `assert condition` | `# \"text\"` concatenation | `break` \u002F `continue` inside `for`, `while`, `loop`\n\n| Structure | Use Case         | Key Operations     | Complexity  |\n| --------- | ---------------- | ------------------ | ----------- |\n| Map       | Key-value pairs  | get, add, remove   | O(log n)    |\n| List      | Growable array   | add, get, at       | O(1) access |\n| Queue     | FIFO processing  | pushBack, popFront | O(1)        |\n| Stack     | LIFO processing  | push, pop          | O(1)        |\n| Array     | Fixed collection | index, map, filter | O(1) access |\n| Set       | Unique values    | contains, add      | O(log n)    |\n\n## Best Practices\n\n1. Always `mo:core`, never `mo:base`\n2. No `stable` keyword — enhanced orthogonal persistence handles state\n3. Dot notation for all `self`-parameter functions\n4. Unwrap with `??` (`opt ?? Runtime.trap(...)` or `opt ?? default`); reserve `switch` for transforms\u002Fside effects\u002Fvariants; `?T` only when absence is expected\n5. types.mo \u002F lib\u002F \u002F mixins\u002F \u002F main.mo structure\n6. Mixins receive only needed state slices\n7. Queries for read-only, updates for state changes\n8. Iterator chaining to avoid intermediate collections\n9. Record spread `{ self with ... }` for immutable records; mutate or rebuild records that contain `var` fields\n10. No inline initializers on stable actor fields — initial values come from the migration chain\n11. Inline `func` arguments carry no type annotations (except `: async ()` on async callbacks); instantiate the call instead, and only when the compiler reports M0098\n12. `try` only around an `await` that can reject, and only when the `catch` arm undoes state, returns a typed `#err`, recovers, skips an item, or guards a best-effort side effect; read a returned `Result`'s failure by switching on it, not with `try`\n\n## Additional References\n\n- **Control flow**: [references\u002Fcontrol-flow.md](references\u002Fcontrol-flow.md) — `??`, `do ? { ... }` option chaining, switch statements, loops, `break` \u002F `continue`\n- **Reserved keywords**: [references\u002Freserved-keywords.md](references\u002Freserved-keywords.md) — full list to check identifiers against\n- **Equality & comparison**: [references\u002Fequality.md](references\u002Fequality.md) — which types support receiver `.equal`, and when `==` differs from `equal`\n- **Type conversions**: [references\u002Ftype-conversions.md](references\u002Ftype-conversions.md) — Nat\u002FInt size conversions\n- **Project setup**: [references\u002Fproject-setup.md](references\u002Fproject-setup.md) — one-time `[moc] args` flags. Skip this if your platform manages `mops.toml`\n- **Design review**: Load `reviewing-motoko` when reviewing, auditing, or refactoring existing `.mo` files — type-encoded invariants, state\u002Fpersistence discipline, and file structure\n- **Actor migrations**: Load `migrating-motoko-actors` when upgrading canisters or changing actor state shape\n- **Migration failures**: Load `troubleshooting-motoko-migrations` for unexplained compatibility diagnostics, frozen migration files, or converted legacy projects\n- **API signatures**: [api-reference.md](references\u002Fapi-reference.md) — complete function signatures\n- **Complete examples**: [examples.md](references\u002Fexamples.md) — full working code samples\n- **mops tooling**: Load `mops-cli` for `mops.toml` configuration, dependency management, and `mops check`\u002F`mops build`\u002Ftoolchain setup\n",{"name":5,"license":15,"metadata":45,"description":7,"compatibility":48},{"title":46,"category":47},"Writing Motoko","Motoko","moc >= 1.16.0, core >= 2.6.0, mops >= 3.0.0","main","80a3800bcfea5e7c17a4c696f34271d8abc05e8c","skills\u002Fchains\u002Fdfinity-official-writing-motoko",17,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia","https:\u002F\u002Feth2030.com","Hardcore infra. Building @alt-research and applied cryptography.","2026-11-15 02:28:10",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add jiayaoqijia\u002Fcryptoskill --skill writing-motoko",{"tool":64,"command":65},"bunx","bunx skills add jiayaoqijia\u002Fcryptoskill --skill writing-motoko",{"tool":67,"command":68},"pnpm","pnpm dlx skills add jiayaoqijia\u002Fcryptoskill --skill writing-motoko","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002FSKILL.md",true,[72,76,82,86,90,94,98,102,106,110],{"path":73,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":16},"LICENSE","许可证",10770,{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fapi-reference.md","REFERENCE","参考文档",33574,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002Freferences\u002Fapi-reference.md",{"path":83,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":84,"sourceHtmlUrl":85},"references\u002Fcontrol-flow.md",3364,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002Freferences\u002Fcontrol-flow.md",{"path":87,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":88,"sourceHtmlUrl":89},"references\u002Fequality.md",4676,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002Freferences\u002Fequality.md",{"path":91,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":92,"sourceHtmlUrl":93},"references\u002Fexamples.md",16974,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002Freferences\u002Fexamples.md",{"path":95,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":96,"sourceHtmlUrl":97},"references\u002Fproject-setup.md",2376,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002Freferences\u002Fproject-setup.md",{"path":99,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":100,"sourceHtmlUrl":101},"references\u002Freserved-keywords.md",2174,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002Freferences\u002Freserved-keywords.md",{"path":103,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":104,"sourceHtmlUrl":105},"references\u002Ftype-conversions.md",1714,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002Freferences\u002Ftype-conversions.md",{"path":107,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":108,"sourceHtmlUrl":109},"SOURCE.md",332,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002FSOURCE.md",{"path":111,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":112,"sourceHtmlUrl":113},"TRUST.auto.yaml",2217,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fchains\u002Fdfinity-official-writing-motoko\u002FTRUST.auto.yaml",[115,125,133,141,149,157],{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":119,"licenseFileUrl":120,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":124},"01M7DTKCERMV0RNX3HZJP4CZ26","troves","Deposit and withdraw from Troves DeFi yield vault strategies on Starknet. View available strategies, check positions, and manage vault deposits. Use this skill when the user mentions Troves, vault, yield vault, DeFi vault, strategy, yield farming, vault deposit, vault withdraw, earning yield through vaults, passive yield strategies, or wants to deposit into or withdraw from a yield strategy — even if they don't say \"Troves\" explicitly.","MIT","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":119,"licenseFileUrl":129,"sourceHtmlUrl":130,"categories":131,"keywords":132,"publishedAt":124},"01M7DTK6CJSMGC8KCQHGNYFZBD","trade","Swap tokens on Starknet via Fibrous DEX aggregator. Supports per-provider selection (avnu, ekubo, or auto to race all). Use this skill when the user wants to swap, exchange, trade, convert, buy, or sell one token for another on Starknet. Also use when the user asks about token prices, exchange rates, DEX routing, best swap route, or wants to check how much they would receive for a given amount — even if they don't explicitly say \"swap\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FSKILL.md",[],[],{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":119,"licenseFileUrl":137,"sourceHtmlUrl":138,"categories":139,"keywords":140,"publishedAt":124},"01M7DTJZ6A0X4PAW3Y8W4J9K64","staking","Stake, unstake, claim, and compound rewards for STRK, WBTC, tBTC, SolvBTC, and LBTC on Starknet. View validators, pools, and staking positions. Use this skill when the user mentions staking, delegating, validators, staking pools, rewards, compounding, unstaking, earning yield, passive income on crypto, or wants to earn on their STRK or BTC tokens — even if they don't say \"stake\" explicitly.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FSKILL.md",[],[],{"skillNo":142,"name":143,"nameZh":6,"description":144,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":119,"licenseFileUrl":145,"sourceHtmlUrl":146,"categories":147,"keywords":148,"publishedAt":124},"01M7DTJSDZJKCDMW7GHRF4BRH5","send","Send STRK, ETH, or any ERC-20 token to a Starknet address. Supports simulation (dry-run) before execution. Use this skill when the user wants to send, transfer, pay, tip, or move tokens to another wallet address on Starknet. Also trigger when the user mentions sending funds to someone, making a payment, transferring assets, or moving crypto to a specific address — even if they just say \"pay 10 STRK to 0x...\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FSKILL.md",[],[],{"skillNo":150,"name":151,"nameZh":6,"description":152,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":119,"licenseFileUrl":153,"sourceHtmlUrl":154,"categories":155,"keywords":156,"publishedAt":124},"01M7DTJG1E480D51ZQ7WKDQ26K","portfolio","View a comprehensive DeFi portfolio dashboard and optimize portfolio allocation via automated rebalancing. Use this skill when the user wants an overview, summary, dashboard, total value, net worth, portfolio rebalancing, target allocation, or wants to see all their DeFi positions across Starknet at once. Also trigger when the user asks \"what do I have\", \"show me everything\", \"how much am I worth\", \"my positions\", \"my investments\", \"rebalance my portfolio\", \"I want 50% ETH\", \"optimize my holdings\", or any request for a holistic view of their Starknet holdings — even if they don't explicitly say \"portfolio\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FSKILL.md",[],[],{"skillNo":158,"name":159,"nameZh":6,"description":160,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":119,"licenseFileUrl":161,"sourceHtmlUrl":162,"categories":163,"keywords":164,"publishedAt":124},"01M7DTJ7M8TE9R2N36HFBZDGVD","multi-swap","Execute multiple token swaps in a single Starknet transaction via Fibrous (default). Supports per-provider selection (avnu, ekubo, or auto to race all). Supports 2-3 swap pairs bundled into one multicall. Use this skill when the user wants to swap multiple token pairs at once, do batch swaps, execute several trades simultaneously, perform parallel swaps, or do bulk trading in one transaction. Also trigger when the user mentions \"two swaps\", \"three swaps\", \"swap X and Y at the same time\", or wants to convert multiple tokens in a single call.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FSKILL.md",[],[]]