Smart contracts are bits of code intended to facilitate, verify, and enforce an agreement between multiple parties, allowing for transactions to happen without the need for a third party. Smart Contract Patterns is a digest on everything making those bits of code smarter.
Procedures, one the many updates our developers have recently introduced, have been added to Scilla.
If you’re familiar with Scilla, Zilliqa’s smart contract programming language, you already know about transitions, which are the equivalent of object methods in other languages. With the introduction of procedures we are adding a nifty piece of logic that should make your coding life easier. Let’s first recap things a bit.
transition foo (vname_1 : vtype_1, vname_2 : vtype_2, ...)
Transitions are defined with the keyword
transition followed by the parameters to be passed. They are the public interfaces of Scilla smart contracts, through which users (or other contracts) can modify the contract’s fields (i.e mutable states). When a transition is executed, its contract’s state is modified.
What’s a Procedure?
procedure foo (vname_1 : vtype_1, vname_2 : vtype_2, ...)
Procedures are defined with the keyword
procedure followed by the parameters to be passed. Similar to transitions, they can modify the mutable states of a contract. However, they differ in that they are not included in the contract’s public interface. In other words, procedures are like private transitions that can only be used within the scope of the contract, and as such can only be invoked by the contract’s transitions and procedures (though it is not possible for a procedure to be called recursively).
First, by defining a procedure, that bit of code can be reused by other transitions and procedures. Reusability makes for a more consistent, efficient and easier to maintain codebase. Second, by identifying bits of logic in a transition that can be decoupled makes for smaller transitions. Smaller transitions make for a code that is easier to read and reason about. An example of the use of procedures can be found in the test suite in the shogi_proc contract:
Since the contract is supposed to shut down once the game is over, the procedure Winner updates all the fields which to ensure that nothing further happens in the contract. The procedure is called from two different places — one when a player resigns, and one when a King is taken by another piece. Without a procedure, the code in the procedure body would have to be duplicated, as is the case in the original Shogi contract.
By separating subroutines inside of transitions and creating reusable bits of code, procedures make for smaller transitions, more readable and reusable code.
For further information, connect with us on one of our social channels: