// File: /contracts/LowGasVRF2/Lean/MultiprizeLean.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";

import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import "@chainlink/contracts/src/v0.8/ConfirmedOwner.sol";

/// @title Multiprize lean contract
/// @author Luis Pando
/// @notice It consumes VRF v2 from Chainlink. It has the role
/// "operator" that is the one used by a backend app to make some calls
/// @dev It saves in an ordered array the player wallet and the current
/// entries count. So buying entries has a complexity of O(1)
/// For calculating the winners, from the huge random numbers generated by Chainlink
/// a normalized random is generated by using the module method, adding 1 to have
/// a random from 1 to entriesCount.
/// So next step is to perform a binary search on the ordered array to get the
/// winner
/// A raffle can have several prizes. So if the winner candidate has already won a prize
/// in the same raffle or is blacklisted, a new random number from the pool generated by
/// Chainlink is used to get a new winner candidate.
/// If there are no more random numbers in the pool, the algorithm will loop to the left
/// until a valid player (not a previous winner or blacklisted) is found
contract MultiprizeLean is
    AccessControl,
    ReentrancyGuard,
    VRFConsumerBaseV2,
    ConfirmedOwner
{
    ////////// CHAINLINK VRF v2 /////////////////

    VRFCoordinatorV2Interface COORDINATOR;

    // Your subscription ID.
    uint64 immutable s_subscriptionId;

    // Goerli coordinator. For other networks,
    // see https://docs.chain.link/docs/vrf-contracts/#configurations
    address immutable vrfCoordinator; // = 0x2Ca8E0C643bDe4C2E08ab1fA0da3401AdAD7734D;

    // The gas lane to use, which specifies the maximum gas price to bump to.
    // For a list of available gas lanes on each network,
    // see https://docs.chain.link/docs/vrf-contracts/#configurations
    bytes32 immutable keyHash; // = 0x79d3d8832d904592c0bf9818b621522c988bb8b0c05cdc3b15aea1b6e8db0c15;

    // Depends on the number of requested values that you want sent to the
    // fulfillRandomWords() function. Storing each word costs about 20,000 gas,
    // so 100,000 is a safe default for this example contract. Test and adjust
    // this limit based on the network that you select, the size of the request,
    // and the processing of the callback request in the fulfillRandomWords()
    // function.
    uint32 callbackGasLimit = 2500000;

    // The default is 3, but you can set this higher.
    uint16 immutable requestConfirmations = 3;

    // Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS.
    uint32 constant numWords = 20;

    address s_owner;

    uint32 constant MAX_NUM_PRIZES = 10;

    struct RequestStatus {
        bool exists; // whether a requestId exists
        uint256 id; // Metawin Id (the raffle Id)
        uint256 size; // total amount of entries. Used to normalize the random number generated
    }
    mapping(uint256 => RequestStatus) public s_requests; // map of requests sent to Chainlink

    event RequestSent(uint256 requestId, uint32 numWords);

    /////////////// END CHAINKINK VRF V2 //////////////

    error EntryNotAllowed(string errorType);

    event WinnersOfRaffle(
        uint256 indexed raffleId,
        WinnersStruct[] winnersList
    );

    event PrizePaidOutToStaker(
        uint256 indexed raffleId,
        address indexed seller,
        uint256 idPrize
    );

    // Event sent when the raffle is created by the operator
    event RaffleCreated(uint256 indexed raffleId);
    // Event sent when the owner of the nft stakes it for the raffle
    event RaffleStarted(uint256 indexed raffleId, address indexed seller);
    // Event sent when the raffle is finished (either early cashout or successful completion)
    event RaffleEnded(uint256 indexed raffleId, uint256 amountRaised);
    // Event sent a winner is calculated after doing a binary search on the entriesBought array
    event WinnerSelected(
        uint256 indexed raffleId,
        address indexed winner,
        uint256 randomNumber
    );
    // Event sent when one or more entries are sold (info from the price structure)
    event EntrySold(
        uint256 indexed raffleId,
        address indexed buyer,
        uint256 currentSize,
        uint256 priceStructureId
    );
    // Event sent when a free entry is added by the operator
    event FreeEntry(
        uint256 indexed raffleId,
        address[] buyer,
        uint256 amount,
        uint256 currentSize
    );
    // Event sent when a raffle is asked to cancel by the operator
    event RaffleCancelled(uint256 indexed raffleId, uint256 amountRaised);
    // The raffle is closed successfully and the platform receives the fee
    event FeeTransferredToPlatform(
        uint256 indexed raffleId,
        uint256 amountTransferred
    );

    event EarlyCashoutTriggered(uint256 indexed raffleId, uint256 amountRaised);
    event SetWinnerTriggered(uint256 indexed raffleId, uint256 amountRaised);
    // Emitted when an entry is cancelled
    event EntryCancelled(
        uint256 indexed raffleId,
        uint256 amountOfEntriesCanceled,
        address player
    );

    // Every raffle has a funding structure.
    struct FundingStructure {
        uint128 minimumFundsInWeis;
        uint128 desiredFundsInWeis;
    }
    mapping(uint256 => FundingStructure) public fundingList;

    struct BatchRaffleDTO {
        RaffleDTO raffleDTO;
        PriceStructure[] prices;
        PrizeStruct[] prizes;
    }

    struct RaffleDTO {
        ENTRY_TYPE entryType; // how to buy entries on the raffle. Directly, via the hamburger or both
        uint48 commissionInBasicPoints;
        uint48 maxEntriesPerUser; // maximum number of entries allowed per user, to avoid abuse
        uint48 totalEntriesCap; // Max amount of entries allowed. Some games will have only 2
        uint128 desiredFundsInWeis;
        uint128 minimumFundsInWeis;
    }

    // Main raffle data struct
    struct RaffleStruct {
        uint48 platformPercentage; // percentage of the funds raised that goes to the platform
        uint48 numOfPrizes; // amount of prizes this raffle will have
        uint48 cancellingDate; // If the raffle is cancelled, here is saved that date
    }
    // The main structure is an array of raffles
    RaffleStruct[] public raffles;
    /*  
    // Map that contains the number of entries each user has bought, to prevent abuse, and the claiming info
    struct ClaimStruct {
        uint48 numEntriesPerUser;
        bool claimed;
        uint256 amountSpentInWeis;
    }
    mapping(bytes32 => ClaimStruct) public claimsData;

    // Map with the addresses linked to a particular raffle + nft
    mapping(bytes32 => address) public requiredNFTWallets;
*/
    struct PriceStructure {
        uint256 id;
        uint48 numEntries;
        uint256 price;
    }
    mapping(uint256 => PriceStructure) public pricesList;

    struct EntryInfoStruct {
        STATUS status; // status of the raffle. Can be created, accepted, ended, etc
        ENTRY_TYPE entryType;
        uint48 entriesLength; // to easy frontend, the length of the entries array is saved here
        uint128 amountRaised; // funds raised so far in wei
    }
    // The main structure is an array of raffles
    EntryInfoStruct[] public rafflesEntryInfo;

    // All the different status a raffle can have
    enum STATUS {
        CREATED, // the operator creates the raffle
        ACCEPTED, // the seller stakes the nft for the raffle
        EARLY_CASHOUT, // the seller wants to cashout early
        CANCELLED, // the operator cancels the raffle and transfer the remaining funds after 30 days passes
        CLOSING_REQUESTED, // the operator sets a winner
        ENDED, // the raffle is finished, and NFT and funds were transferred
        CANCEL_REQUESTED // operator asks to cancel the raffle. Players has 30 days to ask for a refund
    }

    enum ENTRY_TYPE {
        ONLY_DIRECTLY,
        ONLY_EXTERNAL_CONTRACT,
        MIXED
    }

    // The operator role is operated by a backend application
    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR");
    // requested by Hamburger. Role for the buy method of the hamburger (only that contract)
    bytes32 public constant MINTERCONTRACT_ROLE = keccak256("MINTERCONTRACT");

    // address of the wallet controlled by the platform that will receive the platform fee
    address payable public destinationWallet =
        payable(0x12334d915d254F1FFD3f7ea80bB5Eba5eA87Fb36);

    ///////////////// PRIZES ////////////////
    struct PrizeStruct {
        address seller;
        address collection;
        uint48 position;
        uint48 tokenId;
        uint48 id; // id of the prize in the external system
        uint128 amount;
    }
    mapping(uint256 => PrizeStruct[MAX_NUM_PRIZES]) public prizesData;

    struct WinnersStruct {
        uint256 idPrize;
        address player;
        uint256 randomNumber;
    }
    mapping(uint256 => WinnersStruct[]) public winnersList;

    ///////////////// PRIZES ////////////////
    struct EntriesBought {
        uint48 currentEntriesLength;
        address player;
    }
    mapping(uint256 => EntriesBought[]) public entriesList;

    constructor(
        uint64 subscriptionId,
        address _vrfCoordinator,
        bytes32 _keyHash
    ) VRFConsumerBaseV2(_vrfCoordinator) ConfirmedOwner(msg.sender) {
        COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator);
        vrfCoordinator = _vrfCoordinator;
        keyHash = _keyHash;
        s_owner = msg.sender;
        s_subscriptionId = subscriptionId;

        _setupRole(OPERATOR_ROLE, msg.sender);
        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    function callVRFAndGetRequestId() internal returns (uint256 requestId) {
        requestId = COORDINATOR.requestRandomWords(
            keyHash,
            s_subscriptionId,
            requestConfirmations,
            callbackGasLimit,
            numWords
        );
        return requestId;
    }

    /// @dev this is the method that will be called by the smart contract to get a random number
    /// @param _id Id of the raffle
    /// @param _entriesSize length of the entries array of that raffle
    function getRandomNumber(
        uint256 _id,
        uint256 _entriesSize,
        uint256 requestId
    ) internal {
        s_requests[requestId] = RequestStatus({
            exists: true,
            id: _id,
            size: _entriesSize
        });

        emit RequestSent(requestId, numWords);
    }

    function fulfillRandomWords(
        uint256 _requestId,
        uint256[] memory _randomWords
    ) internal override {
        require(s_requests[_requestId].exists, "request not found");

        uint256 _raffleId = s_requests[_requestId].id;

        EntryInfoStruct storage entryInfo = rafflesEntryInfo[_raffleId];
        RaffleStruct memory raffle = raffles[_raffleId];
        // Only when the raffle has been asked to be closed and the platform
        require(
            entryInfo.status == STATUS.EARLY_CASHOUT ||
                entryInfo.status == STATUS.CLOSING_REQUESTED,
            "Raffle in wrong status"
        );
        uint256 i;
        uint256 indexRandom;
        uint256 randomNumber;
        while (i < raffle.numOfPrizes) {
            PrizeStruct memory prize = prizesData[_raffleId][i];
            address winner;

            (winner, indexRandom, randomNumber) = getWinnerAddressFromRandom(
                _raffleId,
                _randomWords,
                entryInfo.entriesLength,
                indexRandom
            );

            // Modification 8.3.2023. If there are no more players available, payout the prizes to the stakers and close.
            if (winner == address(0) && indexRandom == 0 && randomNumber == 0) {
                returnRemainingPrizesToStakers(
                    i,
                    raffle.numOfPrizes,
                    _raffleId
                );
                break;
            }
            // there is a valid winner. Transfer the prize
            else {
                if (prize.collection != address(0)) {
                    IERC721 _asset = IERC721(prize.collection);
                    _asset.transferFrom(address(this), winner, prize.tokenId); // transfer the tokens to the winner
                } else if (
                    prize.collection == address(0) && prize.amount != 0
                ) {
                    (bool sentPrize, ) = winner.call{value: prize.amount}("");
                    require(sentPrize, "Failed to send Ether");
                }
            }

            ++i;
            addToWinnersList(_raffleId, prize.id, winner, randomNumber);
        }

        // All nfts and funds transferred. Close the raffle
        entryInfo.status = STATUS.ENDED;
        uint256 amountForPlatform = (entryInfo.amountRaised *
            raffle.platformPercentage) / 10000;
        uint256 amountForSeller = entryInfo.amountRaised - amountForPlatform;
        // transfer amount (75%) to the seller.
        address seller = prizesData[_raffleId][0].seller;
        (bool sent, ) = seller.call{value: amountForSeller}("");
        // transfer the amount to the platform
        (bool sent2, ) = destinationWallet.call{value: amountForPlatform}("");
        require(sent2 && sent, "Failed send Eth");

        emit RaffleEnded(_raffleId, entryInfo.amountRaised);

        emit WinnersOfRaffle(_raffleId, getWinnersData(_raffleId));
    }

    // @notice when the raffle has more prizes than players, the method that returns a winner will
    // return (address(0), 0, 0) to indicate there are no more winners available
    // At that moment X prizes of the Y available has been transferred to the winners
    // So the Y-X remaining prizes will be paid out to the stakers
    function returnRemainingPrizesToStakers(
        uint256 _currentPrizeIndex,
        uint256 _numOfPrizes,
        uint256 _raffleId
    ) internal {
        for (; _currentPrizeIndex < _numOfPrizes; ++_currentPrizeIndex) {
            PrizeStruct memory prize = prizesData[_raffleId][
                _currentPrizeIndex
            ];
            if (prize.collection != address(0)) {
                // transfer nft back to the owner
                IERC721 _asset = IERC721(prize.collection);
                _asset.transferFrom(address(this), prize.seller, prize.tokenId);
            }

            if (prize.amount > 0) {
                (bool sentPrize, ) = prize.seller.call{value: prize.amount}("");
                require(sentPrize, "Failed to send Ether");
            }
            emit PrizePaidOutToStaker(_raffleId, prize.seller, prize.id);
        }
    }

    //////////////////////////////////////////////

    /// @dev internal method to save the prizes in the chain
    /// @param _raffleId id of the competition
    /// @param _prizes array with the prizes data
    function savePrizes(
        uint256 _raffleId,
        PrizeStruct[] calldata _prizes
    ) internal onlyRole(OPERATOR_ROLE) {
        require(_prizes.length > 0, "No prizes");
        require(_prizes.length < numWords, "Too many prizes");

        uint48 prizesLength = uint48(_prizes.length);

        for (uint256 i; i < prizesLength; ++i) {
            PrizeStruct memory p = PrizeStruct({
                seller: _prizes[i].seller,
                amount: _prizes[i].amount,
                position: _prizes[i].position,
                collection: _prizes[i].collection,
                tokenId: _prizes[i].tokenId,
                id: _prizes[i].id
            });

            prizesData[_raffleId][i] = p;
        }
        RaffleStruct storage raffle = raffles[_raffleId];
        raffle.numOfPrizes = prizesLength;
    }

    /// @notice Creates a set of competitions. A competition can have several prizes
    /// either in ETH, NFTs or a mix of both
    /// @param _batchRafflesDTO array of BatchRaffleDTO, that contains prices, prizes, required colletions, etc.
    function createRaffle(
        BatchRaffleDTO[] calldata _batchRafflesDTO
    ) external onlyRole(OPERATOR_ROLE) {
        require(_batchRafflesDTO.length > 0, "No Raffles");
        for (uint256 i; i < _batchRafflesDTO.length; ++i) {
            RaffleDTO calldata _raffleDTO = _batchRafflesDTO[i].raffleDTO;

            require(_raffleDTO.maxEntriesPerUser > 0, "maxEntries is 0");
            require(
                _raffleDTO.commissionInBasicPoints <= 5000,
                "commission too high"
            );

            RaffleStruct memory raffle = RaffleStruct({
                platformPercentage: _raffleDTO.commissionInBasicPoints,
                cancellingDate: 0,
                numOfPrizes: 0
            });

            raffles.push(raffle);

            EntryInfoStruct memory entryInfo = EntryInfoStruct({
                status: STATUS.CREATED,
                entryType: _raffleDTO.entryType,
                amountRaised: 0,
                entriesLength: 0
            });
            rafflesEntryInfo.push(entryInfo);

            uint256 idRaffle = raffles.length - 1;

            require(_batchRafflesDTO[i].prices.length > 0, "No prices");
            for (uint256 j = 0; j < _batchRafflesDTO[i].prices.length; ++j) {
                require(
                    _batchRafflesDTO[i].prices[j].numEntries > 0,
                    "numEntries is 0"
                );

                PriceStructure memory p = PriceStructure({
                    id: idRaffle,
                    numEntries: _batchRafflesDTO[i].prices[j].numEntries,
                    price: _batchRafflesDTO[i].prices[j].price
                });
                pricesList[_batchRafflesDTO[i].prices[j].id] = p;
            }

            savePrizes(idRaffle, _batchRafflesDTO[i].prizes);

            fundingList[idRaffle] = FundingStructure({
                minimumFundsInWeis: _raffleDTO.minimumFundsInWeis,
                desiredFundsInWeis: _raffleDTO.desiredFundsInWeis
            });

            EntriesBought memory entryBought = EntriesBought({
                player: address(0),
                currentEntriesLength: 0
            });
            entriesList[idRaffle].push(entryBought);
            delete entriesList[idRaffle][0];

            emit RaffleCreated(idRaffle);
        }
    }

    /// @dev Everyone can call this method, as in previous versions
    /// It stakes the prizes in the contract
    /// @param _raffleIds array with the ids of the competitions to have prizes staked
    function stake(
        uint256[] calldata _raffleIds
    ) external payable nonReentrant {
        uint256 counterETH = 0;
        uint256 raffleIDsLength = _raffleIds.length;

        for (uint256 j; j < raffleIDsLength; ++j) {
            uint256 _raffleId = _raffleIds[j];
            RaffleStruct memory raffle = raffles[_raffleId];
            EntryInfoStruct storage entryInfo = rafflesEntryInfo[_raffleId];
            uint256 numOfPrizes = raffle.numOfPrizes;
            // Check if the raffle is already created
            require(entryInfo.status == STATUS.CREATED, "Raffle not CREATED");
            // check the raffle has already the prizes set
            require(numOfPrizes > 0, "Prizes not set");

            // first, stake the nfts
            for (uint256 i; i < numOfPrizes; ++i) {
                PrizeStruct memory prize = prizesData[_raffleId][i];
                // if it is an NFT (721 only)
                if (prize.collection != address(0)) {
                    IERC721 token = IERC721(prize.collection);
                    require(
                        token.ownerOf(prize.tokenId) == msg.sender,
                        "NFT is not owned by caller"
                    );
                    token.transferFrom(
                        msg.sender,
                        address(this),
                        prize.tokenId
                    ); // transfer the token to the contract
                }
                // if the prize is ETH, sum the amount
                if (prize.amount > 0) {
                    counterETH += prize.amount;
                }
            }

            entryInfo.status = STATUS.ACCEPTED;

            emit RaffleStarted(_raffleId, msg.sender);
        }
        require(counterETH == msg.value, "ETH Prize not staked");
    }

    /// @dev callable by players. Depending on the number of entries assigned to the price structure the player buys (_id parameter)
    /// one or more entries will be assigned to the player.
    /// Also it is checked the maximum number of entries per user is not reached
    /// As the method is payable, in msg.value there will be the amount paid by the user
    /// @notice If the operator set requiredNFTs when creating the raffle, only the owners of nft on that collection can make a call to this method. This will be
    /// used for special raffles
    /// @param _raffleId: id of the raffle
    /// @param _id: id of the price structure
    function buyEntry(uint256 _raffleId, uint256 _id) external payable {
        EntryInfoStruct storage entryInfo = rafflesEntryInfo[_raffleId];
        if (entryInfo.status != STATUS.ACCEPTED)
            revert EntryNotAllowed("Not in ACCEPTED");
        if (_id == 0) revert EntryNotAllowed("howMany is 0");
        PriceStructure memory priceStruct = pricesList[_id];
        if (priceStruct.id != _raffleId)
            revert EntryNotAllowed("Id not in raffleId");
        uint48 numEntries = priceStruct.numEntries;
        if (numEntries == 0) revert EntryNotAllowed("Id not supported");
        if (msg.value != priceStruct.price)
            revert EntryNotAllowed("msg.value must be equal to the price");
        if (entryInfo.entriesLength == 0) {
            // if is the first entry, added when creating the raffle, overwrite
            entriesList[_raffleId][0].player = msg.sender;
            entriesList[_raffleId][0].currentEntriesLength =
                entryInfo.entriesLength +
                priceStruct.numEntries;
        } else {
            EntriesBought memory entryBought = EntriesBought({
                player: msg.sender,
                currentEntriesLength: entryInfo.entriesLength +
                    priceStruct.numEntries
            });
            entriesList[_raffleId].push(entryBought);
        }

        entryInfo.amountRaised += uint128(msg.value);
        // update the field entriesLength, used in frontend to avoid making extra calls
        entryInfo.entriesLength =
            entryInfo.entriesLength +
            priceStruct.numEntries;

        emit EntrySold(_raffleId, msg.sender, entryInfo.entriesLength, _id); // 2377
    }

    // The operator can add free entries to the raffle
    /// @param _raffleId Id of the raffle
    /// @param _freePlayers array of addresses corresponding to the wallet of the users that won a free entrie
    /// @dev only operator can make this call. Assigns a single entry per user, except if that user already reached the max limit of entries per user
    function giveBatchEntriesForFree(
        uint256 _raffleId,
        address[] memory _freePlayers
    ) external onlyRole(OPERATOR_ROLE) {
        require(
            rafflesEntryInfo[_raffleId].status == STATUS.ACCEPTED,
            "Raffle is not in accepted"
        );

        uint256 freePlayersLength = _freePlayers.length;
        uint48 validPlayersCount = 0;
        for (uint256 i; i < freePlayersLength; ++i) {
            address entry = _freePlayers[i];
            // add a new element to the entriesBought array.
            // as this method only adds 1 entry per call, the amountbought is always 1
            addEntriesBought(
                _raffleId,
                entry,
                rafflesEntryInfo[_raffleId].entriesLength +
                    validPlayersCount +
                    1
            );

            ++validPlayersCount;
        }

        rafflesEntryInfo[_raffleId].entriesLength =
            rafflesEntryInfo[_raffleId].entriesLength +
            validPlayersCount;

        emit FreeEntry(
            _raffleId,
            _freePlayers,
            freePlayersLength,
            rafflesEntryInfo[_raffleId].entriesLength
        );
    }

    function setCashOutActions(
        uint256 _raffleId
    ) internal returns (EntryInfoStruct memory) {
        EntryInfoStruct storage raffle = rafflesEntryInfo[_raffleId];

        FundingStructure memory funding = fundingList[_raffleId];

        address seller = prizesData[_raffleId][0].seller;
        require(seller == msg.sender, "Not the seller");
        // Check if the raffle is already accepted
        require(
            raffle.status == STATUS.ACCEPTED,
            "Raffle not in accepted status"
        );
        require(
            raffle.amountRaised >= funding.minimumFundsInWeis,
            "Not enough funds raised"
        );

        raffle.status = STATUS.EARLY_CASHOUT;

        emit EarlyCashoutTriggered(_raffleId, raffle.amountRaised);

        return raffle;
    }

    function earlyCashOut(uint256 _raffleId) external onlyRole(OPERATOR_ROLE) {
        EntryInfoStruct memory raffle = setWinnerActions(_raffleId);
        uint256 requestId = callVRFAndGetRequestId();
        getRandomNumber(_raffleId, raffle.entriesLength, requestId);
    }

    function setWinnerActions(
        uint256 _raffleId
    ) internal returns (EntryInfoStruct memory) {
        EntryInfoStruct storage raffle = rafflesEntryInfo[_raffleId];

        emit SetWinnerTriggered(_raffleId, raffle.amountRaised);

        FundingStructure memory funding = fundingList[_raffleId];
        // Check if the raffle is already accepted or is called again because early cashout failed
        require(raffle.status == STATUS.ACCEPTED, "Raffle in wrong status");
        require(
            raffle.amountRaised >= funding.minimumFundsInWeis,
            "Not enough funds raised"
        );

        require(
            funding.desiredFundsInWeis <= raffle.amountRaised,
            "Desired funds not raised"
        );
        raffle.status = STATUS.CLOSING_REQUESTED;

        return raffle;
    }

    /// @param _raffleId Id of the raffle
    /// @notice the operator finish the raffle, if the desired funds has been reached
    /// @dev it triggers Chainlink VRF2 consumer, and generates a random number that is normalized and checked that corresponds to a MW player
    function setWinner(uint256 _raffleId) external onlyRole(OPERATOR_ROLE) {
        EntryInfoStruct memory raffle = setWinnerActions(_raffleId);
        uint256 requestId = callVRFAndGetRequestId();
        getRandomNumber(_raffleId, raffle.entriesLength, requestId);
    }

    /// @param _newAddress new address of the platform
    /// @dev Change the wallet of the platform. The one that will receive the platform fee when the raffle is closed.
    /// Only the admin can change this
    function setDestinationAddress(
        address payable _newAddress
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        destinationWallet = _newAddress;
    }

    /// @param _raffleId Id of the raffle
    /// @dev The operator can cancel the raffle. The NFT is sent back to the seller
    function cancelRaffle(
        uint256 _raffleId
    ) external nonReentrant onlyRole(OPERATOR_ROLE) {
        EntryInfoStruct storage entryInfo = rafflesEntryInfo[_raffleId];
        RaffleStruct storage raffle = raffles[_raffleId];

        // Dont cancel twice, or cancel an already ended raffle
        require(
            entryInfo.status != STATUS.ENDED &&
                entryInfo.status != STATUS.CANCELLED &&
                entryInfo.status != STATUS.EARLY_CASHOUT &&
                entryInfo.status != STATUS.CLOSING_REQUESTED &&
                entryInfo.status != STATUS.CANCEL_REQUESTED,
            "Wrong status"
        );

        // only if the raffle is in accepted status the NFT is staked and could have entries sold
        if (entryInfo.status == STATUS.ACCEPTED) {
            for (uint256 i; i < raffle.numOfPrizes; ++i) {
                PrizeStruct memory prize = prizesData[_raffleId][i];
                if (prize.collection != address(0)) {
                    // transfer nft to the owner
                    IERC721 _asset = IERC721(prize.collection);
                    _asset.transferFrom(
                        address(this),
                        prize.seller,
                        prize.tokenId
                    );
                }

                if (prize.amount > 0) {
                    (bool sentPrize, ) = prize.seller.call{value: prize.amount}(
                        ""
                    );
                    require(sentPrize, "Failed to send Ether");
                }
            }
        }

        (bool sent, ) = destinationWallet.call{value: entryInfo.amountRaised}(
            ""
        );
        require(sent, "Fail send Eth to MW");

        entryInfo.status = STATUS.CANCEL_REQUESTED;
        raffle.cancellingDate = uint48(block.timestamp);

        emit RaffleCancelled(_raffleId, entryInfo.amountRaised);
    }

    function setChainlinkVRFCallbackGasLimit(
        uint32 _newLimit
    ) external onlyRole("OPERATOR") {
        callbackGasLimit = _newLimit;
    }

    /*
    // Requested by Valerio Di Napoli.
    /// @param _raffleId id of the raffle
    /// @param _amountOfEntries amount of entries. Must be lower than maxEntriesPerUser
    /// @param _player The address of the player
    /// @notice Called by other contract created by Valerio, that minted an NFT and after that call this method
    /// @dev add entries but they are free so no payable
    function createFreeEntriesFromExternalContract(
        uint256 _raffleId,
        uint48 _amountOfEntries,
        address _player
    ) external onlyRole(MINTERCONTRACT_ROLE) {
        // if can buy run this code.
        bytes32 hash = keccak256(abi.encode(_player, _raffleId));

        RaffleStruct storage raffle = raffles[_raffleId];

        require(
            raffle.entryType == ENTRY_TYPE.ONLY_EXTERNAL_CONTRACT ||
                raffle.entryType == ENTRY_TYPE.MIXED,
            "Entry type not allowed"
        );

        winnersManager.addEntriesBought(
            _raffleId,
            _player,
            raffle.entriesLength + _amountOfEntries
        );
        // update the field entriesLength.
        raffle.entriesLength += _amountOfEntries;
        //update claim data
        claimsData[hash].numEntriesPerUser += _amountOfEntries;

        address[] memory players = new address[](1);
        players[0] = _player;
        emit FreeEntry(
            _raffleId,
            players,
            _amountOfEntries,
            raffle.entriesLength
        );
    }

    function getRaffleData(
        uint256 _idRaffle
    ) external view returns (RaffleStruct memory) {
        return raffles[_idRaffle];
    }

    function raffleNotInAcceptedState(
        uint256 _raffleId
    ) external view returns (bool) {
        RaffleStruct memory raffle = raffles[_raffleId];
        return (raffle.status != STATUS.ACCEPTED);
    }

    function playerIsBlacklisted(address _player) external view returns (bool) {
        return false;
    }
    */

    function findUpperBound(
        EntriesBought[] memory array,
        uint256 element
    ) internal pure 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].currentEntriesLength > 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].currentEntriesLength == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    function getWinnerLoopingToTheLeft(
        uint256 _raffleId,
        uint256 position,
        uint256 _randomNumber
    ) internal view returns (address candidate, uint256, uint256) {
        uint256 count = 0;
        uint256 i = position;
        EntriesBought[] memory localEntriesList = entriesList[_raffleId];
        uint256 entriesLength = localEntriesList.length;

        while (count < entriesLength) {
            if (i == entriesLength) i = position - 1;
            candidate = localEntriesList[i].player;
            //   emit NewCandidate(_raffleId, candidate, i);
            if (isValidCandidate(_raffleId, candidate))
                return (candidate, i, _randomNumber);
            if (i == 0) i = entriesLength - 1;
            else i = --i;
            ++count;
        }
        //revert("All users blacklisted");
        return (address(0), 0, 0);
    }

    function getWinnerAddressFromRandom(
        uint256 _raffleId,
        uint256[] memory _randomWords,
        uint256 entriesLength,
        uint256 randomIndex
    ) internal view returns (address, uint256, uint256) {
        address candidate = address(0);
        uint256 position = 0;
        uint256 _randomNumber = (_randomWords[randomIndex] % entriesLength) + 1;

        // general case. Find a candidate not winner before and not blacklisted
        do {
            // get a new candidate
            (candidate, position) = getCandidate(_raffleId, _randomNumber);
            // check if already a previous winner or blacklisted
            if (isValidCandidate(_raffleId, candidate))
                return (candidate, randomIndex, _randomNumber);
            else {
                //    emit AlreadyWinner(_raffleId, candidate, randomIndex);
                ++randomIndex;
                // check if all the random numbers has been used or not
                if (randomIndex == _randomWords.length) {
                    //limit reached
                    //    emit LimitReached(randomIndex, position);
                    break;
                } else {
                    _randomNumber =
                        (_randomWords[randomIndex] % entriesLength) +
                        1;
                }
            }
        } while (randomIndex - 1 <= _randomWords.length);

        // if all the random words were used and no viable candidate was found, run a loop
        // through the left. Otherwise, we have a viable candidate. Return it
        return getWinnerLoopingToTheLeft(_raffleId, position, _randomNumber);
    }

    function isValidCandidate(
        uint256 _idRaffle,
        address _candidate
    ) internal view returns (bool) {
        WinnersStruct[] memory localWinnersList = winnersList[_idRaffle];
        uint256 winnersLength = localWinnersList.length;
        if (_candidate == address(0)) return false;
        for (uint256 i; i < winnersLength; ++i) {
            if (localWinnersList[i].player == _candidate) {
                return false;
            }
        }
        return true;
    }

    function getCandidate(
        uint256 _raffleId,
        uint256 _normalizedRandomNumber
    ) internal view returns (address, uint256) {
        EntriesBought[] memory localEntriesList = entriesList[_raffleId];

        uint256 position = findUpperBound(
            localEntriesList,
            _normalizedRandomNumber
        );

        return (localEntriesList[position].player, position);
    }

    function addEntriesBought(
        uint256 _raffleId,
        address _player,
        uint48 _currentEntriesLength
    ) internal {
        if (
            entriesList[_raffleId][0].currentEntriesLength == 0
        ) // if is the first entry, added when creating the raffle, overwrite
        {
            entriesList[_raffleId][0].player = _player;
            entriesList[_raffleId][0]
                .currentEntriesLength = _currentEntriesLength;
        } else {
            EntriesBought memory entryBought = EntriesBought({
                player: _player,
                currentEntriesLength: _currentEntriesLength
            });
            entriesList[_raffleId].push(entryBought);
        }
    }

    /// @dev if a player has been blacklisted, their entries must be void
    /// this has a cost in gas, but this makes cheaper in gas the callback from chainlink
    /// This method has to be called for every raffle of the blacklisted player
    /// @param _raffleId Id of the raffle
    /// @param entriesToCancel array that contains the index of the entries to cancel. 0 based
    /// @param _player blacklisted player who owns the entry to be voided

    function cancelEntry(
        uint256 _raffleId,
        uint256[] calldata entriesToCancel,
        address _player
    ) external onlyRole(OPERATOR_ROLE) {
        uint256 totalEntriesBoughtCancelled = 0;
        for (uint256 i; i < entriesToCancel.length; i++) {
            EntriesBought storage entry = entriesList[_raffleId][
                entriesToCancel[i]
            ];

            require(entry.player == _player, "Entry did not belong to player");

            entry.player = address(0);

            uint256 previousTotalEntriesLength;
            if (entriesToCancel[i] == 0) previousTotalEntriesLength = 0;
            else
                previousTotalEntriesLength = entriesList[_raffleId][
                    entriesToCancel[i] - 1
                ].currentEntriesLength;
            totalEntriesBoughtCancelled +=
                entry.currentEntriesLength -
                previousTotalEntriesLength;
        }
        emit EntryCancelled(_raffleId, totalEntriesBoughtCancelled, _player);
    }

    function addToWinnersList(
        uint256 _idRaffle,
        uint48 _idPrize,
        address _winner,
        uint256 _randomNumber
    ) internal {
        WinnersStruct memory winnerData = WinnersStruct({
            player: _winner,
            randomNumber: _randomNumber,
            idPrize: _idPrize
        });

        winnersList[_idRaffle].push(winnerData);
    }

    /// Views visible for everyone
    function getWinnersData(
        uint256 _idRaffle
    ) public view returns (WinnersStruct[] memory) {
        return winnersList[_idRaffle];
    }

    function getEntriesBought(
        uint256 _idRaffle
    ) public view returns (EntriesBought[] memory) {
        return entriesList[_idRaffle];
    }
}

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



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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @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.
        return (a & b) + (a ^ b) / 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 == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`.
        // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
        // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
        // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
        // good first aproximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1;
        uint256 x = a;
        if (x >> 128 > 0) {
            x >>= 128;
            result <<= 64;
        }
        if (x >> 64 > 0) {
            x >>= 64;
            result <<= 32;
        }
        if (x >> 32 > 0) {
            x >>= 32;
            result <<= 16;
        }
        if (x >> 16 > 0) {
            x >>= 16;
            result <<= 8;
        }
        if (x >> 8 > 0) {
            x >>= 8;
            result <<= 4;
        }
        if (x >> 4 > 0) {
            x >>= 4;
            result <<= 2;
        }
        if (x >> 2 > 0) {
            result <<= 1;
        }

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        uint256 result = sqrt(a);
        if (rounding == Rounding.Up && result * result < a) {
            result += 1;
        }
        return result;
    }
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: @openzeppelin/contracts/utils/introspection/ERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// File: @openzeppelin/contracts/utils/Strings.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

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

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// File: @openzeppelin/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

        _;

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

// File: @openzeppelin/contracts/access/IAccessControl.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

// File: @openzeppelin/contracts/access/AccessControl.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(uint160(account), 20),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}

// File: @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;
}

// File: @chainlink/contracts/src/v0.8/interfaces/OwnableInterface.sol



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

interface OwnableInterface {
  function owner() external returns (address);

  function transferOwnership(address recipient) external;

  function acceptOwnership() external;
}

// File: @chainlink/contracts/src/v0.8/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: @chainlink/contracts/src/v0.8/ConfirmedOwnerWithProposal.sol



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

import "./interfaces/OwnableInterface.sol";

/**
 * @title The ConfirmedOwner contract
 * @notice A contract with helpers for basic contract ownership.
 */
contract ConfirmedOwnerWithProposal is OwnableInterface {
  address private s_owner;
  address private s_pendingOwner;

  event OwnershipTransferRequested(address indexed from, address indexed to);
  event OwnershipTransferred(address indexed from, address indexed to);

  constructor(address newOwner, address pendingOwner) {
    require(newOwner != address(0), "Cannot set owner to zero");

    s_owner = newOwner;
    if (pendingOwner != address(0)) {
      _transferOwnership(pendingOwner);
    }
  }

  /**
   * @notice Allows an owner to begin transferring ownership to a new address,
   * pending.
   */
  function transferOwnership(address to) public override onlyOwner {
    _transferOwnership(to);
  }

  /**
   * @notice Allows an ownership transfer to be completed by the recipient.
   */
  function acceptOwnership() external override {
    require(msg.sender == s_pendingOwner, "Must be proposed owner");

    address oldOwner = s_owner;
    s_owner = msg.sender;
    s_pendingOwner = address(0);

    emit OwnershipTransferred(oldOwner, msg.sender);
  }

  /**
   * @notice Get the current owner
   */
  function owner() public view override returns (address) {
    return s_owner;
  }

  /**
   * @notice validate, transfer ownership, and emit relevant events
   */
  function _transferOwnership(address to) private {
    require(to != msg.sender, "Cannot transfer to self");

    s_pendingOwner = to;

    emit OwnershipTransferRequested(s_owner, to);
  }

  /**
   * @notice validate access
   */
  function _validateOwnership() internal view {
    require(msg.sender == s_owner, "Only callable by owner");
  }

  /**
   * @notice Reverts if called by anyone other than the contract owner.
   */
  modifier onlyOwner() {
    _validateOwnership();
    _;
  }
}

// File: @chainlink/contracts/src/v0.8/ConfirmedOwner.sol



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

import "./ConfirmedOwnerWithProposal.sol";

/**
 * @title The ConfirmedOwner contract
 * @notice A contract with helpers for basic contract ownership.
 */
contract ConfirmedOwner is ConfirmedOwnerWithProposal {
  constructor(address newOwner) ConfirmedOwnerWithProposal(newOwner, address(0)) {}
}