Contract Mastery: Transactions

Transactions

Transactions are objects that are signed by one or more accounts and are sent to the chain to interact with it.

The body is declared using the transaction keyword and its contents are contained in curly braces.

transaction {

// transaction contents

}

The four optional main phases:

Prepare phase

The prepare phase is used when access to the private AuthAccount object of signing accounts is required for your transaction.

For each signer of the transaction the signing account is passed as an argument to the prepare phase. For example, if the transaction has three signers, the prepare must have three parameters of type AuthAccount.

prepare(signer1: AuthAccount) {

}

Pre Phase

The pre phase is executed after the prepare phase, and is used for checking if explicit conditions hold before executing the remainder of the transaction. A common example would be checking requisite balances before transferring tokens between accounts.

pre{

sendingAccount.balance > 0

}

Execute Phase

The execute phase does exactly what it says, it executes the main logic of the transaction. This phase is optional, but it is a best practice to add your main transaction logic in the section, so it is explicit.

execute {

let publicAccount = getAccount(0x03)

}

Post Phase

Statements inside of the post phase are used to verify that your transaction logic has been executed properly. It contains zero or more condition checks.

For example, a transfer transaction might ensure that the final balance has a certain value, or e.g. it was incremented by a specific amount.

post {

result.balance == 30: "Balance after transaction is incorrect!"

}