0

I am creating a simple application that allows a user to set an account address as a string and return it. Part of the criteria is that each name should be unique. A user should be able to change their string if they wish. So far I have the following, which works well as far as I can see;

pragma solidity ^0.8.7;

contract Test {
    mapping(string=>address) _names;
    mapping(address=>string) _addresses;
    
    function setName(string memory name) external {
        require(_names[name]==address(0), "Duplicate name");
        
        _names[name] = msg.sender;
        _addresses[msg.sender] = name;
    }
    
    function readName() external view returns (string memory) {
        return _addresses[msg.sender];
    }
}

The problem I have is that when a user changes their account string, it does not allow the previously set string to be reused by another account (or the same account for that matter). Do I need to remove the previous string values from the mapping in order to reuse account names?

1 Answer 1

0

Yes. Try

    function setName(string memory name) external {
        require(_names[name]==address(0), "Duplicate name");

        _names[_addresses[msg.sender]] = address(0);

        _names[name] = msg.sender;
        _addresses[msg.sender] = name;
    }
1
  • This worked a treat. Thank you very much for this. Commented Nov 29, 2021 at 1:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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