You are taking quiz solidityquiz.com/q/12fve. After 0 of 10 questions, you have 0.00 points.

Question #45 Difficulty: 3

According to the Solidity 0.8.17 compiler (200 optimization runs)

    // Which contract will use fewer storage slots to save the true/false value for an incremental set of key values, A, B, C, or SAME (for the same gas)?

contract A {
  mapping(uint256 => bool) values;

  function isSet(uint256 key) external view returns (bool) {
    return values[key];
  }

  function set(uint256 key, bool value) external {
    values[key] = value;
  }
}

contract B {
  mapping(uint256 => uint256) bits;

  function isSet(uint256 key) external view returns (bool) {
      uint256 _block = bits[key / 256];
      uint256 _mask = uint256(1) << uint256(key % 256);
      return _block & _mask != 0;
  }

  function set(uint256 key, bool value) external {
    if (value) {
      bits[key / 256] |= uint256(1) << uint256(key % 256);
    } else {
      bits[key / 256] &= uint256(0) << uint256(key % 256);
    }
  }
}

contract C {
  struct Packed {
    bool[32] value; // 1 packed storage slot
  }
  mapping(uint256 => Packed) internal packed;

  function isSet(uint256 key) external view returns (bool) {
      return packed[key / 32].value[key % 32];
  }

  function set(uint256 key, bool value) external {
    packed[key / 32].value[key % 32] = value;
  }
}

Hint:

A Solidity bool is 8 bits, and don't forget to consider packing values.

Answer:

Mode : Quiz

If you want to quit the current quiz and go back to training mode, click here.