How to store unique value in an array using for loop in Solidity? - solidity

I want to store unique addresses in the array and then increment the count. But I am not able to do it. The count variable is not incremented and returns 0. Also redundant addresses are stored in the array.
Can you please help?
function placeBid() public payable notOwner afterStart beforeEnd returns(bool){
require(auctionState == State.Running);
uint currentBid = 0;
if(totalBidder>0)
{
currentBid = bids[msg.sender] + msg.value;
require(currentBid > highestBindingBid);
}
else{
require(msg.value > startBid && msg.value > highestBindingBid);
currentBid = msg.value;
}
bids[msg.sender] = currentBid;
for(uint i=0; i<bidders.length; i++){
if(msg.sender!=bidders[i])
bidders.push(payable(msg.sender));
totalBidder++;
}
}
highestBindingBid = currentBid;
highestBidder = payable(msg.sender);
return true;
}

An easy (and cheaper compared to your snippet) way to push only unique items to a storage array is to duplicate the values in a mapping, and then validate against the mapping.
pragma solidity ^0.8;
contract MyContract {
address payable[] public bidders;
mapping (address => bool) isBidder; // default `false`
// only add `msg.sender` to `bidders` if it's not there yet
function placeBid() public {
// check against the mapping
if (isBidder[msg.sender] == false) {
// push the unique item to the array
bidders.push(payable(msg.sender));
// don't forget to set the mapping value as well
isBidder[msg.sender] = true;
}
}
}

Related

Solidity ParseError: Expected primary expression

When I am compiling with truffle it is giving me this error
I got this error after adding payable
prior to that it was
winners[j].transfer(betwa*(10000+(LoserBet*10000/WinnerBet))/10000);
I had to add it because I was getting another error
Which was
TypeError: "send" and "transfer" are only available for objects of type "address payable", not "address".
My Complete Contract :
pragma solidity ^0.5.16;
contract Betting {
address public owner;
uint256 public minimumBet;
uint256 public totalBetsOne;
uint256 public totalBetsTwo;
address[] public players;
struct Player {
uint256 amountBet;
uint16 teamSelected;
}
// The address of the player and => the user info
mapping(address => Player) public playerInfo;
function() external payable {}
constructor() public {
owner = msg.sender;
minimumBet = 100000000000000;
}
function kill() public {
if(msg.sender == owner) selfdestruct(msg.sender);
}
function checkPlayerExists(address player) public view returns(bool){
for(uint256 i = 0; i < players.length; i++){
if(players[i] == player) return true;
}
return false;
}
function bet(uint8 _teamSelected) public payable {
//The first require is used to check if the player already exist
require(!checkPlayerExists(msg.sender));
//The second one is used to see if the value sended by the player is
//Higher than the minimum value
require(msg.value >= minimumBet);
//We set the player informations : amount of the bet and selected team
playerInfo[msg.sender].amountBet = msg.value;
playerInfo[msg.sender].teamSelected = _teamSelected;
//then we add the address of the player to the players array
players.push(msg.sender);
//at the end, we increment the stakes of the team selected with the player bet
if ( _teamSelected == 1){
totalBetsOne += msg.value;
}
else{
totalBetsTwo += msg.value;
}
}
// Generates a number between 1 and 10 that will be the winner
function distributePrizes(uint16 teamWinner) public {
address[1000] memory winners;
//We have to create a temporary in memory array with fixed size
//Let's choose 1000
uint256 count = 0; // This is the count for the array of winners
uint256 LoserBet = 0; //This will take the value of all losers bet
uint256 WinnerBet = 0; //This will take the value of all winners bet
address playerAddress;
//We loop through the player array to check who selected the winner team
for(uint256 i = 0; i < players.length; i++){
playerAddress = players[i];
//If the player selected the winner team
//We add his address to the winners array
if(playerInfo[playerAddress].teamSelected == teamWinner){
winners[count] = playerAddress;
count++;
}
}
//We define which bet sum is the Loser one and which one is the winner
if ( teamWinner == 1){
LoserBet = totalBetsTwo;
WinnerBet = totalBetsOne;
}
else{
LoserBet = totalBetsOne;
WinnerBet = totalBetsTwo;
}
//We loop through the array of winners, to give ethers to the winners
for(uint256 j = 0; j < count; j++){
// Check that the address in this fixed array is not empty
if(winners[j] != address(0)){
address add = winners[j];
uint256 betwa = playerInfo[add].amountBet;
//Transfer the money to the user
payable(winners[j]).transfer( (betwa*(10000+(LoserBet*10000/WinnerBet)))/10000 );
}
}
delete playerInfo[playerAddress]; // Delete all the players
players.length = 0; // Delete all the players array
LoserBet = 0; //reinitialize the bets
WinnerBet = 0;
totalBetsOne = 0;
totalBetsTwo = 0;
}
function AmountOne() public view returns(uint256){
return totalBetsOne;
}
function AmountTwo() public view returns(uint256){
return totalBetsTwo;
}
}
What I have tried is making the address payable in this function but It is not working I have tried to replace memory with payable but still it isn't working
My versions
Truffle v5.4.18 (core: 5.4.18)
Solidity v0.5.16 (solc-js)
Node v14.15.1
Web3.js v1.5.3
The payable() conversion from address to address payable was introduced in Solidity 0.6.
Source: https://docs.soliditylang.org/en/latest/060-breaking-changes.html#new-features
Since your contract is using (deprecated) version 0.5.16, it doesn't allow this conversion. So you need to define the winners array already as address payable:
// added `payable`
address payable[1000] memory winners;
Then you'll be able to use the .transfer() method of the address payable type:
// `winners[j]` is payable
winners[j].transfer(...);

how to add function for closing and opening bet per match smart contract?

source code:https://github.com/laronlineworld/bettingMatch/blob/main/bettingMatch.sol
How to open and close bet per match
function bet(uint16 _matchSelected, uint16 _resultSelected) public payable {
//Check if the player already exist
// require(!checkIfPlayerExists(msg.sender));
//Check if the value sended by the player is higher than the min value
require(msg.value >= minimumBet);
//Set the player informations : amount of the bet, match and result selected
playerInfo[msg.sender].amountBet = msg.value;
playerInfo[msg.sender].matchSelected = _matchSelected;
playerInfo[msg.sender].resultSelected = _resultSelected;
//Add the address of the player to the players array
players.push(msg.sender);
//Finally increment the stakes of the team selected with the player bet
if ( _resultSelected == 1){
totalBetHome[_matchSelected] += msg.value;
}
else if( _resultSelected == 2){
totalBetAway[_matchSelected] += msg.value;
}
else{
totalBetDraw[_matchSelected] += msg.value;
}
}
This is the code for opening the betting
/* Function to enable betting */
function beginVotingPeriod() public onlyOwner returns(bool) {
bettingActive = true;
return true;
}
how about opening the bet per match?
also closing the bet per match
/* Function to close voting and handle payout. Can only be called by the owner. */
function closeVoting() public onlyOwner returns (bool) {
// Close the betting period
bettingActive = false;
return true;
}
The linked code recognizes a match as index of these arrays: totalBetHome, totalBetAway and totalBetDraw.
You can add a mapping where the key is the match ID, and the value is a flag signalizing whether there's a betting enabled on the match or not.
// default value for each is `false`
mapping (uint256 => bool) isMatchEnabled;
function enableBetting(uint256 _matchId) external onlyOwner {
isBettingEnabled[_matchId] = true;
}
function disableBetting(uint256 _matchId) external onlyOwner {
isBettingEnabled[_matchId] = false;
}
Then you can amend the bet() function - add a condition requiring betting for this match to be enabled.
function bet(uint16 _matchSelected, uint16 _resultSelected) public payable {
require(isBettingEnabled[_matchSelected] == true);
// rest of your code
}
Note: Solidity v0.4.2 that you're using in the linked code, is few years old and has few security issues. The current version (August 2021) is 0.8.7. Consider upgrading to the latest version.

Solidity: Returns filtered array of structs without 'push'

I have this contract with an array of structs:
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract Tickets {
struct Ticket {
uint id;
int val;
}
Ticket[] tickets;
function addTicket(uint id, int val) public returns(bool success) {
Ticket memory newTicket;
newTicket.id = id;
newTicket.val = val;
tickets.push(newTicket);
return true;
}
function getTicket(uint id) public view returns(Ticket memory) {
uint index;
for(uint i = 0; i<tickets.length; i++){
if (tickets[i].id == id) {
index = i;
break;
}
}
Ticket memory t = tickets[index];
return t;
}
function findTickets(int val) public view returns(Ticket[] memory) {
Ticket[] memory result;
for(uint i = 0; i<tickets.length; i++){
if (tickets[i].val == val) {
result.push(tickets[i]); // HERE IS THE ERROR
}
}
return result;
}
}
I need to returns a filtered by val array but when I buil this code: result.push(tickets[i].id); it throw this error:
TypeError: Member "push" is not available in struct Tickets.Ticket memory[] memory outside of storage.
How I can implement the filter without using push ?
Returning dynamic-length array of struct is still a bit tricky in Solidity (even in the current 0.8 version). So I made a little workaround to make it work even in the 0.6.
Determine the result count, you'll need it for step 2.
Create a fixed-length array
Fill the fixed-length array
Return the fixed-length array
function findTickets(int val) public view returns(Ticket[] memory) {
uint256 resultCount;
for (uint i = 0; i < tickets.length; i++) {
if (tickets[i].val == val) {
resultCount++; // step 1 - determine the result count
}
}
Ticket[] memory result = new Ticket[](resultCount); // step 2 - create the fixed-length array
uint256 j;
for (uint i = 0; i < tickets.length; i++) {
if (tickets[i].val == val) {
result[j] = tickets[i]; // step 3 - fill the array
j++;
}
}
return result; // step 4 - return
}

If statement in for loop not filtering out items in solidity

// #param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
// #return _id - list of ids for homes
function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
uint [] results;
for(uint i = 0 ; i<homes.length; i++) {
if(keccak256(homes[i].physicalAddress) == keccak256(_physicalAddress) && homes[i].available == true) {
results.push(homes[i].id);
}
}
return results;
}
The result is supposed to be a list of ids which match the physical address entered however it does not filter through but returns all the available homes.
When I change to using String utils nothing changes.
Here is the whole code:
pragma solidity ^0.4.0;
import "browser/StringUtils.sol";
// #title HomeListing
contract HomeListing {
struct Home {
uint id;
string physicalAddress;
bool available;
}
Home[] public homes;
mapping (address => Home) hostToHome;
event HomeEvent(uint _id);
event Test(uint length);
constructor() {
}
// #param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
function addHome(string _physicalAddress) public {
uint _id = uint(keccak256(_physicalAddress, msg.sender));
homes.push(Home(_id, _physicalAddress, true));
}
// #param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
// #return _id - list of ids for homes
function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
uint [] results;
for(uint i = 0 ; i<homes.length; i++) {
string location = homes[i].physicalAddress;
if(StringUtils.equal(location,_physicalAddress )) {
results.push(homes[i].id);
}
}
return results;
}
}
The part giving you trouble is the line uint[] results;. Arrays declared as local variables reference storage memory by default. From the "What is the memory keyword" section of the Solidity docs:
There are defaults for the storage location depending on which type of variable it concerns:
state variables are always in storage
function arguments are in memory by default
local variables of struct, array or mapping type reference storage by default
local variables of value type (i.e. neither array, nor struct nor mapping) are stored in the stack
The result is you're referencing the first storage slot of your contract, which happens to be Home[] public homes. That's why you're getting the entire array back.
To fix the problem, you need to use a memory array. However, you have an additional problem in that you can't use dynamic memory arrays in Solidity. A workaround is to decide on a result size limit and declare your array statically.
Example (limited to 10 results):
function listHomesByAddress(string _physicalAddress) public view returns(uint[10]) {
uint [10] memory results;
uint j = 0;
for(uint i = 0 ; i<homes.length && j < 10; i++) {
if(keccak256(homes[i].physicalAddress) == keccak256(_physicalAddress) && homes[i].available == true) {
results[j++] = homes[i].id;
}
}
return results;
}

Add element to struct

I can't use ( push ) because it is used with state variable only
This is the error :
Error message
Is there any alternatives for ( push )
contract m{
struct Message{
address sender;
address receiver;
uint msgContent;
} // end struct
Message[] all;
function get ( address from ) internal
returns ( Message[] subMsgs){
for ( uint i=0; i<all.length ; i++)
{
if ( all[i].sender == from )
{
subMsgs.push (all[i]);
}
}
return subMsgs;
}
} // end contract
You can only use push on dynamic-size arrays (i.e. storage arrays), and not fixed-size arrays (i.e. memory arrays) (see Solidity array documentation for more info).
So to achieve what you want, you'll need to create a memory array with a desired size and assign each element one by one. Here is the example code:
contract m {
struct Message{
address sender;
address receiver;
uint msgContent;
} // end struct
Message[] all;
function get(address from) internal returns (Message[]) {
// Note: this might create an array that has more elements than needed
// if you want to optimize this, you'll need to loop through the `all` array
// to find out how many elements from the sender, and then construct the subMsg
// with the correct size
Message[] memory subMsgs = new Message[](all.length);
uint count = 0;
for (uint i=0; i<all.length ; i++)
{
if (all[i].sender == from)
{
subMsgs[count] = all[i];
count++;
}
}
return subMsgs;
}
} // end contract