Solidity

檢查契約是否存在於列表中

  • October 7, 2019

我有一個契約,它創建另一個契約並將它們儲存在一個列表中。如何檢查具有特定索引的契約是否已經存在?

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);
   }
}

我有點不確定你想要什麼,但假設_id與列表中項目的位置無關,並且你需要一種方法來列舉User系統中的 s,你可能需要一個數組和一個映射,即:

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);
   }
}

如果您不需要列舉Users,那麼只需一個映射 ( mapping(uint256 => User)) 就可以了,就像@goodvibration 的回答一樣。

使用映射而不是數組:

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);
}

引用自:https://ethereum.stackexchange.com/questions/76537