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
    Commented 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
    Commented Jan 6, 2020 at 11:39

Your Answer

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

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