Search code examples
substratepolkadot

Data structure for nested storage map


How to declare the type for following data structure?

A product can have many candidates and each candidate has a stake. But same candidate can remain in more than one product with different stakes. I also need to query stake from a candidate id, and candidate ids from product id.

    #[pallet::storage]
    #[pallet::getter(fn governor_group)]
    pub type ProductId<T> = StorageMap<_, Blake2_128Concat, ProductId, Vec<CandidateId>>; 

    #[pallet::storage]
    #[pallet::getter(fn candidate_nominee)]
    pub type Stakes<T> = StorageMap<_, Blake2_128Concat, CandidateId, Stake>;

In the above code each candidate can have only one stake.

Nested storage map are not allowed in substrate like:

    #[pallet::storage]
    #[pallet::getter(fn governor_group)]
    pub type ProductId<T> = StorageMap<_, Blake2_128Concat, ProductId, Stakes>; 

Solution

  • I think you are looking for a StorageDoubleMap.

    This allows you to have:

    Key -> Key -> Value
    

    So that would look like:

    #[pallet::storage]
    #[pallet::getter(fn governor_group)]
    pub type ProductId<T> = StorageMap<
        _,
        Blake2_128Concat,
        ProductId,
        Blake2_128Concat,
        CandidateId,
        Stakes,
    >;
    

    You may need to introduce other maps which clarify sub-context of this double map, or create some data structures which hold the information you are looking for.

    Note that we support an arbitrary nesting of maps with StorageNMap, which just extends this concept further and further.