Skip to content

Latest commit

 

History

History
92 lines (74 loc) · 3.37 KB

README.md

File metadata and controls

92 lines (74 loc) · 3.37 KB

Counter

In this example, we show how implement a counter (0 to MAX_COUNT) coin to store a current count on Chia Blockchain.

Chia Concepts and Design Patterns

This exmple demostrates several Chia concepts and design patterns:

  1. Outer and Inner puzzles
  2. Currying
  3. Singleton
  4. Storing State
    • Deriving current state from previous coin spend

Counter Puzzle

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)
    )
)    

Terminal Puzzle

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)
        )
    )
)

Notebooks

See the working examples via the notebooks: