How best to organize storage with nested StorageMaps?

Hi guys!!! I have an issue with organizing nested StorageMaps.
I have, for example, 5 tokens (there can be from 2 to 15), and n users. I need to write a structure that would allow me to get the balance of the user and the token, something like this StorageMap<Address, StorageMap<ContractId, u64>> But the compiler swears at this. I thought, what if somehow you can get a hash from the Address - ContractId bundle and do StorageMap<Hash, u64> What is the best way to do this?

2 Likes

Example how I did it

contract;
use std::hash::sha256;

storage {
    counter: StorageMap<b256, u64> = StorageMap {},
}

abi Counter {
    #[storage(read, write)]
    fn increment(address: Address, contract_id: ContractId);
    #[storage(read)]
    fn count(address: Address, contract_id: ContractId) -> u64;
}

impl Counter for Contract {
    #[storage(read)]
    fn count(address: Address, contract_id: ContractId) -> u64 {
        let key = sha256((address, contract_id));
        storage.counter.get(key)
    }

    #[storage(read, write)]
    fn increment(address: Address, contract_id: ContractId) {
        let key = sha256((address, contract_id));
        storage.counter.insert(key, storage.counter.get(key) + 1);
    }
}

1 Like

Using a tuple of the Address and ContractId would be the preferred way to do this until nested mappings are implemented.

Use (Address, ContractId) as the key (first type)

3 Likes

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.