Skip to main content

Function Declaration

Functions are declared using the fn keyword:

Basic Functions

Simple Functions

Functions with no parameters or return value:

Functions with Parameters

Functions accept typed parameters:

Parameter Modes

Leo supports different parameter visibility modes:

Private Parameters (Default)

Parameters are private by default:

Public Parameters

Mark parameters as public to expose them on-chain:
Public parameters are visible on the blockchain. Use them only for data that should be publicly accessible.

Return Types

Single Return Values

Functions can return a single value:

Multiple Return Values

Return tuples for multiple values:

No Return Value

Functions without a return type implicitly return ():

Function Types

Regular Functions

Standard functions for off-chain computation:

Entry Point Functions

Functions that can be called from outside the program (transitions):
Entry point functions are defined at the program scope level and can return Final to trigger on-chain state changes.

Finalize Functions

Functions that execute on-chain and can modify mappings:
See Finalize for detailed information about on-chain functions.

Special Variables

self.caller

Access the caller’s address within functions:

Function Composition

Calling Functions

Functions can call other functions:

Helper Functions

Create helper functions for reusable logic:

Function Documentation

Document functions with comments:

Best Practices

1. Single Responsibility

Each function should have one clear purpose:

2. Descriptive Names

Use clear, descriptive function names:

3. Validate Inputs

Check preconditions at the start of functions:

4. Small, Focused Functions

Break complex logic into smaller functions:

5. Consistent Parameter Order

Use consistent parameter ordering:

Common Patterns

Factory Functions

Create instances of types:

Predicate Functions

Return boolean conditions:

Transform Functions

Transform data from one form to another:

Builder Pattern

Build complex structures step by step:

Finalize Pattern

Combine off-chain and on-chain computation:

Next Steps

Finalize

On-chain computation

Records

Work with private records

Statements

Control flow in functions

Operators

Use operators in functions