Hey guys.
So, we have already covered what the Leo language is here.
And how to install Leo and how to write the phrase “Hello Leo” we learned here.
Now it’s time to dive even further into the Leo Language Guide. Fasten your seatbelts, we are in for an exciting journey.
Leo Language Guide
Statically Typed
Leo is a statically typed language, which means we must know the type of each variable before executing a circuit.
Explicit Types Required
There is no undefined
or null
value in Leo. When assigning a new variable, the type of the value must be explicitly stated.
Pass by Value
Expressions in Leo are always passed by value, which means their values are always copied when they are used as function inputs or in right sides of assignments.
Data Types and Values
Booleans
Leo supports the traditional true
or false
boolean values. The explicit bool
type for booleans in statements is required.
let b: bool = false;
Integers
Leo supports signed integer types i8
, i16
, i32
, i64
, i128
and unsigned integer types u8
, u16
, u32
, u64
, u128
.
let b: u8 = 1u8;
INFO
Higher bit length integers generate more constraints in the circuit, which can slow down computation time.
A Note on Leo Integers
Leo will not default to an integer type. The definition of a integer must include an explicit type.
Type casting is supported as of Leo v1.8.2
let a: u8 = 2u8; // explicit type
let b: u16 = a as u16; // type casting
let b: u8 = 2; // implicit type -- not supported
Field Elements
Leo supports the field
type for the base field elements of the elliptic curve. These are unsigned integers below the modulus of the base field.
let a: field = 1field;
let b: field = 21888242871839275222246405745257275088548364400416034343698204186575808495617field;
Group Elements
The set of affine points on the elliptic curve passed into the Leo compiler forms a group. Leo supports a subgroup of this group, generated by a generator point, as a primitive data type. Group elements are special since their values can be defined from the x-coordinate of a coordinate pair, such as 0group
. The group type keyword group
must be used when specifying a group value.
let b: group = 0group; // the point with 0 x-coordinate
The aforementioned generator point can be obtained via a constant associated to the group
type.
let g: group = group::GEN; // the group generator
Scalar Elements
Leo supports the scalar
type for scalar field elements of the elliptic curve subgroup. These are unsigned integers below the modulus of the scalar field.
let a: scalar = 1scalar;
Addresses
Addresses are defined to enable compiler-optimized routines for parsing and operating over addresses. These semantics will be accompanied by a standard library in a future sprint.
let receiver: address = aleo1ezamst4pjgj9zfxqq0fwfj8a4cjuqndmasgata3hggzqygggnyfq6kmyd4;
Layout of a Leo Program
A Leo program contains declarations of a Program Scope, Imports , Transition Functions, Helper Functions, Structs , Records, Mappings, and Finalize Functions. Declarations are locally accessible within a program file. If you need a declaration from another Leo file, you must import it.
Program Scope
A program scope in the sense of Leo is a collection of code (its functions) and data (its types) that resides at a program ID on the Aleo blockchain.
import foo.leo;
program hello.aleo {
mapping balances: address => u64; record token {
owner: address,
microcredits: u64,
amount: u64,
} struct message {
sender: address,
object: u64,
} transition mint_public(
public receiver: address,
public amount: u64,
) -> token {
return token {
owner: receiver,
microcredits: 0u64,
amount,
} then finalize(receiver, amount);
} finalize mint_public(
public receiver: address,
public amount: u64,
) {
let current_amount: u64 = Mapping::get_or_use(account, receiver, 0u64);
Mapping::set(account, receiver, current_amount + amount);
} function compute(a: u64, b: u64) -> u64 {
return a + b;
}
}
The following must be declared inside the program scope in a Leo file:
- mappings
- record types
- struct types
- transition functions
- helper functions
- finalize functions
The following must be declared outside the program scope in a Leo file:
- imports
Program ID
A program ID is declared as {name}.{network}
. The first character of a name
must be lowercase. name
can contain lowercase letters, numbers, and underscores. Currently, aleo
is the only supported network
domain.
program hello.aleo; // valid
program Foo.aleo; // invalid
program baR.aleo; // invalid
program 0foo.aleo; // invalid
program 0_foo.aleo; // invalid
program _foo.aleo; // invalid
Import
You can import dependencies that are downloaded to the imports
directory. An import is declared as import {filename}.leo;
This will look for imports/{filename}.leo
and bring all declarations into the current file scope. If there are duplicate names for declarations, Leo will fail to compile. Ordering is enforced for imports, which must be at the top of file.
CAUTION
Leo imports are unstable and currently only provide minimal functionality. Their syntax is expected to change.
import foo.leo; // Import all `foo.leo` declarations into the `hello.aleo` program.
program hello.aleo { }
Struct
A struct data type is declared as struct {name} {}
. Structs contain component declarations {name}: {type},
.
struct array3 {
a0: u32,
a1: u32,
a2: u32,
}
Record
A record data type is declared as record {name} {}
. Records contain component declarations {visibility} {name}: {type},
.
A visibility can be either constant
, public
, or private
. Users may also omit the visibility, in which case, Leo will default to private
.
Record data structures must contain the owner
and microcredits
components as shown below. When passing a record as input to a program function, the _nonce: group
component is also required (but it does not need to be declared in the Leo program).
record token {
// The token owner.
owner: address,
// The Aleo balance (in microcredits).
microcredits: u64,
// The token amount.
amount: u64,
}
Transition Function
Transition functions in Leo are declared as transition {name}() {}
. Transition functions can be called directly when running a Leo program (via leo run
). Transition functions contain expressions and statements that can compute values. Transition functions must be in a program's current scope to be called.
program hello.aleo {
transition foo(
public a: field,
b: field,
) -> field {
return a + b;
}
}
Function Inputs
A function input is declared as {visibility} {name}: {type},
Function inputs must be declared just after the function name declaration, in parentheses.
// The transition function `foo` takes a single input `a` with type `field` and visibility `public`.
transition foo(public a: field) { }
Function Outputs
A function output is calculated as return {expression};
. Returning an output ends the execution of the function. The return type of the function declaration must match the type of the returned {expression}
.
transition foo(public a: field) -> field {
// Returns the addition of the public input a and the value `1field`.
return a + 1field;
}
Helper Function
A helper function is declared as function {name}() {}
. Helper functions contain expressions and statements that can compute values, however helper functions cannot produce records
.
Helper functions cannot be called directly from the outside. Instead, they must be called by other functions. Inputs of helper functions cannot have {visibility}
modifiers like transition functions, since they are used only internally, not as part of a program's external interface.
function foo(
a: field,
b: field,
) -> field {
return a + b;
}
Inline Function
An inline function is declared as inline {name}() {}
. Inline functions contain expressions and statements that can compute values. Inline functions cannot be executed directly from the outside, instead the Leo compiler inlines the body of the function at each call site.
Inputs of inline functions cannot have {visibility}
modifiers like transition functions, since they are used only internally, not as part of a program's external interface.
inline foo(
a: field,
b: field,
) -> field {
return a + b;
}
The rules for functions (in the traditional sense) are as follows:
- There are three variants of functions: transition, function, inline.
- transitions can only call functions and inlines.
- functions can only call inlines.
- inlines can only call inlines.
- Direct/indirect recursive calls are not allowed
Finalize Function
A finalize function is declared as finalize {name}:
. A finalize function must immediately follow a transition function, and must have the same name; it is associated with the transition function and is executed on chain, after the zero-knowledge proof of the execution of the associated transition is verified; a finalize function finalizes a transition function on chain. Upon success of the finalize function, the program logic is executed. Upon failure of the finalize function, the program logic is reverted.
program transfer.aleo {
// The function `transfer_public_to_private` turns a specified token amount
// from `account` into a token record for the specified receiver.
//
// This function preserves privacy for the receiver's record, however
// it publicly reveals the caller and the specified token amount.
transition transfer_public_to_private(
public receiver: address,
public amount: u64
) -> token {
// Produce a token record for the token receiver.
let new: token = token {
owner: receiver,
microcredits: 0u64,
amount,
};
// Return the receiver's record, then decrement the token amount of the caller publicly.
return new then finalize(self.caller, amount);
} finalize transfer_public_to_private(
public sender: address,
public amount: u64
) {
// Decrements `account[sender]` by `amount`.
// If `account[sender]` does not exist, it will be created.
// If `account[sender] - amount` underflows, `transfer_public_to_private` is reverted.
let current_amount: u64 = Mapping::get_or_use(account, sender, 0u64);
Mapping::set(account, sender, current_amount - amount);
}
}
Mapping
A mapping is declared as mapping {name}: {key-type} => {value-type}
. Mappings contain key-value pairs. Mappings are stored on chain.
// On-chain storage of an `account` mapping,
// with `address` as the type of keys,
// and `u64` as the type of values.
mapping account: address => u64;
Mapping Operations
The mapping struct allows the programmer to apply updates to a program mapping data structure by calling one of the following functions.
INFO
Mapping operations are only allowed in a finalize function.
program test.aleo {
mapping counter: address => u64;
transition dubble() {
return then finalize(self.caller);
} finalize dubble(addr: address) {
let current_value: u64 = Mapping::get_or_use(counter, addr, 0u64);
Mapping::set(counter, addr, current_value + 1u64);
current_value = Mapping::get(counter, addr);
Mapping::set(counter, addr, current_value + 1u64);
}}
get
A get command, e.g. current_value = Mapping::get(counter, addr);
Gets the value stored at addr
in counter
and stores the result in current_value
If the value at addr
does not exist, then the program will fail to execute.
get_or_use
A get command that uses the provided default in case of failure,
e.g. let current_value: u64 = Mapping::get_or_use(counter, addr, 0u64);
Gets the value stored at addr
in counter
and stores the result in current_value
. If the key is not present, 0u64
is stored in counter
and stored in current_value
.
set
A set command, e.g. Mapping::set(counter, addr, current_value + 1u64);
Sets the addr
entry as current_value + 1u64
in counter
.
contains
A contains command, e.g. let contains: bool = Mapping::contains(counter, addr);
Returns true
if addr
is present in counter
, false
otherwise.
remove
A remove command, e.g. Mapping::remove(counter, addr);
Removes the entry at addr
in counter
.
For Loops
For Loops are declared as for {variable: type} in {lower bound}..{upper bound}
. Unsigned integer types u8
, u16
, and u32
are recommended for loop variable types. The lower bound must be less than the upper bound. Nested loops are supported.
Example
let count: u32 = 0u32;
for i: u32 in 0u32..5u32 {
count += 1u32;
} return count; // returns 5u32
Operators
Operators in Leo compute a value based off of one or more expressions. Leo will try to detect arithmetic operation errors as soon as possible. If an integer overflow or division by zero can be identified at compile time, Leo will quickly tell the programmer. Otherwise, the error will be caught at proving time when transition function inputs are processed.
For instance, addition adds first
with second
, storing the outcome in destination
. For integer types, a constraint is added to check for overflow. For cases where wrapping semantics are needed for integer types, see the Add Wrapped
operator.
let a: u8 = 1u8 + 1u8;
// a is equal to 2
a += 1u8;
// a is now equal to 3a = a.add(1u8);
// a is now equal to 4
Arithmetic Operators
Logical Operators
Relational Operators
Relational operators will always resolve to a boolean bool
value.
Operator Precedence
Operators will prioritize evaluation according to:
Parentheses
To prioritize a different evaluation, use parentheses ()
around the expression.
let result = (a + 1u8) * 2u8;
(a + 1u8)
will be evaluated before multiplying by two * 2u8
.
Commands
Leo supports several commands that can be used to reference information about the Aleo blockchain and the current transaction.
self.caller
Returns the address of the account that is calling the program function.
program test.aleo {
transition matches(addr: address) -> bool {
return self.caller == addr;
}
}
block.height
Returns the height of the current block.
INFO
block.height
is only allowed in a finalize function.
program test.aleo {
transition matches(height: u32) {
return then finalize(height);
} finalize matches(height: u32) {
assert_eq(height, block.height);
}
}
Core Functions
Core functions are functions that are built into the Leo language. They are used to perform cryptographic operations such as hashing, commitment, and random number generation.
Assert and AssertEq
assert
and assert_eq
are used to verify that a condition is true. If the condition is false, the program will fail.
program test.aleo {
transition matches() {
assert(true);
assert_eq(1u8, 1u8);
}
}
Hash
Leo supports the following hashing algorithms: BHP256
, BHP512
, BHP768
, BHP1024
, Pedersen64
, Pedersen128
, Poseidon2
, Poseidon4
, Poseidon8
The output type of a commitment function is specified in the function name. e.g. hash_to_group
will return a group
type. Hash functions take any type as an argument.
let a: scalar = BHP256::hash_to_scalar(1u8);
let b: address = Pedersen64::hash_to_address(1u128);
let c: group = Poseidon2::hash_to_group(1field);
Commit
Leo supports the following commitment algorithms: BHP256
, BHP512
, BHP768
, BHP1024
, Pedersen64
, Pedersen128
The output type of a commitment function is specified in the function name. e.g. commit_to_group
will return a group
type.
The first argument can be any type. The second argument must be a field
type and is used as a blinding factor.
let a: group = BHP256::commit_to_group(1u8, 2field);
let b: address = Pedersen64::commit_to_address(1u128, 2field);
Random
Leo supports the ChaCha
random number generation algorithm.
The output type of a random function is specified in the function name. e.g. rand_group
will return a group
type.
INFO
Random functions are only allowed in a finalize function.
let a: group = ChaCha::rand_group();
let b: u32 = ChaCha::rand_u32();
Deprecated Syntax
Increment and Decrement
increment()
and decrement()
functions are deprecated as of Leo v1.7.0. Please use the Mapping::set()
function instead.
program transfer.aleo {
// On-chain storage of an `account` map,
// with `address` as the key,
// and `u64` as the value.
mapping account: address => u64;
transition transfer_public(...) {...} finalize transfer_public(
public sender: address,
public receiver: address,
public amount: u64
) {
// Decrements `account[sender]` by `amount`.
// If `account[sender]` does not exist, it will be created.
// If `account[sender] - amount` underflows, `transfer_public` is reverted.
let sender_amount: u64 = Mapping::get_or_use(account, sender, 0u64);
Mapping::set(account, sender, sender_amount - amount); // Increments `account[receiver]` by `amount`.
// If `account[receiver]` does not exist, it will be created.
// If `account[receiver] + amount` overflows, `transfer_public` is reverted.
let receiver_amount: u64 = Mapping::get_or_use(account, receiver, 0u64);
Mapping::set(account, receiver, receiver_amount + amount);
}
}
Thank you for reading this article to the end, and sign up for notifications.
See below for all the official links to Aleo:
Website — https://www.aleo.org/
Discord — https://discord.gg/aleohq
Twitter — https://twitter.com/AleoHQ
GitHub — https://github.com/AleoHQ