⚙️ MICHELSON RUNE DIFFICULTY: Adept Behavioral

The Command Pattern in Michelson

Encapsulating state mutations as explicit instructions that can be executed or reverted.

✧ GANG OF FOUR LINEAGE & ARCANUM ✧
GOF DESIGN PATTERN: Command
ARCANUM SCHOOL: Enchantment // Stackmancy
SCRIBE / ARCHON: Joshua Edward McLaughlin Cox
CANONICAL REGISTRATION:
// MICHELSON PATTERN //
parameter (or (int %execute) (unit %undo));
storage (pair int (list int)); # Current state, and history of previous states
code {
  UNPAIR;
  IF_LEFT {
    # execute
    SWAP;
    UNPAIR;
    DUP; # Save current state
    DIG 3;
    ADD; # Apply command
    SWAP;
    DIG 2; CONS; # Push to history
    SWAP; PAIR;
    NIL operation; PAIR
  } {
    # undo
    DROP;
    UNPAIR;
    SWAP;
    IF_CONS {
      SWAP; DROP;
      SWAP; PAIR;
      NIL operation; PAIR
    } {
      PUSH string "CommandError: Nothing to undo"; FAILWITH;
    }
  }
}
Runic Tags: #behavioral #command #stack-based smart contracts #michelson #tezos