To store complicated data structures using events

Hi there, currently there is a mapping(uint256=>mapping(string=>uint256)) _idLocBal; data structure stroing the balance for an id at a location in a smart contract. And it would be usesful to be able to do simple summary statistics such as given a location, what would the average balance be, etc. It would be redundant and costly to create different mappings and run for loops on chain to get such numbers.

This is making me wonder if the best practice of maintaining such a database is to use an off-chain database in a centralized server. The database is updated constantly by listening to relevant events on the _idLocBal mapping above.

Is this how it is done for other DApps? Many thanks in advance if any practical example can be pointed to.

If you don’t need the data on-chain you should definitely do the statistics off chain.

1 Like

I distilled a guideline: any derived information can be stored off-line by emitting events. Only store raw information that cannot be derived on-chain.

Yeah I agree that’s a good general guideline. In some cases it may be possible to derive some information on-chain, but depending on the specific scenario it could be a better tradeoff to store the derived value directly.

An obvious example could be if you need the hash of a string you would store the hash directly instead of storing the string and hashing it every time. As long as you don’t need the string as well.

2 Likes