Is it possible to find the size of a Big_map, or to find out whether a Big_map is empty?
3 Answers
No, it's not possible due to the way bigmaps are stored on-chain, so you can't know it by asking a node or within a smart contract, but indexers generally keep track of how many entries there are in a bigmap and should have this information.
You can use this RPC endpoint to retrieve big_map size in bytes:
/chains/main/blocks/${level}/context/raw/json/big_maps/index/${big_map_id}/total_bytes
-
this is clever, do you know the size of an empty map? is it 0 or is there some sort of overhead?– 0x10Jun 27, 2022 at 4:10
If you want to know this info on-chain in another contract you can keep track of how many entries there are manually inside the contract storage on a counter variable.
Something like self.data.map_length = 0
in smartpy with a self.data.map_length += 1
whenever you add an entry (and inverse when you remove).
Then you can expose the value in an on-chain view with sp.result(self.data.map_length)
and you will be able to know the specific bigmap length from anywhere.
If you do it incorrectly there is risk of the value drifting, so make sure you do plenty of testing if you decide to go this route.