// File: Duel.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }
}

contract Ownable is Context {
    address private _owner;
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    constructor () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    function owner() public view returns (address) {
        return _owner;
    }

    modifier onlyOwner() {
        require(_owner == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

}

contract DuelBettingContract is Ownable, ReentrancyGuard {
    using SafeMath for uint256;

    enum MatchOutcome { NOT_FINISHED, A, B }

    event NewMatchStarted();
    event BetPlaced(address indexed bettor, MatchOutcome outcome, uint256 amount);
    event OutcomeDeclared(MatchOutcome outcome);
    event WinningsDistributed(MatchOutcome winningOutcome);
    event AdminFeesWithdrawn(uint256 amount);

    struct Match {
        uint256 betA;
        uint256 betB;
        MatchOutcome outcome;
        mapping(address => uint256) betsA;
        mapping(address => uint256) betsB;
        address[] bettorsA;
        address[] bettorsB;
    }

    Match currentMatch;
    bool public matchActive = false;
    uint256 public minBetAmount = 10000000000000000; // 0.01e
    uint256 public maxBetAmount = 100000000000000000; // 0.1e
    uint256 public adminFeePercentage = 5;
    uint256 public playerLimit = 25;
    uint256 public accumulatedFees;
    MatchOutcome previousOutcome;

    mapping(address => uint256) lastParticipatedMatch;
    uint256 public currentMatchNonce = 0;

    function startNewMatch() external onlyOwner {
        require(!matchActive, "Finish the current match first");
        
        // bad code but scalable on l2 if required
        for (uint i = 0; i < currentMatch.bettorsA.length; i++) {
            delete currentMatch.betsA[currentMatch.bettorsA[i]];
            delete currentMatch.bettorsA[i];
        }
        for (uint i = 0; i < currentMatch.bettorsB.length; i++) {
            delete currentMatch.betsB[currentMatch.bettorsB[i]];
            delete currentMatch.bettorsB[i];
        }

        currentMatch.betA = 0;
        currentMatch.betB = 0;
        currentMatch.outcome = MatchOutcome.NOT_FINISHED;
        currentMatch.bettorsA = new address[](0);
        currentMatch.bettorsB = new address[](0);
        
        matchActive = true;
        currentMatchNonce = currentMatchNonce.add(1);

        emit NewMatchStarted();
    }

    function _recordBettor(address[] storage bettors, address bettor) private {
        if (lastParticipatedMatch[bettor] < currentMatchNonce) {
            bettors.push(bettor);
            lastParticipatedMatch[bettor] = currentMatchNonce;
        } else if (lastParticipatedMatch[bettor] == currentMatchNonce) {
            revert("You can only bet once per match.");
        }
    }

    function _isContract(address addr) private view returns(bool) {
        uint32 size;
        assembly { size := extcodesize(addr) }
        return size > 0;
    }

    function _betOnOutcome(MatchOutcome outcome, uint256 amount) private {
        require(!_isContract(msg.sender), "Contracts are not allowed to bet");
        require(matchActive, "No active match");
        require(amount >= minBetAmount && amount <= maxBetAmount, "Invalid bet amount");
        require(msg.value == amount, "Mismatched ether sent");

        if (outcome == MatchOutcome.A) {
            require(currentMatch.bettorsA.length < playerLimit, "Player limit reached for Outcome A");
            _recordBettor(currentMatch.bettorsA, msg.sender);
            currentMatch.betA = currentMatch.betA.add(amount);
            currentMatch.betsA[msg.sender] = currentMatch.betsA[msg.sender].add(amount);
        } else if (outcome == MatchOutcome.B) {
            require(currentMatch.bettorsB.length < playerLimit, "Player limit reached for Outcome B");
            _recordBettor(currentMatch.bettorsB, msg.sender);
            currentMatch.betB = currentMatch.betB.add(amount);
            currentMatch.betsB[msg.sender] = currentMatch.betsB[msg.sender].add(amount);
        }

        emit BetPlaced(msg.sender, outcome, amount);
    }

    function betOnOutcomeA(uint256 amount) external payable {
        _betOnOutcome(MatchOutcome.A, amount);
    }

    function betOnOutcomeB(uint256 amount) external payable {
        _betOnOutcome(MatchOutcome.B, amount);
    }

    function declareOutcome(MatchOutcome outcome) external onlyOwner {
        require(matchActive, "No active match");
        require(outcome != MatchOutcome.NOT_FINISHED, "Invalid outcome");
        require(currentMatch.bettorsA.length > 0, "No bets on Outcome A.");
        require(currentMatch.bettorsB.length > 0, "No bets on Outcome B.");
        
        currentMatch.outcome = outcome;
        previousOutcome = outcome;
        
        matchActive = false;

        emit OutcomeDeclared(outcome);
    }

    function distributeWinnings() external onlyOwner nonReentrant {
        require(!matchActive, "Match is still active");
        require(currentMatch.outcome != MatchOutcome.NOT_FINISHED, "Match hasn't finished yet");

        if (currentMatch.outcome == MatchOutcome.A) {
            uint256 adminFee = currentMatch.betB.mul(adminFeePercentage).div(100);
            accumulatedFees = accumulatedFees.add(adminFee);

            uint256 payoutPool = currentMatch.betB.sub(adminFee);
            for (uint i = 0; i < currentMatch.bettorsA.length; i++) {
                address bettor = currentMatch.bettorsA[i];
                uint256 initialBet = currentMatch.betsA[bettor];
                uint256 reward = payoutPool.mul(initialBet).div(currentMatch.betA).add(initialBet); // Added initial bet
                currentMatch.betsA[bettor] = 0; // Prevent re-entrancy
                payable(bettor).transfer(reward);
            }
        } else if (currentMatch.outcome == MatchOutcome.B) {
            uint256 adminFee = currentMatch.betA.mul(adminFeePercentage).div(100);
            accumulatedFees = accumulatedFees.add(adminFee);

            uint256 payoutPool = currentMatch.betA.sub(adminFee);
            for (uint i = 0; i < currentMatch.bettorsB.length; i++) {
                address bettor = currentMatch.bettorsB[i];
                uint256 initialBet = currentMatch.betsB[bettor];
                uint256 reward = payoutPool.mul(initialBet).div(currentMatch.betB).add(initialBet); // Added initial bet
                currentMatch.betsB[bettor] = 0; // Prevent re-entrancy
                payable(bettor).transfer(reward);
            }
        }

        emit WinningsDistributed(currentMatch.outcome);
    }

    function withdrawAccumulatedFees() external onlyOwner {
        require(accumulatedFees > 0, "No fees to withdraw");

        uint256 amount = accumulatedFees;
        accumulatedFees = 0;
        payable(owner()).transfer(amount);

        emit AdminFeesWithdrawn(amount);
    }

    function setLimits(uint256 _minBetAmount, uint256 _maxBetAmount, uint256 _playerLimit) external onlyOwner {
        require(_minBetAmount < _maxBetAmount, "Invalid bet limits");
        require(!matchActive, "Finish the current match first");
        minBetAmount = _minBetAmount;
        maxBetAmount = _maxBetAmount;
        playerLimit = _playerLimit;
    }

    function setAdminFeePercentage(uint256 _adminFeePercentage) external onlyOwner {
        require(_adminFeePercentage < 100, "Fee percentage too high");
        adminFeePercentage = _adminFeePercentage;
    }

    function getNumberOfBettors() external view returns (uint256 numBettorsA, uint256 numBettorsB) {
        numBettorsA = currentMatch.bettorsA.length;
        numBettorsB = currentMatch.bettorsB.length;
    }

    function getMatchBetAmount() external view returns (uint256 betAmountA, uint256 betAmountB) {
        betAmountA = currentMatch.betA;
        betAmountB = currentMatch.betB;
    }
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// File: @openzeppelin/contracts/utils/math/SafeMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}