Conditional
Aqua supports branching: you can return one value or another, recover from the error, or check a boolean expression.

Contract

  • The second branch of the conditional operator is executed if and only if the first block failed.
  • The second block has no access to the first block's data.
  • A conditional block is considered "executed" if and only if any inner block was executed successfully.
  • A conditional block is considered "failed" if and only if the second (recovery) block fails to execute.
Block of code is any number of lines on the same indentation level or deeper

Conditional operations

try

Tries to perform operations, or swallows the error (if there's no catch, otherwise after the try block).
1
try:
2
-- If foo fails with an error, execution will continue
3
-- You should write your logic in a non-blocking fashion:
4
-- If your code below depends on `x`, it may halt as `x` is not resolved.
5
-- See Conditional return below for workaround
6
x <- foo()
Copied!

catch

Catches the standard error from try block.
1
try:
2
foo()
3
catch e:
4
logError(e)
Copied!
Type of e is:
1
data LastError:
2
instruction: string -- What AIR instruction failed
3
msg: string -- Human-readable error message
4
peer_id: string -- On what peer the error happened
Copied!

if

If corresponds to match, mismatch extension of Ο€-calculus.
1
x = true
2
if x:
3
-- always executed
4
foo()
5
​
6
if x == false:
7
-- never executed
8
bar()
9
​
10
if x != false:
11
-- executed
12
baz()
Copied!
Currently, you may only use one ==, != operator in the if expression, or compare with true.
Both operands can be variables.

else

Just the second branch of if, in case the condition does not hold.
1
if true:
2
foo()
3
else:
4
bar()
Copied!
If you want to set a variable based on condition, see Conditional return.

otherwise

You may add otherwise to provide recovery for any block or expression:
1
x <- foo()
2
otherwise:
3
-- if foo can't be executed, then do bar()
4
y <- bar()
Copied!

Conditional return

In Aqua, functions may have only one return expression, which is very last. And conditional expressions cannot define the same variable:
1
try:
2
x <- foo()
3
otherwise:
4
x <- bar() -- Error: name x was already defined in scope, can't compile
Copied!
So to get the value based on condition, we need to use a writeable collection.
1
-- result may have 0 or more values of type string, and is writeable
2
resultBox: *string
3
try:
4
resultBox <- foo()
5
otherwise:
6
resultBox <- bar()
7
​
8
-- now result contains only one value, let's extract it!
9
result = resultBox!
10
​
11
-- Type of result is string
12
-- Please note that if there were no writes to resultBox,
13
-- the first use of result will halt.
14
-- So you need to be careful about it and ensure that there's always a value.
Copied!
Last modified 1mo ago