Map
A Map
is a container that maps keys to instances of another container.
Most commonly, you will use a Map
to store a list of items. For example, the signature could be a
Map<String, Item<String>>
to store a list of signatures for each user. (See the first example.)
Examples
Keeping balances
Let's say you want to keep track of the balances of each user. You can do this with a
Map<String, Item<Uint128>>
.
use cw_storey::containers::{Item, Map};
use cw_storey::CwStorage;
const BALANCES_IX: u8 = 0;
let balances: Map<String, Item<Uint128>> = Map::new(BALANCES_IX);
let mut cw_storage = CwStorage(&mut storage);
let mut access = balances.access(&mut cw_storage);
assert_eq!(access.entry("alice").get().unwrap(), None);
access.entry_mut("alice").set(&Uint128::new(1000)).unwrap();
assert_eq!(access.entry("alice").get().unwrap(), Some(Uint128::new(1000)));
- line 6: Here we construct the
Map
facade. The constructor takes a key, which is the prefix of the keys in the underlying storage backend. - line 8: The
access
(opens in a new tab) method returns aMapAccess
(opens in a new tab) entity, which allows manipulating the map. - line 10: Here we try to access the balance of
alice
. Since she doesn't have one yet, it returnsNone
. Theentry
(opens in a new tab) method returns anItemAccess
(opens in a new tab) entity, which allows manipulating the item stored under the keyalice
. - line 12: Here we set Alice's balance to
1000
. - line 14: We check that the balance is now
1000
.
Iterating over the balances
When iterating over the entries in a Map
using the pairs
, keys
, and values
methods, the
order of the keys is not guaranteed to be sensible (though it is deterministic). If you need a
sensible order, try using the bounded iterators. If they do not exist (BoundedIterableAccessor
is not implemented for the accessor), sensibly ordered iteration is not
possible.
Bounded or sensibly ordered iteration is not possible when both of the following conditions are met:
- The key is dynamically sized (e.g.
String
,Vec<u8>
, etc.). - The value type is a collection (
Map
,Column
, etc.) rather than something likeItem
.
Iterating over the balances is pretty straightforward. The keys
(opens in a new tab) method returns an iterator over
the keys, the values
(opens in a new tab) method returns an iterator over the values, and the pairs
(opens in a new tab) method
returns an iterator over both.
use cw_storey::containers::{Item, Map};
use cw_storey::CwStorage;
use storey::containers::IterableAccessor as _;
const BALANCES_IX: u8 = 1;
let balances: Map<String, Item<Uint128>> = Map::new(BALANCES_IX);
let mut cw_storage = CwStorage(&mut storage);
let mut access = balances.access(&mut cw_storage);
access.entry_mut("bob").set(&Uint128::new(500)).unwrap();
access.entry_mut("carol").set(&Uint128::new(1500)).unwrap();
access.entry_mut("dave").set(&Uint128::new(2000)).unwrap();
assert_eq!(
access.pairs().collect::<Result<Vec<_>, _>>().unwrap(),
vec![
(("bob".to_string(), ()), Uint128::new(500)),
(("carol".to_string(), ()), Uint128::new(1500)),
(("dave".to_string(), ()), Uint128::new(2000)),
]
);
assert_eq!(
access.keys().collect::<Result<Vec<_>, _>>().unwrap(),
vec![("bob".to_string(), ()), ("carol".to_string(), ()), ("dave".to_string(), ())]
);
assert_eq!(
access.values().collect::<Result<Vec<_>, _>>().unwrap(),
vec![Uint128::new(500), Uint128::new(1500), Uint128::new(2000)]
);
- line 4: Here we import the
IterableAccessor
(opens in a new tab) trait. This trait provides unbounded iteration. - line 17: The
pairs
method returns an iterator over the key-value pairs. - line 19: Notice the key type is
(String, ())
. This is likely to become justString
in the future. For now, consider this a quirk of the design. This will make more sense once you get to composite maps.
Bounded iteration
Bounded iteration is also supported in many cases.
use cw_storey::containers::{Item, Map};
use cw_storey::CwStorage;
use storey::containers::BoundedIterableAccessor as _;
const BALANCES_IX: u8 = 1;
let balances: Map<String, Item<Uint128>> = Map::new(BALANCES_IX);
let mut cw_storage = CwStorage(&mut storage);
let mut access = balances.access(&mut cw_storage);
access.entry_mut("bob").set(&Uint128::new(500)).unwrap();
access.entry_mut("carol").set(&Uint128::new(1500)).unwrap();
access.entry_mut("dave").set(&Uint128::new(2000)).unwrap();
assert_eq!(
access.bounded_pairs(Some("bob"), Some("dave")).collect::<Result<Vec<_>, _>>().unwrap(),
vec![(("bob".to_string(), ()), Uint128::new(500)), (("carol".to_string(), ()), Uint128::new(1500))]
);
Here we used the bounded_pairs
(opens in a new tab) method to iterate over some key-value pairs. Other bounded
methods are also available: bounded_keys
(opens in a new tab) and bounded_values
(opens in a new tab).
The bounds are provided as arguments to the methods. Currently, the bounds are inclusive on the lower bound and exclusive on the upper bound. In a future release (soon!) this will be configurable.
Keeping balances with composition
Alright, let's say this time you'd also like to keep track of the balances of each user, but each can have multiple different tokens. This is where composition comes in.
use cw_storey::containers::{Item, Map};
use cw_storey::CwStorage;
const BALANCES_IX: u8 = 0;
let balances: Map<String, Map<String, Item<Uint128>>> = Map::new(BALANCES_IX);
let mut cw_storage = CwStorage(&mut storage);
let mut access = balances.access(&mut cw_storage);
access.entry_mut("alice").entry_mut("USDT").set(&Uint128::new(1000)).unwrap();
access.entry_mut("alice").entry_mut("OSMO").set(&Uint128::new(2000)).unwrap();
assert_eq!(access.entry("alice").entry("USDT").get().unwrap(), Some(Uint128::new(1000)));
assert_eq!(access.entry("alice").entry("OSMO").get().unwrap(), Some(Uint128::new(2000)));
This example is similar to the previous one, but this time we have an extra level of nesting.
First of all, our type is Map<String, Map<String, Item<Uint128>>>
. The outer map maps user
addresses to inner maps. The inner map maps token denominations to actual balances.
When we access the stuff, the first entry
(opens in a new tab)/entry_mut
(opens in a new tab) call accesses a record in the outer map,
and the second one accesses a record in the inner map.
In cw-storage-plus
, you can achieve the same
effect using composite keys (tuples). The example above would then use something like
cw_storage_plus::Map<(String, String), Uint128>
.
Iterating over the balances
Let's take a look at what iteration looks like with a composite map.
use cw_storey::containers::{Item, Map};
use cw_storey::CwStorage;
use cosmwasm_std::Order;
use storey::containers::IterableAccessor as _;
const BALANCES_IX: u8 = 1;
let balances: Map<String, Map<String, Item<u64>>> = Map::new(BALANCES_IX);
let mut cw_storage = CwStorage(&mut storage);
let mut access = balances.access(&mut cw_storage);
access.entry_mut("alice").entry_mut("USDT").set(&1000).unwrap();
access.entry_mut("alice").entry_mut("OSMO").set(&2000).unwrap();
access.entry_mut("bob").entry_mut("USDT").set(&1500).unwrap();
assert_eq!(
access.pairs().collect::<Result<Vec<_>, _>>().unwrap(),
vec![
(("bob".into(), ("USDT".into(), ())), 1500),
(("alice".into(), ("OSMO".into(), ())), 2000),
(("alice".into(), ("USDT".into(), ())), 1000),
]
);
assert_eq!(
access.entry("alice").pairs().collect::<Result<Vec<_>, _>>().unwrap(),
vec![(("OSMO".into(), ()), 2000), (("USDT".into(), ()), 1000)]
);
Here we iterated twice, but each time we got a different view of the data. Each iteration was at a different level.
- line 18: We call
pairs
on the outer map, which gives us all the entries. - line 27: We call
pairs
on the inner map under the keyalice
, which gives us all of Alice's balances.
We can of course do the same with the keys
and values
methods.
In the example above, bounded iteration (and a sensible order of iteration) is only possible for the inner map. The reason for that is explained in the warning box at the beginning of the section.