Solidity中地址的比较

Comparisson of addresses in Solidity

我有一种情况,我想用不重复的元素(设置相同)来填充数组,所以我编写了简单的函数以便在插入之前比较地址。

功能挺简单的,就是不行,只好求助了。。。先谢谢了。

// function to prevent insertion of duplicates in array
function isDuplicate() public view returns (bool){
    for(uint i = 0; i < addressIndices.length; i++){
        if(addressIndices[i] == msg.sender) return true;
        else return false;
  }
}

为了问题的完整,我会提供更多的信息:

第一:主要结构:

struct Match{
    bytes32 teamHome;
    bytes32 teamAway;
    uint teamHomeGoals;
    uint teamAwayGoals;
    uint  oddsTeamHome;
    uint  oddsTeamAway;
    uint  oddsDraw;
    uint outcome; // outcome of a match ( possible values: '1', 'X', '2', mapped to, because of uint, as: '1', '2', '3');
}
struct Bet{
    address bettor; // address a of creator of a bet;
    bytes32 name; // name in a relation with ^ a provided address;
    uint amount; // deposit on bet;
    uint bet; // match index being bet on;
    uint outcome; // bet placed on a outcome; defined as: '1', 'X', '2', mapped to, because of uint, as: '1', '2', '3';

二:下注功能。

function placeBet(bytes32 name, uint _outcome, uint desiredMatchIndex, uint _amount) public payable{
// find a way to store a bid in order to be easily searchable, in order to easily send money to winners;
    //   require(!roundEnd, "Interactions with contract are locked, be careful next time!");
    //   require(state == State.Active, "Betting is over, game have already started!");
      require(msg.value > 0, "It isn't possible to place a bet without a money ");
    if(!isDuplicate()){
        addressIndices.push(msg.sender);
    }
      existingBets[msg.sender].push(Bet({
          bettor: msg.sender,
          name: name,
          amount: _amount,
          bet: desiredMatchIndex,
          outcome: _outcome
      }));
    // emit event, finally;
}

这个问题真的很奇怪: 在我用 3 个不同的地址进行 3 次投注后,我尝试用作集合的数组长度为 7。如果功能有效,则应为 3,否则应为 9。

有什么想法吗?

编辑:isDuplicate() 函数仅适用于第一个插入的地址

当前函数从不超出数组的第一个元素。它 returns 立即 truefalse。试试这个,但正如我在评论中指出的那样,mapping 会让你避免迭代:

// function to prevent insertion of duplicates in array
function isDuplicate() public view returns (bool) {
    for(uint i = 0; i < addressIndices.length; i++){
        if(addressIndices[i] == msg.sender) return true;
    }

    return false;
}