0

I'm implementing a betting smart contracts where users can stake on games and if their team won then admin pay all of the winners by calling function payoutWinners() but the problem is when I call the function payoutWinners, only the first account gets paid not the other winners. Below is the function definition and I need help on how to fix this problem or a workaround thanks

function payoutWinners(uint _gameId) public payable onlyOwner returns(bool){
    require(isValidGamesId(_gameId), "Invalid game Id provided");
    require(!isGameActive(_gameId), " You can only request payment after game is over");

    GameResults memory gameResult = gamesResults[_gameId];
    Bet[] memory allBets = gameBets[_gameId];

    for(uint i = 0; i <= allBets.length; i++){

        Bet memory bet = allBets[i];

        address staker = bet.staker;
        uint160 stakerInt = uint160(staker);
        address payable betStaker = address(stakerInt);

        require(gamersBalances[betStaker][_gameId] > 0, "Your stake cannot be  0 ");

        uint amountToPay = bet.amount * 2;
        require(!bet.paid, "Bet already paid out");

        if(bet.betOn != gameResult.won ){

            continue;

        }else{

            require(amountToPay < address(this).balance, "Inufficient balance please try again later");
            betStaker.transfer(amountToPay);
            gamersBalances[betStaker][_gameId] = 0;
            bet.paid = true;
        }
        emit BetPaid( betStaker,  amountToPay, _gameId);
        return true;
    }
}
  • 4
    You have a return at the end of the loop. – Ismael Aug 22 at 17:56
  • What he said. Also, looping like this risks blowing the block gas limit once your allBets array starts to get large. – Richard Horrocks Aug 22 at 18:21
  • Also i <= allBets.length means you'll run past the end of your array. (You want i < allBets.length.) – smarx Aug 22 at 21:21
  • @Ismael thanks for the correction – Richard Aug 23 at 20:00
  • @RichardHorrocks Yes I understand that is economically expensive if array grows, do you suggest any better ways to do this? – Richard Aug 23 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.