I have a situation where i'd like to fulfill array with elements that are not duplicates ( set alike ), so I wrote simple function in order to compare addresses before insertion.
Function is quite simple, but it doesn't work, so I have to ask for help...thanks in advance.
// 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;
}
}
In order to achieve completness of question, I''ll provide you more information:
First: Main structures:
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';
Second: Function to place a bet.
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;
}
The problem is really weird: After I make 3 bets with 3 different addresses, length of my array that i am trying to use as a set, is 7. If function worked, it should be 3, if not it should be 9.
Any idea?
Edit: isDuplicate() function works only for first inserted address
existingBets
no matter whatisDuplicate()
returns, so the length of that array should be the number of timesplaceBet()
was called. The length ofaddressIndices
should be the number of unique addresses that placed a bet.mapping(address => bool) used;
and thenrequire(!used[msg.sender]); used[msg.sender] = true;
at the top ofplaceBet()
. (This is assuming you don't actually want to add toexistingBets
whenmsg.sender
is a duplicate.)