In this example, we show how implement a counter (0 to MAX_COUNT
) coin to store a current count on Chia Blockchain.
This exmple demostrates several Chia concepts and design patterns:
- Outer and Inner puzzles
- Currying
- Singleton
- Storing State
- Deriving current state from previous coin spend
This is the main puzzle storing the current count. When a coin with this puzzle is spent, a new coin with count + 1
is created. A TERMINAL_PUZZLE
can be provided to customize the output of the last coin (when COUNT
is equal to the MAX_COUNT
).
; MOD: the puzzle itself
; MAX_COUNT: maximum count
; TERMINAL_PUZZLE: an inner puzzle run when the count reach maximum
; AMOUNT: coin amount (odd for singleton)
; COUNT: current count
(mod (MOD MAX_COUNT TERMINAL_PUZZLE AMOUNT COUNT)
(include condition_codes.clib)
(include utils.clib)
(defun create-next-counter (MOD MAX_COUNT TERMINAL_PUZZLE AMOUNT COUNT)
(list
(list CREATE_COIN
(sha256tree
(curry
MOD
(list
MOD MAX_COUNT TERMINAL_PUZZLE AMOUNT
(+ COUNT 1) ; increase count by one
)
)
)
AMOUNT
)
)
)
(if (= MAX_COUNT COUNT)
(a TERMINAL_PUZZLE ()) ; Terminated
(create-next-counter MOD MAX_COUNT TERMINAL_PUZZLE AMOUNT COUNT)
)
)
The terminal puzzles are inner puzzles providing the terminal conditions for the counter puzzle. The create-coin
puzzle will just create a new coin while the terminate-singleton
puzzle will also provide -113
which is a terminate signal for the standard singleton top layer puzzle.
(mod (PUZZLE_HASH AMOUNT)
(include condition_codes.clib)
(list
(list CREATE_COIN PUZZLE_HASH AMOUNT)
)
)
(mod (PUZZLE_HASH AMOUNT)
(include condition_codes.clib)
(list
(list CREATE_COIN PUZZLE_HASH -113) ; terminate singleton
(if (logand AMOUNT 1) ; create even amount
(list CREATE_COIN PUZZLE_HASH (- AMOUNT 1))
(list CREATE_COIN PUZZLE_HASH AMOUNT)
)
)
)
See the working examples via the notebooks: