How do I keep track of what (key, value) pairs exist in a `StorageMap`

In order to keep track of what (key, value) pairs exist in a StorageMap, you may use a StorageVec that contains all the keys that have been mapped in the StorageMap. For example

storage {
    balances: StorageMap<Address, u64>,
    tracked_addresses: StorageVec<Address>,
}

// Every call to `insert()` on `balances` has to be followed by 
// a call to `push()` for `tracked_addresses`
let addr1 = Address::from(<some_b256>);
storage.balances.insert(addr1, <some_balance>);
storage.tracked_addresses.push(addr1);
...

// To iterate over `balances`, we can write
let mut index = 0;
let len = storage.tracked_addresses.len();
while index < len {
    let addr = storage.tracked_addresses.get(index).unwrap();
    let balance = storage.balances.get(addr);
    // ... Do something with `addr` and the corresponding `balance`
    index += 1;
}
66 Likes

Good it should be there and keep growing​:heart::heart:

18 Likes

Regarding StorageMaps, wouldn’t it be more ergonomic if the get function returned an Option<V>?

11 Likes

Excellent question. That is indeed something that I’m working on right now as part of Make use of range storage in the compiler and the standard library by mohammadfawaz · Pull Request #3332 · FuelLabs/sway · GitHub

15 Likes

Oh, awesome! Thank you for answering :pray:

5 Likes