Blog

Complex contracts explained

Complex contracts explained:

@OpenZeppelin

BitMap:

If you are a new auditor and see the following, this might be daunting:


However, there’s no reason to be scared, let’s think about this step by step. In Solidity, a boolean value (bool) takes up a whole storage slot, which is 256 bits, even though it technically only needs a single bit. By using a bitmap, the library packs 256 boolean values into a single uint256 storage slot, greatly optimizing storage usage and, consequently, gas costs for operations. So we have 1 storage slot, which is 32 bytes/256 bits and usually we store one boolean in it. However, using the BitMap library, we are able to store 256 booleans into the same storage slot, a very gas-efficient way. This specifically works if we have sequential indexes: 0,1,2,3,4 .. 255, as they all are stored in the same storage slot (32bytes). This library looks scary because it is using bit-shifting for that purpose but in fact you simply call the “set” and “unset” functions with the corresponding BitMap storage and the index and then you can fetch the boolean for the corresponding index using the “get” function.
That's really it!