3

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;
4

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

Countries[key].length
| improve this answer | |
  • 1
    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 at 11:39
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'

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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