Appendix A - Opcodes Specifications - Algorand Specifications

Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Algorand Specifications

Print this bookGit repositorySuggest an edit

Opcodes have a cost of 1 unless otherwise specified.

The 32 byte public key is the last element on the stack, preceded by the 64 byte signature at the second-to-last element on the stack, preceded by the data which was signed at the third-to-last element on the stack.

INDEX NAME IN NOTES
0 Secp256k1 secp256k1 curve, used in Bitcoin
1 Secp256r1 v7 secp256r1 curve, NIST standard

The 32 byte Y-component of a public key is the last element on the stack, preceded by X-component of a pubkey, preceded by S and R components of a signature, preceded by the data that is fifth element on the stack. All values are big-endian encoded. The signed data must be 32 bytes long, and signatures in lower-S form are only accepted.

The 33 byte public key in a compressed form to be decompressed into X and Y (top) components. All values are big-endian encoded.

S (top) and R elements of a signature, recovery id and data (bottom) are expected on the stack and used to deriver a public key. All values are big-endian encoded. The signed data must be 32 bytes long.

Overflow is an error condition which halts execution and fails the transaction. Full precision is available from addw.

divmodw is available to divide the two-element values produced by mulw and addw.

Overflow is an error condition which halts execution and fails the transaction. Full precision is available from mulw.

btoi fails if the input is longer than 8 bytes.

The notation J,K indicates that two uint64 values J and K are interpreted as a uint128 value, with J as the high uint64 and K the low.

intcblock loads following program bytes into an array of integer constants in the evaluator. These integer constants can be referred to by intc and intc_* which will push the value onto the stack. Subsequent calls to intcblock reset and replace the integer constants available to the script.

bytecblock loads the following program bytes into an array of byte-array constants in the evaluator. These constants can be referred to by bytec and bytec_* which will push the value onto the stack. Subsequent calls to bytecblock reset and replace the bytes constants available to the script.

Fields (see transaction reference)

INDEX NAME TYPE IN NOTES
0 Sender address 32 byte address
1 Fee uint64 microalgos
2 FirstValid uint64 round number
3 FirstValidTime uint64 v7 UNIX timestamp of block before txn.FirstValid. Fails if negative
4 LastValid uint64 round number
5 Note []byte Any data up to 1024 bytes
6 Lease [32]byte 32 byte lease value
7 Receiver address 32 byte address
8 Amount uint64 microalgos
9 CloseRemainderTo address 32 byte address
10 VotePK [32]byte 32 byte address
11 SelectionPK [32]byte 32 byte address
12 VoteFirst uint64 The first round that the participation key is valid.
13 VoteLast uint64 The last round that the participation key is valid.
14 VoteKeyDilution uint64 Dilution for the 2-level participation key
15 Type []byte Transaction type as bytes
16 TypeEnum uint64 Transaction type as integer
17 XferAsset uint64 Asset ID
18 AssetAmount uint64 value in Asset’s units
19 AssetSender address 32 byte address. Source of assets if Sender is the Asset’s Clawback address.
20 AssetReceiver address 32 byte address
21 AssetCloseTo address 32 byte address
22 GroupIndex uint64 Position of this transaction within an atomic transaction group. A stand-alone transaction is implicitly element 0 in a group of 1
23 TxID [32]byte The computed ID for this transaction. 32 bytes.
24 ApplicationID uint64 v2 ApplicationID from ApplicationCall transaction
25 OnCompletion uint64 v2 ApplicationCall transaction on completion action
27 NumAppArgs uint64 v2 Number of ApplicationArgs
29 NumAccounts uint64 v2 Number of Accounts
30 ApprovalProgram []byte v2 Approval program
31 ClearStateProgram []byte v2 Clear state program
32 RekeyTo address v2 32 byte Sender’s new AuthAddr
33 ConfigAsset uint64 v2 Asset ID in asset config transaction
34 ConfigAssetTotal uint64 v2 Total number of units of this asset created
35 ConfigAssetDecimals uint64 v2 Number of digits to display after the decimal place when displaying the asset
36 ConfigAssetDefaultFrozen bool v2 Whether the asset’s slots are frozen by default or not, 0 or 1
37 ConfigAssetUnitName []byte v2 Unit name of the asset
38 ConfigAssetName []byte v2 The asset name
39 ConfigAssetURL []byte v2 URL
40 ConfigAssetMetadataHash [32]byte v2 32 byte commitment to unspecified asset metadata
41 ConfigAssetManager address v2 32 byte address
42 ConfigAssetReserve address v2 32 byte address
43 ConfigAssetFreeze address v2 32 byte address
44 ConfigAssetClawback address v2 32 byte address
45 FreezeAsset uint64 v2 Asset ID being frozen or un-frozen
46 FreezeAssetAccount address v2 32 byte address of the account whose asset slot is being frozen or un-frozen
47 FreezeAssetFrozen bool v2 The new frozen value, 0 or 1
49 NumAssets uint64 v3 Number of Assets
51 NumApplications uint64 v3 Number of Applications
52 GlobalNumUint uint64 v3 Number of global state integers in ApplicationCall
53 GlobalNumByteSlice uint64 v3 Number of global state byteslices in ApplicationCall
54 LocalNumUint uint64 v3 Number of local state integers in ApplicationCall
55 LocalNumByteSlice uint64 v3 Number of local state byteslices in ApplicationCall
56 ExtraProgramPages uint64 v4 Number of additional pages for each of the application’s approval and clear state programs. An ExtraProgramPages of 1 means 2048 more total bytes, or 1024 for each program.
57 Nonparticipation bool v5 Marks an account nonparticipating for rewards
59 NumLogs uint64 v5 Number of Logs (only with itxn in v5). Application mode only
60 CreatedAssetID uint64 v5 Asset ID allocated by the creation of an ASA (only with itxn in v5). Application mode only
61 CreatedApplicationID uint64 v5 ApplicationID allocated by the creation of an application (only with itxn in v5). Application mode only
62 LastLog []byte v6 The last message emitted. Empty bytes if none were emitted. Application mode only
63 StateProofPK [64]byte v6 State proof public key
65 NumApprovalProgramPages uint64 v7 Number of Approval Program pages
67 NumClearStateProgramPages uint64 v7 Number of ClearState Program pages
68 RejectVersion uint64 v12 Application version for which the txn must reject
INDEX NAME TYPE IN NOTES
0 MinTxnFee uint64 microalgos
1 MinBalance uint64 microalgos
2 MaxTxnLife uint64 rounds
3 ZeroAddress address 32 byte address of all zero bytes
4 GroupSize uint64 Number of transactions in this atomic transaction group. At least 1
5 LogicSigVersion uint64 v2 Maximum supported version
6 Round uint64 v2 Current round number. Application mode only.
7 LatestTimestamp uint64 v2 Last confirmed block UNIX timestamp. Fails if negative. Application mode only.
8 CurrentApplicationID uint64 v2 ID of current application executing. Application mode only.
9 CreatorAddress address v3 Address of the creator of the current application. Application mode only.
10 CurrentApplicationAddress address v5 Address that the current application controls. Application mode only.
11 GroupID [32]byte v5 ID of the transaction group. 32 zero bytes if the transaction is not part of a group.
12 OpcodeBudget uint64 v6 The remaining cost that can be spent by opcodes in this program.
13 CallerApplicationID uint64 v6 The application ID of the application that called this application. 0 if this application is at the top-level. Application mode only.
14 CallerApplicationAddress address v6 The application address of the application that called this application. ZeroAddress if this application is at the top-level. Application mode only.
15 AssetCreateMinBalance uint64 v10 The additional minimum balance required to create (and opt-in to) an asset.
16 AssetOptInMinBalance uint64 v10 The additional minimum balance required to opt-in to an asset.
17 GenesisHash [32]byte v10 The Genesis Hash for the network.
18 PayoutsEnabled bool v11 Whether block proposal payouts are enabled.
19 PayoutsGoOnlineFee uint64 v11 The fee required in a keyreg transaction to make an account incentive eligible.
20 PayoutsPercent uint64 v11 The percentage of transaction fees in a block that can be paid to the block proposer.
21 PayoutsMinBalance uint64 v11 The minimum balance an account must have in the agreement round to receive block payouts in the proposal round.
22 PayoutsMaxBalance uint64 v11 The maximum balance an account can have in the agreement round to receive block payouts in the proposal round.

for notes on transaction fields available, see txn. If this transaction is i in the group, gtxn i field is equivalent to txn field.

Fields (see transaction reference)

INDEX NAME TYPE IN NOTES
26 ApplicationArgs []byte v2 Arguments passed to the application in the ApplicationCall transaction
28 Accounts address v2 Accounts listed in the ApplicationCall transaction
48 Assets uint64 v3 Foreign Assets listed in the ApplicationCall transaction
50 Applications uint64 v3 Foreign Apps listed in the ApplicationCall transaction
58 Logs []byte v5 Log messages emitted by an application call (only with itxn in v5). Application mode only
64 ApprovalProgramPages []byte v7 Approval Program as an array of pages
66 ClearStateProgramPages []byte v7 ClearState Program as an array of pages

for notes on transaction fields available, see txn. If top of stack is i, gtxns field is equivalent to gtxn _i_ field. gtxns exists so that i can be calculated, often based on the index of the current transaction.

gload fails unless the requested transaction is an ApplicationCall and T < GroupIndex.

gloads fails unless the requested transaction is an ApplicationCall and A < GroupIndex.

gaid fails unless the requested transaction created an asset or application and T < GroupIndex.

gaids fails unless the requested transaction created an asset or application and A < GroupIndex.

The bnz instruction opcode 0x40 is followed by two immediate data bytes which are a high byte first and low byte second which together form a 16 bit offset which the instruction may branch to. For a bnz instruction at pc, if the last element of the stack is not zero then branch to instruction at pc + 3 + N, else proceed to next instruction at pc + 3. Branch targets must be aligned instructions. (e.g. Branching to the second byte of a 2 byte op will be rejected.) Starting at v4, the offset is treated as a signed 16 bit integer allowing for backward branches and looping. In prior version (v1 to v3), branch offsets are limited to forward branches only, 0-0x7fff.

At v2 it became allowed to branch to the end of the program exactly after the last instruction: bnz to byte N (with 0-indexing) was illegal for a TEAL program with N bytes before v2, and is legal after it. This change eliminates the need for a last instruction of no-op as a branch target at the end. (Branching beyond the end–in other words, to a byte larger than N–is still illegal and will cause the program to fail.)

See bnz for details on how branches work. bz inverts the behavior of bnz.

See bnz for details on how branches work. b always jumps to the offset.

concat fails if the result would be greater than 4096 bytes.

see explanation of bit ordering in setbit

When A is a uint64, index 0 is the least significant bit. Setting bit 3 to 1 on the integer 0 yields 8, or 2^3. When A is a byte array, index 0 is the leftmost bit of the leftmost byte. Setting bits 0 through 11 to 1 in a 4-byte-array of 0s yields the byte array 0xfff00000. Setting bit 3 to 1 on the 1-byte-array 0x00 yields the byte array 0x10.

INDEX NAME NOTES
0 URLEncoding
1 StdEncoding

Warning: Usage should be restricted to very rare use cases. In almost all cases, smart contracts should directly handle non-encoded byte-strings. This opcode should only be used in cases where base64 is the only available option, e.g. interoperability with a third-party that only signs base64 strings.

Decodes A using the base64 encoding E. Specify the encoding with an immediate arg either as URL and Filename Safe (URLEncoding) or Standard (StdEncoding). See RFC 4648 sections 4 and 5. 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.

INDEX NAME TYPE NOTES
0 JSONString []byte
1 JSONUint64 uint64
2 JSONObject []byte

Warning: Usage should be restricted to very rare use cases, as JSON decoding is expensive and quite limited. In addition, JSON objects are large and not optimized for size.

Almost all smart contracts should use simpler and smaller methods (such as the ABI. This opcode should only be used in cases where JSON is only available option, e.g. when a third-party only signs JSON.

params: Txn.Accounts offset (or, since v4, an available account address), available application id (or, since v4, a Txn.ForeignApps offset). Return: value.

params: Txn.Accounts offset (or, since v4, an available account address), available application id (or, since v4, a Txn.ForeignApps offset). Return: 1 if opted in and 0 otherwise.

params: Txn.Accounts offset (or, since v4, an available account address), state key. Return: value. The value is zero (of type uint64) if the key does not exist.

params: Txn.Accounts offset (or, since v4, an available account address), available application id (or, since v4, a Txn.ForeignApps offset), state key. Return: did_exist flag (top of the stack, 1 if the application and key existed and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist.

params: state key. Return: value. The value is zero (of type uint64) if the key does not exist.

params: Txn.ForeignApps offset (or, since v4, an available application id), state key. Return: did_exist flag (top of the stack, 1 if the application and key existed and 0 otherwise), value. The value is zero (of type uint64) if the key does not exist.

params: Txn.Accounts offset (or, since v4, an available account address), state key, value.

params: Txn.Accounts offset (or, since v4, an available account address), state key.

Deleting a key which is already absent has no effect on the application local state. (In particular, it does not cause the program to fail.)

params: state key.

Deleting a key which is already absent has no effect on the application global state. (In particular, it does not cause the program to fail.)

INDEX NAME TYPE NOTES
0 AssetBalance uint64 Amount of the asset unit held by this account
1 AssetFrozen bool Is the asset frozen or not

params: Txn.Accounts offset (or, since v4, an available address), asset id (or, since v4, a Txn.ForeignAssets offset). Return: did_exist flag (1 if the asset existed and 0 otherwise), value.

INDEX NAME TYPE IN NOTES
0 AssetTotal uint64 Total number of units of this asset
1 AssetDecimals uint64 See AssetParams.Decimals
2 AssetDefaultFrozen bool Frozen by default or not
3 AssetUnitName []byte Asset unit name
4 AssetName []byte Asset name
5 AssetURL []byte URL with additional info about the asset
6 AssetMetadataHash [32]byte Arbitrary commitment
7 AssetManager address Manager address
8 AssetReserve address Reserve address
9 AssetFreeze address Freeze address
10 AssetClawback address Clawback address
11 AssetCreator address v5 Creator address

params: Txn.ForeignAssets offset (or, since v4, an available asset id. Return: did_exist flag (1 if the asset existed and 0 otherwise), value.

INDEX NAME TYPE IN NOTES
0 AppApprovalProgram []byte Bytecode of Approval Program
1 AppClearStateProgram []byte Bytecode of Clear State Program
2 AppGlobalNumUint uint64 Number of uint64 values allowed in Global State
3 AppGlobalNumByteSlice uint64 Number of byte array values allowed in Global State
4 AppLocalNumUint uint64 Number of uint64 values allowed in Local State
5 AppLocalNumByteSlice uint64 Number of byte array values allowed in Local State
6 AppExtraProgramPages uint64 Number of Extra Program Pages of code space
7 AppCreator address Creator address
8 AppAddress address Address for which this application has authority
9 AppVersion uint64 v12 Version of the app, incremented each time the approval or clear program changes

params: Txn.ForeignApps offset or an available app id. Return: did_exist flag (1 if the application existed and 0 otherwise), value.

INDEX NAME TYPE IN NOTES
0 AcctBalance uint64 Account balance in microalgos
1 AcctMinBalance uint64 Minimum required balance for account, in microalgos
2 AcctAuthAddr address Address the account is rekeyed to.
3 AcctTotalNumUint uint64 v8 The total number of uint64 values allocated by this account in Global and Local States.
4 AcctTotalNumByteSlice uint64 v8 The total number of byte array values allocated by this account in Global and Local States.
5 AcctTotalExtraAppPages uint64 v8 The number of extra app code pages used by this account.
6 AcctTotalAppsCreated uint64 v8 The number of existing apps created by this account.
7 AcctTotalAppsOptedIn uint64 v8 The number of apps this account is opted into.
8 AcctTotalAssetsCreated uint64 v8 The number of existing ASAs created by this account.
9 AcctTotalAssets uint64 v8 The numbers of ASAs held by this account (including ASAs this account created).
10 AcctTotalBoxes uint64 v8 The number of existing boxes created by this account’s app.
11 AcctTotalBoxBytes uint64 v8 The total number of bytes used by this account’s app’s box keys and values.
12 AcctIncentiveEligible bool v11 Has this account opted into block payouts
13 AcctLastProposed uint64 v11 The round number of the last block this account proposed.
14 AcctLastHeartbeat uint64 v11 The round number of the last block this account sent a heartbeat.
INDEX NAME TYPE NOTES
0 VoterBalance uint64 Online stake in microalgos
1 VoterIncentiveEligible bool Had this account opted into block payouts

params: Txn.Accounts offset (or, since v4, an available account address), available application id (or, since v4, a Txn.ForeignApps offset). Return: value.

pushbytes args are not added to the bytecblock during assembly processes

pushint args are not added to the intcblock during assembly processes

pushbytess args are not added to the bytecblock during assembly processes

pushints args are not added to the intcblock during assembly processes

The call stack is separate from the data stack. Only callsub, retsub, and proto manipulate it.

If the current frame was prepared by proto A R, retsub will remove the ‘A’ arguments from the stack, move the R return values down, and pop any stack locations above the relocated return values.

Fails unless the last instruction executed was a callsub.

match consumes N+1 values from the stack. Let the top stack value be B. The following N values represent an ordered list of match cases/constants (A), where the first value (A[0]) is the deepest in the stack. The immediate arguments are an ordered list of N labels (T). match will branch to target T[I], where A[I] = B. If there are no matches then execution continues on to the next instruction.

bitlen interprets arrays as big-endian integers, unlike setbit/getbit

The notation A,B indicates that A and B are interpreted as a uint128 value, with A as the high uint64 and B the low.

log fails if called more than MaxLogCalls times in a program, or if the sum of logged bytes exceeds 1024 bytes.

itxn_begin initializes Sender to the application address; Fee to the minimum allowable, taking into account MinTxnFee and credit from overpaying in earlier transactions; FirstValid/LastValid to the values in the invoking transaction, and all other fields to zero or empty values.

itxn_field fails if A is of the wrong type for F, including a byte array of the wrong size for use as an address when F is an address field. itxn_field also fails if A is an account, asset, or app that is not available, or an attempt is made extend an array field beyond the limit imposed by consensus parameters. (Addresses set into asset params of acfg transactions need not be available.)

itxn_submit resets the current transaction so that it can not be resubmitted. A new itxn_begin is required to prepare another inner transaction.

itxn_next initializes the transaction exactly as itxn_begin does

Newly created boxes are filled with 0 bytes. box_create will fail if the referenced box already exists with a different size. Otherwise, existing boxes are unchanged by box_create.

For boxes that exceed 4,096 bytes, consider box_create, box_extract, and box_replace

For boxes that exceed 4,096 bytes, consider box_create, box_extract, and box_replace

INDEX NAME NOTES
0 VrfAlgorand

VrfAlgorand is the VRF used in Algorand. It is ECVRF-ED25519-SHA512-Elligator2, specified in the IETF internet draft draft-irtf-cfrg-vrf-03.

INDEX NAME TYPE IN NOTES
0 BlkSeed [32]byte
1 BlkTimestamp uint64
2 BlkProposer address v11
3 BlkFeesCollected uint64 v11
4 BlkBonus uint64 v11
5 BlkBranch [32]byte v11
6 BlkFeeSink address v11
7 BlkProtocol []byte v11
8 BlkTxnCounter uint64 v11
9 BlkProposerPayout uint64 v11

Boxes are of constant length. If C < len(D), then len(D)-C bytes will be removed from the end. If C > len(D), zero bytes will be appended to the end to reach the box length.

INDEX NAME NOTES
0 BN254g1 G1 of the BN254 curve. Points encoded as 32 byte X following by 32 byte Y
1 BN254g2 G2 of the BN254 curve. Points encoded as 64 byte X following by 64 byte Y
2 BLS12_381g1 G1 of the BLS 12-381 curve. Points encoded as 48 byte X following by 48 byte Y
3 BLS12_381g2 G2 of the BLS 12-381 curve. Points encoded as 96 byte X following by 96 byte Y

A and B are curve points in affine representation: field element X concatenated with field element Y. Field element Z is encoded as follows. For the base field elements (Fp), Z is encoded as a big-endian number and must be lower than the field modulus. For the quadratic field extension (Fp2), Z is encoded as the concatenation of the individual encoding of the coefficients. For an Fp2 element of the form Z = Z0 + Z1 i, where i is a formal quadratic non-residue, the encoding of Z is the concatenation of the encoding of Z0 and Z1 in this order. (Z0 and Z1 must be less than the field modulus).

The point at infinity is encoded as (X,Y) = (0,0). Groups G1 and G2 are denoted additively.

Fails if A or B is not in G. A and/or B are allowed to be the point at infinity. Does not check if A and B are in the main prime-order subgroup.

A is a curve point encoded and checked as described in ec_add. Scalar B is interpreted as a big-endian unsigned integer. Fails if B exceeds 32 bytes.

A and B are concatenated points, encoded and checked as described in ec_add. A contains points of the group G, B contains points of the associated group (G2 if G is G1, and vice versa). Fails if A and B have a different number of points, or if any point is not in its described group or outside the main prime-order subgroup - a stronger condition than other opcodes. AVM values are limited to 4096 bytes, so ec_pairing_check is limited by the size of the points in the groups being operated upon.

A is a list of concatenated points, encoded and checked as described in ec_add. B is a list of concatenated scalars which, unlike ec_scalar_mul, must all be exactly 32 bytes long. The name ec_multi_scalar_mul was chosen to reflect common usage, but a more consistent name would be ec_multi_scalar_mul. AVM values are limited to 4096 bytes, so ec_multi_scalar_mul is limited by the size of the points in the group being operated upon.

BN254 points are mapped by the SVDW map. BLS12-381 points are mapped by the SSWU map. G1 element inputs are base field elements and G2 element inputs are quadratic field elements, with nearly the same encoding rules (for field elements) as defined in ec_add. There is one difference of encoding rule: G1 element inputs do not need to be 0-padded if they fit in less than 32 bytes for BN254 and less than 48 bytes for BLS12-381. (As usual, the empty byte array represents 0.) G2 elements inputs need to be always have the required size.

INDEX NAME NOTES
0 BN254Mp110 MiMC configuration for the BN254 curve with Miyaguchi-Preneel mode, 110 rounds, exponent 5, seed “seed”
1 BLS12_381Mp111 MiMC configuration for the BLS12-381 curve with Miyaguchi-Preneel mode, 111 rounds, exponent 5, seed “seed”

A is a list of concatenated 32 byte big-endian unsigned integer scalars. Fail if A’s length is not a multiple of 32 or any element exceeds the curve modulus.

The MiMC hash function has known collisions since any input which is a multiple of the elliptic curve modulus will hash to the same value. MiMC is thus not a general purpose hash function, but meant to be used in zero knowledge applications to match a zk-circuit implementation.