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;
}