Last active
November 8, 2021 17:04
-
-
Save algochoi/fe831538208a616aa085f34061f303f1 to your computer and use it in GitHub Desktop.
PyTeal contract for ABI testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pyteal import * | |
# Method selectors | |
add_method_selector = Bytes("base16", "0xfe6bdf69") | |
empty_method_selector = Bytes("base16", "0xa88c26a5") | |
payment_method_selector = Bytes("base16", "0x535a47ba") | |
# Method signature should be: add(uint64,uint64)uint64 | |
@Subroutine(TealType.none) | |
def add(a, b): | |
# The app should log the first four bytes of the SHA512/256 hash of the word | |
# "return" (0x151f7c75), followed by the method return argument. | |
return Log(Concat(Bytes("base16", "0x151f7c75"), Itob(Add(Btoi(a), Btoi(b))))) | |
# Method signature should be: empty()void | |
@Subroutine(TealType.none) | |
def empty(): | |
return Log(Bytes("base16", "0x151f7c75")) | |
# Method signature should be: payment(pay,address)bool | |
@Subroutine(TealType.none) | |
def payment(addr): | |
prev = Txn.group_index() - Int(1) # index of the pay transaction | |
Assert(Gtxn[prev].type_enum() == TxnType.Payment) | |
return Log(Bytes("base16", "0x151f7c7580")) | |
def approval_program(): | |
program = ( | |
If(Txn.application_id() == Int(0)) | |
.Then(Approve()) | |
.ElseIf(Txn.on_completion() == OnComplete.OptIn) | |
.Then(Approve()) | |
.ElseIf( | |
And( # calling the add method | |
Txn.on_completion() == OnComplete.NoOp, | |
Txn.application_args[0] == add_method_selector, | |
) | |
) | |
.Then(Seq([add(Txn.application_args[1], Txn.application_args[2]), Approve()])) | |
.ElseIf( | |
And( # calling the empty method | |
Txn.on_completion() == OnComplete.NoOp, | |
Txn.application_args[0] == empty_method_selector, | |
) | |
) | |
.Then(Seq([empty(), Approve()])) | |
.ElseIf( | |
And( # calling the payment method | |
Txn.on_completion() == OnComplete.NoOp, | |
Txn.application_args[0] == payment_method_selector, | |
) | |
) | |
.Then(Seq([payment(Txn.application_args[1]), Approve()])) | |
.Else(Reject()) | |
) | |
return Seq(program) | |
def clear_state_program(): | |
return Int(1) | |
if __name__ == "__main__": | |
import os | |
path = os.path.dirname(__file__) | |
with open(os.path.join(path, "abi_method_call.teal"), "w") as f: | |
compiled = compileTeal( | |
approval_program(), mode=Mode.Application, version=5, assembleConstants=True | |
) | |
f.write(compiled) | |
with open(os.path.join(path, "app_clear_state.teal"), "w") as f: | |
compiled = compileTeal( | |
clear_state_program(), | |
mode=Mode.Application, | |
version=5, | |
assembleConstants=True, | |
) | |
f.write(compiled) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment