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.
-
Load the details before you write. Load
writing-motokobefore writing or changing any.mofile. Look up everymo:coreAPI you are not sure of in its API reference instead of guessing a signature. →writing-motoko -
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 plainletandvar: nostable, nopersistent; - heads and patterns without parentheses:
if c {, neverif (c) {;for x in xs.values() {, neverfor (x in xs.values()) {; the same forwhile i < n {,switch x {andcase ?x {; - braced bodies for
if,else,case,tryandcatch, and no;after a block’s last item; - calls always as
f(x), neverf x; do { … }for a block afterawait,ignore,assertandlet … 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-motokokeep parenthesized heads because they must also compile on moc 1; in a moc 2 project, write the forms above. Setsyntax = "moc2"inmo-fmt.tomland keepmops format --checkclean. →migrating-to-moc-2,mops-cli(mops format) - plain
-
Small pieces, not monoliths. Split the backend by role.
types.moholds types.lib/holds domain logic as stateless modules that take state as a parameter.mixins/holds the endpoints: authorize, delegate tolib/, map to a view.main.modeclares 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) -
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. Nocase _that would swallow a case added later. →reviewing-motoko(Type encoding) -
Write today’s idioms.
mo:core, nevermo:base. Contextual-dot calls such asmap.get(key), neverMap.get(map, key)..values(), never.vals().??for a default,{ r with field = v }for a changed copy, implicit arguments such ascompareleft to inference, and a module whose functions takeselfinstead of aclass. →writing-motoko -
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
transientfield keeps its initializer. Nopreupgradeorpostupgrade: enhanced orthogonal persistence keeps the heap across upgrades. →migrating-motoko-actors -
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 wideningNattoInt, 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 -
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 -
State lives in the actor, and mixins get it as parameters. No state in a
mixinblock:main.modeclares it, and eachincludepasses in only the parts that mixin uses.- State a mixin changes goes in as a record with
varfields, such as{ var nextId : Nat }. Declare the record once in the actor and pass that same name to everyincludethat uses it. A barevarfield that a mixin must change moves into such a record, through a migration. - Never pass a
varfield 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 ininclude 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
transientonly 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) - State a mixin changes goes in as a record with
-
Authorize every shared function. Check
calleron 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) -
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 subtractNats without proving the result is not negative, because a negative result traps. →writing-motoko(Error Handling),reviewing-motoko(M2, M3) -
Let the toolchain judge. Use the toolchain pinned in
mops.toml, never a globalmoc. Pinlintokothere too (mops toolchain use lintoko <version>), somops checkalso runs the linter. Runmops check --fixuntil it is clean, which applies the fixes of bothmocandlintoko, andmops testfor the logic inlib/, thenmops buildonce at the end. →mops-cli(mops check,mops lint),writing-motoko(Toolchain) -
Review every change to an existing backend. Run a
reviewing-motokopass before it ships, and fix every Blocker. →reviewing-motoko