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], /, *, overriding_name: Optional[str] = None)
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
- static name_override(name: str) Callable[[...], ABIReturnSubroutine]
- 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.
- classmethod totalAppsCreated(acct: Expr) MaybeValue
Get the number of existing apps created by the account.
Requires program version 8 or higher.
- 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 totalAppsOptedIn(acct: Expr) MaybeValue
Get the number of apps the account is opted into.
Requires program version 8 or higher.
- 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 totalAssets(acct: Expr) MaybeValue
Get the number of ASAs held by the account (including ASAs the account created).
Requires program version 8 or higher.
- 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 totalAssetsCreated(acct: Expr) MaybeValue
Get the number of existing ASAs created by the account.
Requires program version 8 or higher.
- 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 totalBoxBytes(acct: Expr) MaybeValue
Get the total number of bytes used by the account’s app’s box keys and values.
Requires program version 8 or higher.
- 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 totalBoxes(acct: Expr) MaybeValue
Get the number of existing boxes created by the account’s app.
Requires program version 8 or higher.
- 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 totalExtraAppPages(acct: Expr) MaybeValue
Get the number of extra app code pages used by the account.
Requires program version 8 or higher.
- 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 totalNumByteSlice(acct: Expr) MaybeValue
Get the total number of byte array values allocated by the account in Global and Local States.
Requires program version 8 or higher.
- 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 totalNumUint(acct: Expr) MaybeValue
Get the total number of uint64 values allocated by the account in Global and Local States.
Requires program version 8 or higher.
- 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.
- total_apps_created() MaybeValue
Get the number of existing apps created by the account.
- total_apps_opted_in() MaybeValue
Get the number of apps the account is opted into.
- total_assets() MaybeValue
Get the number of ASAs held by the account (including ASAs the account created).
- total_assets_created() MaybeValue
Get the number of existing ASAs created by the account.
- total_box_bytes() MaybeValue
Get the total number of bytes used by the account’s app’s box keys and values.
- total_boxes() MaybeValue
Get the number of existing boxes created by the account’s app.
- total_extra_app_pages() MaybeValue
Get the number of extra app code pages used by the account.
- total_num_byte_slice() MaybeValue
Get the total number of byte array values allocated by the account in Global and Local States.
- total_num_uint() MaybeValue
Get the total number of uint64 values allocated by the account in Global and Local States.
- 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.
- exception pyteal.AlgodClientError(message: str)
Bases:
Exception
- 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 box_create(name: Expr, size: Expr) Expr
Create a box with a given name and size.
New boxes will contain a byte string of all zeros. Performing this operation on a box that already exists will not change its contents.
If successful, this expression returns 0 if the box already existed, otherwise it returns 1.
A failure will occur if you attempt to create a box that already exists with a different size.
- Parameters
name – The key used to reference this box. Must evaluate to a bytes.
size – The number of bytes to reserve for this box. Must evaluate to a uint64.
- classmethod box_delete(name: Expr) Expr
Deletes a box given it’s name.
This expression returns 1 if the box existed, otherwise it returns 0.
Deleting a nonexistent box is allowed, but has no effect.
- Parameters
name – The key the box was created with. Must evaluate to bytes.
- classmethod box_extract(name: Expr, start: Expr, length: Expr) Expr
Extracts bytes in a box given its name, start index and stop index.
- Parameters
name – The key the box was created with. Must evaluate to bytes.
start – The byte index into the box to start reading. Must evaluate to uint64.
length – The byte length into the box from start to stop reading. Must evaluate to uint64.
- classmethod box_get(name: Expr) MaybeValue
Get the full contents of a box given its name.
- Parameters
name – The key the box was created with. Must evaluate to bytes.
- classmethod box_length(name: Expr) MaybeValue
Get the byte length of the box specified by its name.
- Parameters
name – The key the box was created with. Must evaluate to bytes.
- classmethod box_put(name: Expr, value: Expr) Expr
Write all contents to a box given its name.
- Parameters
name – The key the box was created with. Must evaluate to bytes.
value – The value to write to the box. Must evaluate to bytes.
- classmethod box_replace(name: Expr, start: Expr, value: Expr) Expr
Replaces bytes in a box given its name, start index, and value.
- Parameters
name – The key the box was created with. Must evaluate to bytes.
start – The byte index into the box to start writing. Must evaluate to uint64.
value – The value to start writing at start index. Must evaluate to bytes.
- classmethod box_resize(name: Expr, size: Expr) Expr
Resize an existing box.
If the new size is larger than the old size, zero bytes will be added to the end of the box. If the new size is smaller than the old size, the box will be truncated from the end.
- Parameters
name – The key used to reference this box. Must evaluate to a bytes.
size – The new number of bytes to reserve for this box. Must evaluate to a uint64.
- classmethod box_splice(name: Expr, start: Expr, length: Expr, new_content: Expr) Expr
Replaces the range of bytes from start through start + length with new_content.
Bytes after start + length will be shifted to the right.
Recall that boxes are constant length, and this operation will not change the length of the box. Instead content may be adjusted as so:
If the length of the new content is less than length, the bytes following start + length will be shifted to the left, and the end of the box will be padded with zeros.
If the length of the new content is greater than length, the bytes following start + length will be shifted to the right and bytes exceeding the length of the box will be truncated.
- Parameters
name – The name of the box to modify. Must evaluate to bytes.
start – The byte index into the box to start writing. Must evaluate to uint64.
length – The length of the bytes to be replaced. Must evaluate to uint64.
new_content – The new content to write into the box. Must evaluate to bytes.
- 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.- 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>)
- 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.
- 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.
- 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.
- asdict() dict[str, pyteal.OnCompleteAction]
- aslist() list[pyteal.OnCompleteAction]
- get_method_config() MethodConfig
- is_empty() bool
- 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.
- 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.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 beforeTxn.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 beforeTxn.last_valid()
.
- type_of()
Get the return type of this expression.
- class pyteal.BoxCreate(name: Expr, size: Expr)
Bases:
Expr
Create a box with a given name and size.
- __init__(name: Expr, size: Expr) None
- Parameters
name – The key used to reference this box. Must evaluate to a bytes.
size – The number of bytes to reserve for this box. Must evaluate to a uint64.
- 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.BoxDelete(name: Expr)
Bases:
Expr
Deletes a box given its name.
- __init__(name: Expr) None
- Parameters
name – The key the box was created with. Must evaluate to bytes.
- 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.BoxExtract(name: Expr, start: Expr, length: Expr)
Bases:
Expr
Extracts bytes in a box given its name, start index and stop index.
- __init__(name: Expr, start: Expr, length: Expr) None
- Parameters
name – The key the box was created with. Must evaluate to bytes.
start – The byte index into the box to start reading. Must evaluate to uint64.
length – The byte length into the box from start to stop reading. Must evaluate to uint64.
- has_return()
Check if this expression always returns from the current subroutine or program.
- type_of()
Get the return type of this expression.
- pyteal.BoxGet(name: Expr) MaybeValue
Get the full contents of a box given its name.
- Parameters
name – The key the box was created with. Must evaluate to bytes.
- pyteal.BoxLen(name: Expr) MaybeValue
Get the byte length of the box specified by its name.
- Parameters
name – The key the box was created with. Must evaluate to bytes.
- class pyteal.BoxPut(name: Expr, value: Expr)
Bases:
Expr
Write all contents to a box given its name.
- __init__(name: Expr, value: Expr) None
- Parameters
name – The key the box was created with. Must evaluate to bytes.
value – The value to write to the box. Must evaluate to bytes.
- 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.BoxReplace(name: Expr, start: Expr, value: Expr)
Bases:
Expr
Replaces bytes in a box given its name, start index, and value.
Also see BoxSplice.
- __init__(name: Expr, start: Expr, value: Expr) None
- Parameters
name – The key the box was created with. Must evaluate to bytes.
start – The byte index into the box to start writing. Must evaluate to uint64.
value – The value to start writing at start index. Must evaluate to bytes.
- 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.BoxResize(name: Expr, size: Expr)
Bases:
Expr
Resize an existing box.
If the new size is larger than the old size, zero bytes will be added to the end of the box. If the new size is smaller than the old size, the box will be truncated from the end.
- __init__(name: Expr, size: Expr) None
- Parameters
name – The key used to reference this box. Must evaluate to a bytes.
size – The new number of bytes to reserve for this box. Must evaluate to a uint64.
- 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.BoxSplice(name: Expr, start: Expr, length: Expr, new_content: Expr)
Bases:
Expr
Splice content into a box.
- __init__(name: Expr, start: Expr, length: Expr, new_content: Expr) None
Replaces the range of bytes from start through start + length with new_content.
Bytes after start + length will be shifted to the right.
Recall that boxes are constant length, and this operation will not change the length of the box. Instead content may be adjusted as so:
If the length of the new content is less than length, the bytes following start + length will be shifted to the left, and the end of the box will be padded with zeros.
If the length of the new content is greater than length, the bytes following start + length will be shifted to the right and bytes exceeding the length of the box will be truncated.
- Parameters
name – The name of the box to modify. Must evaluate to bytes.
start – The byte index into the box to start writing. Must evaluate to uint64.
length – The length of the bytes to be replaced. Must evaluate to uint64.
new_content – The new content to write into the box. Must evaluate to bytes.
- 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.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.
- 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
- 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.Compilation(ast: Expr, mode: Mode, *, version: int = 2, assemble_constants: bool = False, assembly_type_track: bool = True, optimize: Optional[OptimizeOptions] = None)
Bases:
object
A class that encapsulates the data needed to compile a PyTeal expression
- __init__(ast: Expr, mode: Mode, *, version: int = 2, assemble_constants: bool = False, assembly_type_track: bool = True, optimize: Optional[OptimizeOptions] = None)
Instantiate a Compilation object providing the necessary data to compile a PyTeal expression.
- Parameters
ast – The PyTeal expression to assemble
mode – The program’s mode for execution. Either
Mode.Signature
orMode.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.
assembly_type_track (optional) – When True, the compiler will produce a program with type checking at assembly time (default behavior). When False, the compiler will turn off type checking at assembly time. This is only useful if PyTeal is producing incorrect TEAL code, or the assembler is producing incorrect type errors. Defaults to True.
optimize (optional) – OptimizeOptions that determine which optimizations will be applied.
- compile(*, with_sourcemap: bool = False, teal_filename: Optional[str] = None, pcs_in_sourcemap: bool = False, algod_client: Optional[AlgodClient] = None, annotate_teal: bool = False, annotate_teal_headers: bool = False, annotate_teal_concise: bool = False) CompileResults
Compile the PyTeal
ast
to produce a TEAL program and other artifacts.- Parameters
with_sourcemap (optional) – When True, the compiler will produce a source map that associates each line of the generated TEAL program back to the original PyTeal source code. Defaults to False.
teal_filename (optional) – The filename to use in the sourcemap. Defaults to None.
pcs_in_sourcemap (optional) – When True, the compiler will include the program counter in relevant sourcemap artifacts. This requires an AlgodClient (see next param). Defaults to False.
algod_client (optional) – An AlgodClient to use to fetch program counters. Defaults to None. When pcs_in_sourcemap is True and algod_client is not provided, the compiler will assume that an Algorand Sandbox algod client is running on the default port (4001) and -if this is not the case- will raise an exception.
annotate_teal (optional) – When True, the compiler will produce a TEAL program with comments that describe the PyTeal source code that generated each line of the program. Defaults to False.
annotate_teal_headers (optional) – When True along with annotate_teal being True, a header line with column names will be added at the top of the annotated teal. Defaults to False.
annotate_teal_concise (optional) – When True along with annotate_teal being True, the compiler will provide fewer columns in the annotated teal. Defaults to False.
- Returns
teal: the TEAL program
- sourcemap (optional): if with_sourcemap is True, the following source map data is provided:
teal_filename (optional): the TEAL filename, if this was provided
r3_sourcemap: an R3SourceMap object that maps the generated TEAL program back to the original PyTeal source code and conforms to the specs of the Source Map Revision 3 Proposal
pc_sourcemap (optional): if pcs_in_sourcemap is True, a PCSourceMap object that maps the program counters assembled by the AlgodClient which was utilized in the compilation back to the TEAL program which was generated by the compiler. This conforms to the specs of the Source Map Revision 3 Proposal
annotated_teal (optional): if annotate_teal is True, the TEAL program with comments that describe the PyTeal source code that generated each line of the program
- Return type
A CompileResults object with the following data
- Raises
TealInputError – if an operation in ast is not supported by the supplied mode and version.
TealInternalError – if an internal error is encountered during compilation.
- 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
- class pyteal.CompileResults(teal: str, sourcemap: Optional[PyTealSourceMap] = None)
Bases:
object
Summary of compilation
- sourcemap: pyteal.PyTealSourceMap | None = None
- teal: str
- 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.
- 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.
- pyteal.EcAdd(curve: EllipticCurve, a: Expr, b: Expr) Expr
Add two points on the given elliptic curve.
- Parameters
curve – The elliptic curve to use.
a – The first point to add. Must evaluate to bytes.
b – The second point to add. Must evaluate to bytes.
- Returns
An expression which evaluates to the sum of the two points on the given curve.
- pyteal.EcMapTo(curve: EllipticCurve, a: Expr) Expr
Map field element a to group curve.
- Parameters
curve – The elliptic curve to use.
a – The field element to map. Must evaluate to bytes.
- Returns
An expression that evaluates to the mapped point.
- pyteal.EcMultiScalarMul(curve: EllipticCurve, a: Expr, b: Expr) Expr
Multiply a point on the given elliptic curve by a series of scalars.
- Parameters
curve – The elliptic curve to use.
a – The point to multiply. Must evaluate to bytes.
b – A list of concatenated, big-endian, 32-byte scalar integers to multiply by.
- Returns
An expression that evaluates to curve point
b_0a_0 + b_1a_1 + b_2a_2 + ... + b_Na_N
.
- pyteal.EcPairingCheck(curve: EllipticCurve, a: Expr, b: Expr) Expr
Check the pairing of two points on the given elliptic curve.
- Parameters
curve – The elliptic curve to use.
a – The first point to check. Must evaluate to bytes.
b – The second point to check. Must evaluate to bytes.
- Returns
An expression which evaluates to 1 if the product of the pairing of each point in a with its respective point in b is equal to the identity element of the target group. Otherwise, evaluates to 0.
- pyteal.EcScalarMul(curve: EllipticCurve, point: Expr, scalar: Expr) Expr
Multiply a point on the given elliptic curve by a scalar.
- Parameters
curve – The elliptic curve to use.
point – The point to multiply. Must evaluate to bytes.
scalar – The scalar to multiply by, encoded as a big-endian unsigned integer. Must evaluate to bytes. Fails if this value exceeds 32 bytes.
- Returns
An expression which evaluates to the product of the point and scalar on the given curve.
- pyteal.EcSubgroupCheck(curve: EllipticCurve, a: Expr) Expr
Check if a point is in the main prime-order subgroup of the given elliptic curve.
- Parameters
curve – The elliptic curve to use.
a – The point to check. Must evaluate to bytes.
- Returns
An expression that evaluates to 1 if the point is in the main prime-order subgroup of the curve (including the point at infinity) else 0. Program fails if the point is not in the curve at all.
- 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.EllipticCurve(value)
Bases:
Enum
An enumeration.
- BLS12_381g1 = (2, 'BLS12_381g1', 10)
- BLS12_381g2 = (3, 'BLS12_381g2', 10)
- BN254g1 = (0, 'BN254g1', 10)
- BN254g2 = (1, 'BN254g2', 10)
- 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.
- 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 includingstart + length
.This expression is similar to
Substring
, except this expression uses a start index and length, whileSubstring
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 includingoffset + 2
will be interpreted as a big-endian unsigned integer.If
offset + 2
exceedsLen(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 includingoffset + 4
will be interpreted as a big-endian unsigned integer.If
offset + 4
exceedsLen(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 includingoffset + 8
will be interpreted as a big-endian unsigned integer.If
offset + 8
exceedsLen(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.
- __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 asset_create_min_balance() Global
Get the additional minimum balance required to create (and opt-into) an asset.
Requires program version 10 or higher.
- classmethod asset_opt_in_min_balance() Global
Get the additional minimum balance required to opt-into an asset.
Requires program version 10 or higher.
- 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 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 genesis_hash() Global
Get the genesis hash for the network.
Requires program version 10 or higher.
- 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 opcode_budget() Global
Get the remaining opcode execution budget
Requires program version 6 or higher.
- type_of()
Get the return type of this expression.
- class pyteal.GlobalField(value)
Bases:
Enum
An enumeration.
- asset_create_min_balance = (15, 'AssetCreateMinBalance', <TealType.uint64: 0>, 10)
- asset_opt_in_min_balance = (16, 'AssetOptInMinBalance', <TealType.uint64: 0>, 10)
- 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)
- genesis_hash = (17, 'GenesisHash', <TealType.bytes: 1>, 10)
- 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)
- 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.
- ElseIf(cond)
- __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
, andTxnType.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 accountMinTxnFee
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: pyteal.Expr | None, 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. If the call is meant to create an application, the value None should be passed
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: pyteal.Expr | None, 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. If the call is meant to create an application, the value None should be passed
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 accountMinTxnFee
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
andInnerTxnBuilder.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 theInnerTxn
object. If the inner transaction creates an asset, the new asset ID can be found by looking atInnerTxn.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.
- 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.
- 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.
- 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.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, compile_check: Optional[Callable[[CompileOptions], None]] = 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, compile_check: Optional[Callable[[CompileOptions], None]] = 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.
compile_check (optional) – Callable compile check. Defaults to program version check. This parameter overwrites the default program version check.
- 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 compatibility 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 compatibility 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
- 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
- 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.Optional[~typing.List[~typing.Union[int, str]]] = None, args: ~typing.Optional[~typing.List[~pyteal.Expr]] = None, compile_check: ~typing.Callable[[CompileOptions], None] = <function MultiValue.<lambda>>, root_expr: pyteal.Expr | None = None)
Bases:
LeafExpr
Represents an operation that returns more than one value
- __init__(op: ~pyteal.Op, types: ~typing.List[~pyteal.TealType], *, immediate_args: ~typing.Optional[~typing.List[~typing.Union[int, str]]] = None, args: ~typing.Optional[~typing.List[~pyteal.Expr]] = None, compile_check: ~typing.Callable[[CompileOptions], None] = <function MultiValue.<lambda>>, root_expr: pyteal.Expr | None = None)
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.
- 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: pyteal.Expr | pyteal.SubroutineFnWrapper | pyteal.ABIReturnSubroutine | None = 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)
- box_create = OpType(value='box_create', mode=<Mode.Application: 2>, min_version=8)
- box_del = OpType(value='box_del', mode=<Mode.Application: 2>, min_version=8)
- box_extract = OpType(value='box_extract', mode=<Mode.Application: 2>, min_version=8)
- box_get = OpType(value='box_get', mode=<Mode.Application: 2>, min_version=8)
- box_len = OpType(value='box_len', mode=<Mode.Application: 2>, min_version=8)
- box_put = OpType(value='box_put', mode=<Mode.Application: 2>, min_version=8)
- box_replace = OpType(value='box_replace', mode=<Mode.Application: 2>, min_version=8)
- box_resize = OpType(value='box_resize', mode=<Mode.Application: 2>, min_version=10)
- box_splice = OpType(value='box_splice', mode=<Mode.Application: 2>, min_version=10)
- bsqrt = OpType(value='bsqrt', mode=<Mode.Application|Signature: 3>, min_version=6)
- btoi = OpType(value='btoi', mode=<Mode.Application|Signature: 3>, min_version=2)
- bury = OpType(value='bury', mode=<Mode.Application|Signature: 3>, min_version=8)
- 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)
- dupn = OpType(value='dupn', mode=<Mode.Application|Signature: 3>, min_version=8)
- ec_add = OpType(value='ec_add', mode=<Mode.Application|Signature: 3>, min_version=10)
- ec_map_to = OpType(value='ec_map_to', mode=<Mode.Application|Signature: 3>, min_version=10)
- ec_multi_scalar_mul = OpType(value='ec_multi_scalar_mul', mode=<Mode.Application|Signature: 3>, min_version=10)
- ec_pairing_check = OpType(value='ec_pairing_check', mode=<Mode.Application|Signature: 3>, min_version=10)
- ec_scalar_mul = OpType(value='ec_scalar_mul', mode=<Mode.Application|Signature: 3>, min_version=10)
- ec_subgroup_check = OpType(value='ec_subgroup_check', mode=<Mode.Application|Signature: 3>, min_version=10)
- 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)
- frame_bury = OpType(value='frame_bury', mode=<Mode.Application|Signature: 3>, min_version=8)
- frame_dig = OpType(value='frame_dig', mode=<Mode.Application|Signature: 3>, min_version=8)
- 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)
- 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)
- popn = OpType(value='popn', mode=<Mode.Application|Signature: 3>, min_version=8)
- proto = OpType(value='proto', mode=<Mode.Application|Signature: 3>, min_version=8)
- 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, fee_source: OpUpFeeSource = OpUpFeeSource.Any) Expr
Ensure that the budget will be at least the required_budget.
- Parameters
required_budget – minimum op-code budget to ensure for the upcoming execution.
fee_source (optional) – source that should be used for covering fees on the inner transactions that are generated.
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, fee_source: OpUpFeeSource = OpUpFeeSource.Any) Expr
Maximize the available opcode budget without spending more than the given fee.
- Parameters
fee – fee expenditure cap for the op-code budget maximization.
fee_source (optional) – source that should be used for covering fees on the inner transactions that are generated.
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.OpUpFeeSource(value)
Bases:
Enum
An Enum object that defines the source for fees for the OpUp utility.
- Any = 2
First the excess will be used, remaining fees will be taken from the app account
- AppAccount = 1
The app’s account will cover all fees (set inner_tx.fee=Global.min_tx_fee())
- GroupCredit = 0
Only the excess fee (credit) on the outer group should be used (set inner_tx.fee=0)
- 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
The app to call must be provided by the user.
- OnCall = 1
The app to call is created then deleted for each request to increase budget.
- class pyteal.OptimizeOptions(*, scratch_slots: Optional[bool] = None, frame_pointers: Optional[bool] = None)
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. Starting with program version 9, defaults to optimizing.
frame_pointers (optional) – employ frame pointers instead of scratch slots during compilation. Available only starting in program version 8. Defaults to optimizing starting in program version 8.
- optimize_scratch_slots(version: int) bool
- use_frame_pointers(version: int) bool
- 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.
- 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.
- class pyteal.PyTealSourceMap(teal_filename: str | None, r3_sourcemap: pyteal.R3SourceMap | None, pc_sourcemap: algosdk.source_map.SourceMap | None, annotated_teal: str | None)
Bases:
object
Encapsulate Expr-less source mapping data.
- Fields:
teal_filename
- The filename of the TEAL source file, orNone
if not provided.r3_sourcemap
- TheR3SourceMap
object, orNone
if not provided.pc_sourcemap
- ThePCSourceMap
object (akafor algosdk.source_map.SourceMap
), orNone
if not provided.annotated_teal
- The annotated TEAL code as a string, orNone
if not provided.
NOTE: type
PCSourceMap
is an alias for algosdk.source_map.SourceMap- annotated_teal: str | None
- pc_sourcemap: algosdk.source_map.SourceMap | None
- r3_sourcemap: pyteal.R3SourceMap | None
- teal_filename: str | None
- class pyteal.R3SourceMap(filename: str | None, source_root: str | None, entries: ~typing.Mapping[tuple[int, int], ~pyteal.compiler.sourcemap.R3SourceMapping], index: list[tuple[int, ...]] = <factory>, file_lines: ~typing.Optional[list[str]] = None, source_files: ~typing.Optional[list[str]] = None, source_files_lines: ~typing.Optional[list[list[str] | None]] = None)
Bases:
object
This class is renames mjpieters’ SourceMap. and tweaks it a bit, adding the following functionality:
adds fields
file_lines
,source_files
,entries
__post_init__
(new) - runs a sanity check validation on the ordering of provided entries__repr__
- printing outR3SourceMap(...)
instead ofMJPSourceMap(...)
from_json
- accepting new paramssources_override
,sources_content_override
,target
,add_right_bounds
add_right_bounds
(new) - allow specifying the right column boundsto_json
- accepting new paramwith_contents
The main methods for this class are
from_json
andto_json
which follow the encoding conventions outlined in the Source Map Revison 3 Proposal.- __getitem__(idx: int | tuple[int, int])
- add_right_bounds() None
- entries: Mapping[tuple[int, int], R3SourceMapping]
- file_lines: list[str] | None = None
- filename: str | None
- classmethod from_json(smap: R3SourceMapJSON, sources_override: Optional[list[str]] = None, sources_content_override: list[str] = [], target: Optional[str] = None, add_right_bounds: bool = True) R3SourceMap
Construct an
R3SourceMap
from anR3SourceMapJSON
(aTypedDict
) object.- Parameters
smap – The
R3SourceMapJSON
object to construct from.sources_override – A list of source files to use instead of the ones in the
R3SourceMapJSON
. STRICTLY SPEAKINGsources
OUGHT NOT BE MISSING OR EMPTY inR3SourceMapJSON
. However, currently thePOST v2/teal/compile
endpoint populates this field with an empty list, as it is not provided the name of the Teal file which is being compiled. In order comply with the R3 spec, this field is populated with["unknown"]
when either missing or empty in the JSON and not supplied during construction.sources_content_override –
sourcesContent
is optional and this provides a way at runtime to supply the actual source. When provided, and theR3SourceMapJSON
is either missing or empty, this will be substituted. An error will be raised when attempting to replace a nonemptyR3SourceMapJSON.sourcesContent
.target – The target source code. This is used to populate the
target_extract
field of theR3SourceMapping
.add_right_bounds – Whether to add the right column bounds to the
R3SourceMapping
.
- index: list[tuple[int, ...]]
- source_files: list[str] | None = None
- source_files_lines: list[list[str] | None] | None = None
- source_root: str | None
- to_json(with_contents: bool = False) R3SourceMapJSON
- 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, *, clear_state: Optional[Union[Expr, SubroutineFnWrapper, ABIReturnSubroutine]] = 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, *, clear_state: Optional[Union[Expr, SubroutineFnWrapper, ABIReturnSubroutine]] = 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.
clear_state – an expression describing the behavior of clear state program. This expression will be the entirety of the clear state program; no additional code is inserted by the Router. If not provided, the clear state program will always reject.
- 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.
- compile(*, version: int = 2, assemble_constants: bool = False, optimize: Optional[OptimizeOptions] = None, approval_filename: Optional[str] = None, clear_filename: Optional[str] = None, with_sourcemaps: bool = False, pcs_in_sourcemap: bool = False, algod_client: Optional[AlgodClient] = None, annotate_teal: bool = False, annotate_teal_headers: bool = False, annotate_teal_concise: bool = True) RouterResults
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 Compilation.compile.
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.
- Parameters
version (optional) – The TEAL version to compile to. Defaults to DEFAULT_TEAL_VERSION.
assemble_constants (optional) – When True, the compiler will assemble constants to intc and bytec blocks. Defaults to False.
optimize (optional) – An OptimizeOptions object to use to provide optimization information to the compiler.
approval_filename (optional) – The filename to use in the sourcemap for the approval program. If not provided, the router will use the Router object’s name field with suffix “_approval.teal”.
clear_filename (optional) – The filename to use in the sourcemap for the clear program. If not provided, the router will use the Router object’s name field with suffix “_clear.teal”.
with_sourcemaps (optional) – When True, the compiler will produce source maps that map the generated approval and clear TEAL program back to the original PyTeal source code. Defaults to False.
pcs_in_sourcemap (optional) – When True, the compiler will include the program counter in relevant sourcemap artifacts. This requires an AlgodClient (see next param). Defaults to False.
algod_client (optional) – An AlgodClient to use to fetch program counters. Defaults to None. When pcs_in_sourcemap is True and algod_client is not provided, the compiler will assume that an Algorand Sandbox algod client is running on the default port (4001) and -if this is not the case- will raise an exception.
annotate_teal (optional) – When True, the compiler will produce a TEAL program with comments that describe the PyTeal source code that generated each line of the program. Defaults to False.
annotate_teal_headers (optional) – When True along with annotate_teal being True, a header line with column names will be added at the top of the annotated teal. Defaults to False.
annotate_teal_concise (optional) – When True along with annotate_teal being True, the compiler will provide fewer columns in the annotated teal. Defaults to True.
- Returns
approval_teal (str): compiled approval program
clear_teal (str): compiled clear-state program
abi_contract (abi.Contract): a Python SDK Contract object to allow clients to make off-chain calls
approval_sourcemap (PyTealSourceMap | None): source map results for approval program
clear_sourcemap (PyTealSourceMap | None): source map results for clear-state program
- Return type
A RouterResults containing the following
- 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 Compilation.compile.
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
NOTE: For generating a source map, please refer to the Router.compile method.
- 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
. This argument has been deprecated, and will error on compile time if one wants to access it. Use Router top level argument clear_state instead.update_application (optional) – The allowed calls during
OnComplete.UpdateApplication
.delete_application (optional) – The allowed calls during
OnComplete.DeleteApplication
.
- class pyteal.RouterResults(approval_teal: str, clear_teal: str, abi_contract: algosdk.abi.contract.Contract, approval_sourcemap: Optional[pyteal.PyTealSourceMap] = None, clear_sourcemap: Optional[pyteal.PyTealSourceMap] = None)
Bases:
object
- abi_contract: Contract
- approval_sourcemap: Optional[PyTealSourceMap] = None
- approval_teal: str
- clear_sourcemap: Optional[PyTealSourceMap] = None
- clear_teal: str
- 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: int = 256
- classmethod reset_slot_numbering(start_index: int = 256) None
- 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: pyteal.ScratchSlot | None, value: Expr, index_expression: Optional[Expr] = None)
Bases:
Expr
Expression to store a value in scratch space.
- __init__(slot: pyteal.ScratchSlot | None, 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:
AbstractVar
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).
- load() ScratchLoad
Load value from Scratch Space
- 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.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.
- exception pyteal.SourceMapDisabledError
Bases:
RuntimeError
- msg = '\n Cannot calculate Teal to PyTeal source map because stack frame discovery is turned off.\n\n To enable source maps: import `from feature_gates import FeatureGates` and call `FeatureGates.set_sourcemap_enabled(True)`.\n '
- value = '\n Cannot calculate Teal to PyTeal source map because stack frame discovery is turned off.\n\n To enable source maps: import `from feature_gates import FeatureGates` and call `FeatureGates.set_sourcemap_enabled(True)`.\n '
- 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(), ])
- 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
- get_declaration_by_option(fp_option: bool = True) 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 includingend
.This expression is similar to
Extract
, except this expression uses start and end indexes, whileExtract
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
andExtract
, 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], root_expr: Expr | None = None)
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.
- 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: Optional[Set[ScratchSlot]] = None, visited: Optional[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.
- class pyteal.TealComponent(expr: Expr | None)
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
- stack_frames() NatalStackFrame
- class pyteal.TealConditionalBlock(ops: List[TealOp], root_expr: Expr | None = None)
Bases:
TealBlock
Represents a basic block of TealComponents in a graph ending with a branch condition.
- replaceOutgoing(oldBlock: TealBlock, newBlock: TealBlock) None
Replace one of this block’s child blocks.
- exception pyteal.TealInputError(msg: str)
Bases:
Exception
- exception pyteal.TealInternalError(message: str)
Bases:
Exception
- class pyteal.TealLabel(expr: Expr | None, label: LabelReference, comment: str | None = 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
- getSlots() List[ScratchSlot]
- getSubroutines() List[SubroutineDefinition]
- resolveSubroutine(subroutine: SubroutineDefinition, label: str) None
- class pyteal.TealPragma(version: Optional[int] = None, *, type_track: Optional[bool] = None)
Bases:
TealComponent
- __init__(version: Optional[int] = None, *, type_track: Optional[bool] = None)
Creates an assembler pragma statement.
Only one of the arguments should be set.
- Parameters
version (optional) – Sets the program version.
type_track (optional) – Configures assembler type tracking.
- assemble() str
- exception pyteal.TealPragmaError(message: str)
Bases:
Exception
- exception pyteal.TealSeqError(message: str)
Bases:
TealTypeError
- class pyteal.TealSimpleBlock(ops: list[pyteal.TealOp])
Bases:
TealBlock
Represents a basic block of TealComponents in a graph that does not contain a branch condition.
- getOutgoing() list[pyteal.TealBlock]
Get this block’s children blocks, if any.
- 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, kind: TmplKind)
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.
- classmethod clear_session_templates()
Clear all session templates.
- classmethod session_templates() list[str]
- type_of()
Get the return type of this expression.
- classmethod zero(placeholder) str
Return a zero value for the given template placeholder.
- class pyteal.TxnArray(txnObject: TxnObject, accessField: TxnField, lengthField: TxnField)
Bases:
Array
Represents a transaction array field.
- 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)
- 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.
- class pyteal.TxnObject(makeTxnExpr: Callable[[TxnField], TxnExpr], makeTxnaExpr: Callable[[TxnField, Union[int, Expr]], TxnaExpr])
Bases:
object
Represents a transaction and its fields.
- amount() TxnExpr
Get the amount of the transaction in micro Algos.
Only set when
type_enum()
isTxnType.Payment
.For more information, see https://developer.algorand.org/docs/reference/transactions/#amount
- application_id() TxnExpr
Get the application ID from the ApplicationCall portion of the current transaction.
Only set when
type_enum()
isTxnType.ApplicationCall
.
- property applications: TxnArray
The applications array in an ApplicationCall transaction.
- Type
Requires program version 3 or higher.
- approval_program() TxnExpr
Get the approval program.
Only set when
type_enum()
isTxnType.ApplicationCall
.
- property approval_program_pages: TxnArray
The approval program pages.
- Type
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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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
Requires program version 3 or higher.
- clear_state_program() TxnExpr
Get the clear state program.
Only set when
type_enum()
isTxnType.ApplicationCall
.
- property clear_state_program_pages: TxnArray
The clear state program pages.
- Type
Requires program version 7 or higher.
- close_remainder_to() TxnExpr
Get the 32 byte address of the CloseRemainderTo field.
Only set when
type_enum()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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
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()
isTxnType.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()
isTxnType.ApplicationCall
.
- receiver() TxnExpr
Get the 32 byte address of the receiver.
Only set when
type_enum()
isTxnType.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()
isTxnType.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.
- 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
- vote_first() TxnExpr
Get the first round that the participation key is valid.
Only set when
type_enum()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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()
isTxnType.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.
- classmethod chainlink(message: Expr, proof: Expr, public_key: Expr) VrfVerify
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.
- __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 eachN_i
represents an element innumeratorFactors
and eachD_i
represents an element indenominatorFactors
.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, assembly_type_track: bool = True, 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.
assembly_type_track (optional) – When True, the compiler will produce a program with type checking at assembly time (default behavior). When False, the compiler will turn off type checking at assembly time. This is only useful if PyTeal is producing incorrect TEAL code, or the assembler is producing incorrect type errors. Defaults to True.
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 encountered 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
- 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(