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