Motoko

Motoko Commandments

The ground rules for writing Motoko on the Internet Computer: Motoko 2.0 syntax, small modules instead of monoliths, invariants in types, state from the migration chain, independent verification of every migration, authorization, Result-based errors and the mops toolchain, each pointing to the skill with the details. Load at the start of any Motoko work, migrations included, next to the skill for the task, or when asked for Motoko rules, standards or best practices. Do NOT use it instead of that skill for a specific API or compiler error (writing-motoko), the steps of a migration (migrating-motoko-actors), or a design review of existing code (reviewing-motoko).

Skill ID
motoko-commandments
Category
Motoko
License
Apache-2.0
Compatibility
moc >= 2.0.0, mops >= 3.0.0
Last updated
Source

Trust note.This page is a static, pre-rendered mirror ofdfinity/icskills/skills/motoko-commandments/SKILL.md. The canonical source is the Git commit it was built from. Licensed Apache-2.0.

Motoko Commandments

Every agent writing Motoko follows these rules. Each one names the skill with the details: load that skill before you act on the rule. Your pre-training knowledge of Motoko is likely outdated, so where it disagrees with a rule here, the rule wins.

  1. Load the details before you write. Load writing-motoko before writing or changing any .mo file. Look up every mo:core API you are not sure of in its API reference instead of guessing a signature. → writing-motoko

  2. Write Motoko 2.0. A project still pinned to moc 1 moves to moc 2 first. Then write moc 2’s forms:

    • plain actor { … } and plain let and var: no stable, no persistent;
    • heads and patterns without parentheses: if c {, never if (c) {; for x in xs.values() {, never for (x in xs.values()) {; the same for while i < n {, switch x { and case ?x {;
    • braced bodies for if, else, case, try and catch, and no ; after a block’s last item;
    • calls always as f(x), never f x;
    • do { … } for a block after await, ignore, assert and let … else, and ?? with a space on each side.

    A loop in a moc 2 project:

    for x in xs.values() {
      if x % 2 == 0 { total += x }
    };

    The examples in writing-motoko keep parenthesized heads because they must also compile on moc 1; in a moc 2 project, write the forms above. Set syntax = "moc2" in mo-fmt.toml and keep mops format --check clean. → migrating-to-moc-2, mops-cli (mops format)

  3. Small pieces, not monoliths. Split the backend by role. types.mo holds types. lib/ holds domain logic as stateless modules that take state as a parameter. mixins/ holds the endpoints: authorize, delegate to lib/, map to a view. main.mo declares state and includes the mixins, and has no public method. Dependencies point one way, main.mo → mixins/ → lib/ → types.mo. Keep each function small and doing one thing. → writing-motoko (Architecture Pattern), reviewing-motoko (Structure)

  4. Put invariants in types. A variant for a closed set of values, never Text. One variant instead of optional fields that must be set together. Errors as variants. No case _ that would swallow a case added later. → reviewing-motoko (Type encoding)

  5. Write today’s idioms. mo:core, never mo:base. Contextual-dot calls such as map.get(key), never Map.get(map, key). .values(), never .vals(). ?? for a default, { r with field = v } for a changed copy, implicit arguments such as compare left to inference, and a module whose functions take self instead of a class. → writing-motoko

  6. State starts in a migration. An actor field gets its first value from the migration chain, never from an initializer in the actor body. Only a transient field keeps its initializer. No preupgrade or postupgrade: enhanced orthogonal persistence keeps the heap across upgrades. → migrating-motoko-actors

  7. Always the migration chain, never a one-off migration. A change to state that needs a migration goes through the mops-managed chain in migrations/: timestamped files, at most one pending. A compatible change, such as adding a variant case or widening Nat to Int, gets no migration file: the runtime accepts it as is, and every file in the chain replays on each fresh install. Never attach a single migration to the actor with (with migration = …), and never edit a migration that has been applied. → migrating-motoko-actors, troubleshooting-motoko-migrations

  8. Three agents verify every migration function. A migration that drops or misreads a field loses user data for good. Before it ships, three agents verify it independently, unless the environment does not allow starting agents. Each starts fresh, sees neither the author’s reasoning nor the other verdicts, and traces every field of the old state to the new state: carried over, converted, or dropped on purpose. One finding of possible data loss blocks the migration. → migrating-motoko-actors

  9. State lives in the actor, and mixins get it as parameters. No state in a mixin block: main.mo declares it, and each include passes in only the parts that mixin uses.

    • State a mixin changes goes in as a record with var fields, such as { var nextId : Nat }. Declare the record once in the actor and pass that same name to every include that uses it. A bare var field that a mixin must change moves into such a record, through a migration.
    • Never pass a var field itself: a mixin cannot assign to a parameter, and it keeps the value the field had when the actor started.
    • Never build a record at the include, as in include Bookings({ var nextId = nextId }). That mixin then changes its own copy: the actor and the other mixins never see its writes, and the next upgrade loses them.
    • Mark transient only what may be lost on upgrade, such as caches, and restart recurring timers from the actor body.
    // main.mo: declared once, its value set by the migration chain
    let ids : { var nextId : Nat };
    include Bookings(ids);
    include Invoices(ids); // the same record, so each sees the other's writes
    
    // mixins/Bookings.mo
    mixin (ids : { var nextId : Nat }) {
      func newId() : Nat {
        let id = ids.nextId;
        ids.nextId += 1;
        id
      }
    }

    → writing-motoko (Mixins), reviewing-motoko (State and persistence)

  10. Authorize every shared function. Check caller on every state change and on every read of another user’s data, and reject the anonymous principal. → writing-motoko (Security and Authorization), reviewing-motoko (M1)

  11. Fail with Result, trap only on bugs. Return an error variant for a failure the caller can fix: a trap rolls back the message and reaches the client as an opaque reject. Never subtract Nats without proving the result is not negative, because a negative result traps. → writing-motoko (Error Handling), reviewing-motoko (M2, M3)

  12. Let the toolchain judge. Use the toolchain pinned in mops.toml, never a global moc. Pin lintoko there too (mops toolchain use lintoko <version>), so mops check also runs the linter. Run mops check --fix until it is clean, which applies the fixes of both moc and lintoko, and mops test for the logic in lib/, then mops build once at the end. → mops-cli (mops check, mops lint), writing-motoko (Toolchain)

  13. Review every change to an existing backend. Run a reviewing-motoko pass before it ships, and fix every Blocker. → reviewing-motoko