Solidity Mapping – How to Check for Duplicate Addresses in Mapping

addressesmappingsolidity

I want to have a mapping where it is only possible to add values when they are UNIQUE. It must not be possible to add duplicate keys, but I cannot get it working.

The code:

contract test {
    mapping(string => address) values;

    function AddValue(string randomValue) {
        require(values[randomValue] == 0x0);

        //execute transaction if randomValue doesn't exist
        //cancel transaction - payout if the randomValue exists 
    }
}

In this example I am trying to check whether the values[randomValue] is empty – doesn't exist.
If it doesn't exist the code after may execute. If it DOES exist, the code must stop.
However, I am unable to find a solution.

Best Answer

I've noticed in your example you use a string for key. Solidity uses the keccack256(key) as lookup value. So there's the case you have two different string mapping to the same value. (This is rare because it will mean you have found a collition of sha3).

If you have a mapping to a struct I'd use a boolean field to indicate an entry is used. An empty entry will such fields initially set to false.

struct Entry {
    bytes32 id;
    uint balance;
    bool used;
}

mapping (address => Entry) public collection;

function AddEntry(bytes32 _id, uint _balance) public {
    require(!collection[msg.sender].used);
    collection[msg.sender] = Entry(_id, _balance, true);
}

If you have a mapping to a value like address, you can check directly against an special value like address(0).

mapping (bytes32 => address) public users;

function AddUser(bytes32 id) public {
    require(users[id] != address(0));
    users[id] = msg.sender;
}