Skip to content

Instantly share code, notes, and snippets.

@jasonpaulos
Created September 21, 2021 15:42
Show Gist options
  • Save jasonpaulos/93857c13cf7c52bd9c60c6a14c56326b to your computer and use it in GitHub Desktop.
Save jasonpaulos/93857c13cf7c52bd9c60c6a14c56326b to your computer and use it in GitHub Desktop.
from pyteal import *
@Subroutine(TealType.uint64)
def factorial_iterative(n):
"""Compute and return n! using loops
n! = n * (n - 1) * (n - 2) * ... * 1
"""
i = ScratchVar(TealType.uint64)
product = ScratchVar(TealType.uint64)
return Seq(
product.store(Int(1)),
For(i.store(Int(1)), i.load() <= n, i.store(i.load() + Int(1))).Do(
product.store(product.load() * i.load())
),
Return(product.load()),
)
@Subroutine(TealType.uint64)
def factorial_recursive(n):
"""Compute and return n! using recursion
n! = n * (n - 1) * (n - 2) * ... * 1
"""
return Seq(
# 0! == 1! == 1
If(n <= Int(1)).Then(Return(Int(1))),
Return(n * factorial_recursive(n - Int(1))),
)
def approval_program():
on_call = Seq(
App.globalPut(
Bytes("iterative factorial of 6"), factorial_iterative(Int(6))
), # 720
App.globalPut(
Bytes("recursive factorial of 6"), factorial_recursive(Int(6))
), # 720
Approve(),
)
is_creator = Return(Txn.sender() == Global.creator_address())
program = Cond(
[Txn.on_completion() == OnComplete.NoOp, on_call],
[
Or(
Txn.on_completion() == OnComplete.OptIn,
Txn.on_completion() == OnComplete.CloseOut,
),
Reject(),
],
[
Or(
Txn.on_completion() == OnComplete.UpdateApplication,
Txn.on_completion() == OnComplete.DeleteApplication,
),
is_creator,
],
)
return program
def clear_state_program():
return Approve()
if __name__ == "__main__":
with open("demo_approval.teal", "w") as f:
compiled = compileTeal(approval_program(), mode=Mode.Application, version=4)
f.write(compiled)
with open("demo_clear_state.teal", "w") as f:
compiled = compileTeal(clear_state_program(), mode=Mode.Application, version=4)
f.write(compiled)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment