// File: src/CoinFlipUsa.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@chainlink/contracts/vrf/VRFConsumerBaseV2.sol";
import "@chainlink/contracts/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/shared/interfaces/LinkTokenInterface.sol";
import "./interfaces/ICoinFlipUsa.sol";

contract CoinFlipUsa is ICoinFlipUsa, VRFConsumerBaseV2, Ownable, ReentrancyGuard, Pausable {
    // The subscription ID for the Chainlink VRF service
    uint64 public immutable subscriptionId;

    // The key hash used for the Chainlink VRF service
    bytes32 public constant keyHash = 0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef;

    // The number of confirmations required for the Chainlink VRF service
    uint16 constant requestConfirmations = 3;

    // The gas limit for the Chainlink VRF callback
    uint32 constant callbackGasLimit = 1e5;

    // The number of random words requested from the Chainlink VRF service
    uint32 constant numWords = 1;

    // The token used for betting in the coin flip game
    IERC20 public immutable flipToken;

    // The interface for interacting with the Chainlink VRF Coordinator
    VRFCoordinatorV2Interface public immutable vrfCoordinatorV2;

    // The interface for interacting with the Chainlink LINK token
    LinkTokenInterface public immutable linkToken;

    // The index of the current game
    uint256 public gameIndex = 1;

    // The minimum bet size for the coin flip game, in USA tokens
    uint256 public minimumBetSize = 5 * 1e3 * 1e18;

    // The maximum allowed gas price for participating in the coin flip game
    uint256 public maxAllowedGasPrice = 20;

    // The edge multiplier for winning bets in the coin flip game
    uint256 public winMultiplierEdge = 1900;

    // The address of the player with the current longest winning streak
    address internal currentStreakWinner;

    // The length of the current longest winning streak
    uint256 internal winningStreak = 2;

    // A mapping from player addresses to their coin flip game information
    mapping(address => CoinFlipInfo) internal coinFlipInfo;

    // A mapping from Chainlink VRF request IDs to the player addresses that made the requests
    mapping(uint256 => address) internal requestIdToPlayerAddress;

    constructor(
        address _admin,
        address _vrfCoordinator,
        address _linkTokenContract,
        uint256 _subscriptionId,
        address _flipTokenAddress
    ) VRFConsumerBaseV2(_vrfCoordinator) Ownable(_admin) {
        vrfCoordinatorV2 = VRFCoordinatorV2Interface(_vrfCoordinator);
        linkToken = LinkTokenInterface(_linkTokenContract);
        flipToken = IERC20(_flipTokenAddress);
        subscriptionId = uint64(_subscriptionId);
    }

    /**
     * @notice do a coin flip for a certain amount of tokens
     * @param _flipAmount the amount of tokens to bet
     * @param _playerChoice 1 for heads, 0 for tails
     */
    function flipUsa(uint256 _flipAmount, uint8 _playerChoice) external whenNotPaused nonReentrant {
        // check if _flipAmount exceeds minimumBetSize
        require(_flipAmount >= minimumBetSize, "CoinFlipUsa: bet amount too small");

        // check if the gas price is not too high
        require(tx.gasprice <= maxAllowedGasPrice * 1e9, "CoinFlipUsa: gas price too high");

        // check if the _flipAmount is not large as the tokens balance
        require(_flipAmount <= flipToken.balanceOf(address(this)), "CoinFlipUsa: bet amount too large");

        // player can choose 1 for heads or 0 for tails
        require(_playerChoice <= 1, "CoinFlipUsa: invalid player choice");

        // check if the player has enough allowance
        require(flipToken.allowance(msg.sender, address(this)) >= _flipAmount, "CoinFlipUsa: insufficient allowance");

        // transfer tokens into contract
        require(flipToken.transferFrom(msg.sender, address(this), _flipAmount), "CoinFlipUsa: transfer failed");

        // request a random number from the VRF
        uint256 requestId_ = _requestRandomness();

        // get the CoinFlipInfo struct for the player, this could be populated or empty
        CoinFlipInfo memory coinFlipInfo_ = coinFlipInfo[msg.sender];

        // check if the player has already a game in progress, player can only have one game in progress
        require(
            coinFlipInfo_.result != FlipResult.AWAITINGRESOLUTION, "CoinFlipUsa: game already in progress - be patient"
        );

        uint256 gameIndex_ = gameIndex;

        // populate the CoinFlipInfo struct, all previous values will be overwritten except for the winningStreak

        coinFlipInfo_.betAmount = uint128(_flipAmount);
        coinFlipInfo_.gameIndex = uint32(gameIndex_);
        coinFlipInfo_.requestId = uint64(requestId_);
        coinFlipInfo_.playerChoice = _playerChoice;
        coinFlipInfo_.result = FlipResult.AWAITINGRESOLUTION;

        // save the CoinFlipInfo struct
        coinFlipInfo[msg.sender] = coinFlipInfo_;

        // save the requestId to player address mapping
        requestIdToPlayerAddress[requestId_] = msg.sender;

        gameIndex++;

        emit FlippingCoin(gameIndex_, msg.sender, _flipAmount, _playerChoice);
    }

    /**
     * @notice fulfillRandomWords is called by the VRF Coordinator
     * @param _requestId the requestId that was generated by the VRF Coordinator
     * @param _randomWords the random words that were generated by the VRF Coordinator
     */
    function fulfillRandomWords(uint256 _requestId, uint256[] memory _randomWords) internal override {
        // The first random word is taken and mod 2 is applied to get a binary result (0 or 1)
        uint256 randomResult_ = _randomWords[0] % 2;

        // Fetch the player's address using the requestId from the mapping
        address playerAddress_ = requestIdToPlayerAddress[_requestId];

        // Ensure that the player's address exists in the mapping. If it's not, revert the transaction.
        require(playerAddress_ != address(0), "CoinFlipUsa: player address not found");

        // Call the _solveGame function to determine the outcome of the game using the player's address and the random result
        _solveGame(playerAddress_, randomResult_);
    }

    function _requestRandomness() internal returns (uint256 requestId_) {
        return vrfCoordinatorV2.requestRandomWords(
            keyHash, subscriptionId, requestConfirmations, callbackGasLimit, numWords
        );
    }

    /**
     * @notice This function is used to determine the outcome of the game.
     * @param _playerAddress The address of the player who initiated the coin flip.
     * @param _randomValue The random value that was generated by the VRF Coordinator.
     */
    function _solveGame(address _playerAddress, uint256 _randomValue) internal {
        // Fetch the CoinFlipInfo for the player from the mapping.
        CoinFlipInfo memory coinFlipInfo_ = coinFlipInfo[_playerAddress];

        // Ensure that the game is still awaiting resolution. If it's not, revert the transaction.
        require(coinFlipInfo_.result == FlipResult.AWAITINGRESOLUTION, "CoinFlipUsa: game already resolved");

        // Initialize the variable to store the amount the player will win if they win the coin flip.
        uint256 winAmount_;

        // Initialize the variable to store the result of the coin flip.
        FlipResult result_;

        // If the player's choice matches the random value generated by the VRF Coordinator, the player wins.
        if (coinFlipInfo_.playerChoice == _randomValue) {
            // Increment the player's winning streak.
            coinFlipInfo_.winningStreak++;

            // Set the result to indicate that the player has won.
            result_ = FlipResult.PLAYERWINS;

            // Calculate the amount the player wins. This is their bet amount multiplied by the win multiplier edge divided by 1000.
            winAmount_ = coinFlipInfo_.betAmount * winMultiplierEdge / 1000;

            // Transfer the winning amount to the player.
            flipToken.transfer(_playerAddress, winAmount_);

            // If the player's winning streak is greater than the current winning streak, update the current winning streak and the current streak winner.
            if (coinFlipInfo_.winningStreak > winningStreak) {
                winningStreak = coinFlipInfo_.winningStreak;
                currentStreakWinner = _playerAddress;
            }
        } else {
            // If the player's choice does not match the random value, the house wins.
            // Set the result to indicate that the house has won.
            result_ = FlipResult.HOUSEWINS;

            // Reset the player's winning streak to 0.
            coinFlipInfo_.winningStreak = 0;
        }

        // Update the result in the player's CoinFlipInfo.
        coinFlipInfo_.result = result_;

        // Update the player's CoinFlipInfo in the mapping.
        coinFlipInfo[_playerAddress] = coinFlipInfo_;

        // Emit an event to log the resolution of the coin flip.
        emit CoinFlipResolved(
            coinFlipInfo_.gameIndex, _playerAddress, result_, _randomValue, winAmount_, coinFlipInfo_.winningStreak
        );
    }

    // Configuration functions

    /**
     * @notice set the minimum bet size
     * @param _minimumBetSize the minimum bet size
     */
    function setMinimumBetSize(uint256 _minimumBetSize) external onlyOwner {
        minimumBetSize = _minimumBetSize;
        emit MinimumBetSizeUpdated(_minimumBetSize);
    }

    /**
     * @notice set the win multiplier edge
     * @param _winMultiplierEdge the win multiplier edge
     */
    function setWinMultiplierEdge(uint256 _winMultiplierEdge) external onlyOwner {
        // cannot be greater as 2000 (because then the house would lose money)
        require(_winMultiplierEdge <= 2000, "CoinFlipUsa: win multiplier edge too high");
        winMultiplierEdge = _winMultiplierEdge;
        emit WinMultiplierEdgeUpdated(_winMultiplierEdge);
    }

    /**
     * @notice withdraw tokens from the contract
     * @param _tokenAddress the address of the token
     * @param _destination the address of the destination
     * @param _amount the amount of tokens to withdraw
     */
    function withdrawTokensFromContract(address _tokenAddress, address _destination, uint256 _amount)
        external
        onlyOwner
    {
        IERC20 token = IERC20(_tokenAddress);
        token.transfer(_destination, _amount);
        emit TokenWithdrawn(_tokenAddress, _amount, _destination);
    }

    /**
     * @notice set the max gas price
     * @param _maxGweiFlip the max gas price in gwei
     */
    function setMaxGweiFlip(uint256 _maxGweiFlip) external onlyOwner {
        maxAllowedGasPrice = _maxGweiFlip;
        emit MaxGweiFlipUpdated(_maxGweiFlip);
    }

    /**
     * @notice pause the contract
     */
    function pause() external onlyOwner {
        _pause();
    }

    /**
     * @notice unpause the contract
     */
    function unpause() external onlyOwner {
        _unpause();
    }

    // View functions

    /**
     * @notice return the max bet amount
     */
    function maxFlipBetAmount() public view returns (uint256) {
        return flipToken.balanceOf(address(this));
    }

    /**
     * @notice return the current game index
     */
    function returnCoinFlipInfo(address _playerAddress) external view returns (CoinFlipInfo memory info_) {
        info_ = coinFlipInfo[_playerAddress];
        require(info_.gameIndex != 0, "CoinFlipUsa: game does not exist");
    }

    /**
     * @notice return the player address by requestId
     * @param _requestId the requestId
     */
    function returnPlayerAddressByRequestId(uint256 _requestId) external view returns (address playerAddress_) {
        playerAddress_ = requestIdToPlayerAddress[_requestId];
    }

    /**
     * @notice refund a game in case of VRF request failed
     * @param _playerAddress the address of the player
     *     @dev this function can only be called by the owner
     *     @dev this function can only be called if the game is still awaiting resolution
     */
    function refundDraw(address _playerAddress) external onlyOwner {
        CoinFlipInfo memory coinFlipInfo_ = coinFlipInfo[_playerAddress];
        require(coinFlipInfo_.result == FlipResult.AWAITINGRESOLUTION, "CoinFlipUsa: game already resolved");
        coinFlipInfo_.result = FlipResult.REFUNDED;
        coinFlipInfo[_playerAddress] = coinFlipInfo_;
        // return the tokens to the player
        flipToken.transfer(_playerAddress, coinFlipInfo_.betAmount);
        emit CoinFlipRefunded(coinFlipInfo_.gameIndex, _playerAddress, coinFlipInfo_.betAmount);
    }

    /**
     * @notice return the current streak winner
     */
    function returnCurrentStreakWinner() external view returns (address currentStreakAddress_, uint256 streakCount_) {
        return (currentStreakWinner, winningStreak);
    }
}

// File: lib/openzeppelin-contracts/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @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;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    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
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // 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: lib/openzeppelin-contracts/contracts/utils/Pausable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

// File: lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

// File: lib/chainlink/contracts/src/v0.8/vrf/VRFConsumerBaseV2.sol



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

/** ****************************************************************************
 * @notice Interface for contracts using VRF randomness
 * *****************************************************************************
 * @dev PURPOSE
 *
 * @dev Reggie the Random Oracle (not his real job) wants to provide randomness
 * @dev to Vera the verifier in such a way that Vera can be sure he's not
 * @dev making his output up to suit himself. Reggie provides Vera a public key
 * @dev to which he knows the secret key. Each time Vera provides a seed to
 * @dev Reggie, he gives back a value which is computed completely
 * @dev deterministically from the seed and the secret key.
 *
 * @dev Reggie provides a proof by which Vera can verify that the output was
 * @dev correctly computed once Reggie tells it to her, but without that proof,
 * @dev the output is indistinguishable to her from a uniform random sample
 * @dev from the output space.
 *
 * @dev The purpose of this contract is to make it easy for unrelated contracts
 * @dev to talk to Vera the verifier about the work Reggie is doing, to provide
 * @dev simple access to a verifiable source of randomness. It ensures 2 things:
 * @dev 1. The fulfillment came from the VRFCoordinator
 * @dev 2. The consumer contract implements fulfillRandomWords.
 * *****************************************************************************
 * @dev USAGE
 *
 * @dev Calling contracts must inherit from VRFConsumerBase, and can
 * @dev initialize VRFConsumerBase's attributes in their constructor as
 * @dev shown:
 *
 * @dev   contract VRFConsumer {
 * @dev     constructor(<other arguments>, address _vrfCoordinator, address _link)
 * @dev       VRFConsumerBase(_vrfCoordinator) public {
 * @dev         <initialization with other arguments goes here>
 * @dev       }
 * @dev   }
 *
 * @dev The oracle will have given you an ID for the VRF keypair they have
 * @dev committed to (let's call it keyHash). Create subscription, fund it
 * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
 * @dev subscription management functions).
 * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
 * @dev callbackGasLimit, numWords),
 * @dev see (VRFCoordinatorInterface for a description of the arguments).
 *
 * @dev Once the VRFCoordinator has received and validated the oracle's response
 * @dev to your request, it will call your contract's fulfillRandomWords method.
 *
 * @dev The randomness argument to fulfillRandomWords is a set of random words
 * @dev generated from your requestId and the blockHash of the request.
 *
 * @dev If your contract could have concurrent requests open, you can use the
 * @dev requestId returned from requestRandomWords to track which response is associated
 * @dev with which randomness request.
 * @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
 * @dev if your contract could have multiple requests in flight simultaneously.
 *
 * @dev Colliding `requestId`s are cryptographically impossible as long as seeds
 * @dev differ.
 *
 * *****************************************************************************
 * @dev SECURITY CONSIDERATIONS
 *
 * @dev A method with the ability to call your fulfillRandomness method directly
 * @dev could spoof a VRF response with any random value, so it's critical that
 * @dev it cannot be directly called by anything other than this base contract
 * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
 *
 * @dev For your users to trust that your contract's random behavior is free
 * @dev from malicious interference, it's best if you can write it so that all
 * @dev behaviors implied by a VRF response are executed *during* your
 * @dev fulfillRandomness method. If your contract must store the response (or
 * @dev anything derived from it) and use it later, you must ensure that any
 * @dev user-significant behavior which depends on that stored value cannot be
 * @dev manipulated by a subsequent VRF request.
 *
 * @dev Similarly, both miners and the VRF oracle itself have some influence
 * @dev over the order in which VRF responses appear on the blockchain, so if
 * @dev your contract could have multiple VRF requests in flight simultaneously,
 * @dev you must ensure that the order in which the VRF responses arrive cannot
 * @dev be used to manipulate your contract's user-significant behavior.
 *
 * @dev Since the block hash of the block which contains the requestRandomness
 * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
 * @dev miner could, in principle, fork the blockchain to evict the block
 * @dev containing the request, forcing the request to be included in a
 * @dev different block with a different hash, and therefore a different input
 * @dev to the VRF. However, such an attack would incur a substantial economic
 * @dev cost. This cost scales with the number of blocks the VRF oracle waits
 * @dev until it calls responds to a request. It is for this reason that
 * @dev that you can signal to an oracle you'd like them to wait longer before
 * @dev responding to the request (however this is not enforced in the contract
 * @dev and so remains effective only in the case of unmodified oracle software).
 */
abstract contract VRFConsumerBaseV2 {
  error OnlyCoordinatorCanFulfill(address have, address want);
  address private immutable vrfCoordinator;

  /**
   * @param _vrfCoordinator address of VRFCoordinator contract
   */
  constructor(address _vrfCoordinator) {
    vrfCoordinator = _vrfCoordinator;
  }

  /**
   * @notice fulfillRandomness handles the VRF response. Your contract must
   * @notice implement it. See "SECURITY CONSIDERATIONS" above for important
   * @notice principles to keep in mind when implementing your fulfillRandomness
   * @notice method.
   *
   * @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
   * @dev signature, and will call it once it has verified the proof
   * @dev associated with the randomness. (It is triggered via a call to
   * @dev rawFulfillRandomness, below.)
   *
   * @param requestId The Id initially returned by requestRandomness
   * @param randomWords the VRF output expanded to the requested number of words
   */
  function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual;

  // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
  // proof. rawFulfillRandomness then calls fulfillRandomness, after validating
  // the origin of the call
  function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external {
    if (msg.sender != vrfCoordinator) {
      revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
    }
    fulfillRandomWords(requestId, randomWords);
  }
}

// File: lib/chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface VRFCoordinatorV2Interface {
  /**
   * @notice Get configuration relevant for making requests
   * @return minimumRequestConfirmations global min for request confirmations
   * @return maxGasLimit global max for request gas limit
   * @return s_provingKeyHashes list of registered key hashes
   */
  function getRequestConfig() external view returns (uint16, uint32, bytes32[] memory);

  /**
   * @notice Request a set of random words.
   * @param keyHash - Corresponds to a particular oracle job which uses
   * that key for generating the VRF proof. Different keyHash's have different gas price
   * ceilings, so you can select a specific one to bound your maximum per request cost.
   * @param subId  - The ID of the VRF subscription. Must be funded
   * with the minimum subscription balance required for the selected keyHash.
   * @param minimumRequestConfirmations - How many blocks you'd like the
   * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
   * for why you may want to request more. The acceptable range is
   * [minimumRequestBlockConfirmations, 200].
   * @param callbackGasLimit - How much gas you'd like to receive in your
   * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
   * may be slightly less than this amount because of gas used calling the function
   * (argument decoding etc.), so you may need to request slightly more than you expect
   * to have inside fulfillRandomWords. The acceptable range is
   * [0, maxGasLimit]
   * @param numWords - The number of uint256 random values you'd like to receive
   * in your fulfillRandomWords callback. Note these numbers are expanded in a
   * secure way by the VRFCoordinator from a single random value supplied by the oracle.
   * @return requestId - A unique identifier of the request. Can be used to match
   * a request to a response in fulfillRandomWords.
   */
  function requestRandomWords(
    bytes32 keyHash,
    uint64 subId,
    uint16 minimumRequestConfirmations,
    uint32 callbackGasLimit,
    uint32 numWords
  ) external returns (uint256 requestId);

  /**
   * @notice Create a VRF subscription.
   * @return subId - A unique subscription id.
   * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
   * @dev Note to fund the subscription, use transferAndCall. For example
   * @dev  LINKTOKEN.transferAndCall(
   * @dev    address(COORDINATOR),
   * @dev    amount,
   * @dev    abi.encode(subId));
   */
  function createSubscription() external returns (uint64 subId);

  /**
   * @notice Get a VRF subscription.
   * @param subId - ID of the subscription
   * @return balance - LINK balance of the subscription in juels.
   * @return reqCount - number of requests for this subscription, determines fee tier.
   * @return owner - owner of the subscription.
   * @return consumers - list of consumer address which are able to use this subscription.
   */
  function getSubscription(
    uint64 subId
  ) external view returns (uint96 balance, uint64 reqCount, address owner, address[] memory consumers);

  /**
   * @notice Request subscription owner transfer.
   * @param subId - ID of the subscription
   * @param newOwner - proposed new owner of the subscription
   */
  function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;

  /**
   * @notice Request subscription owner transfer.
   * @param subId - ID of the subscription
   * @dev will revert if original owner of subId has
   * not requested that msg.sender become the new owner.
   */
  function acceptSubscriptionOwnerTransfer(uint64 subId) external;

  /**
   * @notice Add a consumer to a VRF subscription.
   * @param subId - ID of the subscription
   * @param consumer - New consumer which can use the subscription
   */
  function addConsumer(uint64 subId, address consumer) external;

  /**
   * @notice Remove a consumer from a VRF subscription.
   * @param subId - ID of the subscription
   * @param consumer - Consumer to remove from the subscription
   */
  function removeConsumer(uint64 subId, address consumer) external;

  /**
   * @notice Cancel a subscription
   * @param subId - ID of the subscription
   * @param to - Where to send the remaining LINK to
   */
  function cancelSubscription(uint64 subId, address to) external;

  /*
   * @notice Check to see if there exists a request commitment consumers
   * for all consumers and keyhashes for a given sub.
   * @param subId - ID of the subscription
   * @return true if there exists at least one unfulfilled request for the subscription, false
   * otherwise.
   */
  function pendingRequestExists(uint64 subId) external view returns (bool);
}

// File: lib/chainlink/contracts/src/v0.8/shared/interfaces/LinkTokenInterface.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface LinkTokenInterface {
  function allowance(address owner, address spender) external view returns (uint256 remaining);

  function approve(address spender, uint256 value) external returns (bool success);

  function balanceOf(address owner) external view returns (uint256 balance);

  function decimals() external view returns (uint8 decimalPlaces);

  function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);

  function increaseApproval(address spender, uint256 subtractedValue) external;

  function name() external view returns (string memory tokenName);

  function symbol() external view returns (string memory tokenSymbol);

  function totalSupply() external view returns (uint256 totalTokensIssued);

  function transfer(address to, uint256 value) external returns (bool success);

  function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);

  function transferFrom(address from, address to, uint256 value) external returns (bool success);
}

// File: src/interfaces/ICoinFlipUsa.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;

interface ICoinFlipUsa {
    struct CoinFlipInfo {
        uint128 betAmount;
        uint32 gameIndex;
        uint64 requestId;
        uint8 playerChoice; // 1 for heads, 0 for tails
        uint8 winningStreak;
        FlipResult result;
    }

    enum FlipResult {
        NONE, // 0
        AWAITINGRESOLUTION, // 1
        PLAYERWINS, // 2
        HOUSEWINS, // 3
        REFUNDED // 4
    }

    event CoinFlipResolved(
        uint256 indexed gameIndex,
        address indexed playerAddress,
        FlipResult result,
        uint256 randomValue,
        uint256 winAmount,
        uint8 winningStreak
    );

    event TokenWithdrawn(address indexed tokenAddress, uint256 amount, address destination);

    event MinimumBetSizeUpdated(uint256 _minimumBetSize);

    event WinMultiplierEdgeUpdated(uint256 _winMultiplierEdge);

    event FlippingCoin(uint256 indexed gameIndex, address indexed playerAddress, uint256 betAmount, uint8 playerChoice);

    event CoinFlipRefunded(uint256 indexed gameIndex, address indexed playerAddress, uint256 betAmount);

    event MaxGweiFlipUpdated(uint256 _maxGweiFlip);
}

// File: lib/openzeppelin-contracts/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @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) {
        return msg.data;
    }
}