2

I am creating smart contract where I want each account to have unique nick/name attached to address. Here is example code:

mapping (address => string) members;
function isMember() constant returns bool() {
    return members[msg.sender] != "";
}

function register(string _name) {
    if (members[msg.sender] != "") {
        throw("Already registered");
    }

    /* now check if name is already taken...
    foreach (name : members) {
        if (name == _name) {
            throw();
        }
    }
    */
}

Is it possible to utilize mapping to ensure that each nick/name entered into members is unique? Or my best course of action would be to create another property that just holds list of nicks already in use? What is better approach from gas usage standpoint (considering iterating huge lists should incur higher costs)?

5

I changed your string to bytes32 to avoid an additional challenge of doing this with strings - for more clarity.

pragma solidity ^0.4.20;

contract Checker {

    mapping (address => bytes32) members; // using bytes32 instead of string
    mapping (bytes32 => bool) isTaken;

    function isMember(address member) public view returns(bool isIndeed) {
        return (members[member] != 0);
    }

    function isSet(bytes32 name) public view returns(bool isIndeed) {
        return (isTaken[name]);
    }

    function register(bytes32 _name) public returns(bool success){
        require(members[msg.sender] == "");
        require(!isSet(_name));
        members[msg.sender] = _name;
        isTaken[_name] = true;
        return true;
    }

}

Hope it helps.

4
  • shouldn't it be "isNotSet" instead of "isSet" for the check?
    – srinivas
    Apr 20 '20 at 10:52
  • I don't think so. The default isTaken is false, so not taken. So, if isTaken[index] == false then isSet == false. It's quick little scribble so if there's a mistake, please explain. Thanks. Apr 21 '20 at 16:47
  • but wont require(isSet[_name]) fail if isSet returns false?
    – srinivas
    Apr 22 '20 at 6:20
  • 1
    Good catch. Now I see it. It should be require(!isSet(..., not set. I fixed it in the example. Apr 23 '20 at 4:56

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.