1

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)?

4

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.

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.