ETH Price: $3,302.22 (-1.06%)

Transaction Decoder

Block:
21274702 at Nov-26-2024 09:46:23 PM +UTC
Transaction Fee:
0.003492733214091304 ETH $11.53
Gas Used:
275,123 Gas / 12.695169848 Gwei

Emitted Events:

56 EthcoinProxy.0x6624a09eb96dea85bd37279bab3c70e7198a4bf6a00a69c9361c5b3d85e56089( 0x6624a09eb96dea85bd37279bab3c70e7198a4bf6a00a69c9361c5b3d85e56089, 0x000000000000000000000000000000000000000000000000000000000000844d, 0x000000000000000000000000689cd53d4f185a8791416a5998fa18aea661d392, 0000000000000000000000000000000000000000000000000000000000000001 )
57 EthcoinProxy.0xd8810d627023c32a6ef6e70e8a84bed7ae711b4b21bb2f4a6e8d3e812a7da0f1( 0xd8810d627023c32a6ef6e70e8a84bed7ae711b4b21bb2f4a6e8d3e812a7da0f1, 000000000000000000000000689cd53d4f185a8791416a5998fa18aea661d392, 0000000000000000000000000000000000000000000000000003328b944c4000 )
58 VRFCoordinatorV2_5.RandomWordsRequested( keyHash=C6BF2E7B88E5CFBB4946FF23AF846494AE1F3C65270B79EE7876C9AA99D3D45F, requestId=39525435580636852238227976771372404371226408791475473360083005062901930544439, preSeed=66672007868823776666916341651824574495321561040032491344096035296473397769285, subId=31214976814610593129916042500178081708484101830800464239207821191224235780954, minimumRequestConfirmations=3, callbackGasLimit=600000, numWords=1, extraArgs=0x92FD13380000000000000000000000000000000000000000000000000000000000000001, sender=RandomnessOracle )
59 EthcoinProxy.0xd11daf33317d43408335d309c76972bdb13cc2751a9eaade9d3c68c16eadcff1( 0xd11daf33317d43408335d309c76972bdb13cc2751a9eaade9d3c68c16eadcff1, 0x000000000000000000000000000000000000000000000000000000000000844d )

Account State Difference:

  Address   Before After State Difference Code
0x8e670b4d...3f99b8B83
5.492686890603475457 Eth
Nonce: 53225
5.484694157389384153 Eth
Nonce: 53226
0.007992733214091304
(beaverbuild)
16.093728442321988673 Eth16.094767177636606655 Eth0.001038735314617982
0xD7f86b4b...b7a20893a
(Chainlink: VRF Coordinator v2.5)
0xE957ea0b...38C308E29 2.2554822813934 Eth2.2599822813934 Eth0.0045

Execution Trace

ETH 0.0045 0x689cd53d4f185a8791416a5998fa18aea661d392.00010084( )
  • EthcoinProxy.CALL( )
    • Ethcoin.DELEGATECALL( )
    • ETH 0.0045 EthcoinProxy.4d474898( )
      • ETH 0.0045 Ethcoin.mine( mineCount=1 )
        • RandomnessOracle.CALL( )
          • VRFCoordinatorV2_5.requestRandomWords( req=[{name:keyHash, type:bytes32, order:1, indexed:false, value:C6BF2E7B88E5CFBB4946FF23AF846494AE1F3C65270B79EE7876C9AA99D3D45F, valueString:C6BF2E7B88E5CFBB4946FF23AF846494AE1F3C65270B79EE7876C9AA99D3D45F}, {name:subId, type:uint256, order:2, indexed:false, value:31214976814610593129916042500178081708484101830800464239207821191224235780954, valueString:31214976814610593129916042500178081708484101830800464239207821191224235780954}, {name:requestConfirmations, type:uint16, order:3, indexed:false, value:3, valueString:3}, {name:callbackGasLimit, type:uint32, order:4, indexed:false, value:600000, valueString:600000}, {name:numWords, type:uint32, order:5, indexed:false, value:1, valueString:1}, {name:extraArgs, type:bytes, order:6, indexed:false, value:0x92FD13380000000000000000000000000000000000000000000000000000000000000001, valueString:0x92FD13380000000000000000000000000000000000000000000000000000000000000001}] ) => ( requestId=39525435580636852238227976771372404371226408791475473360083005062901930544439 )
            File 1 of 4: EthcoinProxy
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.13;
            import "../lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol";
            contract EthcoinProxy is ERC1967Proxy {
                constructor(address _logic, bytes memory _data) ERC1967Proxy(_logic, _data) {}
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)
            pragma solidity ^0.8.20;
            import {Proxy} from "../Proxy.sol";
            import {ERC1967Utils} from "./ERC1967Utils.sol";
            /**
             * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
             * implementation address that can be changed. This address is stored in storage in the location specified by
             * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
             * implementation behind the proxy.
             */
            contract ERC1967Proxy is Proxy {
                /**
                 * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
                 *
                 * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
                 * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
                 *
                 * Requirements:
                 *
                 * - If `data` is empty, `msg.value` must be zero.
                 */
                constructor(address implementation, bytes memory _data) payable {
                    ERC1967Utils.upgradeToAndCall(implementation, _data);
                }
                /**
                 * @dev Returns the current implementation address.
                 *
                 * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
                 * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                 * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
                 */
                function _implementation() internal view virtual override returns (address) {
                    return ERC1967Utils.getImplementation();
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
            pragma solidity ^0.8.20;
            /**
             * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
             * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
             * be specified by overriding the virtual {_implementation} function.
             *
             * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
             * different contract through the {_delegate} function.
             *
             * The success and return data of the delegated call will be returned back to the caller of the proxy.
             */
            abstract contract Proxy {
                /**
                 * @dev Delegates the current call to `implementation`.
                 *
                 * This function does not return to its internal call site, it will return directly to the external caller.
                 */
                function _delegate(address implementation) internal virtual {
                    assembly {
                        // Copy msg.data. We take full control of memory in this inline assembly
                        // block because it will not return to Solidity code. We overwrite the
                        // Solidity scratch pad at memory position 0.
                        calldatacopy(0, 0, calldatasize())
                        // Call the implementation.
                        // out and outsize are 0 because we don't know the size yet.
                        let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                        // Copy the returned data.
                        returndatacopy(0, 0, returndatasize())
                        switch result
                        // delegatecall returns 0 on error.
                        case 0 {
                            revert(0, returndatasize())
                        }
                        default {
                            return(0, returndatasize())
                        }
                    }
                }
                /**
                 * @dev This is a virtual function that should be overridden so it returns the address to which the fallback
                 * function and {_fallback} should delegate.
                 */
                function _implementation() internal view virtual returns (address);
                /**
                 * @dev Delegates the current call to the address returned by `_implementation()`.
                 *
                 * This function does not return to its internal call site, it will return directly to the external caller.
                 */
                function _fallback() internal virtual {
                    _delegate(_implementation());
                }
                /**
                 * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
                 * function in the contract matches the call data.
                 */
                fallback() external payable virtual {
                    _fallback();
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
            pragma solidity ^0.8.20;
            import {IBeacon} from "../beacon/IBeacon.sol";
            import {Address} from "../../utils/Address.sol";
            import {StorageSlot} from "../../utils/StorageSlot.sol";
            /**
             * @dev This abstract contract provides getters and event emitting update functions for
             * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
             */
            library ERC1967Utils {
                // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
                // This will be fixed in Solidity 0.8.21. At that point we should remove these events.
                /**
                 * @dev Emitted when the implementation is upgraded.
                 */
                event Upgraded(address indexed implementation);
                /**
                 * @dev Emitted when the admin account has changed.
                 */
                event AdminChanged(address previousAdmin, address newAdmin);
                /**
                 * @dev Emitted when the beacon is changed.
                 */
                event BeaconUpgraded(address indexed beacon);
                /**
                 * @dev Storage slot with the address of the current implementation.
                 * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
                 */
                // solhint-disable-next-line private-vars-leading-underscore
                bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                /**
                 * @dev The `implementation` of the proxy is invalid.
                 */
                error ERC1967InvalidImplementation(address implementation);
                /**
                 * @dev The `admin` of the proxy is invalid.
                 */
                error ERC1967InvalidAdmin(address admin);
                /**
                 * @dev The `beacon` of the proxy is invalid.
                 */
                error ERC1967InvalidBeacon(address beacon);
                /**
                 * @dev An upgrade function sees `msg.value > 0` that may be lost.
                 */
                error ERC1967NonPayable();
                /**
                 * @dev Returns the current implementation address.
                 */
                function getImplementation() internal view returns (address) {
                    return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
                }
                /**
                 * @dev Stores a new address in the EIP1967 implementation slot.
                 */
                function _setImplementation(address newImplementation) private {
                    if (newImplementation.code.length == 0) {
                        revert ERC1967InvalidImplementation(newImplementation);
                    }
                    StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
                }
                /**
                 * @dev Performs implementation upgrade with additional setup call if data is nonempty.
                 * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
                 * to avoid stuck value in the contract.
                 *
                 * Emits an {IERC1967-Upgraded} event.
                 */
                function upgradeToAndCall(address newImplementation, bytes memory data) internal {
                    _setImplementation(newImplementation);
                    emit Upgraded(newImplementation);
                    if (data.length > 0) {
                        Address.functionDelegateCall(newImplementation, data);
                    } else {
                        _checkNonPayable();
                    }
                }
                /**
                 * @dev Storage slot with the admin of the contract.
                 * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
                 */
                // solhint-disable-next-line private-vars-leading-underscore
                bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                /**
                 * @dev Returns the current admin.
                 *
                 * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
                 * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                 * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
                 */
                function getAdmin() internal view returns (address) {
                    return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
                }
                /**
                 * @dev Stores a new address in the EIP1967 admin slot.
                 */
                function _setAdmin(address newAdmin) private {
                    if (newAdmin == address(0)) {
                        revert ERC1967InvalidAdmin(address(0));
                    }
                    StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
                }
                /**
                 * @dev Changes the admin of the proxy.
                 *
                 * Emits an {IERC1967-AdminChanged} event.
                 */
                function changeAdmin(address newAdmin) internal {
                    emit AdminChanged(getAdmin(), newAdmin);
                    _setAdmin(newAdmin);
                }
                /**
                 * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
                 * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
                 */
                // solhint-disable-next-line private-vars-leading-underscore
                bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
                /**
                 * @dev Returns the current beacon.
                 */
                function getBeacon() internal view returns (address) {
                    return StorageSlot.getAddressSlot(BEACON_SLOT).value;
                }
                /**
                 * @dev Stores a new beacon in the EIP1967 beacon slot.
                 */
                function _setBeacon(address newBeacon) private {
                    if (newBeacon.code.length == 0) {
                        revert ERC1967InvalidBeacon(newBeacon);
                    }
                    StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
                    address beaconImplementation = IBeacon(newBeacon).implementation();
                    if (beaconImplementation.code.length == 0) {
                        revert ERC1967InvalidImplementation(beaconImplementation);
                    }
                }
                /**
                 * @dev Change the beacon and trigger a setup call if data is nonempty.
                 * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
                 * to avoid stuck value in the contract.
                 *
                 * Emits an {IERC1967-BeaconUpgraded} event.
                 *
                 * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
                 * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
                 * efficiency.
                 */
                function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
                    _setBeacon(newBeacon);
                    emit BeaconUpgraded(newBeacon);
                    if (data.length > 0) {
                        Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                    } else {
                        _checkNonPayable();
                    }
                }
                /**
                 * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
                 * if an upgrade doesn't perform an initialization call.
                 */
                function _checkNonPayable() private {
                    if (msg.value > 0) {
                        revert ERC1967NonPayable();
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
            pragma solidity ^0.8.20;
            /**
             * @dev This is the interface that {BeaconProxy} expects of its beacon.
             */
            interface IBeacon {
                /**
                 * @dev Must return an address that can be used as a delegate call target.
                 *
                 * {UpgradeableBeacon} will check that this address is a contract.
                 */
                function implementation() external view returns (address);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
            pragma solidity ^0.8.20;
            /**
             * @dev Collection of functions related to the address type
             */
            library Address {
                /**
                 * @dev The ETH balance of the account is not enough to perform the operation.
                 */
                error AddressInsufficientBalance(address account);
                /**
                 * @dev There's no code at `target` (it is not a contract).
                 */
                error AddressEmptyCode(address target);
                /**
                 * @dev A call to an address target failed. The target may have reverted.
                 */
                error FailedInnerCall();
                /**
                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                 * `recipient`, forwarding all available gas and reverting on errors.
                 *
                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                 * imposed by `transfer`, making them unable to receive funds via
                 * `transfer`. {sendValue} removes this limitation.
                 *
                 * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                 *
                 * IMPORTANT: because control is transferred to `recipient`, care must be
                 * taken to not create reentrancy vulnerabilities. Consider using
                 * {ReentrancyGuard} or the
                 * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    if (address(this).balance < amount) {
                        revert AddressInsufficientBalance(address(this));
                    }
                    (bool success, ) = recipient.call{value: amount}("");
                    if (!success) {
                        revert FailedInnerCall();
                    }
                }
                /**
                 * @dev Performs a Solidity function call using a low level `call`. A
                 * plain `call` is an unsafe replacement for a function call: use this
                 * function instead.
                 *
                 * If `target` reverts with a revert reason or custom error, it is bubbled
                 * up by this function (like regular Solidity function calls). However, if
                 * the call reverted with no returned reason, this function reverts with a
                 * {FailedInnerCall} error.
                 *
                 * Returns the raw returned data. To convert to the expected return value,
                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                 *
                 * Requirements:
                 *
                 * - `target` must be a contract.
                 * - calling `target` with `data` must not revert.
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but also transferring `value` wei to `target`.
                 *
                 * Requirements:
                 *
                 * - the calling contract must have an ETH balance of at least `value`.
                 * - the called Solidity function must be `payable`.
                 */
                function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                    if (address(this).balance < value) {
                        revert AddressInsufficientBalance(address(this));
                    }
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResultFromTarget(target, success, returndata);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResultFromTarget(target, success, returndata);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a delegate call.
                 */
                function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.delegatecall(data);
                    return verifyCallResultFromTarget(target, success, returndata);
                }
                /**
                 * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
                 * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
                 * unsuccessful call.
                 */
                function verifyCallResultFromTarget(
                    address target,
                    bool success,
                    bytes memory returndata
                ) internal view returns (bytes memory) {
                    if (!success) {
                        _revert(returndata);
                    } else {
                        // only check if target is a contract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        if (returndata.length == 0 && target.code.length == 0) {
                            revert AddressEmptyCode(target);
                        }
                        return returndata;
                    }
                }
                /**
                 * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
                 * revert reason or with a default {FailedInnerCall} error.
                 */
                function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
                    if (!success) {
                        _revert(returndata);
                    } else {
                        return returndata;
                    }
                }
                /**
                 * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
                 */
                function _revert(bytes memory returndata) private pure {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert FailedInnerCall();
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
            // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
            pragma solidity ^0.8.20;
            /**
             * @dev Library for reading and writing primitive types to specific storage slots.
             *
             * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
             * This library helps with reading and writing to such slots without the need for inline assembly.
             *
             * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
             *
             * Example usage to set ERC1967 implementation slot:
             * ```solidity
             * contract ERC1967 {
             *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
             *
             *     function _getImplementation() internal view returns (address) {
             *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
             *     }
             *
             *     function _setImplementation(address newImplementation) internal {
             *         require(newImplementation.code.length > 0);
             *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
             *     }
             * }
             * ```
             */
            library StorageSlot {
                struct AddressSlot {
                    address value;
                }
                struct BooleanSlot {
                    bool value;
                }
                struct Bytes32Slot {
                    bytes32 value;
                }
                struct Uint256Slot {
                    uint256 value;
                }
                struct StringSlot {
                    string value;
                }
                struct BytesSlot {
                    bytes value;
                }
                /**
                 * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                 */
                function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                 */
                function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                 */
                function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                 */
                function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `StringSlot` with member `value` located at `slot`.
                 */
                function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
                 */
                function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := store.slot
                    }
                }
                /**
                 * @dev Returns an `BytesSlot` with member `value` located at `slot`.
                 */
                function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
                 */
                function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := store.slot
                    }
                }
            }
            

            File 2 of 4: VRFCoordinatorV2_5
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.9;
            import {ArbSys} from "./vendor/@arbitrum/nitro-contracts/src/precompiles/ArbSys.sol";
            import {ArbGasInfo} from "./vendor/@arbitrum/nitro-contracts/src/precompiles/ArbGasInfo.sol";
            import {OVM_GasPriceOracle} from "./vendor/@eth-optimism/contracts/v0.8.9/contracts/L2/predeploys/OVM_GasPriceOracle.sol";
            /// @dev A library that abstracts out opcodes that behave differently across chains.
            /// @dev The methods below return values that are pertinent to the given chain.
            /// @dev For instance, ChainSpecificUtil.getBlockNumber() returns L2 block number in L2 chains
            library ChainSpecificUtil {
              // ------------ Start Arbitrum Constants ------------
              /// @dev ARBSYS_ADDR is the address of the ArbSys precompile on Arbitrum.
              /// @dev reference: https://github.com/OffchainLabs/nitro/blob/v2.0.14/contracts/src/precompiles/ArbSys.sol#L10
              address private constant ARBSYS_ADDR = address(0x0000000000000000000000000000000000000064);
              ArbSys private constant ARBSYS = ArbSys(ARBSYS_ADDR);
              /// @dev ARBGAS_ADDR is the address of the ArbGasInfo precompile on Arbitrum.
              /// @dev reference: https://github.com/OffchainLabs/nitro/blob/v2.0.14/contracts/src/precompiles/ArbGasInfo.sol#L10
              address private constant ARBGAS_ADDR = address(0x000000000000000000000000000000000000006C);
              ArbGasInfo private constant ARBGAS = ArbGasInfo(ARBGAS_ADDR);
              uint256 private constant ARB_MAINNET_CHAIN_ID = 42161;
              uint256 private constant ARB_GOERLI_TESTNET_CHAIN_ID = 421613;
              uint256 private constant ARB_SEPOLIA_TESTNET_CHAIN_ID = 421614;
              // ------------ End Arbitrum Constants ------------
              // ------------ Start Optimism Constants ------------
              /// @dev L1_FEE_DATA_PADDING includes 35 bytes for L1 data padding for Optimism
              bytes internal constant L1_FEE_DATA_PADDING =
                "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
              /// @dev OVM_GASPRICEORACLE_ADDR is the address of the OVM_GasPriceOracle precompile on Optimism.
              /// @dev reference: https://community.optimism.io/docs/developers/build/transaction-fees/#estimating-the-l1-data-fee
              address private constant OVM_GASPRICEORACLE_ADDR = address(0x420000000000000000000000000000000000000F);
              OVM_GasPriceOracle private constant OVM_GASPRICEORACLE = OVM_GasPriceOracle(OVM_GASPRICEORACLE_ADDR);
              uint256 private constant OP_MAINNET_CHAIN_ID = 10;
              uint256 private constant OP_GOERLI_CHAIN_ID = 420;
              uint256 private constant OP_SEPOLIA_CHAIN_ID = 11155420;
              /// @dev Base is a OP stack based rollup and follows the same L1 pricing logic as Optimism.
              uint256 private constant BASE_MAINNET_CHAIN_ID = 8453;
              uint256 private constant BASE_GOERLI_CHAIN_ID = 84531;
              // ------------ End Optimism Constants ------------
              /**
               * @notice Returns the blockhash for the given blockNumber.
               * @notice If the blockNumber is more than 256 blocks in the past, returns the empty string.
               * @notice When on a known Arbitrum chain, it uses ArbSys.arbBlockHash to get the blockhash.
               * @notice Otherwise, it uses the blockhash opcode.
               * @notice Note that the blockhash opcode will return the L2 blockhash on Optimism.
               */
              function _getBlockhash(uint64 blockNumber) internal view returns (bytes32) {
                uint256 chainid = block.chainid;
                if (_isArbitrumChainId(chainid)) {
                  if ((_getBlockNumber() - blockNumber) > 256 || blockNumber >= _getBlockNumber()) {
                    return "";
                  }
                  return ARBSYS.arbBlockHash(blockNumber);
                }
                return blockhash(blockNumber);
              }
              /**
               * @notice Returns the block number of the current block.
               * @notice When on a known Arbitrum chain, it uses ArbSys.arbBlockNumber to get the block number.
               * @notice Otherwise, it uses the block.number opcode.
               * @notice Note that the block.number opcode will return the L2 block number on Optimism.
               */
              function _getBlockNumber() internal view returns (uint256) {
                uint256 chainid = block.chainid;
                if (_isArbitrumChainId(chainid)) {
                  return ARBSYS.arbBlockNumber();
                }
                return block.number;
              }
              /**
               * @notice Returns the L1 fees that will be paid for the current transaction, given any calldata
               * @notice for the current transaction.
               * @notice When on a known Arbitrum chain, it uses ArbGas.getCurrentTxL1GasFees to get the fees.
               * @notice On Arbitrum, the provided calldata is not used to calculate the fees.
               * @notice On Optimism, the provided calldata is passed to the OVM_GasPriceOracle predeploy
               * @notice and getL1Fee is called to get the fees.
               */
              function _getCurrentTxL1GasFees(bytes memory txCallData) internal view returns (uint256) {
                uint256 chainid = block.chainid;
                if (_isArbitrumChainId(chainid)) {
                  return ARBGAS.getCurrentTxL1GasFees();
                } else if (_isOptimismChainId(chainid)) {
                  return OVM_GASPRICEORACLE.getL1Fee(bytes.concat(txCallData, L1_FEE_DATA_PADDING));
                }
                return 0;
              }
              /**
               * @notice Returns the gas cost in wei of calldataSizeBytes of calldata being posted
               * @notice to L1.
               */
              function _getL1CalldataGasCost(uint256 calldataSizeBytes) internal view returns (uint256) {
                uint256 chainid = block.chainid;
                if (_isArbitrumChainId(chainid)) {
                  (, uint256 l1PricePerByte, , , , ) = ARBGAS.getPricesInWei();
                  // see https://developer.arbitrum.io/devs-how-tos/how-to-estimate-gas#where-do-we-get-all-this-information-from
                  // for the justification behind the 140 number.
                  return l1PricePerByte * (calldataSizeBytes + 140);
                } else if (_isOptimismChainId(chainid)) {
                  return _calculateOptimismL1DataFee(calldataSizeBytes);
                }
                return 0;
              }
              /**
               * @notice Return true if and only if the provided chain ID is an Arbitrum chain ID.
               */
              function _isArbitrumChainId(uint256 chainId) internal pure returns (bool) {
                return
                  chainId == ARB_MAINNET_CHAIN_ID ||
                  chainId == ARB_GOERLI_TESTNET_CHAIN_ID ||
                  chainId == ARB_SEPOLIA_TESTNET_CHAIN_ID;
              }
              /**
               * @notice Return true if and only if the provided chain ID is an Optimism chain ID.
               * @notice Note that optimism chain id's are also OP stack chain id's.
               */
              function _isOptimismChainId(uint256 chainId) internal pure returns (bool) {
                return
                  chainId == OP_MAINNET_CHAIN_ID ||
                  chainId == OP_GOERLI_CHAIN_ID ||
                  chainId == OP_SEPOLIA_CHAIN_ID ||
                  chainId == BASE_MAINNET_CHAIN_ID ||
                  chainId == BASE_GOERLI_CHAIN_ID;
              }
              function _calculateOptimismL1DataFee(uint256 calldataSizeBytes) internal view returns (uint256) {
                // from: https://community.optimism.io/docs/developers/build/transaction-fees/#the-l1-data-fee
                // l1_data_fee = l1_gas_price * (tx_data_gas + fixed_overhead) * dynamic_overhead
                // tx_data_gas = count_zero_bytes(tx_data) * 4 + count_non_zero_bytes(tx_data) * 16
                // note we conservatively assume all non-zero bytes.
                uint256 l1BaseFeeWei = OVM_GASPRICEORACLE.l1BaseFee();
                uint256 numZeroBytes = 0;
                uint256 numNonzeroBytes = calldataSizeBytes - numZeroBytes;
                uint256 txDataGas = numZeroBytes * 4 + numNonzeroBytes * 16;
                uint256 fixedOverhead = OVM_GASPRICEORACLE.overhead();
                // The scalar is some value like 0.684, but is represented as
                // that times 10 ^ number of scalar decimals.
                // e.g scalar = 0.684 * 10^6
                // The divisor is used to divide that and have a net result of the true scalar.
                uint256 scalar = OVM_GASPRICEORACLE.scalar();
                uint256 scalarDecimals = OVM_GASPRICEORACLE.decimals();
                uint256 divisor = 10 ** scalarDecimals;
                uint256 l1DataFee = (l1BaseFeeWei * (txDataGas + fixedOverhead) * scalar) / divisor;
                return l1DataFee;
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import {ConfirmedOwnerWithProposal} from "./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)) {}
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import {IOwnable} from "../interfaces/IOwnable.sol";
            /// @title The ConfirmedOwner contract
            /// @notice A contract with helpers for basic contract ownership.
            contract ConfirmedOwnerWithProposal is IOwnable {
              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) {
                // solhint-disable-next-line gas-custom-errors
                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.
              function transferOwnership(address to) public override onlyOwner {
                _transferOwnership(to);
              }
              /// @notice Allows an ownership transfer to be completed by the recipient.
              function acceptOwnership() external override {
                // solhint-disable-next-line gas-custom-errors
                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 {
                // solhint-disable-next-line gas-custom-errors
                require(to != msg.sender, "Cannot transfer to self");
                s_pendingOwner = to;
                emit OwnershipTransferRequested(s_owner, to);
              }
              /// @notice validate access
              function _validateOwnership() internal view {
                // solhint-disable-next-line gas-custom-errors
                require(msg.sender == s_owner, "Only callable by owner");
              }
              /// @notice Reverts if called by anyone other than the contract owner.
              modifier onlyOwner() {
                _validateOwnership();
                _;
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            interface AggregatorV3Interface {
              function decimals() external view returns (uint8);
              function description() external view returns (string memory);
              function version() external view returns (uint256);
              function getRoundData(
                uint80 _roundId
              ) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
              function latestRoundData()
                external
                view
                returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.6;
            interface IERC677Receiver {
              function onTokenTransfer(address sender, uint256 amount, bytes calldata data) external;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            interface IOwnable {
              function owner() external returns (address);
              function transferOwnership(address recipient) external;
              function acceptOwnership() external;
            }
            // 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);
            }
            // Copyright 2021-2022, Offchain Labs, Inc.
            // For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE
            // SPDX-License-Identifier: BUSL-1.1
            pragma solidity >=0.4.21 <0.9.0;
            /// @title Provides insight into the cost of using the chain.
            /// @notice These methods have been adjusted to account for Nitro's heavy use of calldata compression.
            /// Of note to end-users, we no longer make a distinction between non-zero and zero-valued calldata bytes.
            /// Precompiled contract that exists in every Arbitrum chain at 0x000000000000000000000000000000000000006c.
            interface ArbGasInfo {
                /// @notice Get gas prices for a provided aggregator
                /// @return return gas prices in wei
                ///        (
                ///            per L2 tx,
                ///            per L1 calldata byte
                ///            per storage allocation,
                ///            per ArbGas base,
                ///            per ArbGas congestion,
                ///            per ArbGas total
                ///        )
                function getPricesInWeiWithAggregator(address aggregator)
                external
                view
                returns (
                    uint256,
                    uint256,
                    uint256,
                    uint256,
                    uint256,
                    uint256
                );
                /// @notice Get gas prices. Uses the caller's preferred aggregator, or the default if the caller doesn't have a preferred one.
                /// @return return gas prices in wei
                ///        (
                ///            per L2 tx,
                ///            per L1 calldata byte
                ///            per storage allocation,
                ///            per ArbGas base,
                ///            per ArbGas congestion,
                ///            per ArbGas total
                ///        )
                function getPricesInWei()
                external
                view
                returns (
                    uint256,
                    uint256,
                    uint256,
                    uint256,
                    uint256,
                    uint256
                );
                /// @notice Get prices in ArbGas for the supplied aggregator
                /// @return (per L2 tx, per L1 calldata byte, per storage allocation)
                function getPricesInArbGasWithAggregator(address aggregator)
                external
                view
                returns (
                    uint256,
                    uint256,
                    uint256
                );
                /// @notice Get prices in ArbGas. Assumes the callers preferred validator, or the default if caller doesn't have a preferred one.
                /// @return (per L2 tx, per L1 calldata byte, per storage allocation)
                function getPricesInArbGas()
                external
                view
                returns (
                    uint256,
                    uint256,
                    uint256
                );
                /// @notice Get the gas accounting parameters. `gasPoolMax` is always zero, as the exponential pricing model has no such notion.
                /// @return (speedLimitPerSecond, gasPoolMax, maxTxGasLimit)
                function getGasAccountingParams()
                external
                view
                returns (
                    uint256,
                    uint256,
                    uint256
                );
                /// @notice Get the minimum gas price needed for a tx to succeed
                function getMinimumGasPrice() external view returns (uint256);
                /// @notice Get ArbOS's estimate of the L1 basefee in wei
                function getL1BaseFeeEstimate() external view returns (uint256);
                /// @notice Get how slowly ArbOS updates its estimate of the L1 basefee
                function getL1BaseFeeEstimateInertia() external view returns (uint64);
                /// @notice Get the L1 pricer reward rate, in wei per unit
                /// Available in ArbOS version 11
                function getL1RewardRate() external view returns (uint64);
                /// @notice Get the L1 pricer reward recipient
                /// Available in ArbOS version 11
                function getL1RewardRecipient() external view returns (address);
                /// @notice Deprecated -- Same as getL1BaseFeeEstimate()
                function getL1GasPriceEstimate() external view returns (uint256);
                /// @notice Get L1 gas fees paid by the current transaction
                function getCurrentTxL1GasFees() external view returns (uint256);
                /// @notice Get the backlogged amount of gas burnt in excess of the speed limit
                function getGasBacklog() external view returns (uint64);
                /// @notice Get how slowly ArbOS updates the L2 basefee in response to backlogged gas
                function getPricingInertia() external view returns (uint64);
                /// @notice Get the forgivable amount of backlogged gas ArbOS will ignore when raising the basefee
                function getGasBacklogTolerance() external view returns (uint64);
                /// @notice Returns the surplus of funds for L1 batch posting payments (may be negative).
                function getL1PricingSurplus() external view returns (int256);
                /// @notice Returns the base charge (in L1 gas) attributed to each data batch in the calldata pricer
                function getPerBatchGasCharge() external view returns (int64);
                /// @notice Returns the cost amortization cap in basis points
                function getAmortizedCostCapBips() external view returns (uint64);
                /// @notice Returns the available funds from L1 fees
                function getL1FeesAvailable() external view returns (uint256);
                /// @notice Returns the equilibration units parameter for L1 price adjustment algorithm
                /// Available in ArbOS version 20
                function getL1PricingEquilibrationUnits() external view returns (uint256);
                /// @notice Returns the last time the L1 calldata pricer was updated.
                /// Available in ArbOS version 20
                function getLastL1PricingUpdateTime() external view returns (uint64);
                /// @notice Returns the amount of L1 calldata payments due for rewards (per the L1 reward rate)
                /// Available in ArbOS version 20
                function getL1PricingFundsDueForRewards() external view returns (uint256);
                /// @notice Returns the amount of L1 calldata posted since the last update.
                /// Available in ArbOS version 20
                function getL1PricingUnitsSinceUpdate() external view returns (uint64);
                /// @notice Returns the L1 pricing surplus as of the last update (may be negative).
                /// Available in ArbOS version 20
                function getLastL1PricingSurplus() external view returns (int256);
            }// Copyright 2021-2022, Offchain Labs, Inc.
            // For license information, see https://github.com/nitro/blob/master/LICENSE
            // SPDX-License-Identifier: BUSL-1.1
            pragma solidity >=0.4.21 <0.9.0;
            /**
             * @title System level functionality
             * @notice For use by contracts to interact with core L2-specific functionality.
             * Precompiled contract that exists in every Arbitrum chain at address(100), 0x0000000000000000000000000000000000000064.
             */
            interface ArbSys {
                /**
                 * @notice Get Arbitrum block number (distinct from L1 block number; Arbitrum genesis block has block number 0)
                 * @return block number as int
                 */
                function arbBlockNumber() external view returns (uint256);
                /**
                 * @notice Get Arbitrum block hash (reverts unless currentBlockNum-256 <= arbBlockNum < currentBlockNum)
                 * @return block hash
                 */
                function arbBlockHash(uint256 arbBlockNum) external view returns (bytes32);
                /**
                 * @notice Gets the rollup's unique chain identifier
                 * @return Chain identifier as int
                 */
                function arbChainID() external view returns (uint256);
                /**
                 * @notice Get internal version number identifying an ArbOS build
                 * @return version number as int
                 */
                function arbOSVersion() external view returns (uint256);
                /**
                 * @notice Returns 0 since Nitro has no concept of storage gas
                 * @return uint 0
                 */
                function getStorageGasAvailable() external view returns (uint256);
                /**
                 * @notice (deprecated) check if current call is top level (meaning it was triggered by an EoA or a L1 contract)
                 * @dev this call has been deprecated and may be removed in a future release
                 * @return true if current execution frame is not a call by another L2 contract
                 */
                function isTopLevelCall() external view returns (bool);
                /**
                 * @notice map L1 sender contract address to its L2 alias
                 * @param sender sender address
                 * @param unused argument no longer used
                 * @return aliased sender address
                 */
                function mapL1SenderContractAddressToL2Alias(address sender, address unused)
                    external
                    pure
                    returns (address);
                /**
                 * @notice check if the caller (of this caller of this) is an aliased L1 contract address
                 * @return true iff the caller's address is an alias for an L1 contract address
                 */
                function wasMyCallersAddressAliased() external view returns (bool);
                /**
                 * @notice return the address of the caller (of this caller of this), without applying L1 contract address aliasing
                 * @return address of the caller's caller, without applying L1 contract address aliasing
                 */
                function myCallersAddressWithoutAliasing() external view returns (address);
                /**
                 * @notice Send given amount of Eth to dest from sender.
                 * This is a convenience function, which is equivalent to calling sendTxToL1 with empty data.
                 * @param destination recipient address on L1
                 * @return unique identifier for this L2-to-L1 transaction.
                 */
                function withdrawEth(address destination)
                    external
                    payable
                    returns (uint256);
                /**
                 * @notice Send a transaction to L1
                 * @dev it is not possible to execute on the L1 any L2-to-L1 transaction which contains data
                 * to a contract address without any code (as enforced by the Bridge contract).
                 * @param destination recipient address on L1
                 * @param data (optional) calldata for L1 contract call
                 * @return a unique identifier for this L2-to-L1 transaction.
                 */
                function sendTxToL1(address destination, bytes calldata data)
                    external
                    payable
                    returns (uint256);
                /**
                 * @notice Get send Merkle tree state
                 * @return size number of sends in the history
                 * @return root root hash of the send history
                 * @return partials hashes of partial subtrees in the send history tree
                 */
                function sendMerkleTreeState()
                    external
                    view
                    returns (
                        uint256 size,
                        bytes32 root,
                        bytes32[] memory partials
                    );
                /**
                 * @notice creates a send txn from L2 to L1
                 * @param position = (level << 192) + leaf = (0 << 192) + leaf = leaf
                 */
                event L2ToL1Tx(
                    address caller,
                    address indexed destination,
                    uint256 indexed hash,
                    uint256 indexed position,
                    uint256 arbBlockNum,
                    uint256 ethBlockNum,
                    uint256 timestamp,
                    uint256 callvalue,
                    bytes data
                );
                /// @dev DEPRECATED in favour of the new L2ToL1Tx event above after the nitro upgrade
                event L2ToL1Transaction(
                    address caller,
                    address indexed destination,
                    uint256 indexed uniqueId,
                    uint256 indexed batchNumber,
                    uint256 indexInBatch,
                    uint256 arbBlockNum,
                    uint256 ethBlockNum,
                    uint256 timestamp,
                    uint256 callvalue,
                    bytes data
                );
                /**
                 * @notice logs a merkle branch for proof synthesis
                 * @param reserved an index meant only to align the 4th index with L2ToL1Transaction's 4th event
                 * @param hash the merkle hash
                 * @param position = (level << 192) + leaf
                 */
                event SendMerkleUpdate(
                    uint256 indexed reserved,
                    bytes32 indexed hash,
                    uint256 indexed position
                );
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.9;
            /* External Imports */
            import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
            /**
             * @title OVM_GasPriceOracle
             * @dev This contract exposes the current l2 gas price, a measure of how congested the network
             * currently is. This measure is used by the Sequencer to determine what fee to charge for
             * transactions. When the system is more congested, the l2 gas price will increase and fees
             * will also increase as a result.
             *
             * All public variables are set while generating the initial L2 state. The
             * constructor doesn't run in practice as the L2 state generation script uses
             * the deployed bytecode instead of running the initcode.
             */
            contract OVM_GasPriceOracle is Ownable {
              /*************
               * Variables *
               *************/
              // Current L2 gas price
              uint256 public gasPrice;
              // Current L1 base fee
              uint256 public l1BaseFee;
              // Amortized cost of batch submission per transaction
              uint256 public overhead;
              // Value to scale the fee up by
              uint256 public scalar;
              // Number of decimals of the scalar
              uint256 public decimals;
              /***************
               * Constructor *
               ***************/
              /**
               * @param _owner Address that will initially own this contract.
               */
              constructor(address _owner) Ownable() {
                transferOwnership(_owner);
              }
              /**********
               * Events *
               **********/
              event GasPriceUpdated(uint256);
              event L1BaseFeeUpdated(uint256);
              event OverheadUpdated(uint256);
              event ScalarUpdated(uint256);
              event DecimalsUpdated(uint256);
              /********************
               * Public Functions *
               ********************/
              /**
               * Allows the owner to modify the l2 gas price.
               * @param _gasPrice New l2 gas price.
               */
              // slither-disable-next-line external-function
              function setGasPrice(uint256 _gasPrice) public onlyOwner {
                gasPrice = _gasPrice;
                emit GasPriceUpdated(_gasPrice);
              }
              /**
               * Allows the owner to modify the l1 base fee.
               * @param _baseFee New l1 base fee
               */
              // slither-disable-next-line external-function
              function setL1BaseFee(uint256 _baseFee) public onlyOwner {
                l1BaseFee = _baseFee;
                emit L1BaseFeeUpdated(_baseFee);
              }
              /**
               * Allows the owner to modify the overhead.
               * @param _overhead New overhead
               */
              // slither-disable-next-line external-function
              function setOverhead(uint256 _overhead) public onlyOwner {
                overhead = _overhead;
                emit OverheadUpdated(_overhead);
              }
              /**
               * Allows the owner to modify the scalar.
               * @param _scalar New scalar
               */
              // slither-disable-next-line external-function
              function setScalar(uint256 _scalar) public onlyOwner {
                scalar = _scalar;
                emit ScalarUpdated(_scalar);
              }
              /**
               * Allows the owner to modify the decimals.
               * @param _decimals New decimals
               */
              // slither-disable-next-line external-function
              function setDecimals(uint256 _decimals) public onlyOwner {
                decimals = _decimals;
                emit DecimalsUpdated(_decimals);
              }
              /**
               * Computes the L1 portion of the fee
               * based on the size of the RLP encoded tx
               * and the current l1BaseFee
               * @param _data Unsigned RLP encoded tx, 6 elements
               * @return L1 fee that should be paid for the tx
               */
              // slither-disable-next-line external-function
              function getL1Fee(bytes memory _data) public view returns (uint256) {
                uint256 l1GasUsed = getL1GasUsed(_data);
                uint256 l1Fee = l1GasUsed * l1BaseFee;
                uint256 divisor = 10 ** decimals;
                uint256 unscaled = l1Fee * scalar;
                uint256 scaled = unscaled / divisor;
                return scaled;
              }
              // solhint-disable max-line-length
              /**
               * Computes the amount of L1 gas used for a transaction
               * The overhead represents the per batch gas overhead of
               * posting both transaction and state roots to L1 given larger
               * batch sizes.
               * 4 gas for 0 byte
               * https://github.com/ethereum/go-ethereum/blob/9ada4a2e2c415e6b0b51c50e901336872e028872/params/protocol_params.go#L33
               * 16 gas for non zero byte
               * https://github.com/ethereum/go-ethereum/blob/9ada4a2e2c415e6b0b51c50e901336872e028872/params/protocol_params.go#L87
               * This will need to be updated if calldata gas prices change
               * Account for the transaction being unsigned
               * Padding is added to account for lack of signature on transaction
               * 1 byte for RLP V prefix
               * 1 byte for V
               * 1 byte for RLP R prefix
               * 32 bytes for R
               * 1 byte for RLP S prefix
               * 32 bytes for S
               * Total: 68 bytes of padding
               * @param _data Unsigned RLP encoded tx, 6 elements
               * @return Amount of L1 gas used for a transaction
               */
              // solhint-enable max-line-length
              function getL1GasUsed(bytes memory _data) public view returns (uint256) {
                uint256 total = 0;
                for (uint256 i = 0; i < _data.length; i++) {
                  if (_data[i] == 0) {
                    total += 4;
                  } else {
                    total += 16;
                  }
                }
                uint256 unsigned = total + overhead;
                return unsigned + (68 * 16);
              }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)
            // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
            pragma solidity ^0.8.0;
            /**
             * @dev Library for managing
             * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
             * types.
             *
             * Sets have the following properties:
             *
             * - Elements are added, removed, and checked for existence in constant time
             * (O(1)).
             * - Elements are enumerated in O(n). No guarantees are made on the ordering.
             *
             * ```
             * contract Example {
             *     // Add the library methods
             *     using EnumerableSet for EnumerableSet.AddressSet;
             *
             *     // Declare a set state variable
             *     EnumerableSet.AddressSet private mySet;
             * }
             * ```
             *
             * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
             * and `uint256` (`UintSet`) are supported.
             *
             * [WARNING]
             * ====
             *  Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable.
             *  See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
             *
             *  In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet.
             * ====
             */
            library EnumerableSet {
                // To implement this library for multiple types with as little code
                // repetition as possible, we write it in terms of a generic Set type with
                // bytes32 values.
                // The Set implementation uses private functions, and user-facing
                // implementations (such as AddressSet) are just wrappers around the
                // underlying Set.
                // This means that we can only create new EnumerableSets for types that fit
                // in bytes32.
                struct Set {
                    // Storage of set values
                    bytes32[] _values;
                    // Position of the value in the `values` array, plus 1 because index 0
                    // means a value is not in the set.
                    mapping(bytes32 => uint256) _indexes;
                }
                /**
                 * @dev Add a value to a set. O(1).
                 *
                 * Returns true if the value was added to the set, that is if it was not
                 * already present.
                 */
                function _add(Set storage set, bytes32 value) private returns (bool) {
                    if (!_contains(set, value)) {
                        set._values.push(value);
                        // The value is stored at length-1, but we add 1 to all indexes
                        // and use 0 as a sentinel value
                        set._indexes[value] = set._values.length;
                        return true;
                    } else {
                        return false;
                    }
                }
                /**
                 * @dev Removes a value from a set. O(1).
                 *
                 * Returns true if the value was removed from the set, that is if it was
                 * present.
                 */
                function _remove(Set storage set, bytes32 value) private returns (bool) {
                    // We read and store the value's index to prevent multiple reads from the same storage slot
                    uint256 valueIndex = set._indexes[value];
                    if (valueIndex != 0) {
                        // Equivalent to contains(set, value)
                        // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                        // the array, and then remove the last element (sometimes called as 'swap and pop').
                        // This modifies the order of the array, as noted in {at}.
                        uint256 toDeleteIndex = valueIndex - 1;
                        uint256 lastIndex = set._values.length - 1;
                        if (lastIndex != toDeleteIndex) {
                            bytes32 lastValue = set._values[lastIndex];
                            // Move the last value to the index where the value to delete is
                            set._values[toDeleteIndex] = lastValue;
                            // Update the index for the moved value
                            set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                        }
                        // Delete the slot where the moved value was stored
                        set._values.pop();
                        // Delete the index for the deleted slot
                        delete set._indexes[value];
                        return true;
                    } else {
                        return false;
                    }
                }
                /**
                 * @dev Returns true if the value is in the set. O(1).
                 */
                function _contains(Set storage set, bytes32 value) private view returns (bool) {
                    return set._indexes[value] != 0;
                }
                /**
                 * @dev Returns the number of values on the set. O(1).
                 */
                function _length(Set storage set) private view returns (uint256) {
                    return set._values.length;
                }
                /**
                 * @dev Returns the value stored at position `index` in the set. O(1).
                 *
                 * Note that there are no guarantees on the ordering of values inside the
                 * array, and it may change when more values are added or removed.
                 *
                 * Requirements:
                 *
                 * - `index` must be strictly less than {length}.
                 */
                function _at(Set storage set, uint256 index) private view returns (bytes32) {
                    return set._values[index];
                }
                /**
                 * @dev Return the entire set in an array
                 *
                 * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                 * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                 * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                 * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                 */
                function _values(Set storage set) private view returns (bytes32[] memory) {
                    return set._values;
                }
                // Bytes32Set
                struct Bytes32Set {
                    Set _inner;
                }
                /**
                 * @dev Add a value to a set. O(1).
                 *
                 * Returns true if the value was added to the set, that is if it was not
                 * already present.
                 */
                function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                    return _add(set._inner, value);
                }
                /**
                 * @dev Removes a value from a set. O(1).
                 *
                 * Returns true if the value was removed from the set, that is if it was
                 * present.
                 */
                function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                    return _remove(set._inner, value);
                }
                /**
                 * @dev Returns true if the value is in the set. O(1).
                 */
                function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                    return _contains(set._inner, value);
                }
                /**
                 * @dev Returns the number of values in the set. O(1).
                 */
                function length(Bytes32Set storage set) internal view returns (uint256) {
                    return _length(set._inner);
                }
                /**
                 * @dev Returns the value stored at position `index` in the set. O(1).
                 *
                 * Note that there are no guarantees on the ordering of values inside the
                 * array, and it may change when more values are added or removed.
                 *
                 * Requirements:
                 *
                 * - `index` must be strictly less than {length}.
                 */
                function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                    return _at(set._inner, index);
                }
                /**
                 * @dev Return the entire set in an array
                 *
                 * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                 * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                 * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                 * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                 */
                function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                    bytes32[] memory store = _values(set._inner);
                    bytes32[] memory result;
                    /// @solidity memory-safe-assembly
                    assembly {
                        result := store
                    }
                    return result;
                }
                // AddressSet
                struct AddressSet {
                    Set _inner;
                }
                /**
                 * @dev Add a value to a set. O(1).
                 *
                 * Returns true if the value was added to the set, that is if it was not
                 * already present.
                 */
                function add(AddressSet storage set, address value) internal returns (bool) {
                    return _add(set._inner, bytes32(uint256(uint160(value))));
                }
                /**
                 * @dev Removes a value from a set. O(1).
                 *
                 * Returns true if the value was removed from the set, that is if it was
                 * present.
                 */
                function remove(AddressSet storage set, address value) internal returns (bool) {
                    return _remove(set._inner, bytes32(uint256(uint160(value))));
                }
                /**
                 * @dev Returns true if the value is in the set. O(1).
                 */
                function contains(AddressSet storage set, address value) internal view returns (bool) {
                    return _contains(set._inner, bytes32(uint256(uint160(value))));
                }
                /**
                 * @dev Returns the number of values in the set. O(1).
                 */
                function length(AddressSet storage set) internal view returns (uint256) {
                    return _length(set._inner);
                }
                /**
                 * @dev Returns the value stored at position `index` in the set. O(1).
                 *
                 * Note that there are no guarantees on the ordering of values inside the
                 * array, and it may change when more values are added or removed.
                 *
                 * Requirements:
                 *
                 * - `index` must be strictly less than {length}.
                 */
                function at(AddressSet storage set, uint256 index) internal view returns (address) {
                    return address(uint160(uint256(_at(set._inner, index))));
                }
                /**
                 * @dev Return the entire set in an array
                 *
                 * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                 * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                 * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                 * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                 */
                function values(AddressSet storage set) internal view returns (address[] memory) {
                    bytes32[] memory store = _values(set._inner);
                    address[] memory result;
                    /// @solidity memory-safe-assembly
                    assembly {
                        result := store
                    }
                    return result;
                }
                // UintSet
                struct UintSet {
                    Set _inner;
                }
                /**
                 * @dev Add a value to a set. O(1).
                 *
                 * Returns true if the value was added to the set, that is if it was not
                 * already present.
                 */
                function add(UintSet storage set, uint256 value) internal returns (bool) {
                    return _add(set._inner, bytes32(value));
                }
                /**
                 * @dev Removes a value from a set. O(1).
                 *
                 * Returns true if the value was removed from the set, that is if it was
                 * present.
                 */
                function remove(UintSet storage set, uint256 value) internal returns (bool) {
                    return _remove(set._inner, bytes32(value));
                }
                /**
                 * @dev Returns true if the value is in the set. O(1).
                 */
                function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                    return _contains(set._inner, bytes32(value));
                }
                /**
                 * @dev Returns the number of values in the set. O(1).
                 */
                function length(UintSet storage set) internal view returns (uint256) {
                    return _length(set._inner);
                }
                /**
                 * @dev Returns the value stored at position `index` in the set. O(1).
                 *
                 * Note that there are no guarantees on the ordering of values inside the
                 * array, and it may change when more values are added or removed.
                 *
                 * Requirements:
                 *
                 * - `index` must be strictly less than {length}.
                 */
                function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                    return uint256(_at(set._inner, index));
                }
                /**
                 * @dev Return the entire set in an array
                 *
                 * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                 * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                 * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                 * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                 */
                function values(UintSet storage set) internal view returns (uint256[] memory) {
                    bytes32[] memory store = _values(set._inner);
                    uint256[] memory result;
                    /// @solidity memory-safe-assembly
                    assembly {
                        result := store
                    }
                    return result;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
            pragma solidity ^0.8.0;
            import "../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.
             *
             * By default, the owner account will be the one that deploys the contract. This
             * can later be changed with {transferOwnership}.
             *
             * This module is used through inheritance. It will make available the modifier
             * `onlyOwner`, which can be applied to your functions to restrict their use to
             * the owner.
             */
            abstract contract Ownable is Context {
                address private _owner;
                event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                /**
                 * @dev Initializes the contract setting the deployer as the initial owner.
                 */
                constructor() {
                    _transferOwnership(_msgSender());
                }
                /**
                 * @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 {
                    require(owner() == _msgSender(), "Ownable: caller is not the owner");
                }
                /**
                 * @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 {
                    require(newOwner != address(0), "Ownable: new owner is the zero address");
                    _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);
                }
            }
            // 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;
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /** ****************************************************************************
              * @notice Verification of verifiable-random-function (VRF) proofs, following
              * @notice https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.3
              * @notice See https://eprint.iacr.org/2017/099.pdf for security proofs.
              * @dev Bibliographic references:
              * @dev Goldberg, et al., "Verifiable Random Functions (VRFs)", Internet Draft
              * @dev draft-irtf-cfrg-vrf-05, IETF, Aug 11 2019,
              * @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05
              * @dev Papadopoulos, et al., "Making NSEC5 Practical for DNSSEC", Cryptology
              * @dev ePrint Archive, Report 2017/099, https://eprint.iacr.org/2017/099.pdf
              * ****************************************************************************
              * @dev USAGE
              * @dev The main entry point is _randomValueFromVRFProof. See its docstring.
              * ****************************************************************************
              * @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 computationally indistinguishable to her from a uniform
              * @dev random sample from the output space.
              * @dev The purpose of this contract is to perform that verification.
              * ****************************************************************************
              * @dev DESIGN NOTES
              * @dev The VRF algorithm verified here satisfies the full uniqueness, full
              * @dev collision resistance, and full pseudo-randomness security properties.
              * @dev See "SECURITY PROPERTIES" below, and
              * @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-3
              * @dev An elliptic curve point is generally represented in the solidity code
              * @dev as a uint256[2], corresponding to its affine coordinates in
              * @dev GF(FIELD_SIZE).
              * @dev For the sake of efficiency, this implementation deviates from the spec
              * @dev in some minor ways:
              * @dev - Keccak hash rather than the SHA256 hash recommended in
              * @dev   https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.5
              * @dev   Keccak costs much less gas on the EVM, and provides similar security.
              * @dev - Secp256k1 curve instead of the P-256 or ED25519 curves recommended in
              * @dev   https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.5
              * @dev   For curve-point multiplication, it's much cheaper to abuse ECRECOVER
              * @dev - _hashToCurve recursively hashes until it finds a curve x-ordinate. On
              * @dev   the EVM, this is slightly more efficient than the recommendation in
              * @dev   https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.4.1.1
              * @dev   step 5, to concatenate with a nonce then hash, and rehash with the
              * @dev   nonce updated until a valid x-ordinate is found.
              * @dev - _hashToCurve does not include a cipher version string or the byte 0x1
              * @dev   in the hash message, as recommended in step 5.B of the draft
              * @dev   standard. They are unnecessary here because no variation in the
              * @dev   cipher suite is allowed.
              * @dev - Similarly, the hash input in _scalarFromCurvePoints does not include a
              * @dev   commitment to the cipher suite, either, which differs from step 2 of
              * @dev   https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.4.3
              * @dev   . Also, the hash input is the concatenation of the uncompressed
              * @dev   points, not the compressed points as recommended in step 3.
              * @dev - In the calculation of the challenge value "c", the "u" value (i.e.
              * @dev   the value computed by Reggie as the nonce times the secp256k1
              * @dev   generator point, see steps 5 and 7 of
              * @dev   https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.3
              * @dev   ) is replaced by its ethereum address, i.e. the lower 160 bits of the
              * @dev   keccak hash of the original u. This is because we only verify the
              * @dev   calculation of u up to its address, by abusing ECRECOVER.
              * ****************************************************************************
              * @dev   SECURITY PROPERTIES
              * @dev Here are the security properties for this VRF:
              * @dev Full uniqueness: For any seed and valid VRF public key, there is
              * @dev   exactly one VRF output which can be proved to come from that seed, in
              * @dev   the sense that the proof will pass _verifyVRFProof.
              * @dev Full collision resistance: It's cryptographically infeasible to find
              * @dev   two seeds with same VRF output from a fixed, valid VRF key
              * @dev Full pseudorandomness: Absent the proofs that the VRF outputs are
              * @dev   derived from a given seed, the outputs are computationally
              * @dev   indistinguishable from randomness.
              * @dev https://eprint.iacr.org/2017/099.pdf, Appendix B contains the proofs
              * @dev for these properties.
              * @dev For secp256k1, the key validation described in section
              * @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.6
              * @dev is unnecessary, because secp256k1 has cofactor 1, and the
              * @dev representation of the public key used here (affine x- and y-ordinates
              * @dev of the secp256k1 point on the standard y^2=x^3+7 curve) cannot refer to
              * @dev the point at infinity.
              * ****************************************************************************
              * @dev OTHER SECURITY CONSIDERATIONS
              *
              * @dev The seed input to the VRF could in principle force an arbitrary amount
              * @dev of work in _hashToCurve, by requiring extra rounds of hashing and
              * @dev checking whether that's yielded the x ordinate of a secp256k1 point.
              * @dev However, under the Random Oracle Model the probability of choosing a
              * @dev point which forces n extra rounds in _hashToCurve is 2⁻ⁿ. The base cost
              * @dev for calling _hashToCurve is about 25,000 gas, and each round of checking
              * @dev for a valid x ordinate costs about 15,555 gas, so to find a seed for
              * @dev which _hashToCurve would cost more than 2,017,000 gas, one would have to
              * @dev try, in expectation, about 2¹²⁸ seeds, which is infeasible for any
              * @dev foreseeable computational resources. (25,000 + 128 * 15,555 < 2,017,000.)
              * @dev Since the gas block limit for the Ethereum main net is 10,000,000 gas,
              * @dev this means it is infeasible for an adversary to prevent correct
              * @dev operation of this contract by choosing an adverse seed.
              * @dev (See TestMeasureHashToCurveGasCost for verification of the gas cost for
              * @dev _hashToCurve.)
              * @dev It may be possible to make a secure constant-time _hashToCurve function.
              * @dev See notes in _hashToCurve docstring.
            */
            contract VRF {
              // See https://www.secg.org/sec2-v2.pdf, section 2.4.1, for these constants.
              // Number of points in Secp256k1
              uint256 private constant GROUP_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
              // Prime characteristic of the galois field over which Secp256k1 is defined
              uint256 private constant FIELD_SIZE =
                // solium-disable-next-line indentation
                0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
              uint256 private constant WORD_LENGTH_BYTES = 0x20;
              // (base^exponent) % FIELD_SIZE
              // Cribbed from https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4
              function _bigModExp(uint256 base, uint256 exponent) internal view returns (uint256 exponentiation) {
                uint256 callResult;
                uint256[6] memory bigModExpContractInputs;
                bigModExpContractInputs[0] = WORD_LENGTH_BYTES; // Length of base
                bigModExpContractInputs[1] = WORD_LENGTH_BYTES; // Length of exponent
                bigModExpContractInputs[2] = WORD_LENGTH_BYTES; // Length of modulus
                bigModExpContractInputs[3] = base;
                bigModExpContractInputs[4] = exponent;
                bigModExpContractInputs[5] = FIELD_SIZE;
                uint256[1] memory output;
                assembly {
                  callResult := staticcall(
                    not(0), // Gas cost: no limit
                    0x05, // Bigmodexp contract address
                    bigModExpContractInputs,
                    0xc0, // Length of input segment: 6*0x20-bytes
                    output,
                    0x20 // Length of output segment
                  )
                }
                if (callResult == 0) {
                  // solhint-disable-next-line gas-custom-errors
                  revert("bigModExp failure!");
                }
                return output[0];
              }
              // Let q=FIELD_SIZE. q % 4 = 3, ∴ x≡r^2 mod q ⇒ x^SQRT_POWER≡±r mod q.  See
              // https://en.wikipedia.org/wiki/Modular_square_root#Prime_or_prime_power_modulus
              uint256 private constant SQRT_POWER = (FIELD_SIZE + 1) >> 2;
              // Computes a s.t. a^2 = x in the field. Assumes a exists
              function _squareRoot(uint256 x) internal view returns (uint256) {
                return _bigModExp(x, SQRT_POWER);
              }
              // The value of y^2 given that (x,y) is on secp256k1.
              function _ySquared(uint256 x) internal pure returns (uint256) {
                // Curve is y^2=x^3+7. See section 2.4.1 of https://www.secg.org/sec2-v2.pdf
                uint256 xCubed = mulmod(x, mulmod(x, x, FIELD_SIZE), FIELD_SIZE);
                return addmod(xCubed, 7, FIELD_SIZE);
              }
              // True iff p is on secp256k1
              function _isOnCurve(uint256[2] memory p) internal pure returns (bool) {
                // Section 2.3.6. in https://www.secg.org/sec1-v2.pdf
                // requires each ordinate to be in [0, ..., FIELD_SIZE-1]
                // solhint-disable-next-line gas-custom-errors
                require(p[0] < FIELD_SIZE, "invalid x-ordinate");
                // solhint-disable-next-line gas-custom-errors
                require(p[1] < FIELD_SIZE, "invalid y-ordinate");
                return _ySquared(p[0]) == mulmod(p[1], p[1], FIELD_SIZE);
              }
              // Hash x uniformly into {0, ..., FIELD_SIZE-1}.
              function _fieldHash(bytes memory b) internal pure returns (uint256 x_) {
                x_ = uint256(keccak256(b));
                // Rejecting if x >= FIELD_SIZE corresponds to step 2.1 in section 2.3.4 of
                // http://www.secg.org/sec1-v2.pdf , which is part of the definition of
                // string_to_point in the IETF draft
                while (x_ >= FIELD_SIZE) {
                  x_ = uint256(keccak256(abi.encodePacked(x_)));
                }
                return x_;
              }
              // Hash b to a random point which hopefully lies on secp256k1. The y ordinate
              // is always even, due to
              // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.4.1.1
              // step 5.C, which references arbitrary_string_to_point, defined in
              // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.5 as
              // returning the point with given x ordinate, and even y ordinate.
              function _newCandidateSecp256k1Point(bytes memory b) internal view returns (uint256[2] memory p) {
                unchecked {
                  p[0] = _fieldHash(b);
                  p[1] = _squareRoot(_ySquared(p[0]));
                  if (p[1] % 2 == 1) {
                    // Note that 0 <= p[1] < FIELD_SIZE
                    // so this cannot wrap, we use unchecked to save gas.
                    p[1] = FIELD_SIZE - p[1];
                  }
                }
                return p;
              }
              // Domain-separation tag for initial hash in _hashToCurve. Corresponds to
              // vrf.go/hashToCurveHashPrefix
              uint256 internal constant HASH_TO_CURVE_HASH_PREFIX = 1;
              // Cryptographic hash function onto the curve.
              //
              // Corresponds to algorithm in section 5.4.1.1 of the draft standard. (But see
              // DESIGN NOTES above for slight differences.)
              //
              // TODO(alx): Implement a bounded-computation hash-to-curve, as described in
              // "Construction of Rational Points on Elliptic Curves over Finite Fields"
              // http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.831.5299&rep=rep1&type=pdf
              // and suggested by
              // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-01#section-5.2.2
              // (Though we can't used exactly that because secp256k1's j-invariant is 0.)
              //
              // This would greatly simplify the analysis in "OTHER SECURITY CONSIDERATIONS"
              // https://www.pivotaltracker.com/story/show/171120900
              function _hashToCurve(uint256[2] memory pk, uint256 input) internal view returns (uint256[2] memory rv) {
                rv = _newCandidateSecp256k1Point(abi.encodePacked(HASH_TO_CURVE_HASH_PREFIX, pk, input));
                while (!_isOnCurve(rv)) {
                  rv = _newCandidateSecp256k1Point(abi.encodePacked(rv[0]));
                }
                return rv;
              }
              /** *********************************************************************
               * @notice Check that product==scalar*multiplicand
               *
               * @dev Based on Vitalik Buterin's idea in ethresear.ch post cited below.
               *
               * @param multiplicand: secp256k1 point
               * @param scalar: non-zero GF(GROUP_ORDER) scalar
               * @param product: secp256k1 expected to be multiplier * multiplicand
               * @return verifies true iff product==scalar*multiplicand, with cryptographically high probability
               */
              function _ecmulVerify(
                uint256[2] memory multiplicand,
                uint256 scalar,
                uint256[2] memory product
              ) internal pure returns (bool verifies) {
                // solhint-disable-next-line gas-custom-errors
                require(scalar != 0, "zero scalar"); // Rules out an ecrecover failure case
                uint256 x = multiplicand[0]; // x ordinate of multiplicand
                uint8 v = multiplicand[1] % 2 == 0 ? 27 : 28; // parity of y ordinate
                // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
                // Point corresponding to address ecrecover(0, v, x, s=scalar*x) is
                // (x⁻¹ mod GROUP_ORDER) * (scalar * x * multiplicand - 0 * g), i.e.
                // scalar*multiplicand. See https://crypto.stackexchange.com/a/18106
                bytes32 scalarTimesX = bytes32(mulmod(scalar, x, GROUP_ORDER));
                address actual = ecrecover(bytes32(0), v, bytes32(x), scalarTimesX);
                // Explicit conversion to address takes bottom 160 bits
                address expected = address(uint160(uint256(keccak256(abi.encodePacked(product)))));
                return (actual == expected);
              }
              // Returns x1/z1-x2/z2=(x1z2-x2z1)/(z1z2) in projective coordinates on P¹(?ₙ)
              function _projectiveSub(
                uint256 x1,
                uint256 z1,
                uint256 x2,
                uint256 z2
              ) internal pure returns (uint256 x3, uint256 z3) {
                unchecked {
                  uint256 num1 = mulmod(z2, x1, FIELD_SIZE);
                  // Note this cannot wrap since x2 is a point in [0, FIELD_SIZE-1]
                  // we use unchecked to save gas.
                  uint256 num2 = mulmod(FIELD_SIZE - x2, z1, FIELD_SIZE);
                  (x3, z3) = (addmod(num1, num2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE));
                }
                return (x3, z3);
              }
              // Returns x1/z1*x2/z2=(x1x2)/(z1z2), in projective coordinates on P¹(?ₙ)
              function _projectiveMul(
                uint256 x1,
                uint256 z1,
                uint256 x2,
                uint256 z2
              ) internal pure returns (uint256 x3, uint256 z3) {
                (x3, z3) = (mulmod(x1, x2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE));
                return (x3, z3);
              }
              /** **************************************************************************
                    @notice Computes elliptic-curve sum, in projective co-ordinates
                    @dev Using projective coordinates avoids costly divisions
                    @dev To use this with p and q in affine coordinates, call
                    @dev _projectiveECAdd(px, py, qx, qy). This will return
                    @dev the addition of (px, py, 1) and (qx, qy, 1), in the
                    @dev secp256k1 group.
                    @dev This can be used to calculate the z which is the inverse to zInv
                    @dev in isValidVRFOutput. But consider using a faster
                    @dev re-implementation such as ProjectiveECAdd in the golang vrf package.
                    @dev This function assumes [px,py,1],[qx,qy,1] are valid projective
                         coordinates of secp256k1 points. That is safe in this contract,
                         because this method is only used by _linearCombination, which checks
                         points are on the curve via ecrecover.
                    **************************************************************************
                    @param px The first affine coordinate of the first summand
                    @param py The second affine coordinate of the first summand
                    @param qx The first affine coordinate of the second summand
                    @param qy The second affine coordinate of the second summand
                    (px,py) and (qx,qy) must be distinct, valid secp256k1 points.
                    **************************************************************************
                    Return values are projective coordinates of [px,py,1]+[qx,qy,1] as points
                    on secp256k1, in P²(?ₙ)
                    @return sx
                    @return sy
                    @return sz
                */
              function _projectiveECAdd(
                uint256 px,
                uint256 py,
                uint256 qx,
                uint256 qy
              ) internal pure returns (uint256 sx, uint256 sy, uint256 sz) {
                unchecked {
                  // See "Group law for E/K : y^2 = x^3 + ax + b", in section 3.1.2, p. 80,
                  // "Guide to Elliptic Curve Cryptography" by Hankerson, Menezes and Vanstone
                  // We take the equations there for (sx,sy), and homogenize them to
                  // projective coordinates. That way, no inverses are required, here, and we
                  // only need the one inverse in _affineECAdd.
                  // We only need the "point addition" equations from Hankerson et al. Can
                  // skip the "point doubling" equations because p1 == p2 is cryptographically
                  // impossible, and required not to be the case in _linearCombination.
                  // Add extra "projective coordinate" to the two points
                  (uint256 z1, uint256 z2) = (1, 1);
                  // (lx, lz) = (qy-py)/(qx-px), i.e., gradient of secant line.
                  // Cannot wrap since px and py are in [0, FIELD_SIZE-1]
                  uint256 lx = addmod(qy, FIELD_SIZE - py, FIELD_SIZE);
                  uint256 lz = addmod(qx, FIELD_SIZE - px, FIELD_SIZE);
                  uint256 dx; // Accumulates denominator from sx calculation
                  // sx=((qy-py)/(qx-px))^2-px-qx
                  (sx, dx) = _projectiveMul(lx, lz, lx, lz); // ((qy-py)/(qx-px))^2
                  (sx, dx) = _projectiveSub(sx, dx, px, z1); // ((qy-py)/(qx-px))^2-px
                  (sx, dx) = _projectiveSub(sx, dx, qx, z2); // ((qy-py)/(qx-px))^2-px-qx
                  uint256 dy; // Accumulates denominator from sy calculation
                  // sy=((qy-py)/(qx-px))(px-sx)-py
                  (sy, dy) = _projectiveSub(px, z1, sx, dx); // px-sx
                  (sy, dy) = _projectiveMul(sy, dy, lx, lz); // ((qy-py)/(qx-px))(px-sx)
                  (sy, dy) = _projectiveSub(sy, dy, py, z1); // ((qy-py)/(qx-px))(px-sx)-py
                  if (dx != dy) {
                    // Cross-multiply to put everything over a common denominator
                    sx = mulmod(sx, dy, FIELD_SIZE);
                    sy = mulmod(sy, dx, FIELD_SIZE);
                    sz = mulmod(dx, dy, FIELD_SIZE);
                  } else {
                    // Already over a common denominator, use that for z ordinate
                    sz = dx;
                  }
                }
                return (sx, sy, sz);
              }
              // p1+p2, as affine points on secp256k1.
              //
              // invZ must be the inverse of the z returned by _projectiveECAdd(p1, p2).
              // It is computed off-chain to save gas.
              //
              // p1 and p2 must be distinct, because _projectiveECAdd doesn't handle
              // point doubling.
              function _affineECAdd(
                uint256[2] memory p1,
                uint256[2] memory p2,
                uint256 invZ
              ) internal pure returns (uint256[2] memory) {
                uint256 x;
                uint256 y;
                uint256 z;
                (x, y, z) = _projectiveECAdd(p1[0], p1[1], p2[0], p2[1]);
                // solhint-disable-next-line gas-custom-errors
                require(mulmod(z, invZ, FIELD_SIZE) == 1, "invZ must be inverse of z");
                // Clear the z ordinate of the projective representation by dividing through
                // by it, to obtain the affine representation
                return [mulmod(x, invZ, FIELD_SIZE), mulmod(y, invZ, FIELD_SIZE)];
              }
              // True iff address(c*p+s*g) == lcWitness, where g is generator. (With
              // cryptographically high probability.)
              function _verifyLinearCombinationWithGenerator(
                uint256 c,
                uint256[2] memory p,
                uint256 s,
                address lcWitness
              ) internal pure returns (bool) {
                // Rule out ecrecover failure modes which return address 0.
                unchecked {
                  // solhint-disable-next-line gas-custom-errors
                  require(lcWitness != address(0), "bad witness");
                  uint8 v = (p[1] % 2 == 0) ? 27 : 28; // parity of y-ordinate of p
                  // Note this cannot wrap (X - Y % X), but we use unchecked to save
                  // gas.
                  bytes32 pseudoHash = bytes32(GROUP_ORDER - mulmod(p[0], s, GROUP_ORDER)); // -s*p[0]
                  bytes32 pseudoSignature = bytes32(mulmod(c, p[0], GROUP_ORDER)); // c*p[0]
                  // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
                  // The point corresponding to the address returned by
                  // ecrecover(-s*p[0],v,p[0],c*p[0]) is
                  // (p[0]⁻¹ mod GROUP_ORDER)*(c*p[0]-(-s)*p[0]*g)=c*p+s*g.
                  // See https://crypto.stackexchange.com/a/18106
                  // https://bitcoin.stackexchange.com/questions/38351/ecdsa-v-r-s-what-is-v
                  address computed = ecrecover(pseudoHash, v, bytes32(p[0]), pseudoSignature);
                  return computed == lcWitness;
                }
              }
              // c*p1 + s*p2. Requires cp1Witness=c*p1 and sp2Witness=s*p2. Also
              // requires cp1Witness != sp2Witness (which is fine for this application,
              // since it is cryptographically impossible for them to be equal. In the
              // (cryptographically impossible) case that a prover accidentally derives
              // a proof with equal c*p1 and s*p2, they should retry with a different
              // proof nonce.) Assumes that all points are on secp256k1
              // (which is checked in _verifyVRFProof below.)
              function _linearCombination(
                uint256 c,
                uint256[2] memory p1,
                uint256[2] memory cp1Witness,
                uint256 s,
                uint256[2] memory p2,
                uint256[2] memory sp2Witness,
                uint256 zInv
              ) internal pure returns (uint256[2] memory) {
                unchecked {
                  // Note we are relying on the wrap around here
                  // solhint-disable-next-line gas-custom-errors
                  require((cp1Witness[0] % FIELD_SIZE) != (sp2Witness[0] % FIELD_SIZE), "points in sum must be distinct");
                  // solhint-disable-next-line gas-custom-errors
                  require(_ecmulVerify(p1, c, cp1Witness), "First mul check failed");
                  // solhint-disable-next-line gas-custom-errors
                  require(_ecmulVerify(p2, s, sp2Witness), "Second mul check failed");
                  return _affineECAdd(cp1Witness, sp2Witness, zInv);
                }
              }
              // Domain-separation tag for the hash taken in _scalarFromCurvePoints.
              // Corresponds to scalarFromCurveHashPrefix in vrf.go
              uint256 internal constant SCALAR_FROM_CURVE_POINTS_HASH_PREFIX = 2;
              // Pseudo-random number from inputs. Matches vrf.go/_scalarFromCurvePoints, and
              // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.4.3
              // The draft calls (in step 7, via the definition of string_to_int, in
              // https://datatracker.ietf.org/doc/html/rfc8017#section-4.2 ) for taking the
              // first hash without checking that it corresponds to a number less than the
              // group order, which will lead to a slight bias in the sample.
              //
              // TODO(alx): We could save a bit of gas by following the standard here and
              // using the compressed representation of the points, if we collated the y
              // parities into a single bytes32.
              // https://www.pivotaltracker.com/story/show/171120588
              function _scalarFromCurvePoints(
                uint256[2] memory hash,
                uint256[2] memory pk,
                uint256[2] memory gamma,
                address uWitness,
                uint256[2] memory v
              ) internal pure returns (uint256 s) {
                return uint256(keccak256(abi.encodePacked(SCALAR_FROM_CURVE_POINTS_HASH_PREFIX, hash, pk, gamma, v, uWitness)));
              }
              // True if (gamma, c, s) is a correctly constructed randomness proof from pk
              // and seed. zInv must be the inverse of the third ordinate from
              // _projectiveECAdd applied to cGammaWitness and sHashWitness. Corresponds to
              // section 5.3 of the IETF draft.
              //
              // TODO(alx): Since I'm only using pk in the ecrecover call, I could only pass
              // the x ordinate, and the parity of the y ordinate in the top bit of uWitness
              // (which I could make a uint256 without using any extra space.) Would save
              // about 2000 gas. https://www.pivotaltracker.com/story/show/170828567
              function _verifyVRFProof(
                uint256[2] memory pk,
                uint256[2] memory gamma,
                uint256 c,
                uint256 s,
                uint256 seed,
                address uWitness,
                uint256[2] memory cGammaWitness,
                uint256[2] memory sHashWitness,
                uint256 zInv
              ) internal view {
                unchecked {
                  // solhint-disable-next-line gas-custom-errors
                  require(_isOnCurve(pk), "public key is not on curve");
                  // solhint-disable-next-line gas-custom-errors
                  require(_isOnCurve(gamma), "gamma is not on curve");
                  // solhint-disable-next-line gas-custom-errors
                  require(_isOnCurve(cGammaWitness), "cGammaWitness is not on curve");
                  // solhint-disable-next-line gas-custom-errors
                  require(_isOnCurve(sHashWitness), "sHashWitness is not on curve");
                  // Step 5. of IETF draft section 5.3 (pk corresponds to 5.3's Y, and here
                  // we use the address of u instead of u itself. Also, here we add the
                  // terms instead of taking the difference, and in the proof construction in
                  // vrf.GenerateProof, we correspondingly take the difference instead of
                  // taking the sum as they do in step 7 of section 5.1.)
                  // solhint-disable-next-line gas-custom-errors
                  require(_verifyLinearCombinationWithGenerator(c, pk, s, uWitness), "addr(c*pk+s*g)!=_uWitness");
                  // Step 4. of IETF draft section 5.3 (pk corresponds to Y, seed to alpha_string)
                  uint256[2] memory hash = _hashToCurve(pk, seed);
                  // Step 6. of IETF draft section 5.3, but see note for step 5 about +/- terms
                  uint256[2] memory v = _linearCombination(c, gamma, cGammaWitness, s, hash, sHashWitness, zInv);
                  // Steps 7. and 8. of IETF draft section 5.3
                  uint256 derivedC = _scalarFromCurvePoints(hash, pk, gamma, uWitness, v);
                  // solhint-disable-next-line gas-custom-errors
                  require(c == derivedC, "invalid proof");
                }
              }
              // Domain-separation tag for the hash used as the final VRF output.
              // Corresponds to vrfRandomOutputHashPrefix in vrf.go
              uint256 internal constant VRF_RANDOM_OUTPUT_HASH_PREFIX = 3;
              struct Proof {
                uint256[2] pk;
                uint256[2] gamma;
                uint256 c;
                uint256 s;
                uint256 seed;
                address uWitness;
                uint256[2] cGammaWitness;
                uint256[2] sHashWitness;
                uint256 zInv;
              }
              /* ***************************************************************************
                 * @notice Returns proof's output, if proof is valid. Otherwise reverts
                 * @param proof vrf proof components
                 * @param seed  seed used to generate the vrf output
                 *
                 * Throws if proof is invalid, otherwise:
                 * @return output i.e., the random output implied by the proof
                 * ***************************************************************************
                 */
              function _randomValueFromVRFProof(Proof memory proof, uint256 seed) internal view returns (uint256 output) {
                _verifyVRFProof(
                  proof.pk,
                  proof.gamma,
                  proof.c,
                  proof.s,
                  seed,
                  proof.uWitness,
                  proof.cGammaWitness,
                  proof.sHashWitness,
                  proof.zInv
                );
                output = uint256(keccak256(abi.encode(VRF_RANDOM_OUTPUT_HASH_PREFIX, proof.gamma)));
                return output;
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.6;
            /**
             * @title VRFTypes
             * @notice The VRFTypes library is a collection of types that is required to fulfill VRF requests
             * \ton-chain. They must be ABI-compatible with the types used by the coordinator contracts.
             */
            library VRFTypes {
              // ABI-compatible with VRF.Proof.
              // This proof is used for VRF V2 and V2Plus.
              struct Proof {
                uint256[2] pk;
                uint256[2] gamma;
                uint256 c;
                uint256 s;
                uint256 seed;
                address uWitness;
                uint256[2] cGammaWitness;
                uint256[2] sHashWitness;
                uint256 zInv;
              }
              // ABI-compatible with VRFCoordinatorV2.RequestCommitment.
              // This is only used for VRF V2.
              struct RequestCommitment {
                uint64 blockNum;
                uint64 subId;
                uint32 callbackGasLimit;
                uint32 numWords;
                address sender;
              }
              // ABI-compatible with VRFCoordinatorV2Plus.RequestCommitment.
              // This is only used for VRF V2Plus.
              struct RequestCommitmentV2Plus {
                uint64 blockNum;
                uint256 subId;
                uint32 callbackGasLimit;
                uint32 numWords;
                address sender;
                bytes extraArgs;
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity 0.8.19;
            import {EnumerableSet} from "../../vendor/openzeppelin-solidity/v4.7.3/contracts/utils/structs/EnumerableSet.sol";
            import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol";
            import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol";
            import {AggregatorV3Interface} from "../../shared/interfaces/AggregatorV3Interface.sol";
            import {IERC677Receiver} from "../../shared/interfaces/IERC677Receiver.sol";
            import {IVRFSubscriptionV2Plus} from "./interfaces/IVRFSubscriptionV2Plus.sol";
            abstract contract SubscriptionAPI is ConfirmedOwner, IERC677Receiver, IVRFSubscriptionV2Plus {
              using EnumerableSet for EnumerableSet.UintSet;
              /// @dev may not be provided upon construction on some chains due to lack of availability
              LinkTokenInterface public LINK;
              /// @dev may not be provided upon construction on some chains due to lack of availability
              AggregatorV3Interface public LINK_NATIVE_FEED;
              // We need to maintain a list of consuming addresses.
              // This bound ensures we are able to loop over them as needed.
              // Should a user require more consumers, they can use multiple subscriptions.
              uint16 public constant MAX_CONSUMERS = 100;
              error TooManyConsumers();
              error InsufficientBalance();
              error InvalidConsumer(uint256 subId, address consumer);
              error InvalidSubscription();
              error OnlyCallableFromLink();
              error InvalidCalldata();
              error MustBeSubOwner(address owner);
              error PendingRequestExists();
              error MustBeRequestedOwner(address proposedOwner);
              error BalanceInvariantViolated(uint256 internalBalance, uint256 externalBalance); // Should never happen
              event FundsRecovered(address to, uint256 amount);
              event NativeFundsRecovered(address to, uint256 amount);
              error LinkAlreadySet();
              error FailedToSendNative();
              error FailedToTransferLink();
              error IndexOutOfRange();
              error LinkNotSet();
              // We use the subscription struct (1 word)
              // at fulfillment time.
              struct Subscription {
                // There are only 1e9*1e18 = 1e27 juels in existence, so the balance can fit in uint96 (2^96 ~ 7e28)
                uint96 balance; // Common link balance used for all consumer requests.
                // a uint96 is large enough to hold around ~8e28 wei, or 80 billion ether.
                // That should be enough to cover most (if not all) subscriptions.
                uint96 nativeBalance; // Common native balance used for all consumer requests.
                uint64 reqCount;
              }
              // We use the config for the mgmt APIs
              struct SubscriptionConfig {
                address owner; // Owner can fund/withdraw/cancel the sub.
                address requestedOwner; // For safely transferring sub ownership.
                // Maintains the list of keys in s_consumers.
                // We do this for 2 reasons:
                // 1. To be able to clean up all keys from s_consumers when canceling a subscription.
                // 2. To be able to return the list of all consumers in getSubscription.
                // Note that we need the s_consumers map to be able to directly check if a
                // consumer is valid without reading all the consumers from storage.
                address[] consumers;
              }
              struct ConsumerConfig {
                bool active;
                uint64 nonce;
                uint64 pendingReqCount;
              }
              // Note a nonce of 0 indicates the consumer is not assigned to that subscription.
              mapping(address => mapping(uint256 => ConsumerConfig)) /* consumerAddress */ /* subId */ /* consumerConfig */
                internal s_consumers;
              mapping(uint256 => SubscriptionConfig) /* subId */ /* subscriptionConfig */ internal s_subscriptionConfigs;
              mapping(uint256 => Subscription) /* subId */ /* subscription */ internal s_subscriptions;
              // subscription nonce used to construct subId. Rises monotonically
              uint64 public s_currentSubNonce;
              // track all subscription id's that were created by this contract
              // note: access should be through the getActiveSubscriptionIds() view function
              // which takes a starting index and a max number to fetch in order to allow
              // "pagination" of the subscription ids. in the event a very large number of
              // subscription id's are stored in this set, they cannot be retrieved in a
              // single RPC call without violating various size limits.
              EnumerableSet.UintSet internal s_subIds;
              // s_totalBalance tracks the total link sent to/from
              // this contract through onTokenTransfer, cancelSubscription and oracleWithdraw.
              // A discrepancy with this contract's link balance indicates someone
              // sent tokens using transfer and so we may need to use recoverFunds.
              uint96 public s_totalBalance;
              // s_totalNativeBalance tracks the total native sent to/from
              // this contract through fundSubscription, cancelSubscription and oracleWithdrawNative.
              // A discrepancy with this contract's native balance indicates someone
              // sent native using transfer and so we may need to use recoverNativeFunds.
              uint96 public s_totalNativeBalance;
              uint96 internal s_withdrawableTokens;
              uint96 internal s_withdrawableNative;
              event SubscriptionCreated(uint256 indexed subId, address owner);
              event SubscriptionFunded(uint256 indexed subId, uint256 oldBalance, uint256 newBalance);
              event SubscriptionFundedWithNative(uint256 indexed subId, uint256 oldNativeBalance, uint256 newNativeBalance);
              event SubscriptionConsumerAdded(uint256 indexed subId, address consumer);
              event SubscriptionConsumerRemoved(uint256 indexed subId, address consumer);
              event SubscriptionCanceled(uint256 indexed subId, address to, uint256 amountLink, uint256 amountNative);
              event SubscriptionOwnerTransferRequested(uint256 indexed subId, address from, address to);
              event SubscriptionOwnerTransferred(uint256 indexed subId, address from, address to);
              struct Config {
                uint16 minimumRequestConfirmations;
                uint32 maxGasLimit;
                // Reentrancy protection.
                bool reentrancyLock;
                // stalenessSeconds is how long before we consider the feed price to be stale
                // and fallback to fallbackWeiPerUnitLink.
                uint32 stalenessSeconds;
                // Gas to cover oracle payment after we calculate the payment.
                // We make it configurable in case those operations are repriced.
                // The recommended number is below, though it may vary slightly
                // if certain chains do not implement certain EIP's.
                // 21000 + // base cost of the transaction
                // 100 + 5000 + // warm subscription balance read and update. See https://eips.ethereum.org/EIPS/eip-2929
                // 2*2100 + 5000 - // cold read oracle address and oracle balance and first time oracle balance update, note first time will be 20k, but 5k subsequently
                // 4800 + // request delete refund (refunds happen after execution), note pre-london fork was 15k. See https://eips.ethereum.org/EIPS/eip-3529
                // 6685 + // Positive static costs of argument encoding etc. note that it varies by +/- x*12 for every x bytes of non-zero data in the proof.
                // Total: 37,185 gas.
                uint32 gasAfterPaymentCalculation;
                // Flat fee charged per fulfillment in millionths of native.
                // So fee range is [0, 2^32/10^6].
                uint32 fulfillmentFlatFeeNativePPM;
                // Discount relative to fulfillmentFlatFeeNativePPM for link payment in millionths of native
                // Should not exceed fulfillmentFlatFeeNativePPM
                // So fee range is [0, 2^32/10^6].
                uint32 fulfillmentFlatFeeLinkDiscountPPM;
                // nativePremiumPercentage is the percentage of the total gas costs that is added to the final premium for native payment
                // nativePremiumPercentage = 10 means 10% of the total gas costs is added. only integral percentage is allowed
                uint8 nativePremiumPercentage;
                // linkPremiumPercentage is the percentage of total gas costs that is added to the final premium for link payment
                // linkPremiumPercentage = 10 means 10% of the total gas costs is added. only integral percentage is allowed
                uint8 linkPremiumPercentage;
              }
              Config public s_config;
              error Reentrant();
              modifier nonReentrant() {
                _nonReentrant();
                _;
              }
              function _nonReentrant() internal view {
                if (s_config.reentrancyLock) {
                  revert Reentrant();
                }
              }
              constructor() ConfirmedOwner(msg.sender) {}
              /**
               * @notice set the LINK token contract and link native feed to be
               * used by this coordinator
               * @param link - address of link token
               * @param linkNativeFeed address of the link native feed
               */
              function setLINKAndLINKNativeFeed(address link, address linkNativeFeed) external onlyOwner {
                // Disallow re-setting link token because the logic wouldn't really make sense
                if (address(LINK) != address(0)) {
                  revert LinkAlreadySet();
                }
                LINK = LinkTokenInterface(link);
                LINK_NATIVE_FEED = AggregatorV3Interface(linkNativeFeed);
              }
              /**
               * @notice Owner cancel subscription, sends remaining link directly to the subscription owner.
               * @param subId subscription id
               * @dev notably can be called even if there are pending requests, outstanding ones may fail onchain
               */
              function ownerCancelSubscription(uint256 subId) external onlyOwner {
                address subOwner = s_subscriptionConfigs[subId].owner;
                if (subOwner == address(0)) {
                  revert InvalidSubscription();
                }
                _cancelSubscriptionHelper(subId, subOwner);
              }
              /**
               * @notice Recover link sent with transfer instead of transferAndCall.
               * @param to address to send link to
               */
              function recoverFunds(address to) external onlyOwner {
                // If LINK is not set, we cannot recover funds.
                // It is possible that this coordinator address was funded with LINK
                // by accident by a user but the LINK token needs to be set first
                // before we can recover it.
                if (address(LINK) == address(0)) {
                  revert LinkNotSet();
                }
                uint256 externalBalance = LINK.balanceOf(address(this));
                uint256 internalBalance = uint256(s_totalBalance);
                if (internalBalance > externalBalance) {
                  revert BalanceInvariantViolated(internalBalance, externalBalance);
                }
                if (internalBalance < externalBalance) {
                  uint256 amount = externalBalance - internalBalance;
                  if (!LINK.transfer(to, amount)) {
                    revert FailedToTransferLink();
                  }
                  emit FundsRecovered(to, amount);
                }
                // If the balances are equal, nothing to be done.
              }
              /**
               * @notice Recover native sent with transfer/call/send instead of fundSubscription.
               * @param to address to send native to
               */
              function recoverNativeFunds(address payable to) external onlyOwner {
                uint256 externalBalance = address(this).balance;
                uint256 internalBalance = uint256(s_totalNativeBalance);
                if (internalBalance > externalBalance) {
                  revert BalanceInvariantViolated(internalBalance, externalBalance);
                }
                if (internalBalance < externalBalance) {
                  uint256 amount = externalBalance - internalBalance;
                  (bool sent, ) = to.call{value: amount}("");
                  if (!sent) {
                    revert FailedToSendNative();
                  }
                  emit NativeFundsRecovered(to, amount);
                }
                // If the balances are equal, nothing to be done.
              }
              /*
               * @notice withdraw LINK earned through fulfilling requests
               * @param recipient where to send the funds
               * @param amount amount to withdraw
               */
              function withdraw(address recipient) external nonReentrant onlyOwner {
                if (address(LINK) == address(0)) {
                  revert LinkNotSet();
                }
                if (s_withdrawableTokens == 0) {
                  revert InsufficientBalance();
                }
                uint96 amount = s_withdrawableTokens;
                s_withdrawableTokens -= amount;
                s_totalBalance -= amount;
                if (!LINK.transfer(recipient, amount)) {
                  revert InsufficientBalance();
                }
              }
              /*
               * @notice withdraw native earned through fulfilling requests
               * @param recipient where to send the funds
               * @param amount amount to withdraw
               */
              function withdrawNative(address payable recipient) external nonReentrant onlyOwner {
                if (s_withdrawableNative == 0) {
                  revert InsufficientBalance();
                }
                // Prevent re-entrancy by updating state before transfer.
                uint96 amount = s_withdrawableNative;
                s_withdrawableNative -= amount;
                s_totalNativeBalance -= amount;
                (bool sent, ) = recipient.call{value: amount}("");
                if (!sent) {
                  revert FailedToSendNative();
                }
              }
              function onTokenTransfer(address /* sender */, uint256 amount, bytes calldata data) external override nonReentrant {
                if (msg.sender != address(LINK)) {
                  revert OnlyCallableFromLink();
                }
                if (data.length != 32) {
                  revert InvalidCalldata();
                }
                uint256 subId = abi.decode(data, (uint256));
                if (s_subscriptionConfigs[subId].owner == address(0)) {
                  revert InvalidSubscription();
                }
                // We do not check that the sender is the subscription owner,
                // anyone can fund a subscription.
                uint256 oldBalance = s_subscriptions[subId].balance;
                s_subscriptions[subId].balance += uint96(amount);
                s_totalBalance += uint96(amount);
                emit SubscriptionFunded(subId, oldBalance, oldBalance + amount);
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function fundSubscriptionWithNative(uint256 subId) external payable override nonReentrant {
                if (s_subscriptionConfigs[subId].owner == address(0)) {
                  revert InvalidSubscription();
                }
                // We do not check that the msg.sender is the subscription owner,
                // anyone can fund a subscription.
                // We also do not check that msg.value > 0, since that's just a no-op
                // and would be a waste of gas on the caller's part.
                uint256 oldNativeBalance = s_subscriptions[subId].nativeBalance;
                s_subscriptions[subId].nativeBalance += uint96(msg.value);
                s_totalNativeBalance += uint96(msg.value);
                emit SubscriptionFundedWithNative(subId, oldNativeBalance, oldNativeBalance + msg.value);
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function getSubscription(
                uint256 subId
              )
                public
                view
                override
                returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address subOwner, address[] memory consumers)
              {
                subOwner = s_subscriptionConfigs[subId].owner;
                if (subOwner == address(0)) {
                  revert InvalidSubscription();
                }
                return (
                  s_subscriptions[subId].balance,
                  s_subscriptions[subId].nativeBalance,
                  s_subscriptions[subId].reqCount,
                  subOwner,
                  s_subscriptionConfigs[subId].consumers
                );
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function getActiveSubscriptionIds(
                uint256 startIndex,
                uint256 maxCount
              ) external view override returns (uint256[] memory ids) {
                uint256 numSubs = s_subIds.length();
                if (startIndex >= numSubs) revert IndexOutOfRange();
                uint256 endIndex = startIndex + maxCount;
                endIndex = endIndex > numSubs || maxCount == 0 ? numSubs : endIndex;
                uint256 idsLength = endIndex - startIndex;
                ids = new uint256[](idsLength);
                for (uint256 idx = 0; idx < idsLength; ++idx) {
                  ids[idx] = s_subIds.at(idx + startIndex);
                }
                return ids;
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function createSubscription() external override nonReentrant returns (uint256 subId) {
                // Generate a subscription id that is globally unique.
                uint64 currentSubNonce = s_currentSubNonce;
                subId = uint256(
                  keccak256(abi.encodePacked(msg.sender, blockhash(block.number - 1), address(this), currentSubNonce))
                );
                // Increment the subscription nonce counter.
                s_currentSubNonce = currentSubNonce + 1;
                // Initialize storage variables.
                address[] memory consumers = new address[](0);
                s_subscriptions[subId] = Subscription({balance: 0, nativeBalance: 0, reqCount: 0});
                s_subscriptionConfigs[subId] = SubscriptionConfig({
                  owner: msg.sender,
                  requestedOwner: address(0),
                  consumers: consumers
                });
                // Update the s_subIds set, which tracks all subscription ids created in this contract.
                s_subIds.add(subId);
                emit SubscriptionCreated(subId, msg.sender);
                return subId;
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function requestSubscriptionOwnerTransfer(
                uint256 subId,
                address newOwner
              ) external override onlySubOwner(subId) nonReentrant {
                // Proposing to address(0) would never be claimable so don't need to check.
                SubscriptionConfig storage subscriptionConfig = s_subscriptionConfigs[subId];
                if (subscriptionConfig.requestedOwner != newOwner) {
                  subscriptionConfig.requestedOwner = newOwner;
                  emit SubscriptionOwnerTransferRequested(subId, msg.sender, newOwner);
                }
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function acceptSubscriptionOwnerTransfer(uint256 subId) external override nonReentrant {
                address oldOwner = s_subscriptionConfigs[subId].owner;
                if (oldOwner == address(0)) {
                  revert InvalidSubscription();
                }
                if (s_subscriptionConfigs[subId].requestedOwner != msg.sender) {
                  revert MustBeRequestedOwner(s_subscriptionConfigs[subId].requestedOwner);
                }
                s_subscriptionConfigs[subId].owner = msg.sender;
                s_subscriptionConfigs[subId].requestedOwner = address(0);
                emit SubscriptionOwnerTransferred(subId, oldOwner, msg.sender);
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function addConsumer(uint256 subId, address consumer) external override onlySubOwner(subId) nonReentrant {
                ConsumerConfig storage consumerConfig = s_consumers[consumer][subId];
                if (consumerConfig.active) {
                  // Idempotence - do nothing if already added.
                  // Ensures uniqueness in s_subscriptions[subId].consumers.
                  return;
                }
                // Already maxed, cannot add any more consumers.
                address[] storage consumers = s_subscriptionConfigs[subId].consumers;
                if (consumers.length == MAX_CONSUMERS) {
                  revert TooManyConsumers();
                }
                // consumerConfig.nonce is 0 if the consumer had never sent a request to this subscription
                // otherwise, consumerConfig.nonce is non-zero
                // in both cases, use consumerConfig.nonce as is and set active status to true
                consumerConfig.active = true;
                consumers.push(consumer);
                emit SubscriptionConsumerAdded(subId, consumer);
              }
              function _deleteSubscription(uint256 subId) internal returns (uint96 balance, uint96 nativeBalance) {
                address[] storage consumers = s_subscriptionConfigs[subId].consumers;
                balance = s_subscriptions[subId].balance;
                nativeBalance = s_subscriptions[subId].nativeBalance;
                // Note bounded by MAX_CONSUMERS;
                // If no consumers, does nothing.
                uint256 consumersLength = consumers.length;
                for (uint256 i = 0; i < consumersLength; ++i) {
                  delete s_consumers[consumers[i]][subId];
                }
                delete s_subscriptionConfigs[subId];
                delete s_subscriptions[subId];
                s_subIds.remove(subId);
                if (balance != 0) {
                  s_totalBalance -= balance;
                }
                if (nativeBalance != 0) {
                  s_totalNativeBalance -= nativeBalance;
                }
                return (balance, nativeBalance);
              }
              function _cancelSubscriptionHelper(uint256 subId, address to) internal {
                (uint96 balance, uint96 nativeBalance) = _deleteSubscription(subId);
                // Only withdraw LINK if the token is active and there is a balance.
                if (address(LINK) != address(0) && balance != 0) {
                  if (!LINK.transfer(to, uint256(balance))) {
                    revert InsufficientBalance();
                  }
                }
                // send native to the "to" address using call
                (bool success, ) = to.call{value: uint256(nativeBalance)}("");
                if (!success) {
                  revert FailedToSendNative();
                }
                emit SubscriptionCanceled(subId, to, balance, nativeBalance);
              }
              modifier onlySubOwner(uint256 subId) {
                _onlySubOwner(subId);
                _;
              }
              function _onlySubOwner(uint256 subId) internal view {
                address subOwner = s_subscriptionConfigs[subId].owner;
                if (subOwner == address(0)) {
                  revert InvalidSubscription();
                }
                if (msg.sender != subOwner) {
                  revert MustBeSubOwner(subOwner);
                }
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            import {IVRFCoordinatorV2Plus} from "./interfaces/IVRFCoordinatorV2Plus.sol";
            import {IVRFMigratableConsumerV2Plus} from "./interfaces/IVRFMigratableConsumerV2Plus.sol";
            import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol";
            /** ****************************************************************************
             * @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 VRFCoordinatorV2Plus.
             * @dev 2. The consumer contract implements fulfillRandomWords.
             * *****************************************************************************
             * @dev USAGE
             *
             * @dev Calling contracts must inherit from VRFConsumerBaseV2Plus, and can
             * @dev initialize VRFConsumerBaseV2Plus's attributes in their constructor as
             * @dev shown:
             *
             * @dev   contract VRFConsumerV2Plus is VRFConsumerBaseV2Plus {
             * @dev     constructor(<other arguments>, address _vrfCoordinator, address _subOwner)
             * @dev       VRFConsumerBaseV2Plus(_vrfCoordinator, _subOwner) 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 a 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, extraArgs),
             * @dev see (IVRFCoordinatorV2Plus for a description of the arguments).
             *
             * @dev Once the VRFCoordinatorV2Plus 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 VRFConsumerBaseV2Plus.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 VRFConsumerBaseV2Plus is IVRFMigratableConsumerV2Plus, ConfirmedOwner {
              error OnlyCoordinatorCanFulfill(address have, address want);
              error OnlyOwnerOrCoordinator(address have, address owner, address coordinator);
              error ZeroAddress();
              // s_vrfCoordinator should be used by consumers to make requests to vrfCoordinator
              // so that coordinator reference is updated after migration
              IVRFCoordinatorV2Plus public s_vrfCoordinator;
              /**
               * @param _vrfCoordinator address of VRFCoordinator contract
               */
              constructor(address _vrfCoordinator) ConfirmedOwner(msg.sender) {
                if (_vrfCoordinator == address(0)) {
                  revert ZeroAddress();
                }
                s_vrfCoordinator = IVRFCoordinatorV2Plus(_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 VRFConsumerBaseV2Plus 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
               */
              // solhint-disable-next-line chainlink-solidity/prefix-internal-functions-with-underscore
              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 != address(s_vrfCoordinator)) {
                  revert OnlyCoordinatorCanFulfill(msg.sender, address(s_vrfCoordinator));
                }
                fulfillRandomWords(requestId, randomWords);
              }
              /**
               * @inheritdoc IVRFMigratableConsumerV2Plus
               */
              function setCoordinator(address _vrfCoordinator) external override onlyOwnerOrCoordinator {
                if (_vrfCoordinator == address(0)) {
                  revert ZeroAddress();
                }
                s_vrfCoordinator = IVRFCoordinatorV2Plus(_vrfCoordinator);
                emit CoordinatorSet(_vrfCoordinator);
              }
              modifier onlyOwnerOrCoordinator() {
                if (msg.sender != owner() && msg.sender != address(s_vrfCoordinator)) {
                  revert OnlyOwnerOrCoordinator(msg.sender, owner(), address(s_vrfCoordinator));
                }
                _;
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity 0.8.19;
            import {BlockhashStoreInterface} from "../interfaces/BlockhashStoreInterface.sol";
            import {VRF} from "../../vrf/VRF.sol";
            import {VRFTypes} from "../VRFTypes.sol";
            import {VRFConsumerBaseV2Plus, IVRFMigratableConsumerV2Plus} from "./VRFConsumerBaseV2Plus.sol";
            import {ChainSpecificUtil} from "../../ChainSpecificUtil.sol";
            import {SubscriptionAPI} from "./SubscriptionAPI.sol";
            import {VRFV2PlusClient} from "./libraries/VRFV2PlusClient.sol";
            import {IVRFCoordinatorV2PlusMigration} from "./interfaces/IVRFCoordinatorV2PlusMigration.sol";
            // solhint-disable-next-line no-unused-import
            import {IVRFCoordinatorV2Plus, IVRFSubscriptionV2Plus} from "./interfaces/IVRFCoordinatorV2Plus.sol";
            // solhint-disable-next-line contract-name-camelcase
            contract VRFCoordinatorV2_5 is VRF, SubscriptionAPI, IVRFCoordinatorV2Plus {
              /// @dev should always be available
              // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i
              BlockhashStoreInterface public immutable BLOCKHASH_STORE;
              // Set this maximum to 200 to give us a 56 block window to fulfill
              // the request before requiring the block hash feeder.
              uint16 public constant MAX_REQUEST_CONFIRMATIONS = 200;
              uint32 public constant MAX_NUM_WORDS = 500;
              // 5k is plenty for an EXTCODESIZE call (2600) + warm CALL (100)
              // and some arithmetic operations.
              uint256 private constant GAS_FOR_CALL_EXACT_CHECK = 5_000;
              // upper bound limit for premium percentages to make sure fee calculations don't overflow
              uint8 private constant PREMIUM_PERCENTAGE_MAX = 155;
              error InvalidRequestConfirmations(uint16 have, uint16 min, uint16 max);
              error GasLimitTooBig(uint32 have, uint32 want);
              error NumWordsTooBig(uint32 have, uint32 want);
              error MsgDataTooBig(uint256 have, uint32 max);
              error ProvingKeyAlreadyRegistered(bytes32 keyHash);
              error NoSuchProvingKey(bytes32 keyHash);
              error InvalidLinkWeiPrice(int256 linkWei);
              error LinkDiscountTooHigh(uint32 flatFeeLinkDiscountPPM, uint32 flatFeeNativePPM);
              error InvalidPremiumPercentage(uint8 premiumPercentage, uint8 max);
              error NoCorrespondingRequest();
              error IncorrectCommitment();
              error BlockhashNotInStore(uint256 blockNum);
              error PaymentTooLarge();
              error InvalidExtraArgsTag();
              error GasPriceExceeded(uint256 gasPrice, uint256 maxGas);
              struct ProvingKey {
                bool exists; // proving key exists
                uint64 maxGas; // gas lane max gas price for fulfilling requests
              }
              mapping(bytes32 => ProvingKey) /* keyHash */ /* provingKey */ public s_provingKeys;
              bytes32[] public s_provingKeyHashes;
              mapping(uint256 => bytes32) /* requestID */ /* commitment */ public s_requestCommitments;
              event ProvingKeyRegistered(bytes32 keyHash, uint64 maxGas);
              event ProvingKeyDeregistered(bytes32 keyHash, uint64 maxGas);
              event RandomWordsRequested(
                bytes32 indexed keyHash,
                uint256 requestId,
                uint256 preSeed,
                uint256 indexed subId,
                uint16 minimumRequestConfirmations,
                uint32 callbackGasLimit,
                uint32 numWords,
                bytes extraArgs,
                address indexed sender
              );
              event RandomWordsFulfilled(
                uint256 indexed requestId,
                uint256 outputSeed,
                uint256 indexed subId,
                uint96 payment,
                bool nativePayment,
                bool success,
                bool onlyPremium
              );
              int256 public s_fallbackWeiPerUnitLink;
              event ConfigSet(
                uint16 minimumRequestConfirmations,
                uint32 maxGasLimit,
                uint32 stalenessSeconds,
                uint32 gasAfterPaymentCalculation,
                int256 fallbackWeiPerUnitLink,
                uint32 fulfillmentFlatFeeNativePPM,
                uint32 fulfillmentFlatFeeLinkDiscountPPM,
                uint8 nativePremiumPercentage,
                uint8 linkPremiumPercentage
              );
              event FallbackWeiPerUnitLinkUsed(uint256 requestId, int256 fallbackWeiPerUnitLink);
              constructor(address blockhashStore) SubscriptionAPI() {
                BLOCKHASH_STORE = BlockhashStoreInterface(blockhashStore);
              }
              /**
               * @notice Registers a proving key to.
               * @param publicProvingKey key that oracle can use to submit vrf fulfillments
               */
              function registerProvingKey(uint256[2] calldata publicProvingKey, uint64 maxGas) external onlyOwner {
                bytes32 kh = hashOfKey(publicProvingKey);
                if (s_provingKeys[kh].exists) {
                  revert ProvingKeyAlreadyRegistered(kh);
                }
                s_provingKeys[kh] = ProvingKey({exists: true, maxGas: maxGas});
                s_provingKeyHashes.push(kh);
                emit ProvingKeyRegistered(kh, maxGas);
              }
              /**
               * @notice Deregisters a proving key.
               * @param publicProvingKey key that oracle can use to submit vrf fulfillments
               */
              function deregisterProvingKey(uint256[2] calldata publicProvingKey) external onlyOwner {
                bytes32 kh = hashOfKey(publicProvingKey);
                ProvingKey memory key = s_provingKeys[kh];
                if (!key.exists) {
                  revert NoSuchProvingKey(kh);
                }
                delete s_provingKeys[kh];
                uint256 s_provingKeyHashesLength = s_provingKeyHashes.length;
                for (uint256 i = 0; i < s_provingKeyHashesLength; ++i) {
                  if (s_provingKeyHashes[i] == kh) {
                    // Copy last element and overwrite kh to be deleted with it
                    s_provingKeyHashes[i] = s_provingKeyHashes[s_provingKeyHashesLength - 1];
                    s_provingKeyHashes.pop();
                    break;
                  }
                }
                emit ProvingKeyDeregistered(kh, key.maxGas);
              }
              /**
               * @notice Returns the proving key hash key associated with this public key
               * @param publicKey the key to return the hash of
               */
              function hashOfKey(uint256[2] memory publicKey) public pure returns (bytes32) {
                return keccak256(abi.encode(publicKey));
              }
              /**
               * @notice Sets the configuration of the vrfv2 coordinator
               * @param minimumRequestConfirmations global min for request confirmations
               * @param maxGasLimit global max for request gas limit
               * @param stalenessSeconds if the native/link feed is more stale then this, use the fallback price
               * @param gasAfterPaymentCalculation gas used in doing accounting after completing the gas measurement
               * @param fallbackWeiPerUnitLink fallback native/link price in the case of a stale feed
               * @param fulfillmentFlatFeeNativePPM flat fee in native for native payment
               * @param fulfillmentFlatFeeLinkDiscountPPM flat fee discount for link payment in native
               * @param nativePremiumPercentage native premium percentage
               * @param linkPremiumPercentage link premium percentage
               */
              function setConfig(
                uint16 minimumRequestConfirmations,
                uint32 maxGasLimit,
                uint32 stalenessSeconds,
                uint32 gasAfterPaymentCalculation,
                int256 fallbackWeiPerUnitLink,
                uint32 fulfillmentFlatFeeNativePPM,
                uint32 fulfillmentFlatFeeLinkDiscountPPM,
                uint8 nativePremiumPercentage,
                uint8 linkPremiumPercentage
              ) external onlyOwner {
                if (minimumRequestConfirmations > MAX_REQUEST_CONFIRMATIONS) {
                  revert InvalidRequestConfirmations(
                    minimumRequestConfirmations,
                    minimumRequestConfirmations,
                    MAX_REQUEST_CONFIRMATIONS
                  );
                }
                if (fallbackWeiPerUnitLink <= 0) {
                  revert InvalidLinkWeiPrice(fallbackWeiPerUnitLink);
                }
                if (fulfillmentFlatFeeLinkDiscountPPM > fulfillmentFlatFeeNativePPM) {
                  revert LinkDiscountTooHigh(fulfillmentFlatFeeLinkDiscountPPM, fulfillmentFlatFeeNativePPM);
                }
                if (nativePremiumPercentage > PREMIUM_PERCENTAGE_MAX) {
                  revert InvalidPremiumPercentage(nativePremiumPercentage, PREMIUM_PERCENTAGE_MAX);
                }
                if (linkPremiumPercentage > PREMIUM_PERCENTAGE_MAX) {
                  revert InvalidPremiumPercentage(linkPremiumPercentage, PREMIUM_PERCENTAGE_MAX);
                }
                s_config = Config({
                  minimumRequestConfirmations: minimumRequestConfirmations,
                  maxGasLimit: maxGasLimit,
                  stalenessSeconds: stalenessSeconds,
                  gasAfterPaymentCalculation: gasAfterPaymentCalculation,
                  reentrancyLock: false,
                  fulfillmentFlatFeeNativePPM: fulfillmentFlatFeeNativePPM,
                  fulfillmentFlatFeeLinkDiscountPPM: fulfillmentFlatFeeLinkDiscountPPM,
                  nativePremiumPercentage: nativePremiumPercentage,
                  linkPremiumPercentage: linkPremiumPercentage
                });
                s_fallbackWeiPerUnitLink = fallbackWeiPerUnitLink;
                emit ConfigSet(
                  minimumRequestConfirmations,
                  maxGasLimit,
                  stalenessSeconds,
                  gasAfterPaymentCalculation,
                  fallbackWeiPerUnitLink,
                  fulfillmentFlatFeeNativePPM,
                  fulfillmentFlatFeeLinkDiscountPPM,
                  nativePremiumPercentage,
                  linkPremiumPercentage
                );
              }
              /// @dev Convert the extra args bytes into a struct
              /// @param extraArgs The extra args bytes
              /// @return The extra args struct
              function _fromBytes(bytes calldata extraArgs) internal pure returns (VRFV2PlusClient.ExtraArgsV1 memory) {
                if (extraArgs.length == 0) {
                  return VRFV2PlusClient.ExtraArgsV1({nativePayment: false});
                }
                if (bytes4(extraArgs) != VRFV2PlusClient.EXTRA_ARGS_V1_TAG) revert InvalidExtraArgsTag();
                return abi.decode(extraArgs[4:], (VRFV2PlusClient.ExtraArgsV1));
              }
              /**
               * @notice Request a set of random words.
               * @param req - a struct containing following fiels for randomness request:
               * 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.
               * subId  - The ID of the VRF subscription. Must be funded
               * with the minimum subscription balance required for the selected keyHash.
               * requestConfirmations - 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].
               * 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]
               * 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.
               * extraArgs - Encoded extra arguments that has a boolean flag for whether payment
               * should be made in native or LINK. Payment in LINK is only available if the LINK token is available to this contract.
               * @return requestId - A unique identifier of the request. Can be used to match
               * a request to a response in fulfillRandomWords.
               */
              function requestRandomWords(
                VRFV2PlusClient.RandomWordsRequest calldata req
              ) external override nonReentrant returns (uint256 requestId) {
                // Input validation using the subscription storage.
                uint256 subId = req.subId;
                if (s_subscriptionConfigs[subId].owner == address(0)) {
                  revert InvalidSubscription();
                }
                // Its important to ensure that the consumer is in fact who they say they
                // are, otherwise they could use someone else's subscription balance.
                mapping(uint256 => ConsumerConfig) storage consumerConfigs = s_consumers[msg.sender];
                ConsumerConfig memory consumerConfig = consumerConfigs[subId];
                if (!consumerConfig.active) {
                  revert InvalidConsumer(subId, msg.sender);
                }
                // Input validation using the config storage word.
                if (
                  req.requestConfirmations < s_config.minimumRequestConfirmations ||
                  req.requestConfirmations > MAX_REQUEST_CONFIRMATIONS
                ) {
                  revert InvalidRequestConfirmations(
                    req.requestConfirmations,
                    s_config.minimumRequestConfirmations,
                    MAX_REQUEST_CONFIRMATIONS
                  );
                }
                // No lower bound on the requested gas limit. A user could request 0
                // and they would simply be billed for the proof verification and wouldn't be
                // able to do anything with the random value.
                if (req.callbackGasLimit > s_config.maxGasLimit) {
                  revert GasLimitTooBig(req.callbackGasLimit, s_config.maxGasLimit);
                }
                if (req.numWords > MAX_NUM_WORDS) {
                  revert NumWordsTooBig(req.numWords, MAX_NUM_WORDS);
                }
                // Note we do not check whether the keyHash is valid to save gas.
                // The consequence for users is that they can send requests
                // for invalid keyHashes which will simply not be fulfilled.
                ++consumerConfig.nonce;
                ++consumerConfig.pendingReqCount;
                uint256 preSeed;
                (requestId, preSeed) = _computeRequestId(req.keyHash, msg.sender, subId, consumerConfig.nonce);
                bytes memory extraArgsBytes = VRFV2PlusClient._argsToBytes(_fromBytes(req.extraArgs));
                s_requestCommitments[requestId] = keccak256(
                  abi.encode(
                    requestId,
                    ChainSpecificUtil._getBlockNumber(),
                    subId,
                    req.callbackGasLimit,
                    req.numWords,
                    msg.sender,
                    extraArgsBytes
                  )
                );
                emit RandomWordsRequested(
                  req.keyHash,
                  requestId,
                  preSeed,
                  subId,
                  req.requestConfirmations,
                  req.callbackGasLimit,
                  req.numWords,
                  extraArgsBytes,
                  msg.sender
                );
                consumerConfigs[subId] = consumerConfig;
                return requestId;
              }
              function _computeRequestId(
                bytes32 keyHash,
                address sender,
                uint256 subId,
                uint64 nonce
              ) internal pure returns (uint256, uint256) {
                uint256 preSeed = uint256(keccak256(abi.encode(keyHash, sender, subId, nonce)));
                return (uint256(keccak256(abi.encode(keyHash, preSeed))), preSeed);
              }
              /**
               * @dev calls target address with exactly gasAmount gas and data as calldata
               * or reverts if at least gasAmount gas is not available.
               */
              function _callWithExactGas(uint256 gasAmount, address target, bytes memory data) private returns (bool success) {
                assembly {
                  let g := gas()
                  // Compute g -= GAS_FOR_CALL_EXACT_CHECK and check for underflow
                  // The gas actually passed to the callee is min(gasAmount, 63//64*gas available).
                  // We want to ensure that we revert if gasAmount >  63//64*gas available
                  // as we do not want to provide them with less, however that check itself costs
                  // gas.  GAS_FOR_CALL_EXACT_CHECK ensures we have at least enough gas to be able
                  // to revert if gasAmount >  63//64*gas available.
                  if lt(g, GAS_FOR_CALL_EXACT_CHECK) {
                    revert(0, 0)
                  }
                  g := sub(g, GAS_FOR_CALL_EXACT_CHECK)
                  // if g - g//64 <= gasAmount, revert
                  // (we subtract g//64 because of EIP-150)
                  if iszero(gt(sub(g, div(g, 64)), gasAmount)) {
                    revert(0, 0)
                  }
                  // solidity calls check that a contract actually exists at the destination, so we do the same
                  if iszero(extcodesize(target)) {
                    revert(0, 0)
                  }
                  // call and return whether we succeeded. ignore return data
                  // call(gas,addr,value,argsOffset,argsLength,retOffset,retLength)
                  success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0)
                }
                return success;
              }
              struct Output {
                ProvingKey provingKey;
                uint256 requestId;
                uint256 randomness;
              }
              function _getRandomnessFromProof(
                Proof memory proof,
                VRFTypes.RequestCommitmentV2Plus memory rc
              ) internal view returns (Output memory) {
                bytes32 keyHash = hashOfKey(proof.pk);
                ProvingKey memory key = s_provingKeys[keyHash];
                // Only registered proving keys are permitted.
                if (!key.exists) {
                  revert NoSuchProvingKey(keyHash);
                }
                uint256 requestId = uint256(keccak256(abi.encode(keyHash, proof.seed)));
                bytes32 commitment = s_requestCommitments[requestId];
                if (commitment == 0) {
                  revert NoCorrespondingRequest();
                }
                if (
                  commitment !=
                  keccak256(abi.encode(requestId, rc.blockNum, rc.subId, rc.callbackGasLimit, rc.numWords, rc.sender, rc.extraArgs))
                ) {
                  revert IncorrectCommitment();
                }
                bytes32 blockHash = ChainSpecificUtil._getBlockhash(rc.blockNum);
                if (blockHash == bytes32(0)) {
                  blockHash = BLOCKHASH_STORE.getBlockhash(rc.blockNum);
                  if (blockHash == bytes32(0)) {
                    revert BlockhashNotInStore(rc.blockNum);
                  }
                }
                // The seed actually used by the VRF machinery, mixing in the blockhash
                uint256 actualSeed = uint256(keccak256(abi.encodePacked(proof.seed, blockHash)));
                uint256 randomness = VRF._randomValueFromVRFProof(proof, actualSeed); // Reverts on failure
                return Output(key, requestId, randomness);
              }
              function _getValidatedGasPrice(bool onlyPremium, uint64 gasLaneMaxGas) internal view returns (uint256 gasPrice) {
                if (tx.gasprice > gasLaneMaxGas) {
                  if (onlyPremium) {
                    // if only the premium amount needs to be billed, then the premium is capped by the gas lane max
                    return uint256(gasLaneMaxGas);
                  } else {
                    // Ensure gas price does not exceed the gas lane max gas price
                    revert GasPriceExceeded(tx.gasprice, gasLaneMaxGas);
                  }
                }
                return tx.gasprice;
              }
              function _deliverRandomness(
                uint256 requestId,
                VRFTypes.RequestCommitmentV2Plus memory rc,
                uint256[] memory randomWords
              ) internal returns (bool success) {
                VRFConsumerBaseV2Plus v;
                bytes memory resp = abi.encodeWithSelector(v.rawFulfillRandomWords.selector, requestId, randomWords);
                // Call with explicitly the amount of callback gas requested
                // Important to not let them exhaust the gas budget and avoid oracle payment.
                // Do not allow any non-view/non-pure coordinator functions to be called
                // during the consumers callback code via reentrancyLock.
                // Note that _callWithExactGas will revert if we do not have sufficient gas
                // to give the callee their requested amount.
                s_config.reentrancyLock = true;
                success = _callWithExactGas(rc.callbackGasLimit, rc.sender, resp);
                s_config.reentrancyLock = false;
                return success;
              }
              /*
               * @notice Fulfill a randomness request.
               * @param proof contains the proof and randomness
               * @param rc request commitment pre-image, committed to at request time
               * @param onlyPremium only charge premium
               * @return payment amount billed to the subscription
               * @dev simulated offchain to determine if sufficient balance is present to fulfill the request
               */
              function fulfillRandomWords(
                Proof memory proof,
                VRFTypes.RequestCommitmentV2Plus memory rc,
                bool onlyPremium
              ) external nonReentrant returns (uint96 payment) {
                uint256 startGas = gasleft();
                // fulfillRandomWords msg.data has 772 bytes and with an additional
                // buffer of 32 bytes, we get 804 bytes.
                /* Data size split:
                 * fulfillRandomWords function signature - 4 bytes
                 * proof - 416 bytes
                 *   pk - 64 bytes
                 *   gamma - 64 bytes
                 *   c - 32 bytes
                 *   s - 32 bytes
                 *   seed - 32 bytes
                 *   uWitness - 32 bytes
                 *   cGammaWitness - 64 bytes
                 *   sHashWitness - 64 bytes
                 *   zInv - 32 bytes
                 * requestCommitment - 320 bytes
                 *   blockNum - 32 bytes
                 *   subId - 32 bytes
                 *   callbackGasLimit - 32 bytes
                 *   numWords - 32 bytes
                 *   sender - 32 bytes
                 *   extraArgs - 128 bytes
                 * onlyPremium - 32 bytes
                 */
                if (msg.data.length > 804) {
                  revert MsgDataTooBig(msg.data.length, 804);
                }
                Output memory output = _getRandomnessFromProof(proof, rc);
                uint256 gasPrice = _getValidatedGasPrice(onlyPremium, output.provingKey.maxGas);
                uint256[] memory randomWords;
                uint256 randomness = output.randomness;
                // stack too deep error
                {
                  uint256 numWords = rc.numWords;
                  randomWords = new uint256[](numWords);
                  for (uint256 i = 0; i < numWords; ++i) {
                    randomWords[i] = uint256(keccak256(abi.encode(randomness, i)));
                  }
                }
                delete s_requestCommitments[output.requestId];
                bool success = _deliverRandomness(output.requestId, rc, randomWords);
                // Increment the req count for the subscription.
                ++s_subscriptions[rc.subId].reqCount;
                // Decrement the pending req count for the consumer.
                --s_consumers[rc.sender][rc.subId].pendingReqCount;
                bool nativePayment = uint8(rc.extraArgs[rc.extraArgs.length - 1]) == 1;
                // stack too deep error
                {
                  // We want to charge users exactly for how much gas they use in their callback with
                  // an additional premium. If onlyPremium is true, only premium is charged without
                  // the gas cost. The gasAfterPaymentCalculation is meant to cover these additional
                  // operations where we decrement the subscription balance and increment the
                  // withdrawable balance.
                  bool isFeedStale;
                  (payment, isFeedStale) = _calculatePaymentAmount(startGas, gasPrice, nativePayment, onlyPremium);
                  if (isFeedStale) {
                    emit FallbackWeiPerUnitLinkUsed(output.requestId, s_fallbackWeiPerUnitLink);
                  }
                }
                _chargePayment(payment, nativePayment, rc.subId);
                // Include payment in the event for tracking costs.
                emit RandomWordsFulfilled(output.requestId, randomness, rc.subId, payment, nativePayment, success, onlyPremium);
                return payment;
              }
              function _chargePayment(uint96 payment, bool nativePayment, uint256 subId) internal {
                Subscription storage subcription = s_subscriptions[subId];
                if (nativePayment) {
                  uint96 prevBal = subcription.nativeBalance;
                  if (prevBal < payment) {
                    revert InsufficientBalance();
                  }
                  subcription.nativeBalance = prevBal - payment;
                  s_withdrawableNative += payment;
                } else {
                  uint96 prevBal = subcription.balance;
                  if (prevBal < payment) {
                    revert InsufficientBalance();
                  }
                  subcription.balance = prevBal - payment;
                  s_withdrawableTokens += payment;
                }
              }
              function _calculatePaymentAmount(
                uint256 startGas,
                uint256 weiPerUnitGas,
                bool nativePayment,
                bool onlyPremium
              ) internal view returns (uint96, bool) {
                if (nativePayment) {
                  return (_calculatePaymentAmountNative(startGas, weiPerUnitGas, onlyPremium), false);
                }
                return _calculatePaymentAmountLink(startGas, weiPerUnitGas, onlyPremium);
              }
              function _calculatePaymentAmountNative(
                uint256 startGas,
                uint256 weiPerUnitGas,
                bool onlyPremium
              ) internal view returns (uint96) {
                // Will return non-zero on chains that have this enabled
                uint256 l1CostWei = ChainSpecificUtil._getCurrentTxL1GasFees(msg.data);
                // calculate the payment without the premium
                uint256 baseFeeWei = weiPerUnitGas * (s_config.gasAfterPaymentCalculation + startGas - gasleft());
                // calculate flat fee in native
                uint256 flatFeeWei = 1e12 * uint256(s_config.fulfillmentFlatFeeNativePPM);
                if (onlyPremium) {
                  return uint96((((l1CostWei + baseFeeWei) * (s_config.nativePremiumPercentage)) / 100) + flatFeeWei);
                } else {
                  return uint96((((l1CostWei + baseFeeWei) * (100 + s_config.nativePremiumPercentage)) / 100) + flatFeeWei);
                }
              }
              // Get the amount of gas used for fulfillment
              function _calculatePaymentAmountLink(
                uint256 startGas,
                uint256 weiPerUnitGas,
                bool onlyPremium
              ) internal view returns (uint96, bool) {
                (int256 weiPerUnitLink, bool isFeedStale) = _getFeedData();
                if (weiPerUnitLink <= 0) {
                  revert InvalidLinkWeiPrice(weiPerUnitLink);
                }
                // Will return non-zero on chains that have this enabled
                uint256 l1CostWei = ChainSpecificUtil._getCurrentTxL1GasFees(msg.data);
                // (1e18 juels/link) ((wei/gas * gas) + l1wei) / (wei/link) = juels
                uint256 paymentNoFee = (1e18 *
                  (weiPerUnitGas * (s_config.gasAfterPaymentCalculation + startGas - gasleft()) + l1CostWei)) /
                  uint256(weiPerUnitLink);
                // calculate the flat fee in wei
                uint256 flatFeeWei = 1e12 *
                  uint256(s_config.fulfillmentFlatFeeNativePPM - s_config.fulfillmentFlatFeeLinkDiscountPPM);
                uint256 flatFeeJuels = (1e18 * flatFeeWei) / uint256(weiPerUnitLink);
                uint256 payment;
                if (onlyPremium) {
                  payment = ((paymentNoFee * (s_config.linkPremiumPercentage)) / 100 + flatFeeJuels);
                } else {
                  payment = ((paymentNoFee * (100 + s_config.linkPremiumPercentage)) / 100 + flatFeeJuels);
                }
                if (payment > 1e27) {
                  revert PaymentTooLarge(); // Payment + fee cannot be more than all of the link in existence.
                }
                return (uint96(payment), isFeedStale);
              }
              function _getFeedData() private view returns (int256 weiPerUnitLink, bool isFeedStale) {
                uint32 stalenessSeconds = s_config.stalenessSeconds;
                uint256 timestamp;
                (, weiPerUnitLink, , timestamp, ) = LINK_NATIVE_FEED.latestRoundData();
                // solhint-disable-next-line not-rely-on-time
                isFeedStale = stalenessSeconds > 0 && stalenessSeconds < block.timestamp - timestamp;
                if (isFeedStale) {
                  weiPerUnitLink = s_fallbackWeiPerUnitLink;
                }
                return (weiPerUnitLink, isFeedStale);
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function pendingRequestExists(uint256 subId) public view override returns (bool) {
                address[] storage consumers = s_subscriptionConfigs[subId].consumers;
                uint256 consumersLength = consumers.length;
                if (consumersLength == 0) {
                  return false;
                }
                for (uint256 i = 0; i < consumersLength; ++i) {
                  if (s_consumers[consumers[i]][subId].pendingReqCount > 0) {
                    return true;
                  }
                }
                return false;
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function removeConsumer(uint256 subId, address consumer) external override onlySubOwner(subId) nonReentrant {
                if (pendingRequestExists(subId)) {
                  revert PendingRequestExists();
                }
                if (!s_consumers[consumer][subId].active) {
                  revert InvalidConsumer(subId, consumer);
                }
                // Note bounded by MAX_CONSUMERS
                address[] memory consumers = s_subscriptionConfigs[subId].consumers;
                uint256 lastConsumerIndex = consumers.length - 1;
                for (uint256 i = 0; i < consumers.length; ++i) {
                  if (consumers[i] == consumer) {
                    address last = consumers[lastConsumerIndex];
                    // Storage write to preserve last element
                    s_subscriptionConfigs[subId].consumers[i] = last;
                    // Storage remove last element
                    s_subscriptionConfigs[subId].consumers.pop();
                    break;
                  }
                }
                s_consumers[consumer][subId].active = false;
                emit SubscriptionConsumerRemoved(subId, consumer);
              }
              /**
               * @inheritdoc IVRFSubscriptionV2Plus
               */
              function cancelSubscription(uint256 subId, address to) external override onlySubOwner(subId) nonReentrant {
                if (pendingRequestExists(subId)) {
                  revert PendingRequestExists();
                }
                _cancelSubscriptionHelper(subId, to);
              }
              /***************************************************************************
               * Section: Migration
               ***************************************************************************/
              address[] internal s_migrationTargets;
              /// @dev Emitted when new coordinator is registered as migratable target
              event CoordinatorRegistered(address coordinatorAddress);
              /// @dev Emitted when new coordinator is deregistered
              event CoordinatorDeregistered(address coordinatorAddress);
              /// @notice emitted when migration to new coordinator completes successfully
              /// @param newCoordinator coordinator address after migration
              /// @param subId subscription ID
              event MigrationCompleted(address newCoordinator, uint256 subId);
              /// @notice emitted when migrate() is called and given coordinator is not registered as migratable target
              error CoordinatorNotRegistered(address coordinatorAddress);
              /// @notice emitted when migrate() is called and given coordinator is registered as migratable target
              error CoordinatorAlreadyRegistered(address coordinatorAddress);
              /// @dev encapsulates data to be migrated from current coordinator
              struct V1MigrationData {
                uint8 fromVersion;
                uint256 subId;
                address subOwner;
                address[] consumers;
                uint96 linkBalance;
                uint96 nativeBalance;
              }
              function _isTargetRegistered(address target) internal view returns (bool) {
                uint256 migrationTargetsLength = s_migrationTargets.length;
                for (uint256 i = 0; i < migrationTargetsLength; ++i) {
                  if (s_migrationTargets[i] == target) {
                    return true;
                  }
                }
                return false;
              }
              function registerMigratableCoordinator(address target) external onlyOwner {
                if (_isTargetRegistered(target)) {
                  revert CoordinatorAlreadyRegistered(target);
                }
                s_migrationTargets.push(target);
                emit CoordinatorRegistered(target);
              }
              function deregisterMigratableCoordinator(address target) external onlyOwner {
                uint256 nTargets = s_migrationTargets.length;
                for (uint256 i = 0; i < nTargets; ++i) {
                  if (s_migrationTargets[i] == target) {
                    s_migrationTargets[i] = s_migrationTargets[nTargets - 1];
                    s_migrationTargets.pop();
                    emit CoordinatorDeregistered(target);
                    return;
                  }
                }
                revert CoordinatorNotRegistered(target);
              }
              function migrate(uint256 subId, address newCoordinator) external nonReentrant {
                if (!_isTargetRegistered(newCoordinator)) {
                  revert CoordinatorNotRegistered(newCoordinator);
                }
                (uint96 balance, uint96 nativeBalance, , address subOwner, address[] memory consumers) = getSubscription(subId);
                // solhint-disable-next-line gas-custom-errors
                require(subOwner == msg.sender, "Not subscription owner");
                // solhint-disable-next-line gas-custom-errors
                require(!pendingRequestExists(subId), "Pending request exists");
                V1MigrationData memory migrationData = V1MigrationData({
                  fromVersion: 1,
                  subId: subId,
                  subOwner: subOwner,
                  consumers: consumers,
                  linkBalance: balance,
                  nativeBalance: nativeBalance
                });
                bytes memory encodedData = abi.encode(migrationData);
                _deleteSubscription(subId);
                IVRFCoordinatorV2PlusMigration(newCoordinator).onMigration{value: nativeBalance}(encodedData);
                // Only transfer LINK if the token is active and there is a balance.
                if (address(LINK) != address(0) && balance != 0) {
                  // solhint-disable-next-line gas-custom-errors
                  require(LINK.transfer(address(newCoordinator), balance), "insufficient funds");
                }
                // despite the fact that we follow best practices this is still probably safest
                // to prevent any re-entrancy possibilities.
                s_config.reentrancyLock = true;
                for (uint256 i = 0; i < consumers.length; ++i) {
                  IVRFMigratableConsumerV2Plus(consumers[i]).setCoordinator(newCoordinator);
                }
                s_config.reentrancyLock = false;
                emit MigrationCompleted(newCoordinator, subId);
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import {VRFV2PlusClient} from "../libraries/VRFV2PlusClient.sol";
            import {IVRFSubscriptionV2Plus} from "./IVRFSubscriptionV2Plus.sol";
            // Interface that enables consumers of VRFCoordinatorV2Plus to be future-proof for upgrades
            // This interface is supported by subsequent versions of VRFCoordinatorV2Plus
            interface IVRFCoordinatorV2Plus is IVRFSubscriptionV2Plus {
              /**
               * @notice Request a set of random words.
               * @param req - a struct containing following fields for randomness request:
               * 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.
               * subId  - The ID of the VRF subscription. Must be funded
               * with the minimum subscription balance required for the selected keyHash.
               * requestConfirmations - 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].
               * 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]
               * 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.
               * extraArgs - abi-encoded extra args
               * @return requestId - A unique identifier of the request. Can be used to match
               * a request to a response in fulfillRandomWords.
               */
              function requestRandomWords(VRFV2PlusClient.RandomWordsRequest calldata req) external returns (uint256 requestId);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            // Future versions of VRFCoordinatorV2Plus must implement IVRFCoordinatorV2PlusMigration
            // to support migrations from previous versions
            interface IVRFCoordinatorV2PlusMigration {
              /**
               * @notice called by older versions of coordinator for migration.
               * @notice only callable by older versions of coordinator
               * @notice supports transfer of native currency
               * @param encodedData - user data from older version of coordinator
               */
              function onMigration(bytes calldata encodedData) external payable;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /// @notice The IVRFMigratableConsumerV2Plus interface defines the
            /// @notice method required to be implemented by all V2Plus consumers.
            /// @dev This interface is designed to be used in VRFConsumerBaseV2Plus.
            interface IVRFMigratableConsumerV2Plus {
              event CoordinatorSet(address vrfCoordinator);
              /// @notice Sets the VRF Coordinator address
              /// @notice This method should only be callable by the coordinator or contract owner
              function setCoordinator(address vrfCoordinator) external;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /// @notice The IVRFSubscriptionV2Plus interface defines the subscription
            /// @notice related methods implemented by the V2Plus coordinator.
            interface IVRFSubscriptionV2Plus {
              /**
               * @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(uint256 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(uint256 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(uint256 subId, address to) external;
              /**
               * @notice Accept 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(uint256 subId) external;
              /**
               * @notice Request subscription owner transfer.
               * @param subId - ID of the subscription
               * @param newOwner - proposed new owner of the subscription
               */
              function requestSubscriptionOwnerTransfer(uint256 subId, address newOwner) external;
              /**
               * @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 with LINK, use transferAndCall. For example
               * @dev  LINKTOKEN.transferAndCall(
               * @dev    address(COORDINATOR),
               * @dev    amount,
               * @dev    abi.encode(subId));
               * @dev Note to fund the subscription with Native, use fundSubscriptionWithNative. Be sure
               * @dev  to send Native with the call, for example:
               * @dev COORDINATOR.fundSubscriptionWithNative{value: amount}(subId);
               */
              function createSubscription() external returns (uint256 subId);
              /**
               * @notice Get a VRF subscription.
               * @param subId - ID of the subscription
               * @return balance - LINK balance of the subscription in juels.
               * @return nativeBalance - native balance of the subscription in wei.
               * @return reqCount - Requests count of subscription.
               * @return owner - owner of the subscription.
               * @return consumers - list of consumer address which are able to use this subscription.
               */
              function getSubscription(
                uint256 subId
              )
                external
                view
                returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address owner, address[] memory consumers);
              /*
               * @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(uint256 subId) external view returns (bool);
              /**
               * @notice Paginate through all active VRF subscriptions.
               * @param startIndex index of the subscription to start from
               * @param maxCount maximum number of subscriptions to return, 0 to return all
               * @dev the order of IDs in the list is **not guaranteed**, therefore, if making successive calls, one
               * @dev should consider keeping the blockheight constant to ensure a holistic picture of the contract state
               */
              function getActiveSubscriptionIds(uint256 startIndex, uint256 maxCount) external view returns (uint256[] memory);
              /**
               * @notice Fund a subscription with native.
               * @param subId - ID of the subscription
               * @notice This method expects msg.value to be greater than or equal to 0.
               */
              function fundSubscriptionWithNative(uint256 subId) external payable;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            // End consumer library.
            library VRFV2PlusClient {
              // extraArgs will evolve to support new features
              bytes4 public constant EXTRA_ARGS_V1_TAG = bytes4(keccak256("VRF ExtraArgsV1"));
              struct ExtraArgsV1 {
                bool nativePayment;
              }
              struct RandomWordsRequest {
                bytes32 keyHash;
                uint256 subId;
                uint16 requestConfirmations;
                uint32 callbackGasLimit;
                uint32 numWords;
                bytes extraArgs;
              }
              function _argsToBytes(ExtraArgsV1 memory extraArgs) internal pure returns (bytes memory bts) {
                return abi.encodeWithSelector(EXTRA_ARGS_V1_TAG, extraArgs);
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            interface BlockhashStoreInterface {
              function getBlockhash(uint256 number) external view returns (bytes32);
            }
            

            File 3 of 4: Ethcoin
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.13;
            import "../lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol";
            import "../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
            import "../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol";
            import "../lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol";
            import "./interfaces/IReverseRegistrar.sol";
            import "./interfaces/IOracle.sol";
            import "./EthcoinStorage.sol";
            contract Ethcoin is Initializable, ERC20Upgradeable, OwnableUpgradeable, UUPSUpgradeable, EthcoinStorage {
                /// @notice Maximum supply of the token
                uint256 public constant MAX_SUPPLY = 21000000e18; // 21 million
                /// @notice Block interval for mining
                uint256 public constant BLOCK_INTERVAL = 1 minutes;
                /// @notice The minimum cost to mine
                uint256 public constant MIN_MINE_COST = 0.0001 ether;
                /// @notice The amount to adjust the mine cost per adjustment
                uint256 public constant MINE_COST_ADJUST_AMOUNT = 0.00001 ether;
                /// @notice The threshold ratio to decrease the mine cost
                uint256 public constant MINE_COST_DECREASE_THRESHOLD = 0.8e18; // 80%
                /// @notice The gas limit to refund
                uint256 public constant REFUND_GAS_LIMIT = 150000;
                event Mine(uint256 indexed blockNumber, address indexed miner, uint256 mineCount);
                event NewETHCBlock(uint256 indexed blockNumber);
                event MinerSelected(uint256 blockNumber, address selectedMiner, uint256 miningReward);
                event FeeCollectorSet(address feeCollector);
                event MineCostSet(uint256 mineCost);
                event OracleSet(address oracle);
                event GasRefundRecorded(address user, uint256 amount);
                event GasRefundClaimed(address user, uint256 amount);
                modifier whenStarted() {
                    require(isStarted, "not started");
                    _;
                }
                /**
                 * @notice Initializes the contract.
                 * @param _reverseRegistrar The reverse registrar
                 */
                function initialize(address _reverseRegistrar) public initializer {
                    __ERC20_init("Ethcoin", "ETHC");
                    __Ownable_init(msg.sender);
                    __UUPSUpgradeable_init();
                    reverseRegistrar = _reverseRegistrar;
                    mineCost = 0.0002 ether;
                    miningReward = 200e18; // 200 ETHC
                    halvingInterval = 10080; // 10080 Ethcoin blocks, ~1 week
                }
                /**
                 * @notice Get the miners for a specific block.
                 * @dev This function doesn't garantee the uniqueness of the miners.
                 * @param _blockNumber The block number
                 * @return The miners
                 */
                function minersOfBlock(uint256 _blockNumber) public view returns (address[] memory) {
                    if (_blockNumber >= upgradeBlockNumber) {
                        uint256 idx;
                        address[] memory miners = new address[](blocks[_blockNumber].totalMineCount);
                        for (uint256 i = 0; i < blocks[_blockNumber].mineBatches.length; i++) {
                            MineBatch memory mineBatch = blocks[_blockNumber].mineBatches[i];
                            for (uint256 j = 0; j < mineBatch.mineCount; j++) {
                                miners[idx] = mineBatch.miner;
                                idx++;
                            }
                        }
                        return miners;
                    } else {
                        return blocks[_blockNumber].miners;
                    }
                }
                /**
                 * @notice Get the number of miners for a specific block.
                 * @dev This function is about to be deprecated.
                 * @param _blockNumber The block number
                 * @return The number of miners
                 */
                function minersOfBlockCount(uint256 _blockNumber) public view returns (uint256) {
                    return blocks[_blockNumber].miners.length;
                }
                /**
                 * @notice Get the total mine count for a specific block.
                 * @param _blockNumber The block number
                 * @return The total mine count
                 */
                function totalMineCountOfBlock(uint256 _blockNumber) public view returns (uint256) {
                    if (_blockNumber >= upgradeBlockNumber) {
                        return blocks[_blockNumber].totalMineCount;
                    } else {
                        return blocks[_blockNumber].miners.length;
                    }
                }
                /**
                 * @notice Get the mine batch count for a specific block.
                 * @param _blockNumber The block number
                 * @return The mine batch count
                 */
                function mineBatchCountOfBlock(uint256 _blockNumber) public view returns (uint256) {
                    return blocks[_blockNumber].mineBatches.length;
                }
                /**
                 * @notice Get the mine batches for a specific block.
                 * @param _blockNumber The block number
                 * @return The mine batches
                 */
                function mineBatchOfBlock(uint256 _blockNumber) public view returns (MineBatch[] memory) {
                    return blocks[_blockNumber].mineBatches;
                }
                /**
                 * @notice Get the mine batch of a specific block by index.
                 * @param _blockNumber The block number
                 * @param _index The index of the mine batch
                 * @return The mine batch
                 */
                function mineBatchOfBlockByIndex(uint256 _blockNumber, uint256 _index) public view returns (MineBatch memory) {
                    return blocks[_blockNumber].mineBatches[_index];
                }
                /**
                 * @notice Get the selected miner for a specific block.
                 * @param _blockNumber The block number
                 * @return The selected miner
                 */
                function selectedMinerOfBlock(uint256 _blockNumber) public view returns (address) {
                    return blocks[_blockNumber].selectedMiner;
                }
                /**
                 * @notice Get the next halving block.
                 * @return The next halving block
                 */
                function nextHalvingBlock() public view returns (uint256) {
                    return lastHalvingBlock + halvingInterval;
                }
                /**
                 * @notice Get the request ID for the target block.
                 * @param _blockNumber The target block number
                 * @return The request ID
                 */
                function getRequestIdByBlockNumber(uint256 _blockNumber) public view returns (uint256) {
                    return blockNumberToRequests[_blockNumber];
                }
                /**
                 * @notice Get the block number for the request ID.
                 * @param _requestId The request ID
                 * @return The block number
                 */
                function getBlockNumberByRequestId(uint256 _requestId) public view returns (uint256) {
                    return requestsToBlockNumber[_requestId];
                }
                /**
                 * @notice Mines the reward multiple times in the current block.
                 * @param mineCount The number of times to mine
                 */
                function mine(uint256 mineCount) public payable whenStarted {
                    require(mineCount > 0, "invalid mine count");
                    require(msg.value == mineCost * mineCount, "mismatch mine cost");
                    _mine(msg.sender, blockNumber + 1, mineCount);
                    _concludeBlock();
                }
                /**
                 * @notice Mines the reward multiple times in the future block.
                 * @param mineCount The number of times to mine per block
                 * @param blockCount The number of future blocks to mine
                 */
                function futureMine(uint256 mineCount, uint256 blockCount) public payable whenStarted {
                    require(mineCount > 0 && blockCount > 0, "invalid mine count or block count");
                    require(msg.value == mineCost * mineCount * blockCount, "mismatch mine cost");
                    for (uint256 i = 0; i < blockCount;) {
                        _mine(msg.sender, blockNumber + 1 + i, mineCount);
                        unchecked {
                            i++;
                        }
                    }
                    _concludeBlock();
                }
                /**
                 * @notice Claims the gas refund.
                 */
                function claimGasRefund() public {
                    uint256 amount = userUnclaimed[msg.sender];
                    require(amount > 0, "no gas refund");
                    // Update the storage first to prevent re-entrancy attack.
                    userUnclaimed[msg.sender] = 0;
                    totalUnclaimed -= amount;
                    (bool sent,) = msg.sender.call{value: amount}("");
                    require(sent, "failed to send Ether");
                    emit GasRefundClaimed(msg.sender, amount);
                }
                /**
                 * @notice Starts the mining.
                 */
                function start() public onlyOwner {
                    require(!isStarted, "already initialized");
                    isStarted = true;
                    lastBlockTime = block.timestamp;
                }
                /**
                 * @notice Sets the fee collector address.
                 * @param _feeCollector The fee collector address
                 */
                function setFeeCollector(address _feeCollector) public onlyOwner {
                    feeCollector = _feeCollector;
                    emit FeeCollectorSet(_feeCollector);
                }
                /**
                 * @notice Sets the oracle.
                 * @param _oracle The oracle
                 */
                function setOracle(address _oracle) public onlyOwner {
                    oracle = _oracle;
                    emit OracleSet(_oracle);
                }
                /**
                 * @notice Sets the ENS name.
                 * @param name The name
                 * @return The ENS node
                 */
                function setName(string memory name) public onlyOwner returns (bytes32) {
                    return IReverseRegistrar(reverseRegistrar).setName(name);
                }
                /**
                 * @notice Re-request the randomness for the target block if ChainLink VRF fails.
                 * @param targetBlock The target block number
                 */
                function requestRandomness(uint256 targetBlock) public onlyOwner {
                    require(targetBlock < blockNumber, "invalid target block");
                    require(selectedMinerOfBlock(targetBlock) == address(0), "miner already selected");
                    // Resuest the randomness from ChainLink VRF.
                    uint256 requestId = IOracle(oracle).requestRandomness();
                    blockNumberToRequests[targetBlock] = requestId;
                    requestsToBlockNumber[requestId] = targetBlock;
                }
                /**
                 * @notice Collects the Ether.
                 * @param amount The amount of Ether to collect
                 */
                function collect(uint256 amount) public {
                    require(msg.sender == feeCollector, "only feeCollector can collect");
                    require(address(this).balance >= amount + totalUnclaimed, "insufficient balance");
                    (bool sent,) = feeCollector.call{value: amount}("");
                    require(sent, "failed to send Ether");
                }
                /**
                 * @notice Oracle fullfills the randomness and selects the miner.
                 * @param requestId The request ID
                 * @param randomNumber The random number
                 */
                function fulfillRandomness(uint256 requestId, uint256 randomNumber) public {
                    require(msg.sender == oracle, "only oracle can select miner");
                    uint256 targetBlock = requestsToBlockNumber[requestId];
                    Block storage blockData = blocks[targetBlock];
                    // Skip if the selected miner is already set.
                    if (blockData.selectedMiner != address(0)) {
                        return;
                    }
                    uint256 randIdx = randomNumber % blockData.totalMineCount;
                    address selectedMiner = _binarySearch(blockData, randIdx);
                    if (selectedMiner == address(0)) {
                        return;
                    }
                    // Mint the mining reward.
                    if (totalSupply() + blockData.miningReward <= MAX_SUPPLY) {
                        _mint(selectedMiner, blockData.miningReward);
                    }
                    // Record the selected miner.
                    blockData.selectedMiner = selectedMiner;
                    emit MinerSelected(targetBlock, selectedMiner, blockData.miningReward);
                }
                function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
                /**
                 * @dev Concludes the block.
                 */
                function _concludeBlock() internal {
                    if (block.timestamp >= lastBlockTime + BLOCK_INTERVAL) {
                        // Proceed to the next block.
                        blockNumber++;
                        lastBlockTime = block.timestamp;
                        // Refund some gas fee for the miner who concludes the block.
                        _refund();
                        // Adjust the mine cost every 10 blocks.
                        if (blockNumber % 10 == 0) {
                            _adjustMineCost();
                        }
                        // Resuest the randomness from ChainLink VRF.
                        uint256 requestId = IOracle(oracle).requestRandomness();
                        // Check if it's time for halving.
                        if (blockNumber >= nextHalvingBlock()) {
                            miningReward = miningReward / 2;
                            halvingInterval = halvingInterval * 2;
                            lastHalvingBlock = blockNumber;
                        }
                        blockNumberToRequests[blockNumber] = requestId;
                        requestsToBlockNumber[requestId] = blockNumber;
                        blocks[blockNumber].miningReward = miningReward;
                        emit NewETHCBlock(blockNumber);
                    }
                }
                /**
                 * @dev Record the gas refund.
                 */
                function _refund() internal {
                    uint256 gasRefund = REFUND_GAS_LIMIT * block.basefee;
                    uint256 ethCollected = blocks[blockNumber].totalMineCount * mineCost;
                    if (gasRefund > ethCollected / 10) {
                        gasRefund = ethCollected / 10;
                    }
                    // Record the gas refund to handle contract miner not able to receive Ether.
                    userUnclaimed[msg.sender] += gasRefund;
                    totalUnclaimed += gasRefund;
                    emit GasRefundRecorded(msg.sender, gasRefund);
                }
                /**
                 * @dev Adjusts the mine cost.
                 */
                function _adjustMineCost() internal {
                    uint256 newLastTenBlockMiningPower;
                    for (uint256 i = 0; i < 10; i++) {
                        newLastTenBlockMiningPower += totalMineCountOfBlock(blockNumber - i);
                    }
                    if (lastTenBlockMiningPower != 0) {
                        if (newLastTenBlockMiningPower > lastTenBlockMiningPower) {
                            mineCost = mineCost + MINE_COST_ADJUST_AMOUNT;
                            emit MineCostSet(mineCost);
                        } else if (
                            newLastTenBlockMiningPower < lastTenBlockMiningPower * MINE_COST_DECREASE_THRESHOLD / 1e18
                                && mineCost > MIN_MINE_COST
                        ) {
                            mineCost = mineCost - MINE_COST_ADJUST_AMOUNT;
                            emit MineCostSet(mineCost);
                        }
                    }
                    // Update the last ten block mining power.
                    lastTenBlockMiningPower = newLastTenBlockMiningPower;
                }
                /**
                 * @dev Mines the reward.
                 * @param user The user address
                 * @param targetBlock The target block number to mine
                 * @param mineCount The number of times to mine
                 */
                function _mine(address user, uint256 targetBlock, uint256 mineCount) internal {
                    uint256 totalMineCount = blocks[targetBlock].totalMineCount;
                    MineBatch memory mineBatch = MineBatch({miner: user, startIdx: totalMineCount, mineCount: mineCount});
                    blocks[targetBlock].mineBatches.push(mineBatch);
                    blocks[targetBlock].totalMineCount = totalMineCount + mineCount;
                    emit Mine(targetBlock, user, mineCount);
                }
                /**
                 * @dev Binary search the miner for the target index.
                 * @param blockData The block data
                 * @param targetIdx The target index
                 * @return The miner address
                 */
                function _binarySearch(Block storage blockData, uint256 targetIdx) internal view returns (address) {
                    uint256 left = 0;
                    uint256 right = blockData.mineBatches.length - 1;
                    while (left <= right) {
                        uint256 mid = left + (right - left) / 2;
                        MineBatch memory mineBatch = blockData.mineBatches[mid];
                        if (mineBatch.startIdx <= targetIdx && targetIdx < mineBatch.startIdx + mineBatch.mineCount) {
                            return mineBatch.miner;
                        } else if (mineBatch.startIdx > targetIdx) {
                            right = mid - 1;
                        } else {
                            left = mid + 1;
                        }
                    }
                    return address(0);
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
            pragma solidity ^0.8.20;
            import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
            import {Initializable} from "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
                /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
                struct OwnableStorage {
                    address _owner;
                }
                // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
                bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
                function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
                    assembly {
                        $.slot := OwnableStorageLocation
                    }
                }
                /**
                 * @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.
                 */
                function __Ownable_init(address initialOwner) internal onlyInitializing {
                    __Ownable_init_unchained(initialOwner);
                }
                function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
                    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) {
                    OwnableStorage storage $ = _getOwnableStorage();
                    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 {
                    OwnableStorage storage $ = _getOwnableStorage();
                    address oldOwner = $._owner;
                    $._owner = newOwner;
                    emit OwnershipTransferred(oldOwner, newOwner);
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
            pragma solidity ^0.8.20;
            /**
             * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
             * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
             * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
             * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
             *
             * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
             * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
             * case an upgrade adds a module that needs to be initialized.
             *
             * For example:
             *
             * [.hljs-theme-light.nopadding]
             * ```solidity
             * contract MyToken is ERC20Upgradeable {
             *     function initialize() initializer public {
             *         __ERC20_init("MyToken", "MTK");
             *     }
             * }
             *
             * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
             *     function initializeV2() reinitializer(2) public {
             *         __ERC20Permit_init("MyToken");
             *     }
             * }
             * ```
             *
             * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
             * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
             *
             * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
             * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
             *
             * [CAUTION]
             * ====
             * Avoid leaving a contract uninitialized.
             *
             * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
             * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
             * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
             *
             * [.hljs-theme-light.nopadding]
             * ```
             * /// @custom:oz-upgrades-unsafe-allow constructor
             * constructor() {
             *     _disableInitializers();
             * }
             * ```
             * ====
             */
            abstract contract Initializable {
                /**
                 * @dev Storage of the initializable contract.
                 *
                 * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
                 * when using with upgradeable contracts.
                 *
                 * @custom:storage-location erc7201:openzeppelin.storage.Initializable
                 */
                struct InitializableStorage {
                    /**
                     * @dev Indicates that the contract has been initialized.
                     */
                    uint64 _initialized;
                    /**
                     * @dev Indicates that the contract is in the process of being initialized.
                     */
                    bool _initializing;
                }
                // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
                bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
                /**
                 * @dev The contract is already initialized.
                 */
                error InvalidInitialization();
                /**
                 * @dev The contract is not initializing.
                 */
                error NotInitializing();
                /**
                 * @dev Triggered when the contract has been initialized or reinitialized.
                 */
                event Initialized(uint64 version);
                /**
                 * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
                 * `onlyInitializing` functions can be used to initialize parent contracts.
                 *
                 * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
                 * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
                 * production.
                 *
                 * Emits an {Initialized} event.
                 */
                modifier initializer() {
                    // solhint-disable-next-line var-name-mixedcase
                    InitializableStorage storage $ = _getInitializableStorage();
                    // Cache values to avoid duplicated sloads
                    bool isTopLevelCall = !$._initializing;
                    uint64 initialized = $._initialized;
                    // Allowed calls:
                    // - initialSetup: the contract is not in the initializing state and no previous version was
                    //                 initialized
                    // - construction: the contract is initialized at version 1 (no reininitialization) and the
                    //                 current contract is just being deployed
                    bool initialSetup = initialized == 0 && isTopLevelCall;
                    bool construction = initialized == 1 && address(this).code.length == 0;
                    if (!initialSetup && !construction) {
                        revert InvalidInitialization();
                    }
                    $._initialized = 1;
                    if (isTopLevelCall) {
                        $._initializing = true;
                    }
                    _;
                    if (isTopLevelCall) {
                        $._initializing = false;
                        emit Initialized(1);
                    }
                }
                /**
                 * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
                 * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
                 * used to initialize parent contracts.
                 *
                 * A reinitializer may be used after the original initialization step. This is essential to configure modules that
                 * are added through upgrades and that require initialization.
                 *
                 * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
                 * cannot be nested. If one is invoked in the context of another, execution will revert.
                 *
                 * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
                 * a contract, executing them in the right order is up to the developer or operator.
                 *
                 * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
                 *
                 * Emits an {Initialized} event.
                 */
                modifier reinitializer(uint64 version) {
                    // solhint-disable-next-line var-name-mixedcase
                    InitializableStorage storage $ = _getInitializableStorage();
                    if ($._initializing || $._initialized >= version) {
                        revert InvalidInitialization();
                    }
                    $._initialized = version;
                    $._initializing = true;
                    _;
                    $._initializing = false;
                    emit Initialized(version);
                }
                /**
                 * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
                 * {initializer} and {reinitializer} modifiers, directly or indirectly.
                 */
                modifier onlyInitializing() {
                    _checkInitializing();
                    _;
                }
                /**
                 * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
                 */
                function _checkInitializing() internal view virtual {
                    if (!_isInitializing()) {
                        revert NotInitializing();
                    }
                }
                /**
                 * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
                 * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
                 * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
                 * through proxies.
                 *
                 * Emits an {Initialized} event the first time it is successfully executed.
                 */
                function _disableInitializers() internal virtual {
                    // solhint-disable-next-line var-name-mixedcase
                    InitializableStorage storage $ = _getInitializableStorage();
                    if ($._initializing) {
                        revert InvalidInitialization();
                    }
                    if ($._initialized != type(uint64).max) {
                        $._initialized = type(uint64).max;
                        emit Initialized(type(uint64).max);
                    }
                }
                /**
                 * @dev Returns the highest version that has been initialized. See {reinitializer}.
                 */
                function _getInitializedVersion() internal view returns (uint64) {
                    return _getInitializableStorage()._initialized;
                }
                /**
                 * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
                 */
                function _isInitializing() internal view returns (bool) {
                    return _getInitializableStorage()._initializing;
                }
                /**
                 * @dev Returns a pointer to the storage namespace.
                 */
                // solhint-disable-next-line var-name-mixedcase
                function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
                    assembly {
                        $.slot := INITIALIZABLE_STORAGE
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)
            pragma solidity ^0.8.20;
            import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
            import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
            import {Initializable} from "./Initializable.sol";
            /**
             * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
             * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
             *
             * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
             * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
             * `UUPSUpgradeable` with a custom implementation of upgrades.
             *
             * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
             */
            abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
                /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
                address private immutable __self = address(this);
                /**
                 * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
                 * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
                 * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
                 * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
                 * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
                 * during an upgrade.
                 */
                string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
                /**
                 * @dev The call is from an unauthorized context.
                 */
                error UUPSUnauthorizedCallContext();
                /**
                 * @dev The storage `slot` is unsupported as a UUID.
                 */
                error UUPSUnsupportedProxiableUUID(bytes32 slot);
                /**
                 * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
                 * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
                 * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
                 * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
                 * fail.
                 */
                modifier onlyProxy() {
                    _checkProxy();
                    _;
                }
                /**
                 * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
                 * callable on the implementing contract but not through proxies.
                 */
                modifier notDelegated() {
                    _checkNotDelegated();
                    _;
                }
                function __UUPSUpgradeable_init() internal onlyInitializing {
                }
                function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
                }
                /**
                 * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
                 * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
                 *
                 * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
                 * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
                 * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
                 */
                function proxiableUUID() external view virtual notDelegated returns (bytes32) {
                    return ERC1967Utils.IMPLEMENTATION_SLOT;
                }
                /**
                 * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
                 * encoded in `data`.
                 *
                 * Calls {_authorizeUpgrade}.
                 *
                 * Emits an {Upgraded} event.
                 *
                 * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
                 */
                function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
                    _authorizeUpgrade(newImplementation);
                    _upgradeToAndCallUUPS(newImplementation, data);
                }
                /**
                 * @dev Reverts if the execution is not performed via delegatecall or the execution
                 * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
                 * See {_onlyProxy}.
                 */
                function _checkProxy() internal view virtual {
                    if (
                        address(this) == __self || // Must be called through delegatecall
                        ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
                    ) {
                        revert UUPSUnauthorizedCallContext();
                    }
                }
                /**
                 * @dev Reverts if the execution is performed via delegatecall.
                 * See {notDelegated}.
                 */
                function _checkNotDelegated() internal view virtual {
                    if (address(this) != __self) {
                        // Must not be called through delegatecall
                        revert UUPSUnauthorizedCallContext();
                    }
                }
                /**
                 * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
                 * {upgradeToAndCall}.
                 *
                 * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
                 *
                 * ```solidity
                 * function _authorizeUpgrade(address) internal onlyOwner {}
                 * ```
                 */
                function _authorizeUpgrade(address newImplementation) internal virtual;
                /**
                 * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
                 *
                 * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
                 * is expected to be the implementation slot in ERC-1967.
                 *
                 * Emits an {IERC1967-Upgraded} event.
                 */
                function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
                    try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                        if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                            revert UUPSUnsupportedProxiableUUID(slot);
                        }
                        ERC1967Utils.upgradeToAndCall(newImplementation, data);
                    } catch {
                        // The implementation is not UUPS
                        revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)
            pragma solidity ^0.8.20;
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
            import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
            import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
            import {Initializable} from "../../proxy/utils/Initializable.sol";
            /**
             * @dev Implementation of the {IERC20} interface.
             *
             * This implementation is agnostic to the way tokens are created. This means
             * that a supply mechanism has to be added in a derived contract using {_mint}.
             *
             * TIP: For a detailed writeup see our guide
             * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
             * to implement supply mechanisms].
             *
             * The default value of {decimals} is 18. To change this, you should override
             * this function so it returns a different value.
             *
             * We have followed general OpenZeppelin Contracts guidelines: functions revert
             * instead returning `false` on failure. This behavior is nonetheless
             * conventional and does not conflict with the expectations of ERC-20
             * applications.
             */
            abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
                /// @custom:storage-location erc7201:openzeppelin.storage.ERC20
                struct ERC20Storage {
                    mapping(address account => uint256) _balances;
                    mapping(address account => mapping(address spender => uint256)) _allowances;
                    uint256 _totalSupply;
                    string _name;
                    string _symbol;
                }
                // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
                bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
                function _getERC20Storage() private pure returns (ERC20Storage storage $) {
                    assembly {
                        $.slot := ERC20StorageLocation
                    }
                }
                /**
                 * @dev Sets the values for {name} and {symbol}.
                 *
                 * All two of these values are immutable: they can only be set once during
                 * construction.
                 */
                function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
                    __ERC20_init_unchained(name_, symbol_);
                }
                function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
                    ERC20Storage storage $ = _getERC20Storage();
                    $._name = name_;
                    $._symbol = symbol_;
                }
                /**
                 * @dev Returns the name of the token.
                 */
                function name() public view virtual returns (string memory) {
                    ERC20Storage storage $ = _getERC20Storage();
                    return $._name;
                }
                /**
                 * @dev Returns the symbol of the token, usually a shorter version of the
                 * name.
                 */
                function symbol() public view virtual returns (string memory) {
                    ERC20Storage storage $ = _getERC20Storage();
                    return $._symbol;
                }
                /**
                 * @dev Returns the number of decimals used to get its user representation.
                 * For example, if `decimals` equals `2`, a balance of `505` tokens should
                 * be displayed to a user as `5.05` (`505 / 10 ** 2`).
                 *
                 * Tokens usually opt for a value of 18, imitating the relationship between
                 * Ether and Wei. This is the default value returned by this function, unless
                 * it's overridden.
                 *
                 * NOTE: This information is only used for _display_ purposes: it in
                 * no way affects any of the arithmetic of the contract, including
                 * {IERC20-balanceOf} and {IERC20-transfer}.
                 */
                function decimals() public view virtual returns (uint8) {
                    return 18;
                }
                /**
                 * @dev See {IERC20-totalSupply}.
                 */
                function totalSupply() public view virtual returns (uint256) {
                    ERC20Storage storage $ = _getERC20Storage();
                    return $._totalSupply;
                }
                /**
                 * @dev See {IERC20-balanceOf}.
                 */
                function balanceOf(address account) public view virtual returns (uint256) {
                    ERC20Storage storage $ = _getERC20Storage();
                    return $._balances[account];
                }
                /**
                 * @dev See {IERC20-transfer}.
                 *
                 * Requirements:
                 *
                 * - `to` cannot be the zero address.
                 * - the caller must have a balance of at least `value`.
                 */
                function transfer(address to, uint256 value) public virtual returns (bool) {
                    address owner = _msgSender();
                    _transfer(owner, to, value);
                    return true;
                }
                /**
                 * @dev See {IERC20-allowance}.
                 */
                function allowance(address owner, address spender) public view virtual returns (uint256) {
                    ERC20Storage storage $ = _getERC20Storage();
                    return $._allowances[owner][spender];
                }
                /**
                 * @dev See {IERC20-approve}.
                 *
                 * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
                 * `transferFrom`. This is semantically equivalent to an infinite approval.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 */
                function approve(address spender, uint256 value) public virtual returns (bool) {
                    address owner = _msgSender();
                    _approve(owner, spender, value);
                    return true;
                }
                /**
                 * @dev See {IERC20-transferFrom}.
                 *
                 * Skips emitting an {Approval} event indicating an allowance update. This is not
                 * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
                 *
                 * NOTE: Does not update the allowance if the current allowance
                 * is the maximum `uint256`.
                 *
                 * Requirements:
                 *
                 * - `from` and `to` cannot be the zero address.
                 * - `from` must have a balance of at least `value`.
                 * - the caller must have allowance for ``from``'s tokens of at least
                 * `value`.
                 */
                function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
                    address spender = _msgSender();
                    _spendAllowance(from, spender, value);
                    _transfer(from, to, value);
                    return true;
                }
                /**
                 * @dev Moves a `value` amount of tokens from `from` to `to`.
                 *
                 * This internal function is equivalent to {transfer}, and can be used to
                 * e.g. implement automatic token fees, slashing mechanisms, etc.
                 *
                 * Emits a {Transfer} event.
                 *
                 * NOTE: This function is not virtual, {_update} should be overridden instead.
                 */
                function _transfer(address from, address to, uint256 value) internal {
                    if (from == address(0)) {
                        revert ERC20InvalidSender(address(0));
                    }
                    if (to == address(0)) {
                        revert ERC20InvalidReceiver(address(0));
                    }
                    _update(from, to, value);
                }
                /**
                 * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
                 * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
                 * this function.
                 *
                 * Emits a {Transfer} event.
                 */
                function _update(address from, address to, uint256 value) internal virtual {
                    ERC20Storage storage $ = _getERC20Storage();
                    if (from == address(0)) {
                        // Overflow check required: The rest of the code assumes that totalSupply never overflows
                        $._totalSupply += value;
                    } else {
                        uint256 fromBalance = $._balances[from];
                        if (fromBalance < value) {
                            revert ERC20InsufficientBalance(from, fromBalance, value);
                        }
                        unchecked {
                            // Overflow not possible: value <= fromBalance <= totalSupply.
                            $._balances[from] = fromBalance - value;
                        }
                    }
                    if (to == address(0)) {
                        unchecked {
                            // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                            $._totalSupply -= value;
                        }
                    } else {
                        unchecked {
                            // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                            $._balances[to] += value;
                        }
                    }
                    emit Transfer(from, to, value);
                }
                /**
                 * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
                 * Relies on the `_update` mechanism
                 *
                 * Emits a {Transfer} event with `from` set to the zero address.
                 *
                 * NOTE: This function is not virtual, {_update} should be overridden instead.
                 */
                function _mint(address account, uint256 value) internal {
                    if (account == address(0)) {
                        revert ERC20InvalidReceiver(address(0));
                    }
                    _update(address(0), account, value);
                }
                /**
                 * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
                 * Relies on the `_update` mechanism.
                 *
                 * Emits a {Transfer} event with `to` set to the zero address.
                 *
                 * NOTE: This function is not virtual, {_update} should be overridden instead
                 */
                function _burn(address account, uint256 value) internal {
                    if (account == address(0)) {
                        revert ERC20InvalidSender(address(0));
                    }
                    _update(account, address(0), value);
                }
                /**
                 * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
                 *
                 * This internal function is equivalent to `approve`, and can be used to
                 * e.g. set automatic allowances for certain subsystems, etc.
                 *
                 * Emits an {Approval} event.
                 *
                 * Requirements:
                 *
                 * - `owner` cannot be the zero address.
                 * - `spender` cannot be the zero address.
                 *
                 * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
                 */
                function _approve(address owner, address spender, uint256 value) internal {
                    _approve(owner, spender, value, true);
                }
                /**
                 * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
                 *
                 * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
                 * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
                 * `Approval` event during `transferFrom` operations.
                 *
                 * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
                 * true using the following override:
                 *
                 * ```solidity
                 * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
                 *     super._approve(owner, spender, value, true);
                 * }
                 * ```
                 *
                 * Requirements are the same as {_approve}.
                 */
                function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
                    ERC20Storage storage $ = _getERC20Storage();
                    if (owner == address(0)) {
                        revert ERC20InvalidApprover(address(0));
                    }
                    if (spender == address(0)) {
                        revert ERC20InvalidSpender(address(0));
                    }
                    $._allowances[owner][spender] = value;
                    if (emitEvent) {
                        emit Approval(owner, spender, value);
                    }
                }
                /**
                 * @dev Updates `owner` s allowance for `spender` based on spent `value`.
                 *
                 * Does not update the allowance value in case of infinite allowance.
                 * Revert if not enough allowance is available.
                 *
                 * Does not emit an {Approval} event.
                 */
                function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
                    uint256 currentAllowance = allowance(owner, spender);
                    if (currentAllowance != type(uint256).max) {
                        if (currentAllowance < value) {
                            revert ERC20InsufficientAllowance(spender, currentAllowance, value);
                        }
                        unchecked {
                            _approve(owner, spender, currentAllowance - value, false);
                        }
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.13;
            interface IReverseRegistrar {
                function setName(string memory name) external returns (bytes32);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.13;
            interface IOracle {
                function requestRandomness() external returns (uint256);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.13;
            import "./interfaces/IReverseRegistrar.sol";
            contract EthcoinStorage {
                /// @notice The reverse registrar
                address public reverseRegistrar;
                /// @notice The flag to check if the mining is started
                bool public isStarted;
                /// @notice The cost to mine
                uint256 public mineCost;
                /// @notice The mining reward
                uint256 public miningReward;
                /// @notice The current block number
                uint256 public blockNumber;
                /// @notice The last block time
                uint256 public lastBlockTime;
                /// @notice The halving interval
                uint256 public halvingInterval;
                /// @notice The last halving block
                uint256 public lastHalvingBlock;
                /// @notice The fee collector address
                address public feeCollector;
                struct MineBatch {
                    /// @notice The miner address
                    address miner;
                    /// @notice The start index
                    uint256 startIdx;
                    /// @notice The mine count
                    uint256 mineCount;
                }
                struct Block {
                    /// @notice [DEPRECATED] The old miner list
                    address[] miners;
                    /// @notice The selected miner
                    address selectedMiner;
                    /// @notice The mining reward of the block
                    uint256 miningReward;
                    /// @notice The mine batch list
                    MineBatch[] mineBatches;
                    /// @notice The total mine count
                    uint256 totalMineCount;
                }
                /// @notice The blocks data
                mapping(uint256 => Block) public blocks;
                /// @notice The block number to request ID mapping
                mapping(uint256 => uint256) public blockNumberToRequests;
                /// @notice The randomness oracle
                address public oracle;
                /// @notice The request ID to block number mapping
                mapping(uint256 => uint256) public requestsToBlockNumber;
                /// @notice The block number that the contract is upgraded
                uint256 public upgradeBlockNumber;
                /// @notice The last ten block mining power
                uint256 public lastTenBlockMiningPower;
                /// @notice The user unclaimed refund balance
                mapping(address => uint256) public userUnclaimed;
                /// @notice The total unclaimed refund balance
                uint256 public totalUnclaimed;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
            pragma solidity ^0.8.20;
            import {Initializable} from "../proxy/utils/Initializable.sol";
            /**
             * @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 ContextUpgradeable is Initializable {
                function __Context_init() internal onlyInitializing {
                }
                function __Context_init_unchained() internal onlyInitializing {
                }
                function _msgSender() internal view virtual returns (address) {
                    return msg.sender;
                }
                function _msgData() internal view virtual returns (bytes calldata) {
                    return msg.data;
                }
                function _contextSuffixLength() internal view virtual returns (uint256) {
                    return 0;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
            pragma solidity ^0.8.20;
            /**
             * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
             * proxy whose upgrades are fully controlled by the current implementation.
             */
            interface IERC1822Proxiable {
                /**
                 * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
                 * address.
                 *
                 * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
                 * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
                 * function revert if invoked through a proxy.
                 */
                function proxiableUUID() external view returns (bytes32);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
            pragma solidity ^0.8.20;
            import {IBeacon} from "../beacon/IBeacon.sol";
            import {Address} from "../../utils/Address.sol";
            import {StorageSlot} from "../../utils/StorageSlot.sol";
            /**
             * @dev This abstract contract provides getters and event emitting update functions for
             * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
             */
            library ERC1967Utils {
                // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
                // This will be fixed in Solidity 0.8.21. At that point we should remove these events.
                /**
                 * @dev Emitted when the implementation is upgraded.
                 */
                event Upgraded(address indexed implementation);
                /**
                 * @dev Emitted when the admin account has changed.
                 */
                event AdminChanged(address previousAdmin, address newAdmin);
                /**
                 * @dev Emitted when the beacon is changed.
                 */
                event BeaconUpgraded(address indexed beacon);
                /**
                 * @dev Storage slot with the address of the current implementation.
                 * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
                 */
                // solhint-disable-next-line private-vars-leading-underscore
                bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                /**
                 * @dev The `implementation` of the proxy is invalid.
                 */
                error ERC1967InvalidImplementation(address implementation);
                /**
                 * @dev The `admin` of the proxy is invalid.
                 */
                error ERC1967InvalidAdmin(address admin);
                /**
                 * @dev The `beacon` of the proxy is invalid.
                 */
                error ERC1967InvalidBeacon(address beacon);
                /**
                 * @dev An upgrade function sees `msg.value > 0` that may be lost.
                 */
                error ERC1967NonPayable();
                /**
                 * @dev Returns the current implementation address.
                 */
                function getImplementation() internal view returns (address) {
                    return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
                }
                /**
                 * @dev Stores a new address in the EIP1967 implementation slot.
                 */
                function _setImplementation(address newImplementation) private {
                    if (newImplementation.code.length == 0) {
                        revert ERC1967InvalidImplementation(newImplementation);
                    }
                    StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
                }
                /**
                 * @dev Performs implementation upgrade with additional setup call if data is nonempty.
                 * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
                 * to avoid stuck value in the contract.
                 *
                 * Emits an {IERC1967-Upgraded} event.
                 */
                function upgradeToAndCall(address newImplementation, bytes memory data) internal {
                    _setImplementation(newImplementation);
                    emit Upgraded(newImplementation);
                    if (data.length > 0) {
                        Address.functionDelegateCall(newImplementation, data);
                    } else {
                        _checkNonPayable();
                    }
                }
                /**
                 * @dev Storage slot with the admin of the contract.
                 * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
                 */
                // solhint-disable-next-line private-vars-leading-underscore
                bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                /**
                 * @dev Returns the current admin.
                 *
                 * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
                 * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                 * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
                 */
                function getAdmin() internal view returns (address) {
                    return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
                }
                /**
                 * @dev Stores a new address in the EIP1967 admin slot.
                 */
                function _setAdmin(address newAdmin) private {
                    if (newAdmin == address(0)) {
                        revert ERC1967InvalidAdmin(address(0));
                    }
                    StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
                }
                /**
                 * @dev Changes the admin of the proxy.
                 *
                 * Emits an {IERC1967-AdminChanged} event.
                 */
                function changeAdmin(address newAdmin) internal {
                    emit AdminChanged(getAdmin(), newAdmin);
                    _setAdmin(newAdmin);
                }
                /**
                 * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
                 * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
                 */
                // solhint-disable-next-line private-vars-leading-underscore
                bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
                /**
                 * @dev Returns the current beacon.
                 */
                function getBeacon() internal view returns (address) {
                    return StorageSlot.getAddressSlot(BEACON_SLOT).value;
                }
                /**
                 * @dev Stores a new beacon in the EIP1967 beacon slot.
                 */
                function _setBeacon(address newBeacon) private {
                    if (newBeacon.code.length == 0) {
                        revert ERC1967InvalidBeacon(newBeacon);
                    }
                    StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
                    address beaconImplementation = IBeacon(newBeacon).implementation();
                    if (beaconImplementation.code.length == 0) {
                        revert ERC1967InvalidImplementation(beaconImplementation);
                    }
                }
                /**
                 * @dev Change the beacon and trigger a setup call if data is nonempty.
                 * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
                 * to avoid stuck value in the contract.
                 *
                 * Emits an {IERC1967-BeaconUpgraded} event.
                 *
                 * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
                 * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
                 * efficiency.
                 */
                function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
                    _setBeacon(newBeacon);
                    emit BeaconUpgraded(newBeacon);
                    if (data.length > 0) {
                        Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                    } else {
                        _checkNonPayable();
                    }
                }
                /**
                 * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
                 * if an upgrade doesn't perform an initialization call.
                 */
                function _checkNonPayable() private {
                    if (msg.value > 0) {
                        revert ERC1967NonPayable();
                    }
                }
            }
            // 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);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
            pragma solidity ^0.8.20;
            import {IERC20} from "../IERC20.sol";
            /**
             * @dev Interface for the optional metadata functions from the ERC20 standard.
             */
            interface IERC20Metadata is IERC20 {
                /**
                 * @dev Returns the name of the token.
                 */
                function name() external view returns (string memory);
                /**
                 * @dev Returns the symbol of the token.
                 */
                function symbol() external view returns (string memory);
                /**
                 * @dev Returns the decimals places of the token.
                 */
                function decimals() external view returns (uint8);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
            pragma solidity ^0.8.20;
            /**
             * @dev Standard ERC20 Errors
             * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
             */
            interface IERC20Errors {
                /**
                 * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
                 * @param sender Address whose tokens are being transferred.
                 * @param balance Current balance for the interacting account.
                 * @param needed Minimum amount required to perform a transfer.
                 */
                error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
                /**
                 * @dev Indicates a failure with the token `sender`. Used in transfers.
                 * @param sender Address whose tokens are being transferred.
                 */
                error ERC20InvalidSender(address sender);
                /**
                 * @dev Indicates a failure with the token `receiver`. Used in transfers.
                 * @param receiver Address to which tokens are being transferred.
                 */
                error ERC20InvalidReceiver(address receiver);
                /**
                 * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
                 * @param spender Address that may be allowed to operate on tokens without being their owner.
                 * @param allowance Amount of tokens a `spender` is allowed to operate with.
                 * @param needed Minimum amount required to perform a transfer.
                 */
                error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
                /**
                 * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
                 * @param approver Address initiating an approval operation.
                 */
                error ERC20InvalidApprover(address approver);
                /**
                 * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
                 * @param spender Address that may be allowed to operate on tokens without being their owner.
                 */
                error ERC20InvalidSpender(address spender);
            }
            /**
             * @dev Standard ERC721 Errors
             * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
             */
            interface IERC721Errors {
                /**
                 * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
                 * Used in balance queries.
                 * @param owner Address of the current owner of a token.
                 */
                error ERC721InvalidOwner(address owner);
                /**
                 * @dev Indicates a `tokenId` whose `owner` is the zero address.
                 * @param tokenId Identifier number of a token.
                 */
                error ERC721NonexistentToken(uint256 tokenId);
                /**
                 * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
                 * @param sender Address whose tokens are being transferred.
                 * @param tokenId Identifier number of a token.
                 * @param owner Address of the current owner of a token.
                 */
                error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
                /**
                 * @dev Indicates a failure with the token `sender`. Used in transfers.
                 * @param sender Address whose tokens are being transferred.
                 */
                error ERC721InvalidSender(address sender);
                /**
                 * @dev Indicates a failure with the token `receiver`. Used in transfers.
                 * @param receiver Address to which tokens are being transferred.
                 */
                error ERC721InvalidReceiver(address receiver);
                /**
                 * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
                 * @param operator Address that may be allowed to operate on tokens without being their owner.
                 * @param tokenId Identifier number of a token.
                 */
                error ERC721InsufficientApproval(address operator, uint256 tokenId);
                /**
                 * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
                 * @param approver Address initiating an approval operation.
                 */
                error ERC721InvalidApprover(address approver);
                /**
                 * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
                 * @param operator Address that may be allowed to operate on tokens without being their owner.
                 */
                error ERC721InvalidOperator(address operator);
            }
            /**
             * @dev Standard ERC1155 Errors
             * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
             */
            interface IERC1155Errors {
                /**
                 * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
                 * @param sender Address whose tokens are being transferred.
                 * @param balance Current balance for the interacting account.
                 * @param needed Minimum amount required to perform a transfer.
                 * @param tokenId Identifier number of a token.
                 */
                error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
                /**
                 * @dev Indicates a failure with the token `sender`. Used in transfers.
                 * @param sender Address whose tokens are being transferred.
                 */
                error ERC1155InvalidSender(address sender);
                /**
                 * @dev Indicates a failure with the token `receiver`. Used in transfers.
                 * @param receiver Address to which tokens are being transferred.
                 */
                error ERC1155InvalidReceiver(address receiver);
                /**
                 * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
                 * @param operator Address that may be allowed to operate on tokens without being their owner.
                 * @param owner Address of the current owner of a token.
                 */
                error ERC1155MissingApprovalForAll(address operator, address owner);
                /**
                 * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
                 * @param approver Address initiating an approval operation.
                 */
                error ERC1155InvalidApprover(address approver);
                /**
                 * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
                 * @param operator Address that may be allowed to operate on tokens without being their owner.
                 */
                error ERC1155InvalidOperator(address operator);
                /**
                 * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
                 * Used in batch transfers.
                 * @param idsLength Length of the array of token identifiers
                 * @param valuesLength Length of the array of token amounts
                 */
                error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
            pragma solidity ^0.8.20;
            /**
             * @dev This is the interface that {BeaconProxy} expects of its beacon.
             */
            interface IBeacon {
                /**
                 * @dev Must return an address that can be used as a delegate call target.
                 *
                 * {UpgradeableBeacon} will check that this address is a contract.
                 */
                function implementation() external view returns (address);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
            pragma solidity ^0.8.20;
            /**
             * @dev Collection of functions related to the address type
             */
            library Address {
                /**
                 * @dev The ETH balance of the account is not enough to perform the operation.
                 */
                error AddressInsufficientBalance(address account);
                /**
                 * @dev There's no code at `target` (it is not a contract).
                 */
                error AddressEmptyCode(address target);
                /**
                 * @dev A call to an address target failed. The target may have reverted.
                 */
                error FailedInnerCall();
                /**
                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                 * `recipient`, forwarding all available gas and reverting on errors.
                 *
                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                 * imposed by `transfer`, making them unable to receive funds via
                 * `transfer`. {sendValue} removes this limitation.
                 *
                 * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                 *
                 * IMPORTANT: because control is transferred to `recipient`, care must be
                 * taken to not create reentrancy vulnerabilities. Consider using
                 * {ReentrancyGuard} or the
                 * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    if (address(this).balance < amount) {
                        revert AddressInsufficientBalance(address(this));
                    }
                    (bool success, ) = recipient.call{value: amount}("");
                    if (!success) {
                        revert FailedInnerCall();
                    }
                }
                /**
                 * @dev Performs a Solidity function call using a low level `call`. A
                 * plain `call` is an unsafe replacement for a function call: use this
                 * function instead.
                 *
                 * If `target` reverts with a revert reason or custom error, it is bubbled
                 * up by this function (like regular Solidity function calls). However, if
                 * the call reverted with no returned reason, this function reverts with a
                 * {FailedInnerCall} error.
                 *
                 * Returns the raw returned data. To convert to the expected return value,
                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                 *
                 * Requirements:
                 *
                 * - `target` must be a contract.
                 * - calling `target` with `data` must not revert.
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but also transferring `value` wei to `target`.
                 *
                 * Requirements:
                 *
                 * - the calling contract must have an ETH balance of at least `value`.
                 * - the called Solidity function must be `payable`.
                 */
                function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                    if (address(this).balance < value) {
                        revert AddressInsufficientBalance(address(this));
                    }
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResultFromTarget(target, success, returndata);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResultFromTarget(target, success, returndata);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a delegate call.
                 */
                function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.delegatecall(data);
                    return verifyCallResultFromTarget(target, success, returndata);
                }
                /**
                 * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
                 * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
                 * unsuccessful call.
                 */
                function verifyCallResultFromTarget(
                    address target,
                    bool success,
                    bytes memory returndata
                ) internal view returns (bytes memory) {
                    if (!success) {
                        _revert(returndata);
                    } else {
                        // only check if target is a contract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        if (returndata.length == 0 && target.code.length == 0) {
                            revert AddressEmptyCode(target);
                        }
                        return returndata;
                    }
                }
                /**
                 * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
                 * revert reason or with a default {FailedInnerCall} error.
                 */
                function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
                    if (!success) {
                        _revert(returndata);
                    } else {
                        return returndata;
                    }
                }
                /**
                 * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
                 */
                function _revert(bytes memory returndata) private pure {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert FailedInnerCall();
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
            // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
            pragma solidity ^0.8.20;
            /**
             * @dev Library for reading and writing primitive types to specific storage slots.
             *
             * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
             * This library helps with reading and writing to such slots without the need for inline assembly.
             *
             * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
             *
             * Example usage to set ERC1967 implementation slot:
             * ```solidity
             * contract ERC1967 {
             *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
             *
             *     function _getImplementation() internal view returns (address) {
             *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
             *     }
             *
             *     function _setImplementation(address newImplementation) internal {
             *         require(newImplementation.code.length > 0);
             *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
             *     }
             * }
             * ```
             */
            library StorageSlot {
                struct AddressSlot {
                    address value;
                }
                struct BooleanSlot {
                    bool value;
                }
                struct Bytes32Slot {
                    bytes32 value;
                }
                struct Uint256Slot {
                    uint256 value;
                }
                struct StringSlot {
                    string value;
                }
                struct BytesSlot {
                    bytes value;
                }
                /**
                 * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                 */
                function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                 */
                function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                 */
                function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                 */
                function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `StringSlot` with member `value` located at `slot`.
                 */
                function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
                 */
                function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := store.slot
                    }
                }
                /**
                 * @dev Returns an `BytesSlot` with member `value` located at `slot`.
                 */
                function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
                 */
                function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                    /// @solidity memory-safe-assembly
                    assembly {
                        r.slot := store.slot
                    }
                }
            }
            

            File 4 of 4: RandomnessOracle
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.13;
            import "@chainlink/contracts/v0.8/dev/vrf/VRFConsumerBaseV2Plus.sol";
            import "@chainlink/contracts/v0.8/dev/interfaces/IVRFCoordinatorV2Plus.sol";
            import "@chainlink/contracts/v0.8/dev/vrf/libraries/VRFV2PlusClient.sol";
            import "./interfaces/IEthcoin.sol";
            import "./interfaces/IOracle.sol";
            contract RandomnessOracle is VRFConsumerBaseV2Plus, IOracle {
                /// @notice The Ethcoin contract
                address public immutable ethcoin;
                /// @notice The VRF coordinator
                IVRFCoordinatorV2Plus public immutable vrfCoordinator;
                /// @notice The subscription ID
                uint256 public subscriptionId;
                /// @notice The 1000 gwei key hash
                bytes32 public keyHash = 0xc6bf2e7b88e5cfbb4946ff23af846494ae1f3c65270b79ee7876c9aa99d3d45f;
                /// @notice The number of request confirmations
                uint16 public requestConfirmations = 3;
                /// @notice The callback gas limit
                uint32 public callbackGasLimit = 600000;
                /// @notice The number of random words
                uint32 public numWords = 1;
                event RandomnessGenerated(uint256 requestId, uint256 randomNumber);
                event VRFParameterSet(
                    bytes32 keyHash, uint256 subscriptionId, uint16 requestConfirmations, uint32 callbackGasLimit
                );
                constructor(address _ethcoin, address _vrfCoordinator, uint256 _subscriptionId)
                    VRFConsumerBaseV2Plus(_vrfCoordinator)
                {
                    ethcoin = _ethcoin;
                    vrfCoordinator = IVRFCoordinatorV2Plus(_vrfCoordinator);
                    subscriptionId = _subscriptionId;
                }
                /**
                 * @dev Requests the random words.
                 * @return The request ID
                 */
                function requestRandomness() public returns (uint256) {
                    require(msg.sender == ethcoin, "RandomnessOracle: caller is not Ethcoin");
                    return vrfCoordinator.requestRandomWords(
                        VRFV2PlusClient.RandomWordsRequest({
                            keyHash: keyHash,
                            subId: subscriptionId,
                            requestConfirmations: requestConfirmations,
                            callbackGasLimit: callbackGasLimit,
                            numWords: numWords,
                            extraArgs: VRFV2PlusClient._argsToBytes(VRFV2PlusClient.ExtraArgsV1({nativePayment: true}))
                        })
                    );
                }
                /**
                 * @notice Sets the subscription ID.
                 * @param _subscriptionId The subscription ID
                 */
                function configureVRFParameter(
                    bytes32 _keyHash,
                    uint256 _subscriptionId,
                    uint16 _requestConfirmations,
                    uint32 _callbackGasLimit
                ) public onlyOwner {
                    keyHash = _keyHash;
                    subscriptionId = _subscriptionId;
                    requestConfirmations = _requestConfirmations;
                    callbackGasLimit = _callbackGasLimit;
                    emit VRFParameterSet(_keyHash, _subscriptionId, _requestConfirmations, _callbackGasLimit);
                }
                /**
                 * @dev Fulfills the random words.
                 * @param requestId The request ID
                 * @param randomWords The random words
                 */
                function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {
                    // Forward the random number to the Ethcoin contract.
                    IEthcoin(ethcoin).fulfillRandomness(requestId, randomWords[0]);
                    emit RandomnessGenerated(requestId, randomWords[0]);
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            import "../interfaces/IVRFCoordinatorV2Plus.sol";
            import "../interfaces/IVRFMigratableConsumerV2Plus.sol";
            import "../../shared/access/ConfirmedOwner.sol";
            /** ****************************************************************************
             * @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 VRFCoordinatorV2Plus.
             * @dev 2. The consumer contract implements fulfillRandomWords.
             * *****************************************************************************
             * @dev USAGE
             *
             * @dev Calling contracts must inherit from VRFConsumerBaseV2Plus, and can
             * @dev initialize VRFConsumerBaseV2Plus's attributes in their constructor as
             * @dev shown:
             *
             * @dev   contract VRFConsumerV2Plus is VRFConsumerBaseV2Plus {
             * @dev     constructor(<other arguments>, address _vrfCoordinator, address _subOwner)
             * @dev       VRFConsumerBaseV2Plus(_vrfCoordinator, _subOwner) 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 a 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, extraArgs),
             * @dev see (IVRFCoordinatorV2Plus for a description of the arguments).
             *
             * @dev Once the VRFCoordinatorV2Plus 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 VRFConsumerBaseV2Plus.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 VRFConsumerBaseV2Plus is IVRFMigratableConsumerV2Plus, ConfirmedOwner {
              error OnlyCoordinatorCanFulfill(address have, address want);
              error OnlyOwnerOrCoordinator(address have, address owner, address coordinator);
              error ZeroAddress();
              IVRFCoordinatorV2Plus public s_vrfCoordinator;
              /**
               * @param _vrfCoordinator address of VRFCoordinator contract
               */
              constructor(address _vrfCoordinator) ConfirmedOwner(msg.sender) {
                s_vrfCoordinator = IVRFCoordinatorV2Plus(_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 VRFConsumerBaseV2Plus 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 != address(s_vrfCoordinator)) {
                  revert OnlyCoordinatorCanFulfill(msg.sender, address(s_vrfCoordinator));
                }
                fulfillRandomWords(requestId, randomWords);
              }
              /**
               * @inheritdoc IVRFMigratableConsumerV2Plus
               */
              function setCoordinator(address _vrfCoordinator) public override onlyOwnerOrCoordinator {
                s_vrfCoordinator = IVRFCoordinatorV2Plus(_vrfCoordinator);
              }
              modifier onlyOwnerOrCoordinator() {
                if (msg.sender != owner() && msg.sender != address(s_vrfCoordinator)) {
                  revert OnlyOwnerOrCoordinator(msg.sender, owner(), address(s_vrfCoordinator));
                }
                _;
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import "../vrf/libraries/VRFV2PlusClient.sol";
            import "./IVRFSubscriptionV2Plus.sol";
            // Interface that enables consumers of VRFCoordinatorV2Plus to be future-proof for upgrades
            // This interface is supported by subsequent versions of VRFCoordinatorV2Plus
            interface IVRFCoordinatorV2Plus is IVRFSubscriptionV2Plus {
              /**
               * @notice Request a set of random words.
               * @param req - a struct containing following fiels for randomness request:
               * 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.
               * subId  - The ID of the VRF subscription. Must be funded
               * with the minimum subscription balance required for the selected keyHash.
               * requestConfirmations - 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].
               * 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]
               * 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.
               * extraArgs - abi-encoded extra args
               * @return requestId - A unique identifier of the request. Can be used to match
               * a request to a response in fulfillRandomWords.
               */
              function requestRandomWords(VRFV2PlusClient.RandomWordsRequest calldata req) external returns (uint256 requestId);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            // End consumer library.
            library VRFV2PlusClient {
              // extraArgs will evolve to support new features
              bytes4 public constant EXTRA_ARGS_V1_TAG = bytes4(keccak256("VRF ExtraArgsV1"));
              struct ExtraArgsV1 {
                bool nativePayment;
              }
              struct RandomWordsRequest {
                bytes32 keyHash;
                uint256 subId;
                uint16 requestConfirmations;
                uint32 callbackGasLimit;
                uint32 numWords;
                bytes extraArgs;
              }
              function _argsToBytes(ExtraArgsV1 memory extraArgs) internal pure returns (bytes memory bts) {
                return abi.encodeWithSelector(EXTRA_ARGS_V1_TAG, extraArgs);
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.13;
            interface IEthcoin {
                function fulfillRandomness(uint256 requestId, uint256 randomNumber) external;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.13;
            interface IOracle {
                function requestRandomness() external returns (uint256);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /// @notice The IVRFMigratableConsumerV2Plus interface defines the
            /// @notice method required to be implemented by all V2Plus consumers.
            /// @dev This interface is designed to be used in VRFConsumerBaseV2Plus.
            interface IVRFMigratableConsumerV2Plus {
              /// @notice Sets the VRF Coordinator address
              /// @notice This method is should only be callable by the coordinator or contract owner
              function setCoordinator(address vrfCoordinator) external;
            }
            // 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)) {}
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /// @notice The IVRFSubscriptionV2Plus interface defines the subscription
            /// @notice related methods implemented by the V2Plus coordinator.
            interface IVRFSubscriptionV2Plus {
              /**
               * @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(uint256 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(uint256 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(uint256 subId, address to) 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(uint256 subId) external;
              /**
               * @notice Request subscription owner transfer.
               * @param subId - ID of the subscription
               * @param newOwner - proposed new owner of the subscription
               */
              function requestSubscriptionOwnerTransfer(uint256 subId, address newOwner) external;
              /**
               * @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 with LINK, use transferAndCall. For example
               * @dev  LINKTOKEN.transferAndCall(
               * @dev    address(COORDINATOR),
               * @dev    amount,
               * @dev    abi.encode(subId));
               * @dev Note to fund the subscription with Native, use fundSubscriptionWithNative. Be sure
               * @dev  to send Native with the call, for example:
               * @dev COORDINATOR.fundSubscriptionWithNative{value: amount}(subId);
               */
              function createSubscription() external returns (uint256 subId);
              /**
               * @notice Get a VRF subscription.
               * @param subId - ID of the subscription
               * @return balance - LINK balance of the subscription in juels.
               * @return nativeBalance - native balance of the subscription in wei.
               * @return reqCount - Requests count of subscription.
               * @return owner - owner of the subscription.
               * @return consumers - list of consumer address which are able to use this subscription.
               */
              function getSubscription(
                uint256 subId
              )
                external
                view
                returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address owner, address[] memory consumers);
              /*
               * @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(uint256 subId) external view returns (bool);
              /**
               * @notice Paginate through all active VRF subscriptions.
               * @param startIndex index of the subscription to start from
               * @param maxCount maximum number of subscriptions to return, 0 to return all
               * @dev the order of IDs in the list is **not guaranteed**, therefore, if making successive calls, one
               * @dev should consider keeping the blockheight constant to ensure a holistic picture of the contract state
               */
              function getActiveSubscriptionIds(uint256 startIndex, uint256 maxCount) external view returns (uint256[] memory);
              /**
               * @notice Fund a subscription with native.
               * @param subId - ID of the subscription
               * @notice This method expects msg.value to be greater than 0.
               */
              function fundSubscriptionWithNative(uint256 subId) external payable;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import "../interfaces/IOwnable.sol";
            /**
             * @title The ConfirmedOwner contract
             * @notice A contract with helpers for basic contract ownership.
             */
            contract ConfirmedOwnerWithProposal is IOwnable {
              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();
                _;
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            interface IOwnable {
              function owner() external returns (address);
              function transferOwnership(address recipient) external;
              function acceptOwnership() external;
            }