实体地址比较

时间:2018-06-29 09:54:55

标签: 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()函数仅适用于第一个插入的地址

2 个答案:

答案 0 :(得分:0)

isDuplicated()问题已解决->

函数isDuplicate(address _address)公共视图返回(布尔){

for(uint i = 0; i < addressIndices.length; i++){
    if(addressIndices[i] == _address) return true;
}
return false;

}

答案 1 :(得分:0)

当前函数的外观永远不会超出数组的第一个元素。它立即返回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;
}