3.5 Control Flow

Conditions

Conditional statements allow you to execute different blocks of code based on specific conditions.

The following example demonstrates an if statement that checks the value of a variable a and updates it accordingly:

let a: u8 = 1u8;

if (a == 1u8) {
    a += 1u8;
} 
else if (a == 2u8) {
    a += 2u8;
} 
else {
    a += 3u8;
}

In this case:

  • If a is 1, it increments by 1.

  • If a is 2, it increments by 2.

  • Otherwise, it increments by 3.

Assert

Assertion are special instructions that allows to stop the execution of a transition under a specific condition.

They can be used simply as follows:

let condition: bool = false;
assert(condition);

This code will always fail when condition is false, and run fine when condition is true.

Here is a more useful example:

transition protected() {
    assert(self.signer == aleo1hn9z4zt6awd6ts9zn8ppkwwvjwrg04ax48krd0fgnnzu6ezg9qxst3v26j);
    // Do whatever only the address above should be allowed to do...
}

This transition won't ever be able to be called by none other than aleo1hn9z4zt6awd6ts9zn8ppkwwvjwrg04ax48krd0fgnnzu6ezg9qxst3v26j .

assert are extremely useful, in particular to validate user inputs.

Loops

A for loop is used to iterate over a range of values. The loop runs a specific number of times, making it ideal for iterating over sequences or performing repeated operations.

for variable: type in lower_bound..upper_bound {
    // Loop body
}
  • The loop variable is declared with a type.

  • The loop iterates from the lower_bound to the upper_bound - 1.

  • The bounds must be integer constants of the same type.

  • The lower_bound must always be less than the upper_bound.

This example demonstrates a simple for loop that counts from 0 to 4 and keeps track of the count:

let count: u32 = 0u32;

for i: u32 in 0u32..5u32 {
    count += 1u32;
}

return count; // returns 5u32
  • The loop runs from 0 to 4, iterating 5 times.

  • count is incremented during each iteration.

  • The function returns 5.

While this code is invalid:

transition variable_loop(iterations: u32) -> u32{
    let output: u32 = 0u32;
    for i: u32 in 0u32..iterations {
        output += 1u32;
    }
    return output;
}

Something like this could be used instead:

const MAX_ITERATIONS: u32 = 100u32;

transition variable_loop(iterations: u32) -> u32 {
    // Ensure the maximum amount of iterations is not exceeded
    assert(iterations <= MAX_ITERATIONS);
    
    let output: u32 = 0u32;
    for i: u32 in 0u32..MAX_ITERATIONS {
        if(i < iterations) {
            output += 1u32;
        }
    }
    return output;
}

Last updated