Map type in starknet::storage is specifically designed for contract storage for this purpose.
Here’s a simple example that demonstrates how to use a Map:
- Declaration: Maps are declared using
Map<KeyType, ValueType>syntax - Storage: Maps must be declared inside the contract’s
Storagestruct- You need to import the
StorageMapReadAccessandStorageMapWriteAccesstraits fromstarknet::storage
- You need to import the
- Operations:
write(key, value): Stores a value for a given keyread(key): Retrieves the value associated with a key
- Maps automatically initialize all values to zero
- Keys and values must be of valid storage types, see Storing Custom Types
Composite Keys
For more complex scenarios, you can use composite keys by combining multiple values:Storage Layout (advanced)
Under the hood, Cairo maps use a deterministic storage layout:- Each key-value pair is stored at a unique address calculated using Pedersen hashes
- The address formula is: mod
- Learn more in the Cairo Book