6

I have a mapping in my smart contract with bytes32 keys and bytes values. How can I check if bytes value exists for specific key? Mapping is something like this:

mapping(bytes32 => bytes) public Countries;
1
  • ## This solution stands for bytes32: ``` Countries[_user] == "" // Returns true if Countries[_user] is not initialized ``` --- pragma solidity ^0.6.0; mapping(address => bytes32) public Countries; function isCountriesInitialized(address _user) external view returns (bool) { if (Countries[_user] == "") return false; return true; } --- I observe that on solidity v0.6.0 it may return 32 for length even though it is not mapped. Example of its returned value: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    – alper
    Jan 6, 2020 at 13:30

1 Answer 1

10

You can check it via .length. It will be 0 if it is empty/uninitialised.

Countries[key].length
1
  • 2
    On solc v.0.6.0 this actually returns True, It sees b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' as length 32 @ivicaa
    – alper
    Jan 6, 2020 at 11:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.