Algo Builder Tutorial Part 6: Using Tmpl expressions from PyTEAL
This is the sixth tutorial in the Algo Builder series:
In this tutorial we will show how to use Tmpl expression from PyTeal in Algo-Builder.
Requirements
Requirements
- Good knowledge about Blockchain and Algorand.
- Detailed introduction to algob
- Knowledge about PyTeal
- Brief Stateful Smart Contracts
Background
Hardcoded values
Suppose you are writing smart contract in PyTeal, now you want to specify an address you will use something like:
Gtxn[1].receiver() == Addr("WWYNX3TKQYVEREVSW6QQP3SXSFOCE3SKUSEIVJ7YAGUPEACNI5UGI4DZCE")
What if you want to deploy multiple contracts with different addresses, this will be tedious.
Therefore PyTeal introduced placeholder values which can be replaced after compilation.
Tmpl
PyTEAL supports Tmpl
which is a template expression for creating placeholder values.
The name to use for this template variable must start with TMPL_
and only consist of uppercase alphanumeric characters and underscores.
For ex: Tmpl.Addr("TMPL_ADDR")
, Tmpl.Int("TMPL_COUNTER")
, Tmpl.Bytes("TMPL_BYTES")
.
when converted to TEAL it will look like this addr TMPL_ADDR
. now you can replace this constant to value of your choice using algob
.
Steps
Example Walkthrough
1. Using Tmpl expression in PyTeal
Example can be found here
First of all, you need to add Tmpl expression in your pyTeal code, code snippet from dynamic-fee.py
example:
# Check that the Receiver field is set to be the TMPL_TO address.
recv_field_check = Gtxn[1].receiver() == Tmpl.Addr("TMPL_TO")
In this code we are checking if receiver field is to TMPL_TO
a placeholder. Now you can replace these placeholders using algob
.
Instead of searching and replacing in each file and each time if you want different values you can automate it and do it in a script
2. Using algob to replace placeholder.
While using with algob you can replace these placeholder with the following,
script can be found here
const scInitParam = {
TMPL_TO: john.addr
}
await deployer.loadLogic('dynamic-fee.py', scInitParam);
You can pass an object with replacement values, algob will replace them for you at the time of compilation.
You can have multiple Tmpl expressions with same placeholder, algob
will find and replace each of them.