【发布时间】:2018-06-29 09:54:55
【问题描述】:
我有一种情况,我想用不重复的元素(设置相似)来完成数组,所以我编写了简单的函数以便在插入之前比较地址。
功能挺简单的,但是不行,只好求助了……先谢谢了。
// 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() 函数仅适用于第一个插入的地址
【问题讨论】:
-
哪个数组的长度是7?无论
isDuplicate()返回什么,您都追加到existingBets,因此该数组的长度应该是调用placeBet()的次数。addressIndices的长度应该是下注的唯一地址的数量。 -
更容易的是映射:
mapping(address => bool) used;,然后在placeBet()的顶部require(!used[msg.sender]); used[msg.sender] = true;。 (这是假设您不想在msg.sender重复时实际上想要添加到existingBets。) -
@smarx 首先,感谢您的努力,我真的很感激!是的,addressIndices 的长度应该是下注的唯一地址的数量。感谢您指出一个更简单的解决方案,但是,最后我需要跟踪唯一地址的长度,以便向所有获胜者发送付款(不确定这是否是最佳方案,但我必须开始有东西)。
-
所以,基本上,您的方法是有道理的,但我还需要跟踪建议映射的长度?
标签: solidity