⚙️ MICHELSON RUNE DIFFICULTY: Adept Behavioral

The Memento Pattern in Michelson

Capturing and restoring the intrinsic state of a contract without violating encapsulation.

✧ GANG OF FOUR LINEAGE & ARCANUM ✧
GOF DESIGN PATTERN: Memento
ARCANUM SCHOOL: Enchantment // Stackmancy
SCRIBE / ARCHON: Joshua Edward McLaughlin Cox
CANONICAL REGISTRATION:
// MICHELSON PATTERN //
parameter (or (int %update_state) (unit %restore));
storage (pair int (option int)); # Current State and Memento
code {
  UNPAIR;
  IF_LEFT {
    # update_state
    SWAP;
    UNPAIR;
    # Save current state as memento
    SOME;
    SWAP; DROP;
    DIG 2;
    PAIR;
    NIL operation; PAIR
  } {
    # restore
    DROP;
    UNPAIR;
    SWAP;
    IF_NONE {
      PUSH string "MementoError: No saved state"; FAILWITH;
    } {
      SWAP; DROP;
      DUP; SOME; # Re-save the memento just in case
      SWAP; PAIR;
      NIL operation; PAIR
    }
  }
}
Runic Tags: #behavioral #memento #stack-based smart contracts #michelson #tezos