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;
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityYou can check it via .length
. It will be 0 if it is empty/uninitialised.
Countries[key].length
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 '20 at 11:39
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'