Karaka Tutorial #6: foreach saving you time and space

Words
368
Reading
2 min
4y
Listen to this post
~2 min

image.png

Karaka is an Automation (clerk) for Hive and Hive Engine blockchains. This tutorial teaches how to use constants to automate Hive and Hive Engine. Get Karaka from https://github.com/Stormrose/karaka

Karaka is a Maori word meaning variously: an English loanword for 'clerk' or 'clock' and a significant coastal plant 'Corynocarpus laevigatus'.

This tutorial builds on the first three tutorials, so try those out first.

  1. Karaka Tutorial #1: A Basic Tutorial config.json example
  2. Karaka Tutorial #2: Hive-Engine Tokens
  3. Karaka Tutorial #3: Constants
  4. Karaka Tutorial #4: Import facts between chains
  5. Karaka Tutorial #5: Oracles

Why foreach?

By now, config.json probably has several rules that are very similar. Whether staking tribal tokens on hive-engine or transferring HIVE balances from multiple accounts to a single gathering place, having similar rules is a readability and maintenance nightmare. Foreach allows wildcard matching within Karaka rules, and that keeps rules maintainable and consistent.

How to use foreach

Foreach is a property within any Karaka rule that is a [list] of "strings". Each string in the list is substituted wherever {0} appears in the rest of the Karaka rule. Perhaps an example is in order:

{
    "foreach": [ "PAL", "VIBES", "WAIV" ],
    "name": "@eturnerx sell and stake {0}",
    "comment": "@eturnerx sell and stake {0}",
    "if": "eturnerx.{0}_balance > 0",
    "then": "stake eturnerx.{0}_balance {0} from eturnerx"
}

This rule will stake PAL, VIBES or WAIV whenever there is a non-zero balance in the eturnerx@eturnerx account. Under the hood, Karaka generates a rule per foreach list item with the wildcard {0} resolved. The wildcard is a direct text replacement that occurs when the config is loaded when Karaka start.
While this example uses hive-engine tokens, you could also use foreach to list accounts, such as:

{
    "foreach": [ "accountone", "accounttwo", "accountthree" ],
    "if": "{0}.hive_balance > 0",
    "then": "transfer ({0}.hive_balance) HIVE from {0} to eturnerx"
}

In this example, the rule instructs Karaka to transfer any non-zero hive balance in either accountone, accounttwo or accountthree to eturnerx@eturnerx.

Summary

Using foreach is a great way to keep rules compact, readable and consistent. Once a rule is set up with foreach, adding more items to the list, such as a new tribal token, is simple.

If you have any questions about Karaka, then please get in touch.

Karaka Tutorial #6: foreach saving you time and space | Ecency