What is Finalize?
Finalize blocks enable on-chain computation and state changes in Leo programs. While regular functions execute off-chain with private inputs, finalize functions run on-chain with public inputs and can modify mapping state.The Final Pattern
Functions returnFinal to trigger on-chain finalization:
final { ... } block specifies which finalize function to call with which arguments.
Finalize Functions
Finalize functions are declared with thefinal fn keywords:
Finalize functions are declared outside the program scope and must have all parameters marked as
public.Complete Example
Here’s a complete token transfer with finalization:Off-Chain + On-Chain Pattern
Combine private computation with public state changes:Accessing Blockchain State
Finalize functions can access blockchain context:Block Context
Available blockchain information:Randomness
Access on-chain randomness:Mapping Operations in Finalize
Finalize functions are the only place where mappings can be modified:Validation in Finalize
Use assertions to validate conditions:Multiple Return Values with Final
Return multiple values along with Final:Finalize Parameters
All finalize parameters must be marked aspublic:
Passing Data to Finalize
Pass data from the off-chain function to the finalize function:Lottery Example
Complete lottery program with finalization:Best Practices
1. Minimize On-Chain Computation
2. Validate Early
3. Atomic Updates
4. Clear Error Conditions
Common Patterns
Conditional State Updates
Time-Based Logic
Rate Limiting
Next Steps
Mappings
Learn about on-chain storage
Functions
Return Final from functions
Records
Combine with private records
Programs
Program structure overview