PyTeal Package

pyteal.Txn = <pyteal.TxnObject object>

The current transaction being evaluated. This is an instance of TxnObject.

pyteal.Gtxn = <pyteal.TxnGroup object>

The current group of transactions being evaluated. This is an instance of TxnGroup.

pyteal.InnerTxn = <pyteal.TxnObject object>

The most recently submitted inner transaction. This is an instance of TxnObject.

If a transaction group was submitted most recently, then this will be the last transaction in that group.

pyteal.Gitxn = <pyteal.InnerTxnGroup object>

The most recently submitted inner transaction group. This is an instance of InnerTxnGroup.

If a single transaction was submitted most recently, then this will be a group of size 1.

class pyteal.ABIReturnSubroutine(fn_implementation: Callable[[...], Expr])

Bases: object

Used to create a PyTeal Subroutine (returning an ABI value) from a python function. It’s primarily intended to define ARC-4 Application entry points though it can also be used more generally.

Disclaimer: ABIReturnSubroutine is still taking shape and is subject to backwards incompatible changes.

  • For ARC-4 Application entry point definition, feel encouraged to use ABIReturnSubroutine. Expect a best-effort attempt to minimize backwards incompatible changes along with a migration path.

  • For general purpose subroutine definition usage, use at your own risk. Based on feedback, the API and usage patterns will change more freely and with less effort to provide migration paths.

This class is meant to be used as a function decorator. For example:

@ABIReturnSubroutine
def abi_sum(toSum: abi.DynamicArray[abi.Uint64], *, output: abi.Uint64) -> Expr:
    i = ScratchVar(TealType.uint64)
    valueAtIndex = abi.Uint64()
    return Seq(
        output.set(0),
        For(i.store(Int(0)), i.load() < toSum.length(), i.store(i.load() + Int(1))).Do(
            Seq(
                toSum[i.load()].store_into(valueAtIndex),
                output.set(output.get() + valueAtIndex.get()),
            )
        ),
    )

program = Seq(
    (to_sum_arr := abi.make(abi.DynamicArray[abi.Uint64])).decode(
        Txn.application_args[1]
    ),
    (res := abi.Uint64()).set(abi_sum(to_sum_arr)),
    abi.MethodReturn(res),
    Int(1),
)
OUTPUT_ARG_NAME: Final[str] = 'output'
is_abi_routable() bool
method_signature(overriding_name: Optional[str] = None) str
method_spec() Method
name() str
type_of() str | pyteal.abi.TypeSpec
class pyteal.AccountParam

Bases: object

classmethod authAddr(acct: Expr) MaybeValue

Get the authorizing address for an account. If the account is not rekeyed, the empty addresss is returned.

Parameters

acct – An index into Txn.accounts that corresponds to the application to check or an address available at runtime. May evaluate to uint64 or an address.

classmethod balance(acct: Expr) MaybeValue

Get the current balance in microalgos an account.

Parameters

acct – An index into Txn.accounts that corresponds to the application to check or an address available at runtime. May evaluate to uint64 or an address.

classmethod minBalance(acct: Expr) MaybeValue

Get the minimum balance in microalgos for an account.

Parameters

acct – An index into Txn.accounts that corresponds to the application to check or an address available at runtime. May evaluate to uint64 or an address.

class pyteal.AccountParamObject(account: Expr)

Bases: object

Represents information about an account

__init__(account: Expr) None

Create a new AccountParamObject for the given account.

Parameters

account – An index into Txn.accounts that corresponds to the application to check or an address available at runtime. May evaluate to uint64 or bytes, respectively.

auth_address() MaybeValue

Get the authorizing address for the account.

If the account is not rekeyed, the empty address is returned.

balance() MaybeValue

Get the current balance in microAlgos for the account

min_balance() MaybeValue

Get the minimum balance in microAlgos for the account.

pyteal.Add(*args: Expr) Expr

Numerical addition.

Produces the sum of all the input arguments.

All arguments must be PyTeal expressions that evaluate to uint64, and there must be at least one argument.

Example

Add(Int(1), Int(2), Int(3))

class pyteal.Addr(address: str)

Bases: LeafExpr

An expression that represents an Algorand address.

__init__(address: str) None

Create a new Addr expression.

Parameters

address – A string containing a valid base32 Algorand address

type_of()

Get the return type of this expression.

pyteal.And(*args: Expr) Expr

Logical and expression.

Produces 1 if all arguments are nonzero. Otherwise produces 0.

All arguments must be PyTeal expressions that evaluate to uint64, and there must be at least one argument.

Example

And(Txn.amount() == Int(500), Txn.fee() <= Int(10))

class pyteal.App(field: AppField, args)

Bases: LeafExpr

An expression related to applications.

classmethod globalDel(key: Expr) App

Delete a key from the global state of the current application.

Parameters

key – The key to delete from the global application state. Must evaluate to bytes.

classmethod globalGet(key: Expr) App

Read from the global state of the current application.

Parameters

key – The key to read from the global application state. Must evaluate to bytes.

classmethod globalGetEx(app: Expr, key: Expr) MaybeValue

Read from the global state of an application.

Parameters
  • app – An index into Txn.applications that corresponds to the application to read from, must be evaluated to uint64 (or, since v4, an application id that appears in Txn.applications or is the CurrentApplicationID, must be evaluated to uint64).

  • key – The key to read from the global application state. Must evaluate to bytes.

classmethod globalPut(key: Expr, value: Expr) App

Write to the global state of the current application.

Parameters
  • key – The key to write in the global application state. Must evaluate to bytes.

  • value – THe value to write in the global application state. Can evaluate to any type.

classmethod id() Global

Get the ID of the current running application.

This is the same as Global.current_application_id().

classmethod localDel(account: Expr, key: Expr) App

Delete a key from an account’s local state for the current application.

Parameters
  • account – An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender, must be evaluated to bytes).

  • key – The key to delete from the account’s local state. Must evaluate to bytes.

classmethod localGet(account: Expr, key: Expr) App

Read from an account’s local state for the current application.

Parameters
  • account – An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender, must be evaluated to bytes).

  • key – The key to read from the account’s local state. Must evaluate to bytes.

classmethod localGetEx(account: Expr, app: Expr, key: Expr) MaybeValue

Read from an account’s local state for an application.

Parameters
  • account – An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender, must be evaluated to bytes).

  • app – An index into Txn.applications that corresponds to the application to read from, must be evaluated to uint64 (or, since v4, an application id that appears in Txn.applications or is the CurrentApplicationID, must be evaluated to int).

  • key – The key to read from the account’s local state. Must evaluate to bytes.

classmethod localPut(account: Expr, key: Expr, value: Expr) App

Write to an account’s local state for the current application.

Parameters
  • account – An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender, must be evaluated to bytes).

  • key – The key to write in the account’s local state. Must evaluate to bytes.

  • value – The value to write in the account’s local state. Can evaluate to any type.

classmethod optedIn(account: Expr, app: Expr) App

Check if an account has opted in for an application.

Parameters
  • account – An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender, must be evaluated to bytes).

  • app – An index into Txn.applications that corresponds to the application to read from, must be evaluated to uint64 (or, since v4, an application id that appears in Txn.applications or is the CurrentApplicationID, must be evaluated to int).

type_of()

Get the return type of this expression.

class pyteal.AppField(value)

Bases: Enum

Enum of app fields used to create App objects.

get_op() Op
globalDel = (<Op.app_global_del: OpType(value='app_global_del', mode=<Mode.Application: 2>, min_version=2)>, <TealType.none: 3>)
globalGet = (<Op.app_global_get: OpType(value='app_global_get', mode=<Mode.Application: 2>, min_version=2)>, <TealType.anytype: 2>)
globalGetEx = (<Op.app_global_get_ex: OpType(value='app_global_get_ex', mode=<Mode.Application: 2>, min_version=2)>, <TealType.none: 3>)
globalPut = (<Op.app_global_put: OpType(value='app_global_put', mode=<Mode.Application: 2>, min_version=2)>, <TealType.none: 3>)
localDel = (<Op.app_local_del: OpType(value='app_local_del', mode=<Mode.Application: 2>, min_version=2)>, <TealType.none: 3>)
localGet = (<Op.app_local_get: OpType(value='app_local_get', mode=<Mode.Application: 2>, min_version=2)>, <TealType.anytype: 2>)
localGetEx = (<Op.app_local_get_ex: OpType(value='app_local_get_ex', mode=<Mode.Application: 2>, min_version=2)>, <TealType.none: 3>)
localPut = (<Op.app_local_put: OpType(value='app_local_put', mode=<Mode.Application: 2>, min_version=2)>, <TealType.none: 3>)
optedIn = (<Op.app_opted_in: OpType(value='app_opted_in', mode=<Mode.Application: 2>, min_version=2)>, <TealType.uint64: 0>)
type_of() TealType
class pyteal.AppParam

Bases: object

classmethod address(app: Expr) MaybeValue

Get the escrow address for the application.

Parameters

app – An index into Txn.applications that correspond to the application to check. Must evaluate to uint64.

classmethod approvalProgram(app: Expr) MaybeValue

Get the bytecode of Approval Program for the application.

Parameters

app – An index into Txn.applications that correspond to the application to check. Must evaluate to uint64.

classmethod clearStateProgram(app: Expr) MaybeValue

Get the bytecode of Clear State Program for the application.

Parameters

app – An index into Txn.applications that correspond to the application to check. Must evaluate to uint64.

classmethod creator(app: Expr) MaybeValue

Get the creator address for the application.

Parameters

app – An index into Txn.applications that correspond to the application to check. Must evaluate to uint64.

classmethod extraProgramPages(app: Expr) MaybeValue

Get the number of Extra Program Pages of code space for the application.

Parameters

app – An index into Txn.applications that correspond to the application to check. Must evaluate to uint64.

classmethod globalNumByteSlice(app: Expr) MaybeValue

Get the number of byte array values allowed in Global State for the application.

Parameters

app – An index into Txn.applications that correspond to the application to check. Must evaluate to uint64.

classmethod globalNumUint(app: Expr) MaybeValue

Get the number of uint64 values allowed in Global State for the application.

Parameters

app – An index into Txn.applications that correspond to the application to check. Must evaluate to uint64.

classmethod localNumByteSlice(app: Expr) MaybeValue

Get the number of byte array values allowed in Local State for the application.

Parameters

app – An index into Txn.applications that correspond to the application to check. Must evaluate to uint64.

classmethod localNumUint(app: Expr) MaybeValue

Get the number of uint64 values allowed in Local State for the application.

Parameters

app – An index into Txn.applications that correspond to the application to check. Must evaluate to uint64.

class pyteal.AppParamObject(app: Expr)

Bases: object

Represents information about an application’s parameters

__init__(app: Expr) None

Create a new AppParamObject for the given application.

Parameters

app – An identifier for the app. It must be an index into Txn.ForeignApps that corresponds to the app to check, or since v4, an application ID that appears in Txn.ForeignApps or is the CurrentApplicationID. In either case, it must evaluate to uint64.

address() MaybeValue

Get the escrow address for the application.

approval_program() MaybeValue

Get the bytecode of Approval Program for the application.

clear_state_program() MaybeValue
creator_address() MaybeValue

Get the creator address for the application.

extra_program_pages() MaybeValue

Get the number of Extra Program Pages of code space for the application.

global_num_byte_slice() MaybeValue

Get the number of byte array values allowed in Global State for the application.

global_num_uint() MaybeValue

Get the number of uint64 values allowed in Global State for the application.

local_num_byte_slice() MaybeValue

Get the number of byte array values allowed in Local State for the application.

local_num_uint() MaybeValue

Get the number of uint64 values allowed in Local State for the application.

pyteal.Approve() Expr

Immediately exit the program and mark the execution as successful.

class pyteal.Arg(index: Union[int, Expr])

Bases: LeafExpr

An expression to get an argument when running in signature verification mode.

__init__(index: Union[int, Expr]) None

Get an argument for this program.

Should only be used in signature verification mode. For application mode arguments, see TxnObject.application_args.

Parameters

index – The index of the argument to get. The index must be between 0 and 255 inclusive. Starting in AVM v5, the index may be a PyTeal expression that evaluates to uint64.

type_of()

Get the return type of this expression.

class pyteal.Array

Bases: ABC

Represents a variable length array of objects.

abstract __getitem__(index: int)

Get the value at a given index in this array.

abstract length() Expr

Get the length of the array.

class pyteal.Assert(cond: Expr, *additional_conds: Expr, comment: Optional[str] = None)

Bases: Expr

A control flow expression to verify that a condition is true.

__init__(cond: Expr, *additional_conds: Expr, comment: Optional[str] = None) None

Create an assert statement that raises an error if the condition is false.

Parameters
  • cond – The condition to check. Must evaluate to a uint64.

  • *additional_conds – Additional conditions to check. Must evaluate to uint64.

  • comment – String comment to place on the line immediately prior to the assert op

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.AssetHolding

Bases: object

classmethod balance(account: Expr, asset: Expr) MaybeValue

Get the amount of an asset held by an account.

Parameters
  • account – An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender, must be evaluated to bytes).

  • asset – The ID of the asset to get, must be evaluated to uint64 (or, since v4, a Txn.assets offset).

classmethod frozen(account: Expr, asset: Expr) MaybeValue

Check if an asset is frozen for an account.

A value of 1 indicates frozen and 0 indicates not frozen.

Parameters
  • account – An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender, must be evaluated to bytes).

  • asset – The ID of the asset to get, must be evaluated to uint64 (or, since v4, a Txn.assets offset).

class pyteal.AssetHoldingObject(asset: Expr, account: Expr)

Bases: object

Represents information about an account’s holding of an asset

__init__(asset: Expr, account: Expr) None

Create a new AssetParamObject for the given asset.

Parameters
  • asset – An identifier for the asset. It must be an index into Txn.ForeignAssets that corresponds to the asset to check, or since v4, an asset ID that appears in Txn.ForeignAssets. In either case, it must evaluate to uint64.

  • account – An identifier for the account. It must be an index into Txn.Accounts that corresponds to the account to check (in which case it must evaluate to uint64), or since v4, an account address that appears in Txn.Accounts or is Txn.Sender (in which case it must evaluate to bytes).

balance() MaybeValue

Get the amount of the asset held by the account.

frozen() MaybeValue

Check if the asset is frozen for the account.

A value of 1 indicates frozen and 0 indicates not frozen.

class pyteal.AssetParam

Bases: object

classmethod clawback(asset: Expr) MaybeValue

Get the clawback address for an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod creator(asset: Expr) MaybeValue

Get the creator address for an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check. Must evaluate to uint64.

classmethod decimals(asset: Expr) MaybeValue

Get the number of decimals for an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod defaultFrozen(asset: Expr) MaybeValue

Check if an asset is frozen by default.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod freeze(asset: Expr) MaybeValue

Get the freeze address for an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod manager(asset: Expr) MaybeValue

Get the manager address for an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod metadataHash(asset: Expr) MaybeValue

Get the arbitrary commitment for an asset.

If set, this will be 32 bytes long.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod name(asset: Expr) MaybeValue

Get the name of an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod reserve(asset: Expr) MaybeValue

Get the reserve address for an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod total(asset: Expr) MaybeValue

Get the total number of units of an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod unitName(asset: Expr) MaybeValue

Get the unit name of an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

classmethod url(asset: Expr) MaybeValue

Get the URL of an asset.

Parameters

asset – An index into Txn.assets that corresponds to the asset to check, must be evaluated to uint64 (or since v4, an asset ID that appears in Txn.assets).

class pyteal.AssetParamObject(asset: Expr)

Bases: object

Represents information about an asset’s parameters

__init__(asset: Expr) None

Create a new AssetParamObject for the given asset.

Parameters

asset – An identifier for the asset. It must be an index into Txn.ForeignAssets that corresponds to the asset to check, or since v4, an asset ID that appears in Txn.ForeignAssets. In either case, it must evaluate to uint64.

clawback_address() MaybeValue

Get the clawback address for the asset.

creator_address() MaybeValue

Get the creator address for the asset.

decimals() MaybeValue

Get the number of decimals for the asset.

default_frozen() MaybeValue

Check if the asset is frozen by default.

freeze_address() MaybeValue

Get the freeze address for the asset.

manager_address() MaybeValue

Get the manager address for the asset.

metadata_hash() MaybeValue

Get the arbitrary commitment for the asset.

If set, this will be 32 bytes long.

name() MaybeValue

Get the name of the asset.

reserve_address() MaybeValue

Get the reserve address for the asset.

total() MaybeValue

Get the total number of units of the asset.

unit_name() MaybeValue

Get the unit name of the asset.

url() MaybeValue

Get the URL of the asset.

pyteal.Balance(account: Expr) UnaryExpr

Get the balance of a user in microAlgos.

Argument must be an index into Txn.Accounts that corresponds to the account to read from, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender).

This operation is only permitted in application mode.

class pyteal.BareCallActions(*, close_out: ~pyteal.OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>), clear_state: ~pyteal.OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>), delete_application: ~pyteal.OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>), no_op: ~pyteal.OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>), opt_in: ~pyteal.OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>), update_application: ~pyteal.OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>))

Bases: object

BareCallActions keep track of bare-call registrations to all OnCompletion cases.

approval_construction() Optional[Expr]
clear_state: OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>)
clear_state_construction() Optional[Expr]
close_out: OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>)
delete_application: OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>)
is_empty() bool
no_op: OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>)
opt_in: OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>)
update_application: OnCompleteAction = OnCompleteAction(action=None, call_config=<CallConfig.NEVER: 0>)
class pyteal.Base64Decode(encoding: Base64Encoding, base64: Expr)

Bases: Expr

An expression that decodes a base64-encoded byte string according to a specific encoding.

See [RFC 4648](https://rfc-editor.org/rfc/rfc4648.html#section-4) (sections 4 and 5) for information on specifications.

It is assumed that the encoding ends with the exact number of = padding characters as required by the RFC. When padding occurs, any unused pad bits in the encoding must be set to zero or the decoding will fail. The special cases of n and r are allowed but completely ignored. An error will result when attempting to decode a string with a character that is not in the encoding alphabet or not one of =, r, or n.

NOTE: Base64Decode usage is not intended for introducing constants. Instead, use Bytes.

has_return()

Check if this expression always returns from the current subroutine or program.

classmethod std(base64: Expr) Expr

Decode a base64-encoded byte string according to the Standard encoding.

Refer to the Base64Decode class documentation for more information.

Parameters

base64 – A base64-encoded byte string.

type_of()

Get the return type of this expression.

classmethod url(base64: Expr) Expr

Decode a base64-encoded byte string according to the URL encoding.

Refer to the Base64Decode class documentation for more information.

Parameters

base64 – A base64-encoded byte string.

class pyteal.BinaryExpr(op: Op, inputType: Union[TealType, Tuple[TealType, TealType]], outputType: TealType, argLeft: Expr, argRight: Expr)

Bases: Expr

An expression with two arguments.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.BitLen(arg: Expr) UnaryExpr

Get the index of the highest nonzero bit in an integer.

If the argument is 0, 0 will be returned.

If the argument is a byte array, it is interpreted as a big-endian unsigned integer.

Requires program version 4 or higher.

pyteal.BitwiseAnd(left: Expr, right: Expr) Expr

Bitwise and expression.

Produces left & right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

pyteal.BitwiseNot(arg: Expr) UnaryExpr

Get the bitwise inverse of a uint64.

Produces ~arg.

pyteal.BitwiseOr(left: Expr, right: Expr) Expr

Bitwise or expression.

Produces left | right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

pyteal.BitwiseXor(left: Expr, right: Expr) Expr

Bitwise xor expression.

Produces left ^ right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

class pyteal.Block(field: BlockField, block: Expr)

Bases: LeafExpr

An expression that accesses a block property.

classmethod seed(block: Expr) Expr

Get the seed of a block.

Parameters

block – A block index that corresponds to the block to check, must be evaluated to uint64. Fails if the block index is not less than Txn.first_valid() or more than 1001 rounds before Txn.last_valid().

classmethod timestamp(block: Expr) Expr

Get the timestamp of a block.

Parameters

block – A block index that corresponds to the block to check, must be evaluated to uint64. Fails if the block index is not less than Txn.first_valid() or more than 1001 rounds before Txn.last_valid().

type_of()

Get the return type of this expression.

class pyteal.Break

Bases: Expr

A break expression

__init__() None

Create a new break expression.

This operation is only permitted in a loop.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.Btoi(arg: Expr) UnaryExpr

Convert a byte string to a uint64.

class pyteal.Bytes(arg1: str | bytes | bytearray, arg2: Optional[str] = None)

Bases: LeafExpr

An expression that represents a byte string.

__init__(arg1: Union[str, bytes, bytearray]) None
__init__(self, arg1: str, arg2: str) None

Create a new byte string.

Depending on the encoding, there are different arguments to pass:

For UTF-8 strings:

Pass the string as the only argument. For example, Bytes("content").

For raw bytes or bytearray objects:

Pass the bytes or bytearray as the only argument. For example, Bytes(b"content").

For base16, base32, or base64 strings:

Pass the base as the first argument and the string as the second argument. For example, Bytes("base16", "636F6E74656E74"), Bytes("base32", "ORFDPQ6ARJK"), Bytes("base64", "Y29udGVudA==").

Special case for base16:

The prefix “0x” may be present in a base16 byte string. For example, Bytes("base16", "0x636F6E74656E74").

type_of()

Get the return type of this expression.

pyteal.BytesAdd(left: Expr, right: Expr) Expr

Add two numbers as bytes.

Produces left + right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesAnd(left: Expr, right: Expr) Expr

Bitwise and expression with bytes as arguments.

Produces left & right. Left and right are zero-left extended to the greater of their lengths. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesDiv(left: Expr, right: Expr) Expr

Divide two numbers as bytes.

Produces left / right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Panics if right is 0.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesEq(left: Expr, right: Expr) Expr

Equality expression with bytes as arguments.

Checks if left == right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesGe(left: Expr, right: Expr) Expr

Greater than or equal to expression with bytes as arguments.

Checks if left >= right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesGt(left: Expr, right: Expr) Expr

Greater than expression with bytes as arguments.

Checks if left > right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesLe(left: Expr, right: Expr) Expr

Less than or equal to expression with bytes as arguments.

Checks if left <= right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesLt(left: Expr, right: Expr) Expr

Less than expression with bytes as arguments.

Checks if left < right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesMinus(left: Expr, right: Expr) Expr

Subtract two numbers as bytes.

Produces left - right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesMod(left: Expr, right: Expr) Expr

Modulo expression with bytes as arguments.

Produces left % right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Panics if right is 0.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesMul(left: Expr, right: Expr) Expr

Multiply two numbers as bytes.

Produces left * right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesNeq(left: Expr, right: Expr) Expr

Difference expression with bytes as arguments.

Checks if left != right, where left and right are interpreted as big-endian unsigned integers. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesNot(arg: Expr) UnaryExpr

Get the bitwise inverse of bytes.

Produces ~arg. Argument must not exceed 64 bytes.

Requires program version 4 or higher.

pyteal.BytesOr(left: Expr, right: Expr) Expr

Bitwise or expression with bytes as arguments.

Produces left | right. Left and right are zero-left extended to the greater of their lengths. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesSqrt(arg: Expr) UnaryExpr

Get the bytes square root of bytes.

This will return the largest integer X such that X^2 <= arg.

Requires program version 6 or higher.

pyteal.BytesXor(left: Expr, right: Expr) Expr

Bitwise xor expression with bytes as arguments.

Produces left ^ right. Left and right are zero-left extended to the greater of their lengths. Arguments must not exceed 64 bytes.

Requires program version 4 or higher.

Parameters
  • left – Must evaluate to bytes.

  • right – Must evaluate to bytes.

pyteal.BytesZero(arg: Expr) UnaryExpr

Get a byte-array of a specified length, containing all zero bytes.

Argument must evaluate to uint64.

Requires program version 4 or higher.

class pyteal.CallConfig(value)

Bases: IntFlag

CallConfig: a “bitset”-like class for more fine-grained control over call or create for a method about an OnComplete case.

This enumeration class allows for specifying one of the four following cases: - CALL - CREATE - ALL - NEVER for a method call on one on_complete case.

ALL = 3
CALL = 1
CREATE = 2
NEVER = 0
approval_condition_under_config() pyteal.Expr | int
clear_state_condition_under_config() int
pyteal.Comment(comment: str, expr: Optional[Expr] = None) Expr

Wrap an existing expression with a comment.

This comment will be present in the compiled TEAL source immediately before the first op of the expression.

Note that when TEAL source is assembled into bytes, all comments are omitted.

Parameters
  • comment – The comment that will be associated with the expression.

  • expr – The expression to be commented.

Returns

A new expression which is functionally equivalent to the input expression, but which will compile with the given comment string.

class pyteal.CompileOptions(*, mode: Mode = Mode.Signature, version: int = 2, optimize: Optional[OptimizeOptions] = None)

Bases: object

addLoopBreakBlock(block: TealSimpleBlock) None
addLoopContinueBlock(block: TealSimpleBlock) None
enterLoop() None
exitLoop() Tuple[List[TealSimpleBlock], List[TealSimpleBlock]]
isInLoop() bool
setSubroutine(subroutine: Optional[SubroutineDefinition]) None
pyteal.Concat(*args: Expr) Expr

Concatenate byte strings.

Produces a new byte string consisting of the contents of each of the passed in byte strings joined together.

All arguments must be PyTeal expressions that evaluate to bytes, and there must be at least one argument.

Example

Concat(Bytes("hello"), Bytes(" "), Bytes("world"))

class pyteal.Cond(*argv: List[Expr])

Bases: Expr

A chainable branching expression that supports an arbitrary number of conditions.

__init__(*argv: List[Expr])

Create a new Cond expression.

At least one argument must be provided, and each argument must be a list with two or more elements. The first element is a condition which evalutes to uint64, and the remaining elements are the body of the condition, which will execute if that condition is true. The last elements of the condition bodies must have the same return type. During execution, each condition is tested in order, and the first condition to evaluate to a true value will cause its associated body to execute and become the value for this Cond expression. If no condition evalutes to a true value, the Cond expression produces an error and the TEAL program terminates.

Example

Cond([Global.group_size() == Int(5), bid],
    [Global.group_size() == Int(4), redeem, log],
    [Global.group_size() == Int(1), wrapup])
has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.Continue

Bases: Expr

A continue expression

__init__() None

Create a new continue expression.

This operation is only permitted in a loop.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.Div(left: Expr, right: Expr) Expr

Divide two numbers.

Produces left / right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

pyteal.Divw(hi: Expr, lo: Expr, y: Expr) TernaryExpr

Performs wide division by interpreting hi and lo as a uint128 value.

Requires program version 6 or higher.

Parameters
  • hi – Quotient’s high 64 bits. Must evaluate to uint64.

  • lo – Quotient’s low 64 bits. Must evaluate to uint64.

  • y – Divisor. Must evaluate to uint64.

class pyteal.DynamicScratchVar(ttype: TealType = TealType.anytype)

Bases: ScratchVar

Example of Dynamic Scratch space whereby the slot index is picked up from the stack:
player_score = DynamicScratchVar(TealType.uint64)

wilt = ScratchVar(TealType.uint64, 129)
kobe = ScratchVar(TealType.uint64)
dt = ScratchVar(TealType.uint64, 131)

seq = Seq(
    player_score.set_index(wilt),
    player_score.store(Int(100)),
    player_score.set_index(kobe),
    player_score.store(Int(81)),
    player_score.set_index(dt),
    player_score.store(Int(73)),
    Assert(player_score.load() == Int(73)),
    Assert(player_score.index() == Int(131)),
    player_score.set_index(wilt),
    Assert(player_score.load() == Int(100)),
    Assert(player_score.index() == Int(129)),
    Int(100),
)
__init__(ttype: TealType = TealType.anytype)

Create a new DynamicScratchVar which references other ScratchVar’s

Parameters

ttype (optional) – The type that this variable can hold. Defaults to TealType.anytype.

index() Expr

Get the index of the referenced ScratchVar.

internal_index() Expr

Get the index of _this_ DynamicScratchVar, as opposed to that of the referenced ScratchVar.

load() ScratchLoad

Load the current value from the referenced ScratchVar.

set_index(index_var: ScratchVar) Expr

Set this DynamicScratchVar to reference the provided index_var. Followup store, load and index operations will use the provided index_var until set_index() is called again to reset the referenced ScratchVar.

storage_type() TealType

Get the type of expressions that can be stored in this ScratchVar.

store(value: Expr) Expr

Store the value in the referenced ScratchVar.

class pyteal.EcdsaCurve(value)

Bases: Enum

Enum representing an elliptic curve specification used in ECDSA.

Secp256k1 = (0, 'Secp256k1', 5)
Secp256r1 = (1, 'Secp256r1', 7)
pyteal.EcdsaDecompress(curve: EcdsaCurve, compressed_pk: Expr) MultiValue

Decompress an ECDSA public key. :param curve: Enum representing the ECDSA curve used for the public key :param compressed_pk: The compressed public key. Must be 33 bytes long and big endian encoded.

Returns

A MultiValue expression representing the two components of the public key, big endian encoded.

pyteal.EcdsaRecover(curve: EcdsaCurve, data: Expr, recovery_id: Expr, sigA: Expr, sigB: Expr) MultiValue

Recover an ECDSA public key from a signature. All byte arguments must be big endian encoded. :param curve: Enum representing the ECDSA curve used for the public key :param data: Hash value of the signed data. Must be 32 bytes long. :param recovery_id: value used to extract public key from signature. Must evaluate to uint. :param sigA: First component of the signature. Must evaluate to bytes. :param sigB: Second component of the signature. Must evaluate to bytes.

Returns

A MultiValue expression representing the two components of the public key, big endian encoded.

pyteal.EcdsaVerify(curve: EcdsaCurve, data: Expr, sigA: Expr, sigB: Expr, pubkey: Union[Tuple[Expr, Expr], MultiValue]) Expr

Verify an ECDSA signature.

The public key argument can be represented as either a tuple of Byte expressions representing the (X,Y) point on the elliptic curve or a MultiValue expression returning two Byte expressions, ex. the value returned by EcdsaDecompress or EcdsaRecover. All byte arguments must be big endian encoded.

Parameters
  • curve – Enum representing the ECDSA curve used for the signature and public key

  • data – Hash value of the signed data. Must be 32 bytes long.

  • sigA – First component of the signature. Must evaluate to bytes.

  • sigB – Second component of the signature. Must evaluate to bytes.

  • pubkey – Public key used to verify signature. Represented as either a tuple of expressions that must evaluate to bytes or as a MultiValue expression that returns two byte values.

Returns

An expression evaluating to either 0 or 1 representing the success of verification

pyteal.Ed25519Verify(data: Expr, sig: Expr, key: Expr) TernaryExpr

Verify the ed25519 signature of the concatenation (“ProgData” + hash_of_current_program + data).

Parameters
  • data – The data signed by the public key. Must evaluate to bytes.

  • sig – The proposed 64-byte signature of the concatenation (“ProgData” + hash_of_current_program + data). Must evaluate to bytes.

  • key – The 32 byte public key that produced the signature. Must evaluate to bytes.

pyteal.Ed25519Verify_Bare(data: Expr, sig: Expr, key: Expr) TernaryExpr

Verify the ed25519 signature of the data against the public key.

Parameters
  • data – The data signed by the public key. Must evaluate to bytes.

  • sig – The proposed 64-byte signature of the data. Must evaluate to bytes.

  • key – The 32 byte public key that produced the signature. Must evaluate to bytes.

class pyteal.EnumInt(name: str)

Bases: LeafExpr

An expression that represents uint64 enum values.

__init__(name: str) None

Create an expression to reference a uint64 enum value.

Parameters

name – The name of the enum value.

type_of()

Get the return type of this expression.

pyteal.Eq(left: Expr, right: Expr) Expr

Equality expression.

Checks if left == right.

Parameters
  • left – A value to check.

  • right – The other value to check. Must evaluate to the same type as left.

class pyteal.Err

Bases: Expr

Expression that causes the program to immediately fail when executed.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.Exp(a: Expr, b: Expr) Expr

Exponential expression.

Produces a ** b.

Requires program version 4 or higher.

Parameters
  • a – Must evaluate to uint64.

  • b – Must evaluate to uint64.

class pyteal.Expr

Bases: ABC

Abstract base class for PyTeal expressions.

And(other: Expr) Expr

Take the logical And of this expression and another one.

This expression must evaluate to uint64.

This is the same as using And() with two arguments.

Or(other: Expr) Expr

Take the logical Or of this expression and another one.

This expression must evaluate to uint64.

This is the same as using Or() with two arguments.

getDefinitionTrace() List[str]
abstract has_return() bool

Check if this expression always returns from the current subroutine or program.

abstract type_of() TealType

Get the return type of this expression.

pyteal.Extract(string: Expr, start: Expr, length: Expr) Expr

Extract a section of a byte string.

Produces a new byte string consisting of the bytes starting at start up to but not including start + length.

This expression is similar to Substring, except this expression uses a start index and length, while Substring uses start and end indexes.

Requires program version 5 or higher.

Parameters
  • string – The byte string.

  • start – The starting index for the extraction. Must be an integer less than or equal to Len(string).

  • length – The number of bytes to extract. Must be an integer such that start + length <= Len(string).

pyteal.ExtractUint16(string: Expr, offset: Expr) Expr

Extract 2 bytes (16 bits) and convert them to an integer.

The bytes starting at offset up to but not including offset + 2 will be interpreted as a big-endian unsigned integer.

If offset + 2 exceeds Len(string), the program fails.

Requires program version 5 or higher.

Parameters
  • string – The bytestring to extract from. Must evaluate to bytes.

  • offset – The offset in the bytestring to start extracing. Must evaluate to uint64.

pyteal.ExtractUint32(string: Expr, offset: Expr) Expr

Extract 4 bytes (32 bits) and convert them to an integer.

The bytes starting at offset up to but not including offset + 4 will be interpreted as a big-endian unsigned integer.

If offset + 4 exceeds Len(string), the program fails.

Requires program version 5 or higher.

Parameters
  • string – The bytestring to extract from. Must evaluate to bytes.

  • offset – The offset in the bytestring to start extracing. Must evaluate to uint64.

pyteal.ExtractUint64(string: Expr, offset: Expr) Expr

Extract 8 bytes (64 bits) and convert them to an integer.

The bytes starting at offset up to but not including offset + 8 will be interpreted as a big-endian unsigned integer.

If offset + 8 exceeds Len(string), the program fails.

Requires program version 5 or higher.

Parameters
  • string – The bytestring to extract from. Must evaluate to bytes.

  • offset – The offset in the bytestring to start extracing. Must evaluate to uint64.

class pyteal.For(start: Expr, cond: Expr, step: Expr)

Bases: Expr

For expression.

Do(doBlock: Expr, *do_block_multi: Expr)
__init__(start: Expr, cond: Expr, step: Expr) None

Create a new For expression.

When this For expression is executed, the condition will be evaluated, and if it produces a true value, doBlock will be executed and return to the start of the expression execution. Otherwise, no branch will be executed.

Parameters
  • start – Expression setting the variable’s initial value

  • cond – The condition to check. Must evaluate to uint64.

  • step – Expression to update the variable’s value.

Example

i = ScratchVar()
For(i.store(Int(0)), i.load() < Int(10), i.store(i.load() + Int(1))
    .Do(expr1, expr2, ...)
has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.Ge(left: Expr, right: Expr) Expr

Greater than or equal to expression.

Checks if left >= right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

class pyteal.GeneratedID(txnIndex: Union[int, Expr])

Bases: LeafExpr

An expression to obtain the ID of an asset or application created by another transaction in the current group.

__init__(txnIndex: Union[int, Expr]) None

Create an expression to extract the created ID from a transaction in the current group.

Requires program version 4 or higher. This operation is only permitted in application mode.

Parameters

txnIndex – The index of the transaction from which the created ID should be obtained. This index may be a Python int, or it may be a PyTeal expression that evaluates at runtime. If it’s an expression, it must evaluate to a uint64. In all cases, the index must be less than the index of the current transaction.

type_of()

Get the return type of this expression.

pyteal.GetBit(value: Expr, index: Expr) Expr

Get the bit value of an expression at a specific index.

The meaning of index differs if value is an integer or a byte string.

  • For integers, bit indexing begins with low-order bits. For example, GetBit(Int(16), Int(4)) yields 1. Any other valid index would yield a bit value of 0. Any integer less than 64 is a valid index.

  • For byte strings, bit indexing begins at the first byte. For example, GetBit(Bytes("base16", "0xf0"), Int(0)) yields 1. Any index less than 4 would yield 1, and any valid index 4 or greater would yield 0. Any integer less than 8*Len(value) is a valid index.

Requires program version 3 or higher.

Parameters
  • value – The value containing bits. Can evaluate to any type.

  • index – The index of the bit to extract. Must evaluate to uint64.

pyteal.GetByte(value: Expr, index: Expr) Expr

Extract a single byte as an integer from a byte string.

Similar to GetBit, indexing begins at the first byte. For example, GetByte(Bytes("base16", "0xff0000"), Int(0)) yields 255. Any other valid index would yield 0.

Requires program version 3 or higher.

Parameters
  • value – The value containing the bytes. Must evaluate to bytes.

  • index – The index of the byte to extract. Must evaluate to an integer less than Len(value).

class pyteal.GitxnExpr(txnIndex: int, field: TxnField)

Bases: TxnExpr

An expression that accesses an inner transaction field from an inner transaction in the last inner group.

class pyteal.GitxnaExpr(txnIndex: int, field: TxnField, index: Union[int, Expr])

Bases: TxnaExpr

An expression that accesses an inner transaction array field from an inner transaction in the last inner group.

class pyteal.Global(field: GlobalField)

Bases: LeafExpr

An expression that accesses a global property.

classmethod caller_app_address() Global

Get the address of the app that submitted the InnerTransaction that triggered this app to execute.

If not called from another app, this will return the ZeroAddress

Requires program version 6 or higher.

classmethod caller_app_id() Global

Get the id of the app that submitted the InnerTransaction that triggered this app to execute.

If not called from another app, this will return 0

Requires program version 6 or higher.

classmethod creator_address() Global

Address of the creator of the current application.

Fails during Signature mode. Requires program version 3 or higher.

classmethod current_application_address() Global

Get the address of that the current application controls.

Fails during Signature mode. Requires program version 5 or higher.

classmethod current_application_id() Global

Get the ID of the current application executing.

Fails during Signature mode.

classmethod group_id() Global

Get the ID of the current transaction group.

If the current transaction is not part of a group, this will return 32 zero bytes.

Requires program version 5 or higher.

classmethod group_size() Global

Get the number of transactions in this atomic transaction group.

This will be at least 1.

classmethod latest_timestamp() Global

Get the latest confirmed block UNIX timestamp.

Fails if negative.

classmethod logic_sig_version() Global

Get the maximum supported program version.

classmethod max_txn_life() Global

Get the maximum number of rounds a transaction can have.

classmethod min_balance() Global

Get the minimum balance in micro Algos.

classmethod min_txn_fee() Global

Get the minimum transaction fee in micro Algos.

classmethod opcode_budget() Global

Get the remaining opcode execution budget

Requires program version 6 or higher.

classmethod round() Global

Get the current round number.

type_of()

Get the return type of this expression.

classmethod zero_address() Global

Get the 32 byte zero address.

class pyteal.GlobalField(value)

Bases: Enum

An enumeration.

caller_app_address = (14, 'CallerApplicationAddress', <TealType.bytes: 1>, 6)
caller_app_id = (13, 'CallerApplicationID', <TealType.uint64: 0>, 6)
creator_address = (9, 'CreatorAddress', <TealType.bytes: 1>, 3)
current_app_address = (10, 'CurrentApplicationAddress', <TealType.bytes: 1>, 5)
current_app_id = (8, 'CurrentApplicationID', <TealType.uint64: 0>, 2)
group_id = (11, 'GroupID', <TealType.bytes: 1>, 5)
group_size = (4, 'GroupSize', <TealType.uint64: 0>, 2)
latest_timestamp = (7, 'LatestTimestamp', <TealType.uint64: 0>, 2)
logic_sig_version = (5, 'LogicSigVersion', <TealType.uint64: 0>, 2)
max_txn_life = (2, 'MaxTxnLife', <TealType.uint64: 0>, 2)
min_balance = (1, 'MinBalance', <TealType.uint64: 0>, 2)
min_txn_fee = (0, 'MinTxnFee', <TealType.uint64: 0>, 2)
opcode_budget = (12, 'OpcodeBudget', <TealType.uint64: 0>, 6)
round = (6, 'Round', <TealType.uint64: 0>, 2)
type_of() TealType
zero_address = (3, 'ZeroAddress', <TealType.bytes: 1>, 2)
pyteal.Gt(left: Expr, right: Expr) Expr

Greater than expression.

Checks if left > right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

class pyteal.GtxnExpr(txnIndex: Union[int, Expr], field: TxnField)

Bases: TxnExpr

An expression that accesses a transaction field from a transaction in the current group.

class pyteal.GtxnaExpr(txnIndex: Union[int, Expr], field: TxnField, index: Union[int, Expr])

Bases: TxnaExpr

An expression that accesses a transaction array field from a transaction in the current group.

class pyteal.If(cond: Expr, thenBranch: Optional[Expr] = None, elseBranch: Optional[Expr] = None)

Bases: Expr

Simple two-way conditional expression.

Else(elseBranch: Expr, *else_branch_multi: Expr)
ElseIf(cond)
Then(thenBranch: Expr, *then_branch_multi: Expr)
__init__(cond: Expr, thenBranch: Optional[Expr] = None, elseBranch: Optional[Expr] = None) None

Create a new If expression.

When this If expression is executed, the condition will be evaluated, and if it produces a true value, thenBranch will be executed and used as the return value for this expression. Otherwise, elseBranch will be executed and used as the return value, if it is provided.

Parameters
  • cond – The condition to check. Must evaluate to uint64.

  • thenBranch – Expression to evaluate if the condition is true.

  • elseBranch (optional) – Expression to evaluate if the condition is false. Must evaluate to the same type as thenBranch, if provided. Defaults to None.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.ImportScratchValue(txnIndex: Union[int, Expr], slotId: Union[int, Expr])

Bases: LeafExpr

An expression to load a scratch value created by another transaction in the current group

__init__(txnIndex: Union[int, Expr], slotId: Union[int, Expr]) None

Create an expression to load a scratch space slot from a transaction in the current group.

Requires program version 4 or higher. This operation is only permitted in application mode.

Parameters
  • txnIndex – The index of the transaction from which the created ID should be obtained. This index may be a Python int, or it may be a PyTeal expression that evaluates at runtime. If it’s an expression, it must evaluate to a uint64. In all cases, the index must be less than the index of the current transaction.

  • slotId – The index of the scratch slot that should be loaded. This index may be a Python int, or it may be a PyTeal expression that evaluates at runtime. If it’s an expression, it must evaluate to a uint64. In all cases, the index must be in the range [0, 256).

type_of()

Get the return type of this expression.

class pyteal.InnerTxnAction(value)

Bases: Enum

An enumeration.

Begin = Op.itxn_begin
Next = Op.itxn_next
Submit = Op.itxn_submit
class pyteal.InnerTxnBuilder

Bases: object

This class represents expressions used to create, modify, and submit inner transactions.

Inner transactions are transactions which applications can dynamically create. Each inner transaction will appear as a transaction inside of the current transaction being executed.

As of program version 5, only the transaction types TxnType.Payment, TxnType.AssetTransfer, TxnType.AssetConfig, and TxnType.AssetFreeze are allowed. Additionally, not all fields are allowed to be set. For example, it is not currently allowed to set the rekeyTo field of an inner transaction.

classmethod Begin() Expr

Begin preparation of a new inner transaction.

This new inner transaction is initialized with its sender to the application address (Global.current_application_address); fee to the minimum allowable, taking into account MinTxnFee and credit from overpaying in earlier transactions; FirstValid/LastValid to the values in the top-level transaction, and all other fields to zero values.

Requires program version 5 or higher. This operation is only permitted in application mode.

classmethod Execute(fields: dict[pyteal.TxnField, pyteal.Expr | list[pyteal.Expr]]) Expr

Performs a single transaction given fields passed in.

A convenience method that accepts fields to submit a single inner transaction, which is equivalent to:

InnerTxnBuilder.Begin()
InnerTxnBuilder.SetFields(fields)
InnerTxnBuilder.Submit()

Requires program version 5 or higher. This operation is only permitted in application mode.

Parameters

fields – A dictionary whose keys are fields to set and whose values are the value each field should take. Each value must evaluate to a type that is compatible with the field being set.

classmethod ExecuteMethodCall(*, app_id: Expr, method_signature: str, args: list[pyteal.abi.BaseType | pyteal.Expr | dict[pyteal.TxnField, pyteal.Expr | list[pyteal.Expr]]], extra_fields: Optional[dict[pyteal.TxnField, pyteal.Expr | list[pyteal.Expr]]] = None) Expr

Performs a single app call transaction formatted as an ABI method call.

A convenience method that accepts fields to submit a single inner transaction, which is equivalent to:

InnerTxnBuilder.Begin()
InnerTxnBuilder.MethodCall(
    app_id=app_id,
    method_signature=method_signature,
    args=args,
    extra_fields=extra_fields,
),
InnerTxnBuilder.Submit()

Requires program version 5 or higher. This operation is only permitted in application mode.

Parameters
  • app_id – An expression that evaluates to a TealType.uint64 corresponding to the application being called.

  • method_signature – A string representing the method signature of the method we’re calling. This is used to do type checking on the arguments passed and to create the method selector passed as the first argument.

  • args

    A list of arguments to pass to the application. The values in this list depend on the kind of argument you wish to pass:

    • For basic ABI arguments (not Reference or Transaction types):

      If an ABI type is passed it MUST match the type specified in the method_signature. If an Expr is passed it must evaluate to TealType.bytes but beyond that no type checking is performed.

    • For Reference arguments:

      Either the Reference type or an Expr that returns the type corresponding to the reference type are allowed. (i.e. Asset is TealType.uint64, Application is TealType.uint64, Account is TealType.bytes)

    • For Transaction arguments:

      A dictionary containing TxnField to Expr that describe Transactions to be pre-pended to the transaction group being constructed. The TxnField.type_enum key MUST be set and MUST match the expected transaction type specified in the method_signature.

  • extra_fields (optional) – A dictionary whose keys are fields to set and whose values are the value each field should take. Each value must evaluate to a type that is compatible with the field being set. These fields are set on the ApplicationCallTransaction being constructed

classmethod MethodCall(*, app_id: Expr, method_signature: str, args: list[pyteal.abi.BaseType | pyteal.Expr | dict[pyteal.TxnField, pyteal.Expr | list[pyteal.Expr]]], extra_fields: Optional[dict[pyteal.TxnField, pyteal.Expr | list[pyteal.Expr]]] = None) Expr

Adds an ABI method call transaction to the current inner transaction group.

InnerTxnBuilder.Begin must be called before a MethodCall can be added.

Requires Teal version 6 or higher. This operation is only permitted in application mode.

Parameters
  • app_id – An expression that evaluates to a TealType.uint64 corresponding to the application being called.

  • method_signature – A string representing the method signature of the method we’re calling. This is used to do type checking on the arguments passed and to create the method selector passed as the first argument.

  • args

    A list of arguments to pass to the application. The values in this list depend on the kind of argument you wish to pass:

    • For basic ABI arguments (not Reference or Transaction types):

      If an ABI type is passed it MUST match the type specified in the method_signature. If an Expr is passed it must evaluate to TealType.bytes but beyond that no type checking is performed.

    • For Reference arguments:

      Either the Reference type or an Expr that returns the type corresponding to the reference type are allowed. (i.e. Asset is TealType.uint64, Application is TealType.uint64, Account is TealType.bytes)

    • For Transaction arguments:

      A dictionary containing TxnField to Expr that describe Transactions to be pre-pended to the transaction group being constructed. The TxnField.type_enum key MUST be set and MUST match the expected transaction type specified in the method_signature.

  • extra_fields (optional) – A dictionary whose keys are fields to set and whose values are the value each field should take. Each value must evaluate to a type that is compatible with the field being set. These fields are set on the ApplicationCallTransaction being constructed

classmethod Next() Expr

Begin preparation of a new inner transaction (in the same transaction group).

This new inner transaction is initialized with its sender to the application address (Global.current_application_address); fee to the minimum allowable, taking into account MinTxnFee and credit from overpaying in earlier transactions; FirstValid/LastValid to the values in the top-level transaction, and all other fields to zero values.

Requires program version 6 or higher. This operation is only permitted in application mode.

classmethod SetField(field: TxnField, value: pyteal.Expr | list[pyteal.Expr]) Expr

Set a field of the current inner transaction.

InnerTxnBuilder.Begin must be called before setting any fields on an inner transaction.

Note: For non-array field (e.g., note), setting it twice will overwrite the original value.

While for array field (e.g., accounts), setting it multiple times will append the values. It is also possible to pass the entire array field if desired (e.g., Txn.accounts) to pass all the references.

Requires program version 5 or higher. This operation is only permitted in application mode.

Parameters
  • field – The field to set on the inner transaction.

  • value – The value to that the field should take. This must evaluate to a type that is compatible with the field being set.

classmethod SetFields(fields: dict[pyteal.TxnField, pyteal.Expr | list[pyteal.Expr]]) Expr

Set multiple fields of the current inner transaction.

InnerTxnBuilder.Begin must be called before setting any fields on an inner transaction.

Note: For non-array field (e.g., note), setting it twice will overwrite the original value.

While for array field (e.g., accounts), setting it multiple times will append the values. It is also possible to pass the entire array field if desired (e.g., Txn.accounts) to pass all the references.

Requires program version 5 or higher. This operation is only permitted in application mode.

Parameters

fields – A dictionary whose keys are fields to set and whose values are the value each field should take. Each value must evaluate to a type that is compatible with the field being set.

classmethod Submit() Expr

Execute the current inner transaction.

InnerTxnBuilder.Begin and InnerTxnBuilder.SetField must be called before submitting an inner transaction.

This will fail if 256 inner transactions have already been executed, or if the inner transaction itself fails. Upon failure, the current program will immediately exit and fail as well.

If the inner transaction is successful, then its effects can be immediately observed by this program with stateful expressions such as Balance. Additionally, the fields of the most recently submitted inner transaction can be examined using the InnerTxn object. If the inner transaction creates an asset, the new asset ID can be found by looking at InnerTxn.created_asset_id().

Requires program version 5 or higher. This operation is only permitted in application mode.

class pyteal.InnerTxnGroup

Bases: object

Represents a group of inner transactions.

__getitem__(txnIndex: int) TxnObject
class pyteal.Int(value: int)

Bases: LeafExpr

An expression that represents a uint64.

__init__(value: int) None

Create a new uint64.

Parameters

value – The integer value this uint64 will represent. Must be a positive value less than 2**64.

type_of()

Get the return type of this expression.

pyteal.Itob(arg: Expr) UnaryExpr

Convert a uint64 string to a byte string.

class pyteal.JsonRef(type: JsonRefType, json_obj: Expr, key: Expr)

Bases: Expr

An expression that accesses the value associated with a given key from a supported utf-8 encoded json object.

The json object must satisfy a particular specification.

classmethod as_object(json_obj: Expr, key: Expr) JsonRef

Access the value of a given key as a json object.

Refer to the JsonRef class documentation for valid json specification.

Parameters
  • json_obj – The utf-8 encoded json object.

  • key – The key to access in the json object.

classmethod as_string(json_obj: Expr, key: Expr) Expr

Access the value of a given key as a string.

Refer to the JsonRef class documentation for valid json specification.

Parameters
  • json_obj – The utf-8 encoded json object.

  • key – The key to access in the json object.

classmethod as_uint64(json_obj: Expr, key: Expr) Expr

Access the value of a given key as a uint64.

Refer to the JsonRef class documentation for valid json specification.

Parameters
  • json_obj – The utf-8 encoded json object.

  • key – The key to access in the json object.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.Keccak256(arg: Expr) UnaryExpr

Get the KECCAK-256 hash of a byte string.

class pyteal.LabelReference(label: str)

Bases: object

addPrefix(prefix: str) None
getLabel() str
pyteal.Le(left: Expr, right: Expr) Expr

Less than or equal to expression.

Checks if left <= right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

class pyteal.LeafExpr

Bases: Expr

Leaf expression base class.

has_return()

Check if this expression always returns from the current subroutine or program.

pyteal.Len(arg: Expr) UnaryExpr

Get the length of a byte string.

pyteal.Log(message: Expr) UnaryExpr

Write a message to log state of the current application.

This will fail if called more than MaxLogCalls times in a program (32 as of AVM v5), or if the sum of the lengths of all logged messages in a program exceeds 1024 bytes.

Parameters

message – The message to write. Must evaluate to bytes.

Requires program version 5 or higher.

pyteal.Lt(left: Expr, right: Expr) Expr

Less than expression.

Checks if left < right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

class pyteal.MaybeValue(op: Op, type: TealType, *, immediate_args: Optional[List[Union[int, str]]] = None, args: Optional[List[Expr]] = None)

Bases: MultiValue

Represents a get operation returning a value that may not exist.

__init__(op: Op, type: TealType, *, immediate_args: Optional[List[Union[int, str]]] = None, args: Optional[List[Expr]] = None)

Create a new MaybeValue.

Parameters
  • op – The operation that returns values.

  • type – The type of the returned value.

  • immediate_args (optional) – Immediate arguments for the op. Defaults to None.

  • args (optional) – Stack arguments for the op. Defaults to None.

hasValue() ScratchLoad

Check if the value exists.

This will return 1 if the value exists, otherwise 0.

property slotOk: ScratchSlot

Get the scratch slot that stores hasValue.

Note: This is mainly added for backwards compatability and normally shouldn’t be used directly in pyteal code.

property slotValue: ScratchSlot

Get the scratch slot that stores the value or the zero value for the type if the value doesn’t exist.

Note: This is mainly added for backwards compatability and normally shouldn’t be used directly in pyteal code.

value() ScratchLoad

Get the value.

If the value exists, it will be returned. Otherwise, the zero value for this type will be returned (i.e. either 0 or an empty byte string, depending on the type).

class pyteal.MethodConfig(*, no_op: CallConfig = CallConfig.NEVER, opt_in: CallConfig = CallConfig.NEVER, close_out: CallConfig = CallConfig.NEVER, clear_state: CallConfig = CallConfig.NEVER, update_application: CallConfig = CallConfig.NEVER, delete_application: CallConfig = CallConfig.NEVER)

Bases: object

MethodConfig keep track of one method’s CallConfigs for all OnComplete cases.

The MethodConfig implementation generalized contract method call such that the registered method call is paired with certain OnCompletion conditions and creation conditions.

approval_cond() pyteal.Expr | int
clear_state: CallConfig = 0
clear_state_cond() pyteal.Expr | int
close_out: CallConfig = 0
delete_application: CallConfig = 0
is_never() bool
no_op: CallConfig = 0
opt_in: CallConfig = 0
update_application: CallConfig = 0
class pyteal.MethodSignature(methodName: str)

Bases: LeafExpr

An expression that represents an ABI method selector

__init__(methodName: str) None

Create a new method selector for ABI method call.

Parameters

methodName – A string containing a valid ABI method signature

type_of() TealType

Get the return type of this expression.

pyteal.MinBalance(account: Expr) UnaryExpr

Get the minimum balance of a user in microAlgos.

For more information about minimum balances, see: https://developer.algorand.org/docs/features/accounts/#minimum-balance

Argument must be an index into Txn.Accounts that corresponds to the account to read from, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender).

Requires program version 3 or higher. This operation is only permitted in application mode.

pyteal.Minus(left: Expr, right: Expr) Expr

Subtract two numbers.

Produces left - right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

pyteal.Mod(left: Expr, right: Expr) Expr

Modulo expression.

Produces left % right.

Parameters
  • left – Must evaluate to uint64.

  • right – Must evaluate to uint64.

class pyteal.Mode(value)

Bases: Flag

Enum of program running modes.

Application = 2
Signature = 1
pyteal.Mul(*args: Expr) Expr

Numerical multiplication.

Produces the product of all the input arguments.

All arguments must be PyTeal expressions that evaluate to uint64, and there must be at least one argument.

Example

Mul(Int(2), Int(3), Int(4))

class pyteal.MultiValue(op: ~pyteal.Op, types: ~typing.List[~pyteal.TealType], *, immediate_args: ~typing.List[~typing.Union[int, str]] = None, args: ~typing.List[~pyteal.Expr] = None, compile_check: ~typing.Callable[[CompileOptions], None] = <function MultiValue.<lambda>>)

Bases: LeafExpr

Represents an operation that returns more than one value

__init__(op: ~pyteal.Op, types: ~typing.List[~pyteal.TealType], *, immediate_args: ~typing.List[~typing.Union[int, str]] = None, args: ~typing.List[~pyteal.Expr] = None, compile_check: ~typing.Callable[[CompileOptions], None] = <function MultiValue.<lambda>>)

Create a new MultiValue.

Parameters
  • op – The operation that returns values.

  • types – The types of the returned values.

  • immediate_args (optional) – Immediate arguments for the op. Defaults to None.

  • args (optional) – Stack arguments for the op. Defaults to None.

outputReducer(reducer: Callable[[...], Expr]) Expr
type_of()

Get the return type of this expression.

class pyteal.NaryExpr(op: Op, inputType: TealType, outputType: TealType, args: Sequence[Expr])

Bases: Expr

N-ary expression base class.

This type of expression takes an arbitrary number of arguments.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.Neq(left: Expr, right: Expr) Expr

Difference expression.

Checks if left != right.

Parameters
  • left – A value to check.

  • right – The other value to check. Must evaluate to the same type as left.

class pyteal.Nonce(base: str, nonce: str, child: Expr)

Bases: Expr

A meta expression only used to change the hash of a TEAL program.

__init__(base: str, nonce: str, child: Expr) None

Create a new Nonce.

The Nonce expression behaves exactly like the child expression passed into it, except it uses the provided nonce string to alter its structure in a way that does not affect execution.

Parameters
  • base – The base of the nonce. Must be one of utf8, base16, base32, or base64.

  • nonce – An arbitrary nonce string that conforms to base.

  • child – The expression to wrap.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.Not(arg: Expr) UnaryExpr

Get the logical inverse of a uint64.

If the argument is 0, then this will produce 1. Otherwise this will produce 0.

class pyteal.OnComplete

Bases: object

An enum of values that TxnObject.on_completion() may return.

ClearState = <pyteal.EnumInt object>
CloseOut = <pyteal.EnumInt object>
DeleteApplication = <pyteal.EnumInt object>
NoOp = <pyteal.EnumInt object>
OptIn = <pyteal.EnumInt object>
UpdateApplication = <pyteal.EnumInt object>
class pyteal.OnCompleteAction(*, action: Optional[Union[Expr, SubroutineFnWrapper, ABIReturnSubroutine]] = None, call_config: CallConfig = CallConfig.NEVER)

Bases: object

OnComplete Action, registers bare calls to one single OnCompletion case.

action: Optional[Union[Expr, SubroutineFnWrapper, ABIReturnSubroutine]] = None
static always(f: pyteal.Expr | pyteal.SubroutineFnWrapper | pyteal.ABIReturnSubroutine) OnCompleteAction
call_config: CallConfig = 0
static call_only(f: pyteal.Expr | pyteal.SubroutineFnWrapper | pyteal.ABIReturnSubroutine) OnCompleteAction
static create_only(f: pyteal.Expr | pyteal.SubroutineFnWrapper | pyteal.ABIReturnSubroutine) OnCompleteAction
is_empty() bool
static never() OnCompleteAction
class pyteal.Op(value)

Bases: Enum

Enum of program opcodes.

acct_params_get = OpType(value='acct_params_get', mode=<Mode.Application: 2>, min_version=6)
add = OpType(value='+', mode=<Mode.Application|Signature: 3>, min_version=2)
addr = OpType(value='addr', mode=<Mode.Application|Signature: 3>, min_version=2)
addw = OpType(value='addw', mode=<Mode.Application|Signature: 3>, min_version=2)
app_global_del = OpType(value='app_global_del', mode=<Mode.Application: 2>, min_version=2)
app_global_get = OpType(value='app_global_get', mode=<Mode.Application: 2>, min_version=2)
app_global_get_ex = OpType(value='app_global_get_ex', mode=<Mode.Application: 2>, min_version=2)
app_global_put = OpType(value='app_global_put', mode=<Mode.Application: 2>, min_version=2)
app_local_del = OpType(value='app_local_del', mode=<Mode.Application: 2>, min_version=2)
app_local_get = OpType(value='app_local_get', mode=<Mode.Application: 2>, min_version=2)
app_local_get_ex = OpType(value='app_local_get_ex', mode=<Mode.Application: 2>, min_version=2)
app_local_put = OpType(value='app_local_put', mode=<Mode.Application: 2>, min_version=2)
app_opted_in = OpType(value='app_opted_in', mode=<Mode.Application: 2>, min_version=2)
app_params_get = OpType(value='app_params_get', mode=<Mode.Application: 2>, min_version=5)
arg = OpType(value='arg', mode=<Mode.Signature: 1>, min_version=2)
args = OpType(value='args', mode=<Mode.Signature: 1>, min_version=5)
assert_ = OpType(value='assert', mode=<Mode.Application|Signature: 3>, min_version=3)
asset_holding_get = OpType(value='asset_holding_get', mode=<Mode.Application: 2>, min_version=2)
asset_params_get = OpType(value='asset_params_get', mode=<Mode.Application: 2>, min_version=2)
b = OpType(value='b', mode=<Mode.Application|Signature: 3>, min_version=2)
b_add = OpType(value='b+', mode=<Mode.Application|Signature: 3>, min_version=4)
b_and = OpType(value='b&', mode=<Mode.Application|Signature: 3>, min_version=4)
b_div = OpType(value='b/', mode=<Mode.Application|Signature: 3>, min_version=4)
b_eq = OpType(value='b==', mode=<Mode.Application|Signature: 3>, min_version=4)
b_ge = OpType(value='b>=', mode=<Mode.Application|Signature: 3>, min_version=4)
b_gt = OpType(value='b>', mode=<Mode.Application|Signature: 3>, min_version=4)
b_le = OpType(value='b<=', mode=<Mode.Application|Signature: 3>, min_version=4)
b_lt = OpType(value='b<', mode=<Mode.Application|Signature: 3>, min_version=4)
b_minus = OpType(value='b-', mode=<Mode.Application|Signature: 3>, min_version=4)
b_mod = OpType(value='b%', mode=<Mode.Application|Signature: 3>, min_version=4)
b_mul = OpType(value='b*', mode=<Mode.Application|Signature: 3>, min_version=4)
b_neq = OpType(value='b!=', mode=<Mode.Application|Signature: 3>, min_version=4)
b_not = OpType(value='b~', mode=<Mode.Application|Signature: 3>, min_version=4)
b_or = OpType(value='b|', mode=<Mode.Application|Signature: 3>, min_version=4)
b_xor = OpType(value='b^', mode=<Mode.Application|Signature: 3>, min_version=4)
balance = OpType(value='balance', mode=<Mode.Application: 2>, min_version=2)
base64_decode = OpType(value='base64_decode', mode=<Mode.Application|Signature: 3>, min_version=7)
bitlen = OpType(value='bitlen', mode=<Mode.Application|Signature: 3>, min_version=4)
bitwise_and = OpType(value='&', mode=<Mode.Application|Signature: 3>, min_version=2)
bitwise_not = OpType(value='~', mode=<Mode.Application|Signature: 3>, min_version=2)
bitwise_or = OpType(value='|', mode=<Mode.Application|Signature: 3>, min_version=2)
bitwise_xor = OpType(value='^', mode=<Mode.Application|Signature: 3>, min_version=2)
block = OpType(value='block', mode=<Mode.Application|Signature: 3>, min_version=7)
bnz = OpType(value='bnz', mode=<Mode.Application|Signature: 3>, min_version=2)
bsqrt = OpType(value='bsqrt', mode=<Mode.Application|Signature: 3>, min_version=6)
btoi = OpType(value='btoi', mode=<Mode.Application|Signature: 3>, min_version=2)
byte = OpType(value='byte', mode=<Mode.Application|Signature: 3>, min_version=2)
bytec = OpType(value='bytec', mode=<Mode.Application|Signature: 3>, min_version=2)
bytec_0 = OpType(value='bytec_0', mode=<Mode.Application|Signature: 3>, min_version=2)
bytec_1 = OpType(value='bytec_1', mode=<Mode.Application|Signature: 3>, min_version=2)
bytec_2 = OpType(value='bytec_2', mode=<Mode.Application|Signature: 3>, min_version=2)
bytec_3 = OpType(value='bytec_3', mode=<Mode.Application|Signature: 3>, min_version=2)
bytecblock = OpType(value='bytecblock', mode=<Mode.Application|Signature: 3>, min_version=2)
bz = OpType(value='bz', mode=<Mode.Application|Signature: 3>, min_version=2)
bzero = OpType(value='bzero', mode=<Mode.Application|Signature: 3>, min_version=4)
callsub = OpType(value='callsub', mode=<Mode.Application|Signature: 3>, min_version=4)
comment = OpType(value='//', mode=<Mode.Application|Signature: 3>, min_version=0)
concat = OpType(value='concat', mode=<Mode.Application|Signature: 3>, min_version=2)
cover = OpType(value='cover', mode=<Mode.Application|Signature: 3>, min_version=5)
dig = OpType(value='dig', mode=<Mode.Application|Signature: 3>, min_version=3)
div = OpType(value='/', mode=<Mode.Application|Signature: 3>, min_version=2)
divmodw = OpType(value='divmodw', mode=<Mode.Application|Signature: 3>, min_version=4)
divw = OpType(value='divw', mode=<Mode.Application|Signature: 3>, min_version=6)
dup = OpType(value='dup', mode=<Mode.Application|Signature: 3>, min_version=2)
dup2 = OpType(value='dup2', mode=<Mode.Application|Signature: 3>, min_version=2)
ecdsa_pk_decompress = OpType(value='ecdsa_pk_decompress', mode=<Mode.Application|Signature: 3>, min_version=5)
ecdsa_pk_recover = OpType(value='ecdsa_pk_recover', mode=<Mode.Application|Signature: 3>, min_version=5)
ecdsa_verify = OpType(value='ecdsa_verify', mode=<Mode.Application|Signature: 3>, min_version=5)
ed25519verify = OpType(value='ed25519verify', mode=<Mode.Application|Signature: 3>, min_version=2)
ed25519verify_bare = OpType(value='ed25519verify_bare', mode=<Mode.Application|Signature: 3>, min_version=7)
eq = OpType(value='==', mode=<Mode.Application|Signature: 3>, min_version=2)
err = OpType(value='err', mode=<Mode.Application|Signature: 3>, min_version=2)
exp = OpType(value='exp', mode=<Mode.Application|Signature: 3>, min_version=4)
expw = OpType(value='expw', mode=<Mode.Application|Signature: 3>, min_version=4)
extract = OpType(value='extract', mode=<Mode.Application|Signature: 3>, min_version=5)
extract3 = OpType(value='extract3', mode=<Mode.Application|Signature: 3>, min_version=5)
extract_uint16 = OpType(value='extract_uint16', mode=<Mode.Application|Signature: 3>, min_version=5)
extract_uint32 = OpType(value='extract_uint32', mode=<Mode.Application|Signature: 3>, min_version=5)
extract_uint64 = OpType(value='extract_uint64', mode=<Mode.Application|Signature: 3>, min_version=5)
gaid = OpType(value='gaid', mode=<Mode.Application: 2>, min_version=4)
gaids = OpType(value='gaids', mode=<Mode.Application: 2>, min_version=4)
ge = OpType(value='>=', mode=<Mode.Application|Signature: 3>, min_version=2)
getbit = OpType(value='getbit', mode=<Mode.Application|Signature: 3>, min_version=3)
getbyte = OpType(value='getbyte', mode=<Mode.Application|Signature: 3>, min_version=3)
gitxn = OpType(value='gitxn', mode=<Mode.Application: 2>, min_version=6)
gitxna = OpType(value='gitxna', mode=<Mode.Application: 2>, min_version=6)
gitxnas = OpType(value='gitxnas', mode=<Mode.Application: 2>, min_version=6)
gload = OpType(value='gload', mode=<Mode.Application: 2>, min_version=4)
gloads = OpType(value='gloads', mode=<Mode.Application: 2>, min_version=4)
gloadss = OpType(value='gloadss', mode=<Mode.Application: 2>, min_version=6)
global_ = OpType(value='global', mode=<Mode.Application|Signature: 3>, min_version=2)
gt = OpType(value='>', mode=<Mode.Application|Signature: 3>, min_version=2)
gtxn = OpType(value='gtxn', mode=<Mode.Application|Signature: 3>, min_version=2)
gtxna = OpType(value='gtxna', mode=<Mode.Application|Signature: 3>, min_version=2)
gtxnas = OpType(value='gtxnas', mode=<Mode.Application|Signature: 3>, min_version=5)
gtxns = OpType(value='gtxns', mode=<Mode.Application|Signature: 3>, min_version=3)
gtxnsa = OpType(value='gtxnsa', mode=<Mode.Application|Signature: 3>, min_version=3)
gtxnsas = OpType(value='gtxnsas', mode=<Mode.Application|Signature: 3>, min_version=5)
int = OpType(value='int', mode=<Mode.Application|Signature: 3>, min_version=2)
intc = OpType(value='intc', mode=<Mode.Application|Signature: 3>, min_version=2)
intc_0 = OpType(value='intc_0', mode=<Mode.Application|Signature: 3>, min_version=2)
intc_1 = OpType(value='intc_1', mode=<Mode.Application|Signature: 3>, min_version=2)
intc_2 = OpType(value='intc_2', mode=<Mode.Application|Signature: 3>, min_version=2)
intc_3 = OpType(value='intc_3', mode=<Mode.Application|Signature: 3>, min_version=2)
intcblock = OpType(value='intcblock', mode=<Mode.Application|Signature: 3>, min_version=2)
itob = OpType(value='itob', mode=<Mode.Application|Signature: 3>, min_version=2)
itxn = OpType(value='itxn', mode=<Mode.Application: 2>, min_version=5)
itxn_begin = OpType(value='itxn_begin', mode=<Mode.Application: 2>, min_version=5)
itxn_field = OpType(value='itxn_field', mode=<Mode.Application: 2>, min_version=5)
itxn_next = OpType(value='itxn_next', mode=<Mode.Application: 2>, min_version=6)
itxn_submit = OpType(value='itxn_submit', mode=<Mode.Application: 2>, min_version=5)
itxna = OpType(value='itxna', mode=<Mode.Application: 2>, min_version=5)
itxnas = OpType(value='itxnas', mode=<Mode.Application: 2>, min_version=6)
json_ref = OpType(value='json_ref', mode=<Mode.Application|Signature: 3>, min_version=7)
keccak256 = OpType(value='keccak256', mode=<Mode.Application|Signature: 3>, min_version=2)
le = OpType(value='<=', mode=<Mode.Application|Signature: 3>, min_version=2)
len = OpType(value='len', mode=<Mode.Application|Signature: 3>, min_version=2)
load = OpType(value='load', mode=<Mode.Application|Signature: 3>, min_version=2)
loads = OpType(value='loads', mode=<Mode.Application|Signature: 3>, min_version=5)
log = OpType(value='log', mode=<Mode.Application: 2>, min_version=5)
logic_and = OpType(value='&&', mode=<Mode.Application|Signature: 3>, min_version=2)
logic_not = OpType(value='!', mode=<Mode.Application|Signature: 3>, min_version=2)
logic_or = OpType(value='||', mode=<Mode.Application|Signature: 3>, min_version=2)
lt = OpType(value='<', mode=<Mode.Application|Signature: 3>, min_version=2)
method_signature = OpType(value='method', mode=<Mode.Application|Signature: 3>, min_version=2)
min_balance = OpType(value='min_balance', mode=<Mode.Application: 2>, min_version=3)
property min_version: int

Get the minimum version where this op is available.

minus = OpType(value='-', mode=<Mode.Application|Signature: 3>, min_version=2)
mod = OpType(value='%', mode=<Mode.Application|Signature: 3>, min_version=2)
property mode: Mode

Get the modes where this op is available.

mul = OpType(value='*', mode=<Mode.Application|Signature: 3>, min_version=2)
mulw = OpType(value='mulw', mode=<Mode.Application|Signature: 3>, min_version=2)
neq = OpType(value='!=', mode=<Mode.Application|Signature: 3>, min_version=2)
pop = OpType(value='pop', mode=<Mode.Application|Signature: 3>, min_version=2)
pushbytes = OpType(value='pushbytes', mode=<Mode.Application|Signature: 3>, min_version=3)
pushint = OpType(value='pushint', mode=<Mode.Application|Signature: 3>, min_version=3)
replace2 = OpType(value='replace2', mode=<Mode.Application|Signature: 3>, min_version=7)
replace3 = OpType(value='replace3', mode=<Mode.Application|Signature: 3>, min_version=7)
retsub = OpType(value='retsub', mode=<Mode.Application|Signature: 3>, min_version=4)
return_ = OpType(value='return', mode=<Mode.Application|Signature: 3>, min_version=2)
select = OpType(value='select', mode=<Mode.Application|Signature: 3>, min_version=3)
setbit = OpType(value='setbit', mode=<Mode.Application|Signature: 3>, min_version=3)
setbyte = OpType(value='setbyte', mode=<Mode.Application|Signature: 3>, min_version=3)
sha256 = OpType(value='sha256', mode=<Mode.Application|Signature: 3>, min_version=2)
sha3_256 = OpType(value='sha3_256', mode=<Mode.Application|Signature: 3>, min_version=7)
sha512_256 = OpType(value='sha512_256', mode=<Mode.Application|Signature: 3>, min_version=2)
shl = OpType(value='shl', mode=<Mode.Application|Signature: 3>, min_version=4)
shr = OpType(value='shr', mode=<Mode.Application|Signature: 3>, min_version=4)
sqrt = OpType(value='sqrt', mode=<Mode.Application|Signature: 3>, min_version=4)
store = OpType(value='store', mode=<Mode.Application|Signature: 3>, min_version=2)
stores = OpType(value='stores', mode=<Mode.Application|Signature: 3>, min_version=5)
substring = OpType(value='substring', mode=<Mode.Application|Signature: 3>, min_version=2)
substring3 = OpType(value='substring3', mode=<Mode.Application|Signature: 3>, min_version=2)
swap = OpType(value='swap', mode=<Mode.Application|Signature: 3>, min_version=3)
txn = OpType(value='txn', mode=<Mode.Application|Signature: 3>, min_version=2)
txna = OpType(value='txna', mode=<Mode.Application|Signature: 3>, min_version=2)
txnas = OpType(value='txnas', mode=<Mode.Application|Signature: 3>, min_version=5)
uncover = OpType(value='uncover', mode=<Mode.Application|Signature: 3>, min_version=5)
vrf_verify = OpType(value='vrf_verify', mode=<Mode.Application|Signature: 3>, min_version=7)
class pyteal.OpUp(mode: OpUpMode, target_app_id: Optional[Expr] = None)

Bases: object

Utility for increasing opcode budget during app execution.

Requires program version 6 or higher.

Example

# OnCall mode: doesn't accept target_app_id as an argument
opup = OpUp(OpUpMode.OnCall)
program_with_opup = Seq(
    ...,
    opup.ensure_budget(Int(1000)),
    ...,
)

# Explicit mode: requires target_app_id as an argument
opup = OpUp(OpUpMode.Explicit, Int(1))
program_with_opup = Seq(
    ...,
    opup.ensure_budget(Int(1000)),
    ...,
)
__init__(mode: OpUpMode, target_app_id: Optional[Expr] = None)

Create a new OpUp object.

Parameters
  • mode – OpUpMode that determines the style of budget increase to use. See the OpUpMode Enum for more information.

  • target_app_id (optional) – In Explicit mode, the OpUp utility requires the app_id to target for inner app calls. Defaults to None.

ensure_budget(required_budget: Expr) Expr

Ensure that the budget will be at least the required_budget.

Note: the available budget just prior to calling ensure_budget() must be high enough to execute the budget increase code. The exact budget required depends on the provided required_budget expression, but a budget of ~20 should be sufficient for most use cases. If lack of budget is an issue then consider moving the call to ensure_budget() earlier in the pyteal program.

maximize_budget(fee: Expr) Expr

Maximize the available opcode budget without spending more than the given fee.

Note: the available budget just prior to calling maximize_budget() must be high enough to execute the budget increase code. The exact budget required depends on the provided fee expression, but a budget of ~25 should be sufficient for most use cases. If lack of budget is an issue then consider moving the call to maximize_budget() earlier in the pyteal program.

class pyteal.OpUpMode(value)

Bases: Enum

An Enum object that defines the mode used for the OpUp utility.

Note: the Explicit mode requires the app id to be provided through the foreign apps array in order for it to be accessible during evaluation.

Explicit = 0
OnCall = 1
class pyteal.OptimizeOptions(*, scratch_slots: bool = False)

Bases: object

An object which specifies the optimizations to be performed and relevant context.

_skip_slots: the slots that should be skipped during optimization. At the moment this includes:

1. reserved slots because they may have dependencies outside the current application. For example, the ‘gloads’ opcode can access the slots of other applications in the tx group. 2. global slots because they’re outside the scope of global optimizations, which only apply to the control flow graph of a single subroutine. 3. slots used with dynamic scratch vars. These slots use indirection by means of the ‘stores’ opcode and dependencies can only be determined at runtime.

Parameters

scratch_slots (optional) – cancel contiguous store/load operations that have no load dependencies elsewhere.

pyteal.Or(*args: Expr) Expr

Logical or expression.

Produces 1 if any argument is nonzero. Otherwise produces 0.

All arguments must be PyTeal expressions that evaluate to uint64, and there must be at least one argument.

pyteal.Pop(arg: Expr) UnaryExpr

Pop a value from the stack.

class pyteal.Pragma(child: Expr, *, compiler_version: str, **kwargs: Any)

Bases: Expr

A meta expression which defines a pragma for a specific subsection of PyTeal code.

This expression does not affect the underlying compiled TEAL code in any way.

__init__(child: Expr, *, compiler_version: str, **kwargs: Any) None

Define a pragma for a specific subsection of PyTeal code.

The Pragma expression does not affect the underlying compiled TEAL code in any way, it merely sets a pragma for the underlying expression.

Parameters
  • child – The expression to wrap.

  • compiler_version – Acceptable versions of the compiler. Will fail if the current PyTeal version is not contained in the range. Follows the npm semver range scheme for specifying compatible versions.

For example:

@Subroutine(TealType.uint64)
def example() -> Expr:
    # this will fail during compilation if the current PyTeal version does not satisfy
    # the version constraint
    return Pragma(
        Seq(...),
        compiler_version="^0.14.0"
    )
has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.Reject() Expr

Immediately exit the program and mark the execution as unsuccessful.

pyteal.Replace(original: Expr, start: Expr, replacement: Expr) Expr

Replace a portion of original bytes with new bytes at a given starting point.

Requires program version 7 or higher.

Parameters
  • original – The value containing the original bytes. Must evaluate to bytes.

  • start – The index of the byte where replacement starts. Must evaluate to an integer less than Len(original).

  • replacement – The value containing the replacement bytes. Must evaluate to bytes with length at most Len(original) - start.

class pyteal.Return(value: Optional[Expr] = None)

Bases: Expr

Return a value from the current execution context.

__init__(value: Optional[Expr] = None) None

Create a new Return expression.

If called from the main program, this will immediately exit the program and the value returned will be the program’s success value (must be a uint64, 0 indicates failure, 1 or greater indicates success).

If called from within a subroutine, this will return from the current subroutine with either no value if the subroutine does not produce a return value, or the given return value if it does produce a return value.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.Router(name: str, bare_calls: Optional[BareCallActions] = None, descr: Optional[str] = None)

Bases: object

The Router class helps construct the approval and clear state programs for an ARC-4 compliant application.

Additionally, this class can produce an ARC-4 contract description object for the application.

WARNING: The ABI Router is still taking shape and is subject to backwards incompatible changes.

  • Based on feedback, the API and usage patterns are likely to change.

  • Expect migration issues in future PyTeal versions.

For these reasons, we strongly recommend using pragma to pin the version of PyTeal in your source code.

__init__(name: str, bare_calls: Optional[BareCallActions] = None, descr: Optional[str] = None) None
Parameters
  • name – the name of the smart contract, used in the JSON object.

  • bare_calls – the bare app call registered for each on_completion.

  • descr – a description of the smart contract, used in the JSON object.

add_method_handler(method_call: ABIReturnSubroutine, overriding_name: Optional[str] = None, method_config: Optional[MethodConfig] = None, description: Optional[str] = None) ABIReturnSubroutine

Add a method call handler to this Router.

Parameters
  • method_call – An ABIReturnSubroutine that implements the method body.

  • overriding_name (optional) – A name for this method. Defaults to the function name of method_call.

  • method_config (optional) – An object describing the on completion actions and creation/non-creation call statuses that are valid for calling this method. All invalid configurations will be rejected. Defaults to MethodConfig(no_op=CallConfig.CALL) (i.e. only the no-op action during a non-creation call is accepted) if none is provided.

  • description (optional) – A description for this method. Defaults to the docstring of method_call, if there is one.

build_program() tuple[pyteal.Expr, pyteal.Expr, algosdk.abi.contract.Contract]

Constructs ASTs for approval and clear-state programs from the registered methods and bare app calls in the router, and also generates a Contract object to allow client read and call the methods easily.

Note that if no methods or bare app call actions have been registered to either the approval or clear state programs, then that program will reject all transactions.

Returns

A tuple of three objects.

  • approval_program: an AST for approval program

  • clear_state_program: an AST for clear-state program

  • contract: a Python SDK Contract object to allow clients to make off-chain calls

compile_program(*, version: int = 2, assemble_constants: bool = False, optimize: Optional[OptimizeOptions] = None) tuple[str, str, algosdk.abi.contract.Contract]

Constructs and compiles approval and clear-state programs from the registered methods and bare app calls in the router, and also generates a Contract object to allow client read and call the methods easily.

This method combines Router.build_program and compileTeal.

Note that if no methods or bare app call actions have been registered to either the approval or clear state programs, then that program will reject all transactions.

Returns

A tuple of three objects.

  • approval_program: compiled approval program string

  • clear_state_program: compiled clear-state program string

  • contract: a Python SDK Contract object to allow clients to make off-chain calls

contract_construct() Contract

A helper function in constructing a Contract object.

It takes out the method spec from approval program methods, and constructs an Contract object.

Returns

A Python SDK Contract object constructed from the registered methods on this router.

method(func: Optional[Callable] = None, /, *, name: Optional[str] = None, description: Optional[str] = None, no_op: Optional[CallConfig] = None, opt_in: Optional[CallConfig] = None, close_out: Optional[CallConfig] = None, clear_state: Optional[CallConfig] = None, update_application: Optional[CallConfig] = None, delete_application: Optional[CallConfig] = None)

This is an alternative way to register a method, as supposed to add_method_handler.

This is a decorator that’s meant to be used over a Python function, which is internally wrapped with ABIReturnSubroutine. Additional keyword arguments on this decorator can be used to specify the OnCompletion statuses that are valid for the registered method.

NOTE: By default, all OnCompletion actions other than no_op are set to CallConfig.NEVER, while no_op field is set to CallConfig.CALL. However, if you provide any keywords for OnCompletion actions, then the no_op field will default to CallConfig.NEVER.

Parameters
  • func – A function that implements the method body. This should NOT be wrapped with the ABIReturnSubroutine decorator yet.

  • name (optional) – A name for this method. Defaults to the function name of func.

  • description (optional) – A description for this method. Defaults to the docstring of func, if there is one.

  • no_op (optional) – The allowed calls during OnComplete.NoOp.

  • opt_in (optional) – The allowed calls during OnComplete.OptIn.

  • close_out (optional) – The allowed calls during OnComplete.CloseOut.

  • clear_state (optional) – The allowed calls during OnComplete.ClearState.

  • update_application (optional) – The allowed calls during OnComplete.UpdateApplication.

  • delete_application (optional) – The allowed calls during OnComplete.DeleteApplication.

class pyteal.ScratchIndex(slot: ScratchSlot)

Bases: Expr

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.ScratchLoad(slot: Optional[ScratchSlot] = None, type: TealType = TealType.anytype, index_expression: Optional[Expr] = None)

Bases: Expr

Expression to load a value from scratch space.

__init__(slot: Optional[ScratchSlot] = None, type: TealType = TealType.anytype, index_expression: Optional[Expr] = None)

Create a new ScratchLoad expression.

Parameters
  • slot (optional) – The slot to load the value from.

  • type (optional) – The type being loaded from this slot, if known. Defaults to TealType.anytype.

  • index_expression (optional) – As an alternative to slot, an expression can be supplied for the slot index.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.ScratchSlot(requestedSlotId: Optional[int] = None)

Bases: object

Represents the allocation of a scratch space slot.

__init__(requestedSlotId: Optional[int] = None)

Initializes a scratch slot with a particular id

Parameters

requestedSlotId (optional) – A scratch slot id that the compiler must store the value. This id may be a Python int in the range [0-256).

index() ScratchIndex
load(type: TealType = TealType.anytype) ScratchLoad

Get an expression to load a value from this slot.

Parameters

type (optional) – The type being loaded from this slot, if known. Defaults to TealType.anytype.

nextSlotId = 256
store(value: Optional[Expr] = None) Expr

Get an expression to store a value in this slot.

Parameters

value (optional) – The value to store in this slot. If not included, the last value on the stack will be stored. NOTE: storing the last value on the stack breaks the typical semantics of PyTeal, only use if you know what you’re doing.

class pyteal.ScratchStackStore(slot: ScratchSlot)

Bases: Expr

Expression to store a value from the stack in scratch space.

NOTE: This expression breaks the typical semantics of PyTeal, only use if you know what you’re doing.

__init__(slot: ScratchSlot)

Create a new ScratchStackStore expression.

Parameters

slot – The slot to store the value in.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.ScratchStore(slot: Optional[ScratchSlot], value: Expr, index_expression: Optional[Expr] = None)

Bases: Expr

Expression to store a value in scratch space.

__init__(slot: Optional[ScratchSlot], value: Expr, index_expression: Optional[Expr] = None)

Create a new ScratchStore expression.

Parameters
  • slot (optional) – The slot to store the value in.

  • value – The value to store.

  • index_expression (optional) – As an alternative to slot, an expression can be supplied for the slot index.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.ScratchVar(type: TealType = TealType.anytype, slotId: Optional[int] = None)

Bases: object

Interface around Scratch space, similar to get/put local/global state

Example

myvar = ScratchVar(TealType.uint64)
Seq([
    myvar.store(Int(5)),
    Assert(myvar.load() == Int(5))
])
__init__(type: TealType = TealType.anytype, slotId: Optional[int] = None)

Create a new ScratchVar with an optional type.

Parameters
  • type (optional) – The type that this variable can hold. An error will be thrown if an expression with an incompatible type is stored in this variable. Defaults to TealType.anytype.

  • slotId (optional) – A scratch slot id that the compiler must store the value. This id may be a Python int in the range [0-256).

index() Expr
load() ScratchLoad

Load value from Scratch Space

storage_type() TealType

Get the type of expressions that can be stored in this ScratchVar.

store(value: Expr) Expr

Store value in Scratch Space

Parameters

value – The value to store. Must conform to this ScratchVar’s type.

class pyteal.Seq(*exprs)

Bases: Expr

A control flow expression to represent a sequence of expressions.

__init__(*exprs: Expr) None
__init__(exprs: List[Expr]) None

Create a new Seq expression.

The new Seq expression will take on the return value of the final expression in the sequence.

Parameters

exprs – The expressions to include in this sequence. All expressions that are not the final one in this list must not return any values.

Example

Seq([
    App.localPut(Bytes("key"), Bytes("value")),
    Int(1)
])
has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.SetBit(value: Expr, index: Expr, newBitValue: Expr) TernaryExpr

Set the bit value of an expression at a specific index.

The meaning of index differs if value is an integer or a byte string.

  • For integers, bit indexing begins with low-order bits. For example, SetBit(Int(0), Int(4), Int(1)) yields the integer 16 (2^4). Any integer less than 64 is a valid index.

  • For byte strings, bit indexing begins at the first byte. For example, SetBit(Bytes("base16", "0x00"), Int(7), Int(1)) yields the byte string 0x01. Any integer less than 8*Len(value) is a valid index.

Requires program version 3 or higher.

Parameters
  • value – The value containing bits. Can evaluate to any type.

  • index – The index of the bit to set. Must evaluate to uint64.

  • newBitValue – The new bit value to set. Must evaluate to the integer 0 or 1.

pyteal.SetByte(value: Expr, index: Expr, newByteValue: Expr) TernaryExpr

Set a single byte in a byte string from an integer value.

Similar to SetBit, indexing begins at the first byte. For example, SetByte(Bytes("base16", "0x000000"), Int(0), Int(255)) yields the byte string 0xff0000.

Requires program version 3 or higher.

Parameters
  • value – The value containing the bytes. Must evaluate to bytes.

  • index – The index of the byte to set. Must evaluate to an integer less than Len(value).

  • newByteValue – The new byte value to set. Must evaluate to an integer less than 256.

pyteal.Sha256(arg: Expr) UnaryExpr

Get the SHA-256 hash of a byte string.

pyteal.Sha3_256(arg: Expr) UnaryExpr

Get the SHA3-256 hash of a byte string.

pyteal.Sha512_256(arg: Expr) UnaryExpr

Get the SHA-512/256 hash of a byte string.

pyteal.ShiftLeft(a: Expr, b: Expr) Expr

Bitwise left shift expression.

Produces a << b. This is equivalent to a times 2^b, modulo 2^64.

Requires program version 4 or higher.

Parameters
  • a – Must evaluate to uint64.

  • b – Must evaluate to uint64.

pyteal.ShiftRight(a: Expr, b: Expr) Expr

Bitwise right shift expression.

Produces a >> b. This is equivalent to a divided by 2^b.

Requires program version 4 or higher.

Parameters
  • a – Must evaluate to uint64.

  • b – Must evaluate to uint64.

pyteal.Sqrt(arg: Expr) UnaryExpr

Get the integer square root of a uint64.

This will return the largest integer X such that X^2 <= arg.

Requires program version 4 or higher.

class pyteal.Subroutine(return_type: TealType, name: Optional[str] = None)

Bases: object

Used to create a PyTeal subroutine from a Python function.

This class is meant to be used as a function decorator. For example:

@Subroutine(TealType.uint64)
def mySubroutine(a: Expr, b: Expr) -> Expr:
    return a + b

program = Seq([
    App.globalPut(Bytes("key"), mySubroutine(Int(1), Int(2))),
    Approve(),
])
__init__(return_type: TealType, name: Optional[str] = None) None

Define a new subroutine with the given return type.

Parameters

return_type – The type that the return value of this subroutine must conform to. TealType.none indicates that this subroutine does not return any value.

class pyteal.SubroutineCall(subroutine: SubroutineDefinition, args: list[pyteal.Expr | pyteal.ScratchVar | pyteal.abi.BaseType], *, output_kwarg: Optional[OutputKwArgInfo] = None)

Bases: Expr

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.SubroutineDeclaration(subroutine: SubroutineDefinition, body: Expr, deferred_expr: Optional[Expr] = None)

Bases: Expr

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.SubroutineDefinition(implementation: Callable[[...], Expr], return_type: TealType, name_str: Optional[str] = None, has_abi_output: bool = False)

Bases: object

Class that leverages TEAL’s callsub and retsub opcode-pair for subroutines

__init__(implementation: Callable[[...], Expr], return_type: TealType, name_str: Optional[str] = None, has_abi_output: bool = False) None
Parameters
  • implementation – The python function defining the subroutine

  • return_type – the TealType to be returned by the subroutine

  • name_str (optional) – the name that is used to identify the subroutine. If omitted, the name defaults to the implementation’s __name__ attribute

  • has_abi_output (optional) – the boolean that tells if ABI output kwarg for subroutine is used.

argument_count() int
arguments() list[str]
get_declaration() SubroutineDeclaration
invoke(args: list[pyteal.Expr | pyteal.ScratchVar | pyteal.abi.BaseType]) SubroutineCall
name() str
nextSubroutineId = 0
class pyteal.SubroutineFnWrapper(fn_implementation: Callable[[...], Expr], return_type: TealType, name: Optional[str] = None)

Bases: object

has_return()
name() str
type_of()
pyteal.Substring(string: Expr, start: Expr, end: Expr) Expr

Take a substring of a byte string.

Produces a new byte string consisting of the bytes starting at start up to but not including end.

This expression is similar to Extract, except this expression uses start and end indexes, while Extract uses a start index and length.

Requires program version 2 or higher.

Parameters
  • string – The byte string.

  • start – The starting index for the substring. Must be an integer less than or equal to Len(string).

  • end – The ending index for the substring. Must be an integer greater or equal to start, but less than or equal to Len(string).

pyteal.Suffix(string: Expr, start: Expr) Expr

Take a suffix of a byte string.

Produces a new byte string consisting of the suffix of the byte string starting at start

This expression is similar to Substring and Extract, except this expression only uses a start index.

Requires program version 5 or higher.

Parameters
  • string – The byte string.

  • start – The starting index for the suffix. Must be an integer less than or equal to Len(string).

class pyteal.TealBlock(ops: List[TealOp])

Bases: ABC

Represents a basic block of TealComponents in a graph.

classmethod FromOp(options: CompileOptions, op: TealOp, *args: Expr) Tuple[TealBlock, TealSimpleBlock]

Create a path of blocks from a TealOp and its arguments.

Returns

The starting and ending block of the path that encodes the given TealOp and arguments.

classmethod GetReferencedScratchSlots(start: TealBlock) List[ScratchSlot]

Get all scratch slot references for the graph starting at this TealBlock.

Returns

A list of ScratchSlots where each element represents a reference to that slot by a TealOp in the graph. The order of the list is consistent, and there may be duplicate ScratchSlots in the list if the same slot is referenced multiple times.

classmethod Iterate(start: TealBlock) Iterator[TealBlock]

Perform a breadth-first search of the graph of blocks starting with start.

classmethod MatchScratchSlotReferences(actual: List[ScratchSlot], expected: List[ScratchSlot]) bool

Determine if there is a mapping between the actual and expected lists of ScratchSlots.

A mapping is defined as follows:
  • The actual and expected lists must have the same length.

  • For every ScratchSlot referenced by either list:

    • If the slot appears in both lists, it must appear the exact same number of times and at the exact same indexes in both lists.

    • If the slot appears only in one list, for each of its appearances in that list, there must be a ScratchSlot in the other list that appears the exact same number of times and at the exact same indexes.

Returns

True if and only if a mapping as described above exists between actual and expected.

classmethod NormalizeBlocks(start: TealBlock) TealBlock

Minimize the number of blocks in the graph of blocks starting with start by combining sequential blocks. This operation does not alter the operations of the graph or the functionality of its underlying program, however it does mutate the input graph.

Returns

The new starting point of the altered graph. May be the same or differant than start.

addIncoming(parent: Optional[TealBlock] = None, visited: Optional[List[TealBlock]] = None) None

Calculate the parent blocks for this block and its children.

Parameters
  • parent (optional) – The parent block to this one, if it has one. Defaults to None.

  • visited (optional) – Used internally to remember blocks that have been visited. Set to None.

abstract getOutgoing() List[TealBlock]

Get this block’s children blocks, if any.

isTerminal() bool

Check if this block ends the program.

abstract replaceOutgoing(oldBlock: TealBlock, newBlock: TealBlock) None

Replace one of this block’s child blocks.

validateSlots(slotsInUse: Set[ScratchSlot] = None, visited: Set[Tuple[int, ...]] = None) List[TealCompileError]
validateTree(parent: Optional[TealBlock] = None, visited: Optional[List[TealBlock]] = None) None

Check that this block and its children have valid parent pointers.

Parameters
  • parent (optional) – The parent block to this one, if it has one. Defaults to None.

  • visited (optional) – Used internally to remember blocks that have been visited. Set to None.

exception pyteal.TealCompileError(msg: str, sourceExpr: Optional[Expr])

Bases: Exception

class pyteal.TealComponent(expr: Optional[Expr])

Bases: ABC

class Context

Bases: object

class ExprEqualityContext

Bases: AbstractContextManager

class ScratchSlotEqualityContext

Bases: AbstractContextManager

checkExprEquality = True
checkScratchSlotEquality = True
classmethod ignoreExprEquality()
classmethod ignoreScratchSlotEquality()

When comparing TealOps, do not verify the equality of any ScratchSlot arguments.

This is commonly used in testing to verify the that two control flow graphs contains the same operations, but may use different ScratchSlots in them. In this case, you will most likely want to also use use the following code after comparing with this option enabled:

TealBlock.MatchScratchSlotReferences(
    TealBlock.GetReferencedScratchSlots(actual),
    TealBlock.GetReferencedScratchSlots(expected),
)

This ensures that the ScratchSlot usages between the two control flow graphs is equivalent. See TealBlock.MatchScratchSlotReferences for more info.

abstract assemble() str
assignSlot(slot: ScratchSlot, location: int) None
getSlots() List[ScratchSlot]
getSubroutines() List[SubroutineDefinition]
resolveSubroutine(subroutine: SubroutineDefinition, label: str) None
class pyteal.TealConditionalBlock(ops: List[TealOp])

Bases: TealBlock

Represents a basic block of TealComponents in a graph ending with a branch condition.

getOutgoing() List[TealBlock]

Get this block’s children blocks, if any.

replaceOutgoing(oldBlock: TealBlock, newBlock: TealBlock) None

Replace one of this block’s child blocks.

setFalseBlock(block: TealBlock) None

Set the block that this one should branch to if its condition is false.

setTrueBlock(block: TealBlock) None

Set the block that this one should branch to if its condition is true.

exception pyteal.TealInputError(msg: str)

Bases: Exception

exception pyteal.TealInternalError(message: str)

Bases: Exception

class pyteal.TealLabel(expr: Optional[Expr], label: LabelReference, comment: str = None)

Bases: TealComponent

assemble() str
getLabelRef() LabelReference
class pyteal.TealOp(expr: Optional[Expr], op: Op, *args: Union[int, str, LabelReference, ScratchSlot, SubroutineDefinition])

Bases: TealComponent

assemble() str
assignSlot(slot: ScratchSlot, location: int) None
getOp() Op
getSlots() List[ScratchSlot]
getSubroutines() List[SubroutineDefinition]
resolveSubroutine(subroutine: SubroutineDefinition, label: str) None
exception pyteal.TealPragmaError(message: str)

Bases: Exception

class pyteal.TealSimpleBlock(ops: List[TealOp])

Bases: TealBlock

Represents a basic block of TealComponents in a graph that does not contain a branch condition.

getOutgoing() List[TealBlock]

Get this block’s children blocks, if any.

replaceOutgoing(oldBlock: TealBlock, newBlock: TealBlock) None

Replace one of this block’s child blocks.

setNextBlock(block: TealBlock) None

Set the block that follows this one.

class pyteal.TealType(value)

Bases: Enum

Teal type enum.

anytype = 2
bytes = 1
none = 3
uint64 = 0
exception pyteal.TealTypeError(actual, expected)

Bases: Exception

class pyteal.Tmpl(op: Op, type: TealType, name: str)

Bases: LeafExpr

Template expression for creating placeholder values.

classmethod Addr(placeholder: str)

Create a new Addr template.

Parameters

placeholder – The name to use for this template variable. Must start with TMPL_ and only consist of uppercase alphanumeric characters and underscores.

classmethod Bytes(placeholder: str)

Create a new Bytes template.

Parameters

placeholder – The name to use for this template variable. Must start with TMPL_ and only consist of uppercase alphanumeric characters and underscores.

classmethod Int(placeholder: str)

Create a new Int template.

Parameters

placeholder – The name to use for this template variable. Must start with TMPL_ and only consist of uppercase alphanumeric characters and underscores.

type_of()

Get the return type of this expression.

class pyteal.TxnArray(txnObject: TxnObject, accessField: TxnField, lengthField: TxnField)

Bases: Array

Represents a transaction array field.

__getitem__(index: Union[int, Expr]) TxnaExpr

Get the value at a given index in this array.

length() TxnExpr

Get the length of the array.

class pyteal.TxnExpr(op: Op, name: str, field: TxnField)

Bases: LeafExpr

An expression that accesses a transaction field from the current transaction.

type_of()

Get the return type of this expression.

class pyteal.TxnField(value)

Bases: Enum

An enumeration.

accounts = (28, 'Accounts', <TealType.bytes: 1>, True, 2)
amount = (8, 'Amount', <TealType.uint64: 0>, False, 2)
application_args = (26, 'ApplicationArgs', <TealType.bytes: 1>, True, 2)
application_id = (24, 'ApplicationID', <TealType.uint64: 0>, False, 2)
applications = (50, 'Applications', <TealType.uint64: 0>, True, 3)
approval_program = (30, 'ApprovalProgram', <TealType.bytes: 1>, False, 2)
approval_program_pages = (64, 'ApprovalProgramPages', <TealType.bytes: 1>, True, 7)
asset_amount = (18, 'AssetAmount', <TealType.uint64: 0>, False, 2)
asset_close_to = (21, 'AssetCloseTo', <TealType.bytes: 1>, False, 2)
asset_receiver = (20, 'AssetReceiver', <TealType.bytes: 1>, False, 2)
asset_sender = (19, 'AssetSender', <TealType.bytes: 1>, False, 2)
assets = (48, 'Assets', <TealType.uint64: 0>, True, 3)
clear_state_program = (31, 'ClearStateProgram', <TealType.bytes: 1>, False, 2)
clear_state_program_pages = (66, 'ClearStateProgramPages', <TealType.bytes: 1>, True, 7)
close_remainder_to = (9, 'CloseRemainderTo', <TealType.bytes: 1>, False, 2)
config_asset = (33, 'ConfigAsset', <TealType.uint64: 0>, False, 2)
config_asset_clawback = (44, 'ConfigAssetClawback', <TealType.bytes: 1>, False, 2)
config_asset_decimals = (35, 'ConfigAssetDecimals', <TealType.uint64: 0>, False, 2)
config_asset_default_frozen = (36, 'ConfigAssetDefaultFrozen', <TealType.uint64: 0>, False, 2)
config_asset_freeze = (43, 'ConfigAssetFreeze', <TealType.bytes: 1>, False, 2)
config_asset_manager = (41, 'ConfigAssetManager', <TealType.bytes: 1>, False, 2)
config_asset_metadata_hash = (40, 'ConfigAssetMetadataHash', <TealType.bytes: 1>, False, 2)
config_asset_name = (38, 'ConfigAssetName', <TealType.bytes: 1>, False, 2)
config_asset_reserve = (42, 'ConfigAssetReserve', <TealType.bytes: 1>, False, 2)
config_asset_total = (34, 'ConfigAssetTotal', <TealType.uint64: 0>, False, 2)
config_asset_unit_name = (37, 'ConfigAssetUnitName', <TealType.bytes: 1>, False, 2)
config_asset_url = (39, 'ConfigAssetURL', <TealType.bytes: 1>, False, 2)
created_application_id = (61, 'CreatedApplicationID', <TealType.uint64: 0>, False, 5)
created_asset_id = (60, 'CreatedAssetID', <TealType.uint64: 0>, False, 5)
extra_program_pages = (56, 'ExtraProgramPages', <TealType.uint64: 0>, False, 4)
fee = (1, 'Fee', <TealType.uint64: 0>, False, 2)
first_valid = (2, 'FirstValid', <TealType.uint64: 0>, False, 2)
first_valid_time = (3, 'FirstValidTime', <TealType.uint64: 0>, False, 7)
freeze_asset = (45, 'FreezeAsset', <TealType.uint64: 0>, False, 2)
freeze_asset_account = (46, 'FreezeAssetAccount', <TealType.bytes: 1>, False, 2)
freeze_asset_frozen = (47, 'FreezeAssetFrozen', <TealType.uint64: 0>, False, 2)
global_num_byte_slices = (53, 'GlobalNumByteSlice', <TealType.uint64: 0>, False, 3)
global_num_uints = (52, 'GlobalNumUint', <TealType.uint64: 0>, False, 3)
group_index = (22, 'GroupIndex', <TealType.uint64: 0>, False, 2)
last_log = (62, 'LastLog', <TealType.bytes: 1>, False, 6)
last_valid = (4, 'LastValid', <TealType.uint64: 0>, False, 2)
lease = (6, 'Lease', <TealType.bytes: 1>, False, 2)
local_num_byte_slices = (55, 'LocalNumByteSlice', <TealType.uint64: 0>, False, 3)
local_num_uints = (54, 'LocalNumUint', <TealType.uint64: 0>, False, 3)
logs = (58, 'Logs', <TealType.bytes: 1>, True, 5)
nonparticipation = (57, 'Nonparticipation', <TealType.uint64: 0>, False, 5)
note = (5, 'Note', <TealType.bytes: 1>, False, 2)
num_accounts = (2, 'NumAccounts', <TealType.uint64: 0>, False, 2)
num_app_args = (27, 'NumAppArgs', <TealType.uint64: 0>, False, 2)
num_applications = (51, 'NumApplications', <TealType.uint64: 0>, False, 3)
num_approval_program_pages = (65, 'NumApprovalProgramPages', <TealType.uint64: 0>, False, 7)
num_assets = (49, 'NumAssets', <TealType.uint64: 0>, False, 3)
num_clear_state_program_pages = (67, 'NumClearStateProgramPages', <TealType.uint64: 0>, False, 7)
num_logs = (59, 'NumLogs', <TealType.uint64: 0>, False, 5)
on_completion = (25, 'OnCompletion', <TealType.uint64: 0>, False, 2)
receiver = (7, 'Receiver', <TealType.bytes: 1>, False, 2)
rekey_to = (32, 'RekeyTo', <TealType.bytes: 1>, False, 2)
selection_pk = (11, 'SelectionPK', <TealType.bytes: 1>, False, 2)
sender = (0, 'Sender', <TealType.bytes: 1>, False, 2)
state_proof_pk = (63, 'StateProofPK', <TealType.bytes: 1>, False, 6)
tx_id = (23, 'TxID', <TealType.bytes: 1>, False, 2)
type = (15, 'Type', <TealType.bytes: 1>, False, 2)
type_enum = (16, 'TypeEnum', <TealType.uint64: 0>, False, 2)
type_of() TealType
vote_first = (12, 'VoteFirst', <TealType.uint64: 0>, False, 2)
vote_key_dilution = (14, 'VoteKeyDilution', <TealType.uint64: 0>, False, 2)
vote_last = (13, 'VoteLast', <TealType.uint64: 0>, False, 2)
vote_pk = (10, 'VotePK', <TealType.bytes: 1>, False, 2)
xfer_asset = (17, 'XferAsset', <TealType.uint64: 0>, False, 2)
class pyteal.TxnGroup

Bases: object

Represents a group of transactions.

__getitem__(txnIndex: Union[int, Expr]) TxnObject
class pyteal.TxnObject(makeTxnExpr: Callable[[TxnField], TxnExpr], makeTxnaExpr: Callable[[TxnField, Union[int, Expr]], TxnaExpr])

Bases: object

Represents a transaction and its fields.

property accounts: TxnArray

The accounts array in an ApplicationCall transaction.

Type

TxnArray

amount() TxnExpr

Get the amount of the transaction in micro Algos.

Only set when type_enum() is TxnType.Payment.

For more information, see https://developer.algorand.org/docs/reference/transactions/#amount

property application_args: TxnArray

Application call arguments array.

Type

TxnArray

application_id() TxnExpr

Get the application ID from the ApplicationCall portion of the current transaction.

Only set when type_enum() is TxnType.ApplicationCall.

property applications: TxnArray

The applications array in an ApplicationCall transaction.

Type

TxnArray

Requires program version 3 or higher.

approval_program() TxnExpr

Get the approval program.

Only set when type_enum() is TxnType.ApplicationCall.

property approval_program_pages: TxnArray

The approval program pages.

Type

TxnArray

Requires program version 7 or higher.

asset_amount() TxnExpr

Get the amount of the asset being transferred, measured in the asset’s units.

Only set when type_enum() is TxnType.AssetTransfer.

For more information, see https://developer.algorand.org/docs/reference/transactions/#assetamount

asset_close_to() TxnExpr

Get the closeout address of the asset transfer.

Only set when type_enum() is TxnType.AssetTransfer.

For more information, see https://developer.algorand.org/docs/reference/transactions/#assetcloseto

asset_receiver() TxnExpr

Get the recipient of the asset transfer.

Only set when type_enum() is TxnType.AssetTransfer.

For more information, see https://developer.algorand.org/docs/reference/transactions/#assetreceiver

asset_sender() TxnExpr

Get the 32 byte address of the subject of clawback.

Only set when type_enum() is TxnType.AssetTransfer.

For more information, see https://developer.algorand.org/docs/reference/transactions/#assetsender

property assets: TxnArray

The foreign asset array in an ApplicationCall transaction.

Type

TxnArray

Requires program version 3 or higher.

clear_state_program() TxnExpr

Get the clear state program.

Only set when type_enum() is TxnType.ApplicationCall.

property clear_state_program_pages: TxnArray

The clear state program pages.

Type

TxnArray

Requires program version 7 or higher.

close_remainder_to() TxnExpr

Get the 32 byte address of the CloseRemainderTo field.

Only set when type_enum() is TxnType.Payment.

For more information, see https://developer.algorand.org/docs/reference/transactions/#closeremainderto

config_asset() TxnExpr

Get the asset ID in asset config transaction.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#configasset

config_asset_clawback() TxnExpr

Get the 32 byte asset clawback address.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#clawbackaddr

config_asset_decimals() TxnExpr

Get the number of digits to display after the decimal place when displaying the asset.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#decimals

config_asset_default_frozen() TxnExpr

Check if the asset’s slots are frozen by default or not.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#defaultfrozen

config_asset_freeze() TxnExpr

Get the 32 byte asset freeze address.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#freezeaddr

config_asset_manager() TxnExpr

Get the 32 byte asset manager address.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#manageraddr

config_asset_metadata_hash() TxnExpr

Get the 32 byte commitment to some unspecified asset metdata.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#metadatahash

config_asset_name() TxnExpr

Get the asset name.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#assetname

config_asset_reserve() TxnExpr

Get the 32 byte asset reserve address.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#reserveaddr

config_asset_total() TxnExpr

Get the total number of units of this asset created.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#total

config_asset_unit_name() TxnExpr

Get the unit name of the asset.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#unitname

config_asset_url() TxnExpr

Get the asset URL.

Only set when type_enum() is TxnType.AssetConfig.

For more information, see https://developer.algorand.org/docs/reference/transactions/#url

created_application_id() TxnExpr

Get the application ID allocated by the creation of an application.

Only set when type_enum() is TxnType.ApplicationCall and this is an app creation call.

Requires program version 5 or higher.

  • v5 - Only works on inner transactions.

  • >= v6 - Works on top-level and inner transactions.

created_asset_id() TxnExpr

Get the asset ID allocated by the creation of an ASA.

Only set when type_enum() is TxnType.AssetConfig and this is an asset creation transaction.

Requires program version 5 or higher.

  • v5 - Only works on inner transactions.

  • >= v6 - Works on top-level and inner transactions.

extra_program_pages() TxnExpr

Get the number of additional pages for each of the application’s approval and clear state programs.

1 additional page means 2048 more total bytes, or 1024 for each program.

Only set when type_enum() is TxnType.ApplicationCall and this is an app creation call.

Requires program version 4 or higher.

fee() TxnExpr

Get the transaction fee in micro Algos.

For more information, see https://developer.algorand.org/docs/reference/transactions/#fee

first_valid() TxnExpr

Get the first valid round number.

For more information, see https://developer.algorand.org/docs/reference/transactions/#firstvalid

first_valid_time() TxnExpr

Get the UNIX timestamp of block before txn.FirstValid. Fails if negative.

For more information, see https://developer.algorand.org/docs/reference/transactions/#firstvalidtime

freeze_asset() TxnExpr

Get the asset ID being frozen or un-frozen.

Only set when type_enum() is TxnType.AssetFreeze.

For more information, see https://developer.algorand.org/docs/reference/transactions/#freezeasset

freeze_asset_account() TxnExpr

Get the 32 byte address of the account whose asset slot is being frozen or un-frozen.

Only set when type_enum() is TxnType.AssetFreeze.

For more information, see https://developer.algorand.org/docs/reference/transactions/#freezeaccount

freeze_asset_frozen() TxnExpr

Get the new frozen value for the asset.

Only set when type_enum() is TxnType.AssetFreeze.

For more information, see https://developer.algorand.org/docs/reference/transactions/#assetfrozen

global_num_byte_slices() TxnExpr

Get the schema count of global state byte slices in an application creation call.

Only set when type_enum() is TxnType.ApplicationCall and this is an app creation call.

Requires program version 3 or higher.

global_num_uints() TxnExpr

Get the schema count of global state integers in an application creation call.

Only set when type_enum() is TxnType.ApplicationCall and this is an app creation call.

Requires program version 3 or higher.

group_index() TxnExpr

Get the position of the transaction within the atomic transaction group.

A stand-alone transaction is implictly element 0 in a group of 1.

For more information, see https://developer.algorand.org/docs/reference/transactions/#group

last_log() TxnExpr

A convenience method for getting the last logged message from a transaction.

Only application calls may log a message. Returns an empty string if no messages were logged.

Only set when type_enum() is TxnType.ApplicationCall.

Requires program version 6 or higher.

last_valid() TxnExpr

Get the last valid round number.

For more information, see https://developer.algorand.org/docs/reference/transactions/#lastvalid

lease() TxnExpr

Get the transaction lease.

For more information, see https://developer.algorand.org/docs/reference/transactions/#lease

local_num_byte_slices() TxnExpr

Get the schema count of local state byte slices in an application creation call.

Only set when type_enum() is TxnType.ApplicationCall and this is an app creation call.

Requires program version 3 or higher.

local_num_uints() TxnExpr

Get the schema count of local state integers in an application creation call.

Only set when type_enum() is TxnType.ApplicationCall and this is an app creation call.

Requires program version 3 or higher.

property logs: TxnArray

The log messages emitted by an application call.

Type

TxnArray

Requires program version 5 or higher.

  • v5 - Only works on inner transactions.

  • >= v6 - Works on top-level and inner transactions.

nonparticipation() TxnExpr

Marks an account nonparticipating for rewards.

Only set when type_enum() is TxnType.KeyRegistration.

For more information, see https://developer.algorand.org/docs/reference/transactions/#nonparticipation

Requires program version 5 or higher.

note() TxnExpr

Get the transaction note.

For more information, see https://developer.algorand.org/docs/reference/transactions/#note

on_completion() TxnExpr

Get the on completion action from the ApplicationCall portion of the transaction.

Only set when type_enum() is TxnType.ApplicationCall.

receiver() TxnExpr

Get the 32 byte address of the receiver.

Only set when type_enum() is TxnType.Payment.

For more information, see https://developer.algorand.org/docs/reference/transactions/#receiver

rekey_to() TxnExpr

Get the sender’s new 32 byte AuthAddr.

For more information, see https://developer.algorand.org/docs/reference/transactions/#rekeyto

selection_pk() TxnExpr

Get the VRF public key.

Only set when type_enum() is TxnType.KeyRegistration.

For more information, see https://developer.algorand.org/docs/reference/transactions/#selectionpk

sender() TxnExpr

Get the 32 byte address of the sender.

For more information, see https://developer.algorand.org/docs/reference/transactions/#sender

state_proof_pk() TxnExpr

Get the state proof public key commitment from a transaction.

Requires program version 6 or higher.

tx_id() TxnExpr

Get the 32 byte computed ID for the transaction.

type() TxnExpr

Get the type of this transaction as a byte string.

In most cases it is preferable to use type_enum() instead.

For more information, see https://developer.algorand.org/docs/reference/transactions/#type

type_enum() TxnExpr

Get the type of this transaction.

See TxnType for possible values.

vote_first() TxnExpr

Get the first round that the participation key is valid.

Only set when type_enum() is TxnType.KeyRegistration.

For more information, see https://developer.algorand.org/docs/reference/transactions/#votefirst

vote_key_dilution() TxnExpr

Get the dilution for the 2-level participation key.

Only set when type_enum() is TxnType.KeyRegistration.

For more information, see https://developer.algorand.org/docs/reference/transactions/#votekeydilution

vote_last() TxnExpr

Get the last round that the participation key is valid.

Only set when type_enum() is TxnType.KeyRegistration.

For more information, see https://developer.algorand.org/docs/reference/transactions/#votelast

vote_pk() TxnExpr

Get the root participation public key.

Only set when type_enum() is TxnType.KeyRegistration.

For more information, see https://developer.algorand.org/docs/reference/transactions/#votepk

xfer_asset() TxnExpr

Get the ID of the asset being transferred.

Only set when type_enum() is TxnType.AssetTransfer.

For more information, see https://developer.algorand.org/docs/reference/transactions/#xferasset

class pyteal.TxnType

Bases: object

Enum of all possible transaction types.

ApplicationCall = <pyteal.EnumInt object>
AssetConfig = <pyteal.EnumInt object>
AssetFreeze = <pyteal.EnumInt object>
AssetTransfer = <pyteal.EnumInt object>
KeyRegistration = <pyteal.EnumInt object>
Payment = <pyteal.EnumInt object>
Unknown = <pyteal.EnumInt object>
class pyteal.TxnaExpr(staticOp: Op, dynamicOp: Optional[Op], name: str, field: TxnField, index: Union[int, Expr])

Bases: LeafExpr

An expression that accesses a transaction array field from the current transaction.

type_of()

Get the return type of this expression.

class pyteal.UnaryExpr(op: Op, inputType: TealType, outputType: TealType, arg: Expr)

Bases: Expr

An expression with a single argument.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.VrfVerify(standard: VrfVerifyStandard, message: Expr, proof: Expr, public_key: Expr)

Bases: MultiValue

An expression that verifies the proof of a message against a public key.

classmethod algorand(message: Expr, proof: Expr, public_key: Expr) VrfVerify

Verifies the proof of a message against a public key using the Algorand VRF standard.

Parameters
  • message – The message to verify.

  • proof – The proof of the message.

  • public_key – The public key to use to verify the proof.

Returns

A MultiValue expression representing the VRF output and a verification flag.

Verifies the proof of a message against a public key using the Chainlink VRF standard.

Parameters
  • message – The message to verify.

  • proof – The proof of the message.

  • public_key – The public key to use to verify the proof.

Returns

A MultiValue expression representing the VRF output and a verification flag.

class pyteal.While(cond: Expr)

Bases: Expr

While expression.

Do(doBlock: Expr, *do_block_multi: Expr)
__init__(cond: Expr) None

Create a new While expression.

When this While expression is executed, the condition will be evaluated, and if it produces a true value, doBlock will be executed and return to the start of the expression execution. Otherwise, no branch will be executed.

Parameters

cond – The condition to check. Must evaluate to uint64.

Example

i = ScratchVar()
i.store(Int(0))
While(i.load() < pt.Int(2))
    .Do(Pop(Int(1)), i.store(i.load() + Int(1)))
has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

class pyteal.WideRatio(numeratorFactors: List[Expr], denominatorFactors: List[Expr])

Bases: Expr

A class used to calculate expressions of the form (N_1 * N_2 * N_3 * ...) / (D_1 * D_2 * D_3 * ...)

Use this class if all inputs to the expression are uint64s, the output fits in a uint64, and all intermediate values fit in a uint128.

__init__(numeratorFactors: List[Expr], denominatorFactors: List[Expr]) None

Create a new WideRatio expression with the given numerator and denominator factors.

This will calculate (N_1 * N_2 * N_3 * ...) / (D_1 * D_2 * D_3 * ...), where each N_i represents an element in numeratorFactors and each D_i represents an element in denominatorFactors.

Requires program version 5 or higher.

Parameters
  • numeratorFactors – The factors in the numerator of the ratio. This list must have at least 1 element. If this list has exactly 1 element, then denominatorFactors must have more than 1 element (otherwise basic division should be used).

  • denominatorFactors – The factors in the denominator of the ratio. This list must have at least 1 element.

has_return()

Check if this expression always returns from the current subroutine or program.

type_of()

Get the return type of this expression.

pyteal.compileTeal(ast: Expr, mode: Mode, *, version: int = 2, assembleConstants: bool = False, optimize: Optional[OptimizeOptions] = None) str

Compile a PyTeal expression into TEAL assembly.

Parameters
  • ast – The PyTeal expression to assemble.

  • mode – The mode of the program to assemble. Must be Signature or Application.

  • version (optional) – The program version used to assemble the program. This will determine which expressions and fields are able to be used in the program and how expressions compile to TEAL opcodes. Defaults to 2 if not included.

  • assembleConstants (optional) – When true, the compiler will produce a program with fully assembled constants, rather than using the pseudo-ops int, byte, and addr. These constants will be assembled in the most space-efficient way, so enabling this may reduce the compiled program’s size. Enabling this option requires a minimum program version of 3. Defaults to false.

  • optimize (optional) – OptimizeOptions that determine which optimizations will be applied.

Returns

A TEAL assembly program compiled from the input expression.

Raises
  • TealInputError – if an operation in ast is not supported by the supplied mode and version.

  • TealInternalError – if an internal error is encounter during compilation.

pyteal.pragma(*, compiler_version: str, **kwargs: Any) None

Specify pragmas for the compiler.

Parameters

compiler_version

Acceptable versions of the compiler. Will fail if the current PyTeal version is not contained in the range. Follows the npm semver range scheme for specifying compatible versions.

For example:

# this will immediately fail if the current PyTeal version does not satisfy the
# version constraint
pragma(compiler_version="^0.14.0")
class pyteal.abi.Account

Bases: ReferenceType

address() Expr

Get the address of the account.

asset_holding(asset: pyteal.Expr | pyteal.abi.Asset) AssetHoldingObject

Get information about an asset held by this account.

Parameters

asset – An identifier for the asset. It must be one of the following: an abi.Asset reference object, an expression holding an index into Txn.ForeignAssets that corresponds to the asset (in which case it must evaluate to uint64), or since v4, an expression holding an asset ID that appears in Txn.ForeignAssets (in which case it must evaluate to uint64).

params() AccountParamObject

Get information about the account.

class pyteal.abi.AccountTypeSpec

Bases: ReferenceTypeSpec

annotation_type() type[pyteal.abi.Account]

Get the annotation type associated with this spec

new_instance() Account

Create a new instance of the specified type.

class pyteal.abi.Address

Bases: StaticArray[Byte, Literal[<AddressLength.Bytes: 32>]]

get() Expr

Return the 32-byte value held by this Address as a PyTeal expression.

The expression will have the type TealType.bytes.

set(value: ~typing.Union[str, bytes, ~pyteal.Expr, ~typing.Sequence[~pyteal.abi.Byte], ~pyteal.abi.StaticArray[~pyteal.abi.Byte, ~typing.Literal[<AddressLength.Bytes: 32>]], ~pyteal.abi.ComputedValue[~pyteal.abi.StaticArray[~pyteal.abi.Byte, ~typing.Literal[<AddressLength.Bytes: 32>]]], ~pyteal.abi.Address, ~pyteal.abi.ComputedValue[~pyteal.abi.Address]])

Set the value of this Address to the input value.

The behavior of this method depends on the input argument type:

  • str: set the value to the address from the encoded address string. This string must be a valid 58-character base-32 Algorand address with checksum.

  • bytes: set the value to the raw address bytes. This byte string must have length 32.

  • Expr: set the value to the result of a PyTeal expression, which must evaluate to a TealType.bytes. The program will fail if the evaluated byte string length is not 32.

  • Sequence[Byte]: set the bytes of this Address to those contained in this Python sequence (e.g. a list or tuple). A compiler error will occur if the sequence length is not 32.

  • StaticArray[Byte, 32]: copy the bytes from a StaticArray of 32 bytes.

  • ComputedValue[StaticArray[Byte, 32]]: copy the bytes from a StaticArray of 32 bytes produced by a ComputedValue.

  • Address: copy the value from another Address.

  • ComputedValue[Address]: copy the value from an Address produced by a ComputedValue.

Parameters

value – The new value this Address should take. This must follow the above constraints.

Returns

An expression which stores the given value into this Address.

type_spec() AddressTypeSpec

Get the TypeSpec for this ABI type instance.

class pyteal.abi.AddressLength(value)

Bases: IntEnum

An enumeration.

Bytes = 32
String = 58
class pyteal.abi.AddressTypeSpec

Bases: StaticArrayTypeSpec

annotation_type() type[pyteal.abi.Address]

Get the annotation type associated with this spec

new_instance() Address

Create a new instance of the specified type.

class pyteal.abi.Application

Bases: ReferenceType

application_id() Expr

Get the ID of the application.

params() AppParamObject

Get information about the application’s parameters.

class pyteal.abi.ApplicationCallTransaction

Bases: Transaction

class pyteal.abi.ApplicationCallTransactionTypeSpec

Bases: TransactionTypeSpec

annotation_type() type[pyteal.abi.ApplicationCallTransaction]

Get the annotation type associated with this spec

new_instance() ApplicationCallTransaction

Create a new instance of the specified type.

txn_type_enum() Expr

Get the integer transaction type value this TransactionTypeSpec represents.

See TxnType for the complete list.

If this is a generic TransactionTypeSpec, i.e. type txn, this method will raise an error, since this type does not represent a single transaction type.

class pyteal.abi.ApplicationTypeSpec

Bases: ReferenceTypeSpec

annotation_type() type[pyteal.abi.Application]

Get the annotation type associated with this spec

new_instance() Application

Create a new instance of the specified type.

class pyteal.abi.Array(spec: ArrayTypeSpec)

Bases: BaseType, Generic[T]

The abstract base class for both ABI static and dynamic array instances.

This class contains basic implementations of ABI array methods, including:
  • basic array elements setting method

  • basic encoding and decoding of ABI array

  • item retrieving by index (expression or integer)

__getitem__(index: Union[int, Expr]) ArrayElement[T]

Retrieve an element by its index in this array.

Indexes start at 0.

Parameters

index – either a Python integer or a PyTeal expression that evaluates to a TealType.uint64. If a Python integer is used, this function will raise an error if its value is negative. In either case, if the index is outside of the bounds of this array, the program will fail at runtime.

Returns

An ArrayElement that corresponds to the element at the given index. This type is a ComputedValue.

decode(encoded: Expr, *, start_index: Optional[Expr] = None, end_index: Optional[Expr] = None, length: Optional[Expr] = None) Expr

Decode a substring of the passed in encoded byte string and set it as this type’s value.

Parameters
  • encoded – An expression containing the bytes to decode. Must evaluate to TealType.bytes.

  • start_index (optional) – An expression containing the index to start decoding. Must evaluate to TealType.uint64. Defaults to None.

  • end_index (optional) – An expression containing the index to stop decoding. Must evaluate to TealType.uint64. Defaults to None.

  • length (optional) – An expression containing the length of the substring to decode. Must evaluate to TealType.uint64. Defaults to None.

Returns

An expression that partitions the needed parts from given byte strings and stores into the scratch variable.

encode() Expr

Encode the ABI array to be a byte string.

Returns

A PyTeal expression that encodes this ABI array to a byte string.

abstract length() Expr

Get the element number of this ABI array.

Returns

A PyTeal expression that represents the array length.

set(values: Sequence[T]) Expr

Set the ABI array with a sequence of ABI type variables.

The function first type-check the argument values to make sure the sequence of ABI type variables before storing them to the underlying ScratchVar. If any of the input element does not match expected array element type, error would be raised about type-mismatch.

If static length of array is not available, this function would * infer the array length from the sequence element number. * store the inferred array length in uint16 format. * concatenate the encoded array length at the beginning of array encoding.

Parameters

values – The sequence of ABI type variables to store in ABI array.

Returns

A PyTeal expression that stores encoded sequence of ABI values in its internal ScratchVar.

type_spec() ArrayTypeSpec[T]

Get the TypeSpec for this ABI type instance.

class pyteal.abi.ArrayElement(array: Array[T], index: Expr)

Bases: ComputedValue[T]

The class that represents an ABI array element.

This class requires a reference to the array that the array element belongs to, and a PyTeal expression (required to be TealType.uint64) which contains the array index.

__init__(array: Array[T], index: Expr) None

Creates a new ArrayElement.

Parameters
  • array – The ABI array that the array element belongs to.

  • index – A PyTeal expression (required to be TealType.uint64) stands for array index.

produced_type_spec() TypeSpec

Get the ABI TypeSpec that this object produces.

store_into(output: T) Expr

Partitions the byte string of the given ABI array and stores the byte string of array element in the ABI value output.

The function first checks if the output type matches with array element type, and throw error if type-mismatch.

Parameters

output – An ABI typed value that the array element byte string stores into.

Returns

An expression that stores the byte string of the array element into value output.

class pyteal.abi.ArrayTypeSpec(value_type_spec: TypeSpec)

Bases: TypeSpec, Generic[T]

The abstract base class for both static and dynamic array TypeSpecs.

abstract is_length_dynamic() bool

Check if this array has a dynamic or static length.

storage_type() TealType

Get the TealType that the underlying ScratchVar should hold for this type.

value_type_spec() TypeSpec

Get the TypeSpec of the value type this array can hold.

class pyteal.abi.Asset

Bases: ReferenceType

asset_id() Expr

Get the ID of the asset.

holding(account: pyteal.Expr | pyteal.abi.Account) AssetHoldingObject

Get information about this asset held by an account.

Parameters

account – An identifier for the account. It must be one of the following: an abi.Account reference object, an expression holding an index into Txn.Accounts that corresponds to the account (in which case it must evaluate to uint64), or since v4, an expression holding an account address that appears in Txn.Accounts or is Txn.Sender (in which case it must evaluate to bytes).

params() AssetParamObject

Get information about the asset’s parameters.

class pyteal.abi.AssetConfigTransaction

Bases: Transaction

class pyteal.abi.AssetConfigTransactionTypeSpec

Bases: TransactionTypeSpec

annotation_type() type[pyteal.abi.AssetConfigTransaction]

Get the annotation type associated with this spec

new_instance() AssetConfigTransaction

Create a new instance of the specified type.

txn_type_enum() Expr

Get the integer transaction type value this TransactionTypeSpec represents.

See TxnType for the complete list.

If this is a generic TransactionTypeSpec, i.e. type txn, this method will raise an error, since this type does not represent a single transaction type.

class pyteal.abi.AssetFreezeTransaction

Bases: Transaction

class pyteal.abi.AssetFreezeTransactionTypeSpec

Bases: TransactionTypeSpec

annotation_type() type[pyteal.abi.AssetFreezeTransaction]

Get the annotation type associated with this spec

new_instance() AssetFreezeTransaction

Create a new instance of the specified type.

txn_type_enum() Expr

Get the integer transaction type value this TransactionTypeSpec represents.

See TxnType for the complete list.

If this is a generic TransactionTypeSpec, i.e. type txn, this method will raise an error, since this type does not represent a single transaction type.

class pyteal.abi.AssetTransferTransaction

Bases: Transaction

class pyteal.abi.AssetTransferTransactionTypeSpec

Bases: TransactionTypeSpec

annotation_type() type[pyteal.abi.AssetTransferTransaction]

Get the annotation type associated with this spec

new_instance() AssetTransferTransaction

Create a new instance of the specified type.

txn_type_enum() Expr

Get the integer transaction type value this TransactionTypeSpec represents.

See TxnType for the complete list.

If this is a generic TransactionTypeSpec, i.e. type txn, this method will raise an error, since this type does not represent a single transaction type.

class pyteal.abi.AssetTypeSpec

Bases: ReferenceTypeSpec

annotation_type() type[pyteal.abi.Asset]

Get the annotation type associated with this spec

new_instance() Asset

Create a new instance of the specified type.

class pyteal.abi.BaseType(spec: TypeSpec)

Bases: ABC

The abstract base class for all ABI type instances.

The value of the type is contained in a unique ScratchVar that only this instance has access to. As a result, the value of an ABI type is mutable and can be efficiently referenced multiple times without needing to recompute it.

__init__(spec: TypeSpec) None

Create a new BaseType.

abstract decode(encoded: Expr, *, start_index: Optional[Expr] = None, end_index: Optional[Expr] = None, length: Optional[Expr] = None) Expr

Decode a substring of the passed in encoded string and set it as this type’s value.

The arguments to this function are means to be as flexible as possible for the caller. Multiple types of substrings can be specified based on the arguments, as listed below:

  • Entire string: if start_index, end_index, and length are all None, the entire encoded string is decoded.

  • Prefix: if start_index is None and one of end_index or length is provided, a prefix of the encoded string is decoded. The range is 0 through end_index or length (they are equivalent).

  • Suffix: if start_index is provided and end_index and length are None, a suffix of the encoded string is decoded. The range is start_index through the end of the string.

  • Substring specified with end_index: if start_index and end_index are provided and length is None, a substring of the encoded string is decoded. The range is start_index through end_index.

  • Substring specified with length: if start_index and length are provided and end_index is None, a substring of the encoded string is decoded. The range is start_index through start_index+length.

Parameters
  • encoded – An expression containing the bytes to decode. Must evaluate to TealType.bytes.

  • start_index (optional) – An expression containing the index to start decoding. Must evaluate to TealType.uint64. Defaults to None.

  • end_index (optional) – An expression containing the index to stop decoding. Must evaluate to TealType.uint64. Defaults to None.

  • length (optional) – An expression containing the length of the substring to decode. Must evaluate to TealType.uint64. Defaults to None.

Returns

An expression that performs the necessary steps in order to decode the given string into a value.

abstract encode() Expr

Encode this ABI type to a byte string.

Returns

A PyTeal expression that encodes this type to a byte string.

type_spec() TypeSpec

Get the TypeSpec for this ABI type instance.

class pyteal.abi.Bool

Bases: BaseType

decode(encoded: Expr, *, start_index: Optional[Expr] = None, end_index: Optional[Expr] = None, length: Optional[Expr] = None) Expr

Decode a substring of the passed in encoded string and set it as this type’s value.

The arguments to this function are means to be as flexible as possible for the caller. Multiple types of substrings can be specified based on the arguments, as listed below:

  • Entire string: if start_index, end_index, and length are all None, the entire encoded string is decoded.

  • Prefix: if start_index is None and one of end_index or length is provided, a prefix of the encoded string is decoded. The range is 0 through end_index or length (they are equivalent).

  • Suffix: if start_index is provided and end_index and length are None, a suffix of the encoded string is decoded. The range is start_index through the end of the string.

  • Substring specified with end_index: if start_index and end_index are provided and length is None, a substring of the encoded string is decoded. The range is start_index through end_index.

  • Substring specified with length: if start_index and length are provided and end_index is None, a substring of the encoded string is decoded. The range is start_index through start_index+length.

Parameters
  • encoded – An expression containing the bytes to decode. Must evaluate to TealType.bytes.

  • start_index (optional) – An expression containing the index to start decoding. Must evaluate to TealType.uint64. Defaults to None.

  • end_index (optional) – An expression containing the index to stop decoding. Must evaluate to TealType.uint64. Defaults to None.

  • length (optional) – An expression containing the length of the substring to decode. Must evaluate to TealType.uint64. Defaults to None.

Returns

An expression that performs the necessary steps in order to decode the given string into a value.

decode_bit(encoded, bit_index: Expr) Expr
encode() Expr

Encode this ABI type to a byte string.

Returns

A PyTeal expression that encodes this type to a byte string.

get() Expr

Return the value held by this Bool as a PyTeal expression.

If the held value is true, an expression that evaluates to 1 will be returned. Otherwise, an expression that evaluates to 0 will be returned. In either case, the expression will have the type TealType.uint64.

set(value: Union[bool, Expr, Bool, ComputedValue[Bool]]) Expr

Set the value of this Bool to the input value.

The behavior of this method depends on the input argument type:

  • bool: set the value to a Python boolean value.

  • Expr: set the value to the result of a PyTeal expression, which must evaluate to a TealType.uint64. All values greater than 0 are considered true, while 0 is considered false.

  • Bool: copy the value from another Bool.

  • ComputedValue[Bool]: copy the value from a Bool produced by a ComputedValue.

Parameters

value – The new value this Bool should take. This must follow the above constraints.

Returns

An expression which stores the given value into this Bool.

class pyteal.abi.BoolTypeSpec

Bases: TypeSpec

annotation_type() type[pyteal.abi.Bool]

Get the annotation type associated with this spec

byte_length_static() int

Get the byte length of this ABI type’s encoding. Only valid for static types.

is_dynamic() bool

Check if this ABI type is dynamic.

If a type is dynamic, the length of its encoding depends on its value. Otherwise, the type is considered static (not dynamic).

new_instance() Bool

Create a new instance of the specified type.

storage_type() TealType

Get the TealType that the underlying ScratchVar should hold for this type.

class pyteal.abi.Byte

Bases: Uint

class pyteal.abi.ByteTypeSpec

Bases: UintTypeSpec

annotation_type() type[pyteal.abi.Byte]

Get the annotation type associated with this spec

new_instance() Byte

Create a new instance of the specified type.

class pyteal.abi.ComputedValue

Bases: ABC, Generic[T_co]

Represents an ABI Type whose value must be computed by an expression.

abstract produced_type_spec() TypeSpec

Get the ABI TypeSpec that this object produces.

abstract store_into(output: T_co) Expr

Compute the value and store it into an existing ABI type instance.

NOTE: If you call this method multiple times, the computation to determine the value will be repeated each time. For this reason, it is recommended to only issue a single call to either store_into or use.

Parameters

output – The object where the computed value will be stored. This object must have the same type as this class’s produced type.

Returns

An expression which stores the computed value represented by this class into the output object.

use(action: Callable[[T_co], Expr]) Expr

Compute the value and pass it to a callable expression.

NOTE: If you call this method multiple times, the computation to determine the value will be repeated each time. For this reason, it is recommended to only issue a single call to either store_into or use.

Parameters

action – A callable object that will receive an instance of this class’s produced type with the computed value. The callable object may use that value as it sees fit, but it must return an Expr to be included in the program’s AST.

Returns

An expression which contains the returned expression from invoking action with the computed value.

class pyteal.abi.DynamicArray(array_type_spec: DynamicArrayTypeSpec[T])

Bases: Array[T]

The class that represents ABI dynamic array type.

length() Expr

Get the element number of this ABI dynamic array.

The array length (element number) is encoded in the first 2 bytes of the byte encoding.

Returns

A PyTeal expression that represents the dynamic array length.

set(values: Union[Sequence[T], DynamicArray[T], ComputedValue[DynamicArray[T]]]) Expr

Set the elements of this DynamicArray to the input values.

The behavior of this method depends on the input argument type:

  • Sequence[T]: set the elements of this DynamicArray to those contained in this Python sequence (e.g. a list or tuple). A compiler error will occur if any element in the sequence does not match this DynamicArray’s element type.

  • DynamicArray[T]: copy the elements from another DynamicArray. The argument’s element type must exactly match this DynamicArray’s element type, otherwise an error will occur.

  • ComputedValue[DynamicArray[T]]: copy the elements from a DynamicArray produced by a ComputedValue. The element type produced by the ComputedValue must exactly match this DynamicArray’s element type, otherwise an error will occur.

Parameters

values – The new elements this DynamicArray should have. This must follow the above constraints.

Returns

An expression which stores the given value into this DynamicArray.

type_spec() DynamicArrayTypeSpec[T]

Get the TypeSpec for this ABI type instance.

class pyteal.abi.DynamicArrayTypeSpec(value_type_spec: TypeSpec)

Bases: ArrayTypeSpec[T]

annotation_type() type['DynamicArray[T]']

Get the annotation type associated with this spec

byte_length_static() int

Get the byte length of this ABI type’s encoding. Only valid for static types.

is_dynamic() bool

Check if this ABI type is dynamic.

If a type is dynamic, the length of its encoding depends on its value. Otherwise, the type is considered static (not dynamic).

is_length_dynamic() bool

Check if this array has a dynamic or static length.

new_instance() DynamicArray[T]

Create a new instance of the specified type.

class pyteal.abi.DynamicBytes

Bases: DynamicArray[Byte]

The convenience class that represents ABI dynamic byte array.

get() Expr

Get the byte encoding of this DynamicBytes.

Dropping the uint16 encoding prefix for dynamic array length.

Returns

A Pyteal expression that loads byte encoding of this DynamicBytes, and drop the first uint16 DynamicArray length encoding.

set(values: Union[bytes, bytearray, Expr, Sequence[Byte], DynamicArray[Byte], ComputedValue[DynamicArray[Byte]]]) Expr

Set the elements of this DynamicBytes to the input values.

The behavior of this method depends on the input argument type:

  • bytes: set the value to the Python byte string.

  • bytearray: set the value to the Python byte array.

  • Expr: set the value to the result of a PyTeal expression, which must evaluate to a TealType.bytes.

  • Sequence[Byte]: set the bytes of this String to those contained in this Python sequence (e.g. a list or tuple).

  • DynamicArray[Byte]: copy the bytes from another DynamicArray. The argument’s element type must exactly match Byte, otherwise an error will occur.

  • ComputedValue[DynamicArray[Byte]]: copy the bytes from a DynamicArray produced by a ComputedValue. The argument’s element type must exactly match Byte, otherwise an error will occur.

Parameters

values – The new elements this DynamicBytes should have. This must follow the above constraints.

Returns

An expression which stores the given value into this DynamicBytes.

type_spec() DynamicBytesTypeSpec

Get the TypeSpec for this ABI type instance.

class pyteal.abi.DynamicBytesTypeSpec

Bases: DynamicArrayTypeSpec[Byte]

annotation_type() type['DynamicBytes']

Get the annotation type associated with this spec

new_instance() DynamicBytes

Create a new instance of the specified type.

class pyteal.abi.KeyRegisterTransaction

Bases: Transaction

class pyteal.abi.KeyRegisterTransactionTypeSpec

Bases: TransactionTypeSpec

annotation_type() type[pyteal.abi.KeyRegisterTransaction]

Get the annotation type associated with this spec

new_instance() KeyRegisterTransaction

Create a new instance of the specified type.

txn_type_enum() Expr

Get the integer transaction type value this TransactionTypeSpec represents.

See TxnType for the complete list.

If this is a generic TransactionTypeSpec, i.e. type txn, this method will raise an error, since this type does not represent a single transaction type.

class pyteal.abi.MethodReturn(arg: BaseType)

Bases: Expr

has_return() bool

Check if this expression always returns from the current subroutine or program.

type_of() TealType

Get the return type of this expression.

class pyteal.abi.NamedTuple

Bases: Tuple

A NamedTuple is a Tuple that has named elements, inspired by Python’s typing.NamedTuple.

A new NamedTuple type can be created by subclassing this class and adding field annotations. Every field annotation must be an instantiable ABI type wrapped in the abi.Field annotation.

For example:

from pyteal import *

class User(abi.NamedTuple):
    address: abi.Field[abi.Address]
    balance: abi.Field[abi.Uint64]

# User is equivalent to abi.Tuple2[abi.Address, abi.Uint64]

my_user = User()
__getattr__(field: str) TupleElement[Any]

Retrieve an element by its field in this NamedTuple.

For example:

from pyteal import *

class User(abi.NamedTuple):
    address: abi.Field[abi.Address]
    balance: abi.Field[abi.Uint64]

@ABIReturnSubroutine
def get_user_balance(user: User, *, output: abi.Uint64) -> Expr:
    return output.set(user.balance)
Parameters

field – a Python string containing the field to access. This function will raise an KeyError if the field is not available in the defined NamedTuple.

Returns

A TupleElement that corresponds to the element at the given field name, returning a ComputedType. Due to Python type limitations, the parameterized type of the TupleElement is Any.

class pyteal.abi.NamedTupleTypeSpec(instance_class: type['NamedTuple'], *value_type_specs: TypeSpec)

Bases: TupleTypeSpec

A NamedTupleType inherits from TupleTypeSpec, allowing for more than 5 elements.

annotation_type() type[pyteal.abi.NamedTuple]

Get the annotation type associated with this spec

new_instance() NamedTuple

Create a new instance of the specified type.

class pyteal.abi.PaymentTransaction

Bases: Transaction

class pyteal.abi.PaymentTransactionTypeSpec

Bases: TransactionTypeSpec

annotation_type() type[pyteal.abi.PaymentTransaction]

Get the annotation type associated with this spec

new_instance() PaymentTransaction

Create a new instance of the specified type.

txn_type_enum() Expr

Get the integer transaction type value this TransactionTypeSpec represents.

See TxnType for the complete list.

If this is a generic TransactionTypeSpec, i.e. type txn, this method will raise an error, since this type does not represent a single transaction type.

class pyteal.abi.ReferenceType(spec: ReferenceTypeSpec)

Bases: BaseType

decode(encoded: Expr, *, start_index: Optional[Expr] = None, end_index: Optional[Expr] = None, length: Optional[Expr] = None) Expr

Decode a substring of the passed in encoded string and set it as this type’s value.

The arguments to this function are means to be as flexible as possible for the caller. Multiple types of substrings can be specified based on the arguments, as listed below:

  • Entire string: if start_index, end_index, and length are all None, the entire encoded string is decoded.

  • Prefix: if start_index is None and one of end_index or length is provided, a prefix of the encoded string is decoded. The range is 0 through end_index or length (they are equivalent).

  • Suffix: if start_index is provided and end_index and length are None, a suffix of the encoded string is decoded. The range is start_index through the end of the string.

  • Substring specified with end_index: if start_index and end_index are provided and length is None, a substring of the encoded string is decoded. The range is start_index through end_index.

  • Substring specified with length: if start_index and length are provided and end_index is None, a substring of the encoded string is decoded. The range is start_index through start_index+length.

Parameters
  • encoded – An expression containing the bytes to decode. Must evaluate to TealType.bytes.

  • start_index (optional) – An expression containing the index to start decoding. Must evaluate to TealType.uint64. Defaults to None.

  • end_index (optional) – An expression containing the index to stop decoding. Must evaluate to TealType.uint64. Defaults to None.

  • length (optional) – An expression containing the length of the substring to decode. Must evaluate to TealType.uint64. Defaults to None.

Returns

An expression that performs the necessary steps in order to decode the given string into a value.

encode() Expr

Encode this ABI type to a byte string.

Returns

A PyTeal expression that encodes this type to a byte string.

referenced_index() Expr

Get the reference index for this value.

The three reference types (account, application, asset) contain indexes into a foreign array of the transaction. This method returns that index.

If this reference type is an application or asset, note that this DOES NOT return the application or asset ID. See application_id() or asset_id() for that.

type_spec() ReferenceTypeSpec

Get the TypeSpec for this ABI type instance.

class pyteal.abi.ReferenceTypeSpec

Bases: TypeSpec

abstract annotation_type() type[pyteal.abi.ReferenceType]

Get the annotation type associated with this spec

bit_size() int

Get the bit size of the index this reference type holds

byte_length_static() int

Get the byte length of this ABI type’s encoding. Only valid for static types.

is_dynamic() bool

Check if this ABI type is dynamic.

If a type is dynamic, the length of its encoding depends on its value. Otherwise, the type is considered static (not dynamic).

abstract new_instance() ReferenceType

Create a new instance of the specified type.

storage_type() TealType

Get the TealType that the underlying ScratchVar should hold for this type.

class pyteal.abi.ReturnedValue(type_spec: TypeSpec, computation_expr: Expr)

Bases: ComputedValue

produced_type_spec() TypeSpec

Get the ABI TypeSpec that this object produces.

store_into(output: BaseType) Expr

Compute the value and store it into an existing ABI type instance.

NOTE: If you call this method multiple times, the computation to determine the value will be repeated each time. For this reason, it is recommended to only issue a single call to either store_into or use.

Parameters

output – The object where the computed value will be stored. This object must have the same type as this class’s produced type.

Returns

An expression which stores the computed value represented by this class into the output object.

class pyteal.abi.StaticArray(array_type_spec: StaticArrayTypeSpec[T, N])

Bases: Array[T], Generic[T, N]

The class that represents ABI static array type.

__getitem__(index: Union[int, Expr]) ArrayElement[T]

Retrieve an element by its index in this StaticArray.

Indexes start at 0.

Parameters

index – either a Python integer or a PyTeal expression that evaluates to a TealType.uint64. If a Python integer is used, this function will raise an error if its value is negative or if the index is equal to or greater than the length of this StaticArray. If a PyTeal expression is used, the program will fail at runtime if the index is outside of the bounds of this StaticArray.

Returns

An ArrayElement that corresponds to the element at the given index. This type is a ComputedValue.

length() Expr

Get the element number of this ABI static array.

Returns

A PyTeal expression that represents the static array length.

set(values: Union[Sequence[T], StaticArray[T, N], ComputedValue[StaticArray[T, N]]]) Expr

Set the elements of this StaticArray to the input values.

The behavior of this method depends on the input argument type:

  • Sequence[T]: set the elements of this StaticArray to those contained in this Python sequence (e.g. a list or tuple). A compiler error will occur if any element in the sequence does not match this StaticArray’s element type, or if the sequence length does not equal this StaticArray’s length.

  • StaticArray[T, N]: copy the elements from another StaticArray. The argument’s element type and length must exactly match this StaticArray’s element type and length, otherwise an error will occur.

  • ComputedValue[StaticArray[T, N]]: copy the elements from a StaticArray produced by a ComputedValue. The element type and length produced by the ComputedValue must exactly match this StaticArray’s element type and length, otherwise an error will occur.

Parameters

values – The new elements this StaticArray should have. This must follow the above constraints.

Returns

An expression which stores the given value into this StaticArray.

type_spec() StaticArrayTypeSpec[T, N]

Get the TypeSpec for this ABI type instance.

class pyteal.abi.StaticArrayTypeSpec(value_type_spec: TypeSpec, array_length: int)

Bases: ArrayTypeSpec[T], Generic[T, N]

annotation_type() type['StaticArray[T, N]']

Get the annotation type associated with this spec

byte_length_static() int

Get the byte length of this ABI type’s encoding. Only valid for static types.

is_dynamic() bool

Check if this ABI type is dynamic.

If a type is dynamic, the length of its encoding depends on its value. Otherwise, the type is considered static (not dynamic).

is_length_dynamic() bool

Check if this array has a dynamic or static length.

length_static() int

Get the size of this static array type.

Returns

A Python integer that represents the static array length.

new_instance() StaticArray[T, N]

Create a new instance of the specified type.

class pyteal.abi.StaticBytes(array_type_spec: StaticBytesTypeSpec[N])

Bases: StaticArray[Byte, N], Generic[N]

The convenience class that represents ABI static byte array.

get() Expr

Get the byte encoding of this StaticBytes.

Returns

A Pyteal expression that loads byte encoding of this StaticBytes.

set(values: Union[bytes, bytearray, Expr, Sequence[Byte], StaticArray[Byte, N], ComputedValue[StaticArray[Byte, N]]]) Expr

Set the elements of this StaticBytes to the input values.

The behavior of this method depends on the input argument type:

  • bytes: set the value to the Python byte string.

  • bytearray: set the value to the Python byte array.

  • Expr: set the value to the result of a PyTeal expression, which must evaluate to a TealType.bytes.

  • Sequence[Byte]: set the bytes of this String to those contained in this Python sequence (e.g. a list or tuple).

  • StaticArray[Byte, N]: copy the bytes from another StaticArray. The argument’s element type and length must exactly match Byte and this StaticBytes’ length, otherwise an error will occur.

  • ComputedValue[StaticArray[Byte, N]]: copy the bytes from a StaticArray produced by a ComputedType. The argument’s element type and length must exactly match Byte and this StaticBytes’ length, otherwise an error will occur.

Parameters

values – The new elements this StaticBytes should have. This must follow the above constraints.

Returns

An expression which stores the given value into this StaticBytes.

type_spec() StaticBytesTypeSpec

Get the TypeSpec for this ABI type instance.

class pyteal.abi.StaticBytesTypeSpec(array_length: int)

Bases: StaticArrayTypeSpec[Byte, N], Generic[N]

annotation_type() type['StaticBytes[N]']

Get the annotation type associated with this spec

new_instance() StaticBytes[N]

Create a new instance of the specified type.

class pyteal.abi.String

Bases: DynamicArray[Byte]

get() Expr

Return the value held by this String as a PyTeal expression.

The expression will have the type TealType.bytes.

set(value: Union[str, bytes, Expr, Sequence[Byte], DynamicArray[Byte], ComputedValue[DynamicArray[Byte]], String, ComputedValue[String]]) Expr

Set the value of this String to the input value.

The behavior of this method depends on the input argument type:

  • str: set the value to the Python string.

  • bytes: set the value to the Python byte string.

  • Expr: set the value to the result of a PyTeal expression, which must evaluate to a TealType.bytes.

  • Sequence[Byte]: set the bytes of this String to those contained in this Python sequence (e.g. a list or tuple).

  • DynamicArray[Byte]: copy the bytes from a DynamicArray.

  • ComputedValue[DynamicArray[Byte]]: copy the bytes from a DynamicArray produced by a ComputedValue.

  • String: copy the value from another String.

  • ComputedValue[String]: copy the value from a String produced by a ComputedValue.