0

I've got a contract which creates another contracts and stores them in a list. How can I check that contract with specific index already exists?

import "./User.sol";

contract Main is Ownable {

    User[] private _users;

    function createUser(uint256 _id) onlyOwner external {
        // How can I check if User in list of _users??
        // I tried different approaches but it gives compilation or VM Exception while processing transaction: invalid opcode errors

        // require(address(_users[_id]) == address(0), "User already exists.");
        User user = new User(_id);

        emit UserCreated(user, _users.length);

        _users.push(user);
    }
}
1

I'm a little unsure of what you want, but assuming _id is unrelated to an item's position in the list and you require a way to enumerate the Users in the system, you probably need both an array and a mapping, i.e.:

import "./User.sol";

contract Main is Ownable {

    User[] private _users;
    mapping(uint256 => bool) userExists;

    function createUser(uint256 _id) onlyOwner external {
        require(!userExists[_id], "User already exists.");
        userExists[_id] = true;

        User user = new User(_id);

        emit UserCreated(user, _users.length);

        _users.push(user);
    }
}

If you don't need to enumerate the Users, then just a mapping (mapping(uint256 => User)) will do, as in @goodvibration's answer.

| improve this answer | |
0

Use a mapping instead of an array:

mapping (uint256 => User) private users;
uint256 private numOfUsers;

function createUser(uint256 _id) onlyOwner external {
    require(users[_id] == User(0), "User already exists");
    users[_id] = new User(_id);
    emit UserCreated(users[_id], ++numOfUsers);
}
| improve this answer | |

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.