Skip to main content

What are Mappings?

Mappings provide persistent, on-chain key-value storage in Leo programs. They are similar to hash maps or dictionaries in other languages, but their state is stored on the Aleo blockchain and can be accessed by anyone.

Mapping Declaration

Mappings are declared at the program level using the mapping keyword:

Multiple Mappings

Programs can declare multiple mappings:

Mapping Operations

Mappings can only be accessed from finalize functions, not from regular functions.

Reading from Mappings

Use Mapping::get_or_use() to read values:
get_or_use() returns the existing value if the key exists, or the default value if the key doesn’t exist. This prevents errors when accessing non-existent keys.

Writing to Mappings

Use Mapping::set() to write values:

Complete Example

Here’s a complete token program using mappings:

Mapping Key Types

Mapping keys can be any primitive type:
Mapping keys must be primitive types. Complex types like structs or records cannot be used as keys.

Mapping Value Types

Mapping values can be primitive types or arrays:

Lottery Example

Here’s a lottery program that uses mappings:

Access Patterns

Increment/Decrement

Conditional Updates

Multiple Mapping Updates

Visibility and Access

Public by Default

All mapping data is public and visible on the blockchain:

Read-Only from Outside

Mappings can only be modified from finalize functions within the program:

Gas and Efficiency

Minimize Reads

Batch Operations

Error Handling

Underflow Protection

Explicit Validation

Best Practices

1. Use Descriptive Names

2. Initialize with Defaults

3. Validate Before Updates

4. Document Mapping Purpose

Common Patterns

Token Balances

Global Counters

Access Control

Limitations

No Iteration

You cannot iterate over mapping keys or values:

No Deletion

Mappings cannot delete entries. Set to zero/default instead:

No Existence Check

Use get_or_use() with a sentinel value to check existence:

Next Steps

Finalize

Learn about finalize functions

Records

Combine with private records

Functions

Call finalize from functions

Programs

Program structure overview