// File: Arrays.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
   /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * `array` is expected to be sorted in ascending order, and to contain no
     * repeated elements.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        if (array.length == 0) {
            return 0;
        }

        uint256 low = 0;
        uint256 high = array.length;

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds down (it does integer division with truncation).
            if (array[mid] > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && array[low - 1] == element) {
            return low - 1;
        } else {
            return low;
        }
    }
}

// File: bettingContract.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./ERC20Snapshot.sol";
import "./Ownable.sol";
import "./ILockableERC20.sol";
import "./IRiskFreeBetting.sol";

/**
███╗   ██╗ █████╗ ████████╗██╗   ██╗██████╗ ███████╗    ██████╗  ██████╗ ██╗   ██╗    ██╗███╗   ██╗██╗   ██╗
████╗  ██║██╔══██╗╚══██╔══╝██║   ██║██╔══██╗██╔════╝    ██╔══██╗██╔═══██╗╚██╗ ██╔╝    ██║████╗  ██║██║   ██║
██╔██╗ ██║███████║   ██║   ██║   ██║██████╔╝█████╗      ██████╔╝██║   ██║ ╚████╔╝     ██║██╔██╗ ██║██║   ██║
██║╚██╗██║██╔══██║   ██║   ██║   ██║██╔══██╗██╔══╝      ██╔══██╗██║   ██║  ╚██╔╝      ██║██║╚██╗██║██║   ██║
██║ ╚████║██║  ██║   ██║   ╚██████╔╝██║  ██║███████╗    ██████╔╝╚██████╔╝   ██║       ██║██║ ╚████║╚██████╔╝
╚═╝  ╚═══╝╚═╝  ╚═╝   ╚═╝    ╚═════╝ ╚═╝  ╚═╝╚══════╝    ╚═════╝  ╚═════╝    ╚═╝       ╚═╝╚═╝  ╚═══╝ ╚═════╝ 

* @title WOOINU Betting Contract
* @author Nature Boy Inu <spaceowl.eth>
*/
contract bettingInu is
    IRiskFreeBetting,
    ERC20("Leglock", "LEG"),
    ILockableERC20,
    ERC20Snapshot,
    Ownable
{
    /**
     * @dev Modifier that check if `x` index exists by checking if the index is lower than
     * the amount of bets created, and reverts if index is 0
     * @param index: Index of the bet
     */
    modifier exists(uint256 index) {
        require(
            index < _bets.length && index != 0,
            "LEG: That bet does not exist"
        );
        _;
    }

    /**
     * @dev
     * _bets: Array of all the bets created
     * _tokenContract: The contract of the ERC20
     * _lockLength: After a user adds tokens, this defines how much those tokens will be locked for
     * _locks: A mapping of User => Timestamp of when he can unlock his tokens
     * bets_: A mapping of User => Bet index => _bet_ struct for choice and amount
     * _totalBetted: A mapping of Bet index => Choice => Total amount betted
     */
    bet__[] private _bets;
    IERC20 private _tokenContract;
    uint256 private _lockLength;
    mapping(address => _lock) private _locks;
    mapping(address => mapping(uint256 => _bet_)) private bets_;
    mapping(uint256 => mapping(uint256 => uint256)) private _totalBetted;

    /**
     * @dev Sets the token contract (ERC20) and the total amount for lock, and increases
     * the bets length by 1 using an empty bet
     */
    constructor(IERC20 __tokenContract) {
        _tokenContract = __tokenContract;
        _lockLength = 600;
        bet__ memory bet_;
        _bets.push(bet_);
    }

    /**
     * @return Returns the ERC20 being used
     */
    function tokenContract() external view override returns (IERC20) {
        return _tokenContract;
    }

    /**
     * @return Returns how much time tokens are locked for
     */
    function lockLength() external view override returns (uint256) {
        return _lockLength;
    }

    /**
     * @return The amount of decimals, the same as WOOINU
     */
    function decimals() public view virtual override returns (uint8) {
        return 9;
    }

    /**
     * @return Returns all the bets that have been done + ongoing bets.
     */
    function bets() external view override returns (bet__[] memory) {
        return _bets;
    }

    /**
     * @return The amount of tokens that have been betted on a choice
     * @param index: The index of the bet
     * @param choice: The choice of the bet
     */
    function totalBetted(uint256 index, uint256 choice)
        external
        view
        override
        returns (uint256)
    {
        require(
            choice <= _bets[index].choices && choice != 0,
            "LEG: That is not a valid bet"
        );
        return _totalBetted[index][choice];
    }

    /**
     * @return Returns a bet by its index
     * @param index: The index of the bet
     */
    function betByIndex(uint256 index)
        external
        view
        override
        returns (bet__ memory)
    {
        return _bets[index];
    }

    /**
     * @return Returns when a user can unlock his coin + the amount he has locked
     * @param user: The user to check
     */
    function lock(address user) external view override returns (_lock memory) {
        return _locks[user];
    }

    /**
     * @return Returns how much a user has betted on a bet
     * @param user: The user to check
     * @param index: The index of the bet
     */
    function betOf(address user, uint256 index)
        external
        view
        override
        returns (_bet_ memory)
    {
        return bets_[user][index];
    }

    /**
     * @dev Function that check if a user can unlock their tokens
     * @param user: The user to unlock for
     */
    function checkForUnlock(address user) internal {
        _lock memory lock_ = _locks[user];
        if (lock_.endDate <= block.timestamp && lock_.endDate != 0) {
            delete _locks[user];
            emit unlock(user, lock_.amount);
            return;
        }
    }

    /**
     * @dev Checks if user has enough unlocked LEG's and reverts
     * if he doesn't, Also unlocks if the lock has ended
     * @param user: The user to check for
     * @param amount: The amount needed for the user to have
     */
    function checkForLock(address user, uint256 amount) internal {
        // Checks for unlock
        checkForUnlock(user);
        if (_locks[user].amount != 0) {
            require(
                balanceOf(user) - _locks[user].amount >= amount,
                "LEG: You can only transfer unlocked or available LEG"
            );
        }
    }

    /**
     * @dev Checks for lock before transfering, calls checkForLock()
     * @param from: User sending the transaction
     * @param to: Not used
     * @param amount: The amount transfered
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override(ERC20, ERC20Snapshot) {
        checkForLock(from, amount);
        super._beforeTokenTransfer(from, to, amount);
    }

    /**
     * @dev Creates a bet for people to bet on and takes a snapshot of balances(See openzeppelin@ERC20Snapshot.sol) and emits betcreated
     * @param metadataURI: The URI used to check for info like image, etc.
     * @param choices: The amount of choices allowed to bet on
     * @param end: How much seconds until the betting period ends
     */
    function createBet(
        string memory metadataURI,
        uint256 end,
        uint256 choices
    ) external payable override onlyOwner {
        uint256 index = _bets.length;
        _snapshot();
        uint256 _end = block.timestamp + end;
        bet__ memory __bet;
        __bet.totalReward = msg.value;
        __bet.metadataURI = metadataURI;
        __bet.end = _end;
        __bet.choices = choices;
        _bets.push(__bet);
        emit betCreated(index, metadataURI, msg.value, _end);
    }

    /**
     * @dev Bets on a bet and emits _bet(), gets balance from snapshot. amount can be 0 to change the choice
     * @param index: The index of the bet
     * @param amount: The amount to bet on it
     * @param __bet: What to bet on
     */
    function bet(
        uint256 index,
        uint256 amount,
        uint256 __bet
    ) external override exists(index) {
        address sender = _msgSender();
        bet__ memory bet_ = _bets[index];
        _bet_ memory amountAndChoice = bets_[sender][index];
        require(
            block.timestamp < bet_.end,
            "LEG: The betting period has ended"
        );
        require(
            __bet <= bet_.choices && __bet != 0,
            "LEG: That is not a valid bet"
        );
        require(
            balanceOfAt(sender, index) - amountAndChoice.amount >= amount,
            "LEG: You do not have enough LEG"
        );
        /// @dev If its a new choice, remove from the old totalBetted and
        /// add to the new choices total betted by (old amount betted + the new amount betted)
        /// if it isn't it will just add on top of it
        if (
            __bet != amountAndChoice.choice && amountAndChoice.choice != 0
        ) {
            _totalBetted[index][amountAndChoice.choice] -= amountAndChoice.amount;
            _totalBetted[index][__bet] += (amountAndChoice.amount + amount);
        } else {
            _totalBetted[index][__bet] += amount;
        }
        bets_[sender][index].amount += amount;
        bets_[sender][index].choice = __bet;
        emit _bet(index, amount, sender, __bet);
    }

    /**
     * @dev Wraps the ERC20 and locks it.
     * Emits _deposit()
     * @param amount: Amount of tokens to wrap
     */
    function deposit(uint256 amount) external override {
        address sender = _msgSender();
        // Unlocks if it hasn't already. This would ensure that its not renewing the lock for already unlocked tokens
        checkForUnlock(sender);
        _tokenContract.transferFrom(sender, address(this), amount);
        _locks[sender] = _lock(
            _locks[sender].amount + amount,
            (block.timestamp + _lockLength)
        );
        _mint(sender, amount);
        emit _deposit(sender, amount);
    }

    /**
     * @dev Redeems the wrapped tokens for the ERC20. Emits withdrawal()
     * @param amount: Amount to redeem
     */
    function withdraw(uint256 amount) external override {
        address sender = _msgSender();
        // Using _burn() will call before token transfer, which will check for locks
        _burn(sender, amount);
        _tokenContract.transfer(sender, amount);
        emit withdrawal(sender, amount);
    }

    /**
     * @dev Public function that returns how much unclaimed rewards a user has
     * for x index, used by collectReward()
     * @param user: The user to check rewards for
     * @param index: The index of a bet to check rewards for
     * @return Amount of unclaimed ETH in wei 
     */
    function unclaimedReward(address user, uint256 index)
        public
        view
        override
        exists(index)
        returns (uint256)
    {
        bet__ memory bet_ = _bets[index];
        require(
            block.timestamp >= bet_.end,
            "LEG: The betting period has not ended"
        );
        require(
            bets_[user][index].amount != 0,
            "LEG: You have not betted on that or you have already collected the reward"
        );
        require(
            bet_.winningChoice != 0,
            "LEG: Please wait until the results of this bet have been published"
        );
        require(
            bet_.winningChoice == bets_[user][index].choice,
            "LEG: You chose the wrong choice"
        );
        return
            (bet_.totalReward * bets_[user][index].amount) /
            _totalBetted[index][bet_.winningChoice];
    }

    /**
     * @dev Collects the reward of winning a bet
     * @param index: The index of the bet to collect rewards from
     */
    function claimReward(uint256 index) external override exists(index) {
        address sender = _msgSender();
        uint256 amountToReward = unclaimedReward(sender, index);
        delete bets_[sender][index];
        payable(sender).transfer(amountToReward);
        emit rewardCollected(sender, index, amountToReward);
    }

    /**
     * @dev A command that can only be used by the owner to choose the winning choice of a bet, emits betFinalized()
     * @param index: The index of the bet to finalize
     * @param winningChoice: The winningChoice of the bet
     */
    function finalizeBet(uint256 index, uint256 winningChoice)
        external
        override
        onlyOwner
        exists(index)
    {
        require(
            _bets[index].end <= block.timestamp,
            "LEG: This bet has not ended yet"
        );
        require(
            winningChoice <= _bets[index].choices,
            "LEG: That is not a valid winning bet"
        );
        require(
            _bets[index].winningChoice == 0,
            "LEG: You have already finalized this bet"
        );
        _bets[index].winningChoice = winningChoice;
        emit betFinalized(index, winningChoice);
    }

    /**
     * @dev A command that only the the owner can call that changes how much time
     * funds are locked for
     * @param newLockLength: The new amount of time locks will be
     */
    function setLockLength(uint256 newLockLength) external onlyOwner {
        _lockLength = newLockLength;
    }

    /**
     * @dev A command that only the owner can call that changes the ERC20 being used for this contract
     * @param newContract: The new ERC20 being used
     */
    function setTokenContract(IERC20 newContract) external onlyOwner {
        _tokenContract = newContract;
    }
}

// File: Context.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

// File: Counters.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

// File: ERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./IERC20Metadata.sol";
import "./Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of returning `false` on failure. This behavior is nonetheless conventional
 * and does not conflict with the expectations of ERC20 applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping (address => uint256) private _balances;

    mapping (address => mapping (address => uint256)) private _allowances;

    mapping (address => mapping(uint256 => uint256)) private _vote;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor (string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5,05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        require(currentAllowance >= amount, "BINU: transfer amount exceeds allowance");
        unchecked {
            _approve(sender, _msgSender(), currentAllowance - amount);
        }

        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "BINU: decreased allowance below zero");
        unchecked {
            _approve(_msgSender(), spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(address sender, address recipient, uint256 amount) internal virtual {
        require(sender != address(0), "BINU: transfer from the zero address");
        require(recipient != address(0), "BINU: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "BINU: transfer amount exceeds balance");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "BINU: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "BINU: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "BINU: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "BINU: approve from the zero address");
        require(spender != address(0), "BINU: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be to transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}

// File: ERC20Snapshot.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ERC20.sol";
import "./Arrays.sol";
import "./Counters.sol";

/**
 * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
 * total supply at the time are recorded for later access.
 *
 * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
 * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
 * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
 * used to create an efficient ERC20 forking mechanism.
 *
 * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
 * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
 * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
 * and the account address.
 *
 * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it
 * return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this
 * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract.
 *
 * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient
 * alternative consider {ERC20Votes}.
 *
 * ==== Gas Costs
 *
 * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
 * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
 * smaller since identical balances in subsequent snapshots are stored as a single entry.
 *
 * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
 * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
 * transfers will have normal cost until the next snapshot, and so on.
 */

abstract contract ERC20Snapshot is ERC20 {
    // Inspired by Jordi Baylina's MiniMeToken to record historical balances:
    // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol

    using Arrays for uint256[];
    using Counters for Counters.Counter;

    // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
    // Snapshot struct, but that would impede usage of functions that work on an array.
    struct Snapshots {
        uint256[] ids;
        uint256[] values;
    }

    mapping (address => Snapshots) private _accountBalanceSnapshots;
    Snapshots private _totalSupplySnapshots;

    // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
    Counters.Counter private _currentSnapshotId;

    /**
     * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
     */
    event Snapshot(uint256 id);

    /**
     * @dev Creates a new snapshot and returns its snapshot id.
     *
     * Emits a {Snapshot} event that contains the same id.
     *
     * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
     * set of accounts, for example using {AccessControl}, or it may be open to the public.
     *
     * [WARNING]
     * ====
     * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
     * you must consider that it can potentially be used by attackers in two ways.
     *
     * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
     * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
     * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
     * section above.
     *
     * We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
     * ====
     */
    function _snapshot() internal virtual returns (uint256) {
        _currentSnapshotId.increment();

        uint256 currentId = _getCurrentSnapshotId();
        emit Snapshot(currentId);
        return currentId;
    }

    /**
     * @dev Get the current snapshotId
     */
    function _getCurrentSnapshotId() internal view virtual returns (uint256) {
        return _currentSnapshotId.current();
    }

    /**
     * @dev Retrieves the balance of `account` at the time `snapshotId` was created.
     */
    function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) {
        (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);

        return snapshotted ? value : balanceOf(account);
    }

    /**
     * @dev Retrieves the total supply at the time `snapshotId` was created.
     */
    function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) {
        (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);

        return snapshotted ? value : totalSupply();
    }

    // Update balance and/or total supply snapshots before the values are modified. This is implemented
    // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
      super._beforeTokenTransfer(from, to, amount);

      if (from == address(0)) {
        // mint
        _updateAccountSnapshot(to);
        _updateTotalSupplySnapshot();
      } else if (to == address(0)) {
        // burn
        _updateAccountSnapshot(from);
        _updateTotalSupplySnapshot();
      } else {
        // transfer
        _updateAccountSnapshot(from);
        _updateAccountSnapshot(to);
      }
    }

    function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
        private view returns (bool, uint256)
    {
        require(snapshotId > 0, "ERC20Snapshot: id is 0");
        require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id");

        // When a valid snapshot is queried, there are three possibilities:
        //  a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
        //  created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
        //  to this id is the current one.
        //  b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
        //  requested id, and its value is the one to return.
        //  c) More snapshots were created after the requested one, and the queried value was later modified. There will be
        //  no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
        //  larger than the requested one.
        //
        // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
        // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
        // exactly this.

        uint256 index = snapshots.ids.findUpperBound(snapshotId);

        if (index == snapshots.ids.length) {
            return (false, 0);
        } else {
            return (true, snapshots.values[index]);
        }
    }

    function _updateAccountSnapshot(address account) private {
        _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
    }

    function _updateTotalSupplySnapshot() private {
        _updateSnapshot(_totalSupplySnapshots, totalSupply());
    }

    function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
        uint256 currentId = _getCurrentSnapshotId();
        if (_lastSnapshotId(snapshots.ids) < currentId) {
            snapshots.ids.push(currentId);
            snapshots.values.push(currentValue);
        }
    }

    function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
        if (ids.length == 0) {
            return 0;
        } else {
            return ids[ids.length - 1];
        }
    }
}

// File: IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// File: IERC20Metadata.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: ILockableERC20.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./IWERC20.sol";

/**
 * @dev Interface for an ERC20 that locks users tokens
 * in exchange for other tokens.
 * Each time you wrap tokens, you should add a _lock struct for the user
 * and check if tokens are unlocked on withdrawal, on unlock emit unlock()
 */
interface ILockableERC20 is IWERC20 {
    /**
     * @dev Struct of a lock
     * @param amount: Amount of coins locked
     * @param endDate: The timestamp of when the coins get unlocked
     */
    struct _lock {
        uint256 amount;
        uint256 endDate;
    }

    /**
     * @dev Event emmited when a user unlocks his tokens
     * @return The user
     */
    event unlock(address user, uint256 amount);

    /**
     * @return Returns when a user can unlock his tokens + the amount he has locked
     * @param user: The user to check
     */
    function lock(address user) external view returns (_lock memory);

    /**
     * @return Returns how much time tokens are locked for
     */
    function lockLength() external view returns (uint256);
}

// File: IRiskFreeBetting.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

/**
 * @dev The interface for risk free bets
 */
interface IRiskFreeBetting {
    /**
     * @dev Event emitted when a bet is created.
     * @return The index, The URI, The reward, and The timestamp of when it ends
     */
    event betCreated(
        uint256 index,
        string metadataURI,
        uint256 reward,
        uint256 end
    );

    /**
     * @dev Event emmited when a bets result is given by the owner
     * @return The index and The winning choice
     */
    event betFinalized(uint256 index, uint256 choice);

    /**
     * @dev Event emmited when a user bets
     * @return Index of the bet, Amount betted, The user and The choice the user chose
     */
    event _bet(uint256 index, uint256 amount, address sender, uint256 choice);

    /**
     * @dev Event emmited when a user collects his reward
     * @return The user, The index of the bet, Amount rewarded
     */
    event rewardCollected(address user, uint256 index, uint256 rewardAmount);

    /**
     * @dev Struct of a bet
     * @param totalReward: The total amount of $ETH to reward to user
     * @param Choices: Amount of choices
     * @param metadataURI: A URI for a bets metadata (name, image, etc.)
     * @param end: The timestamp of when the betting period will be finished
     * @param winningChoice: After its finalized, this will show who won
     */
    struct bet__ {
        uint256 totalReward;
        uint256 choices;
        uint256 end;
        uint256 winningChoice;
        string metadataURI;
    }

    /**
     * @dev A struct to store a users bet, user to make sure the user has betted
     * to collect his reward
     * @param choice: The choice he betted
     * @param amount: Amount of tokens betted
     */
    struct _bet_ {
        uint256 choice;
        uint256 amount;
    }

    /**
     * @return Returns how much a user has betted on a bet
     * @param user: The user to check
     * @param index: The index of the bet
     */
    function betOf(address user, uint256 index)
        external
        view
        returns (_bet_ memory);

    /**
     * @return Returns all the bets that have been done + ongoing bets.
     */
    function bets() external view returns (bet__[] memory);

    /**
     * @return Returns a bet by its index
     * @param index: The index of the bet
     */
    function betByIndex(uint256 index) external view returns (bet__ memory);

    /**
     * @dev Creates a bet for people to bet on and takes a snapshot of balances(See openzeppelin@ERC20Snapshot.sol) and emits betcreated
     * @param metadataURI: The URI used to check for info like image, etc.
     * @param choices: The amount of choices allowed to bet on
     * @param end: How much seconds until the betting period ends
     */
    function createBet(
        string memory metadataURI,
        uint256 end,
        uint256 choices
    ) external payable;

    /**
     * @dev Bets on a bet and emits _bet(), gets balance from snapshot. amount can be 0 to change the choice
     * @param index: The index of the bet
     * @param amount: The amount to bet on it
     * @param __bet: What to bet on
     */
    function bet(
        uint256 index,
        uint256 amount,
        uint256 __bet
    ) external;

    /**
     * @dev Public function that returns how much unclaimed rewards a user has
     * for x index, used by collectReward()
     * @param user: The user to check rewards for
     * @param index: The index of a bet to check rewards for
     * @return Amount of unclaimed ETH in wei */
    function unclaimedReward(address user, uint256 index)
        external
        view
        returns (uint256);

    /**
     * @dev Collects the reward of winning a bet
     * @param index: The index of the bet to collect rewards from
     */
    function claimReward(uint256 index) external;

    /**
     * @dev A command that can only be used by the owner to choose the winning choice of a bet, emits betFinalized()
     * @param index: The index of the bet to finalize
     * @param winningChoice: The winningChoice of the bet
     */
    function finalizeBet(uint256 index, uint256 winningChoice) external;

     /**
     * @return The amount of tokens that have been betted on a choice
     * @param index: The index of the bet
     * @param choice: The choice of the bet
     */
     function totalBetted(uint256 index, uint256 choice) external view returns (uint256);
}

// File: IWERC20.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./IERC20.sol";

/**
 * @dev Interface for the wrapped token
 */
interface IWERC20 is IERC20 {
    /**
     * @dev Event emmited when a user deposit WOOINU
     * @return The user, the amount deposited
     */
    event _deposit(address user, uint256 amount);

    /**
     * @dev Event emmited when a user withdraws WOOINU
     * @return The user, the amount withdrawed
     */
    event withdrawal(address user, uint256 amount);

    /**
     * @return Returns the ERC20 being used
     */
    function tokenContract() external view returns (IERC20);

    /**
     * @dev Wraps the ERC20.
     * Emits _deposit()
     * @param amount: Amount of tokens to wrap
     */
    function deposit(uint256 amount) external;

    /**
     * @dev Redeems the wrapped tokens for the ERC20. Emits withdrawal()
     * @param amount: Amount to redeem
     */
    function withdraw(uint256 amount) external;
}

// File: Math.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow, so we distribute.
        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a / b + (a % b == 0 ? 0 : 1);
    }
}

// File: Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _setOwner(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _setOwner(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}