UNPKG

witnet-solidity-bridge

Version:

Witnet Solidity Bridge contracts for EVM-compatible chains

579 lines 842 kB
{
  "_format": "hh3-sol-build-info-1",
  "id": "solc-0_8_30-47301052af11a5aa5062e9b98ca44d5e142950cf",
  "solcVersion": "0.8.30",
  "solcLongVersion": "0.8.30+commit.73712a01",
  "userSourceNameMap": {
    "contracts/WitOracle.sol": "project/contracts/WitOracle.sol",
    "contracts/WitOraclePushOnly.sol": "project/contracts/WitOraclePushOnly.sol",
    "contracts/WitOracleRadonRegistry.sol": "project/contracts/WitOracleRadonRegistry.sol",
    "contracts/WitOracleRadonRequestFactory.sol": "project/contracts/WitOracleRadonRequestFactory.sol",
    "contracts/WitPriceFeeds.sol": "project/contracts/WitPriceFeeds.sol",
    "contracts/WitPriceFeedsLegacy.sol": "project/contracts/WitPriceFeedsLegacy.sol",
    "contracts/WitRandomness.sol": "project/contracts/WitRandomness.sol",
    "contracts/WitRandomnessLegacy.sol": "project/contracts/WitRandomnessLegacy.sol",
    "contracts/apps/WitPriceFeedsLegacyBypassV3.sol": "project/contracts/apps/WitPriceFeedsLegacyBypassV3.sol",
    "contracts/apps/WitPriceFeedsLegacyUpgradable.sol": "project/contracts/apps/WitPriceFeedsLegacyUpgradable.sol",
    "contracts/apps/WitPriceFeedsUpgradableV3.sol": "project/contracts/apps/WitPriceFeedsUpgradableV3.sol",
    "contracts/apps/WitPriceFeedsV3.sol": "project/contracts/apps/WitPriceFeedsV3.sol",
    "contracts/apps/WitRandomnessV3.sol": "project/contracts/apps/WitRandomnessV3.sol",
    "contracts/core/WitnetDeployer.sol": "project/contracts/core/WitnetDeployer.sol",
    "contracts/core/WitnetDeployerConfluxCore.sol": "project/contracts/core/WitnetDeployerConfluxCore.sol",
    "contracts/core/WitnetDeployerDeferred.sol": "project/contracts/core/WitnetDeployerDeferred.sol",
    "contracts/core/WitnetDeployerMeter.sol": "project/contracts/core/WitnetDeployerMeter.sol",
    "contracts/core/WitnetUpgradableBase.sol": "project/contracts/core/WitnetUpgradableBase.sol",
    "contracts/core/base/WitOracleBasePushOnly.sol": "project/contracts/core/base/WitOracleBasePushOnly.sol",
    "contracts/core/base/WitOracleBasePushOnlyTrustable.sol": "project/contracts/core/base/WitOracleBasePushOnlyTrustable.sol",
    "contracts/core/base/WitOracleBasePushOnlyTrustless.sol": "project/contracts/core/base/WitOracleBasePushOnlyTrustless.sol",
    "contracts/core/base/WitOracleBasePushOnlyUpgradable.sol": "project/contracts/core/base/WitOracleBasePushOnlyUpgradable.sol",
    "contracts/core/base/WitOracleBaseQueriable.sol": "project/contracts/core/base/WitOracleBaseQueriable.sol",
    "contracts/core/base/WitOracleBaseQueriableTrustable.sol": "project/contracts/core/base/WitOracleBaseQueriableTrustable.sol",
    "contracts/core/base/WitOracleBaseQueriableTrustless.sol": "project/contracts/core/base/WitOracleBaseQueriableTrustless.sol",
    "contracts/core/base/WitOracleBaseQueriableUpgradable.sol": "project/contracts/core/base/WitOracleBaseQueriableUpgradable.sol",
    "contracts/core/base/WitOracleRadonRegistryBase.sol": "project/contracts/core/base/WitOracleRadonRegistryBase.sol",
    "contracts/core/base/WitOracleRadonRegistryBaseUpgradable.sol": "project/contracts/core/base/WitOracleRadonRegistryBaseUpgradable.sol",
    "contracts/core/base/WitOracleRadonRequestFactoryBase.sol": "project/contracts/core/base/WitOracleRadonRequestFactoryBase.sol",
    "contracts/core/base/WitOracleRadonRequestFactoryBaseUpgradable.sol": "project/contracts/core/base/WitOracleRadonRequestFactoryBaseUpgradable.sol",
    "contracts/core/base/WitOracleRadonRequestFactoryModals.sol": "project/contracts/core/base/WitOracleRadonRequestFactoryModals.sol",
    "contracts/core/base/WitOracleRadonRequestFactoryTemplates.sol": "project/contracts/core/base/WitOracleRadonRequestFactoryTemplates.sol",
    "contracts/core/trustable/WitOracleTrustableDefault.sol": "project/contracts/core/trustable/WitOracleTrustableDefault.sol",
    "contracts/core/trustable/WitOracleTrustableExperimental.sol": "project/contracts/core/trustable/WitOracleTrustableExperimental.sol",
    "contracts/core/trustable/WitOracleTrustableObscuro.sol": "project/contracts/core/trustable/WitOracleTrustableObscuro.sol",
    "contracts/core/trustable/WitOracleTrustableOvm2.sol": "project/contracts/core/trustable/WitOracleTrustableOvm2.sol",
    "contracts/core/trustable/WitOracleTrustablePushOnly.sol": "project/contracts/core/trustable/WitOracleTrustablePushOnly.sol",
    "contracts/core/trustable/WitOracleTrustableReef.sol": "project/contracts/core/trustable/WitOracleTrustableReef.sol",
    "contracts/core/trustable/WitOracleTrustableZkSync.sol": "project/contracts/core/trustable/WitOracleTrustableZkSync.sol",
    "contracts/core/trustless/WitOracleRadonRegistryDefaultV21.sol": "project/contracts/core/trustless/WitOracleRadonRegistryDefaultV21.sol",
    "contracts/core/trustless/WitOracleRadonRequestFactoryModalsDefault.sol": "project/contracts/core/trustless/WitOracleRadonRequestFactoryModalsDefault.sol",
    "contracts/core/trustless/WitOracleRadonRequestFactoryTemplatesDefault.sol": "project/contracts/core/trustless/WitOracleRadonRequestFactoryTemplatesDefault.sol",
    "contracts/core/trustless/WitOracleTrustlessDefaultV22.sol": "project/contracts/core/trustless/WitOracleTrustlessDefaultV22.sol",
    "contracts/core/upgradable/WitOracleRadonRegistryUpgradableDefault.sol": "project/contracts/core/upgradable/WitOracleRadonRegistryUpgradableDefault.sol",
    "contracts/core/upgradable/WitOracleRadonRegistryUpgradableNoSha256.sol": "project/contracts/core/upgradable/WitOracleRadonRegistryUpgradableNoSha256.sol",
    "contracts/core/upgradable/WitOracleRadonRegistryUpgradableZkSync.sol": "project/contracts/core/upgradable/WitOracleRadonRegistryUpgradableZkSync.sol",
    "contracts/core/upgradable/WitOracleRadonRequestFactoryUpgradableConfluxCore.sol": "project/contracts/core/upgradable/WitOracleRadonRequestFactoryUpgradableConfluxCore.sol",
    "contracts/core/upgradable/WitOracleRadonRequestFactoryUpgradableDefault.sol": "project/contracts/core/upgradable/WitOracleRadonRequestFactoryUpgradableDefault.sol",
    "contracts/core/upgradable/WitOracleTrustlessUpgradableDefault.sol": "project/contracts/core/upgradable/WitOracleTrustlessUpgradableDefault.sol",
    "contracts/data/WitOracleDataLib.sol": "project/contracts/data/WitOracleDataLib.sol",
    "contracts/data/WitOracleRadonRegistryData.sol": "project/contracts/data/WitOracleRadonRegistryData.sol",
    "contracts/data/WitOracleTrustlessDataLib.sol": "project/contracts/data/WitOracleTrustlessDataLib.sol",
    "contracts/data/WitPriceFeedsDataLib.sol": "project/contracts/data/WitPriceFeedsDataLib.sol",
    "contracts/data/WitPriceFeedsLegacyDataLib.sol": "project/contracts/data/WitPriceFeedsLegacyDataLib.sol",
    "contracts/interfaces/IWitAppliance.sol": "project/contracts/interfaces/IWitAppliance.sol",
    "contracts/interfaces/IWitOracle.sol": "project/contracts/interfaces/IWitOracle.sol",
    "contracts/interfaces/IWitOracleAppliance.sol": "project/contracts/interfaces/IWitOracleAppliance.sol",
    "contracts/interfaces/IWitOracleConsumer.sol": "project/contracts/interfaces/IWitOracleConsumer.sol",
    "contracts/interfaces/IWitOracleQueriable.sol": "project/contracts/interfaces/IWitOracleQueriable.sol",
    "contracts/interfaces/IWitOracleQueriableConsumer.sol": "project/contracts/interfaces/IWitOracleQueriableConsumer.sol",
    "contracts/interfaces/IWitOracleQueriableEvents.sol": "project/contracts/interfaces/IWitOracleQueriableEvents.sol",
    "contracts/interfaces/IWitOracleQueriableExperimental.sol": "project/contracts/interfaces/IWitOracleQueriableExperimental.sol",
    "contracts/interfaces/IWitOracleQueriableTrustableReporter.sol": "project/contracts/interfaces/IWitOracleQueriableTrustableReporter.sol",
    "contracts/interfaces/IWitOracleQueriableTrustlessReporter.sol": "project/contracts/interfaces/IWitOracleQueriableTrustlessReporter.sol",
    "contracts/interfaces/IWitOracleRadonRegistry.sol": "project/contracts/interfaces/IWitOracleRadonRegistry.sol",
    "contracts/interfaces/IWitOracleRadonRegistryEvents.sol": "project/contracts/interfaces/IWitOracleRadonRegistryEvents.sol",
    "contracts/interfaces/IWitOracleRadonRequestFactory.sol": "project/contracts/interfaces/IWitOracleRadonRequestFactory.sol",
    "contracts/interfaces/IWitOracleRadonRequestModal.sol": "project/contracts/interfaces/IWitOracleRadonRequestModal.sol",
    "contracts/interfaces/IWitOracleRadonRequestTemplate.sol": "project/contracts/interfaces/IWitOracleRadonRequestTemplate.sol",
    "contracts/interfaces/IWitOracleTrustableAdmin.sol": "project/contracts/interfaces/IWitOracleTrustableAdmin.sol",
    "contracts/interfaces/IWitOracleTrustless.sol": "project/contracts/interfaces/IWitOracleTrustless.sol",
    "contracts/interfaces/IWitPriceFeeds.sol": "project/contracts/interfaces/IWitPriceFeeds.sol",
    "contracts/interfaces/IWitPriceFeedsAdmin.sol": "project/contracts/interfaces/IWitPriceFeedsAdmin.sol",
    "contracts/interfaces/IWitPriceFeedsConsumer.sol": "project/contracts/interfaces/IWitPriceFeedsConsumer.sol",
    "contracts/interfaces/IWitPriceFeedsEvents.sol": "project/contracts/interfaces/IWitPriceFeedsEvents.sol",
    "contracts/interfaces/IWitPriceFeedsTypes.sol": "project/contracts/interfaces/IWitPriceFeedsTypes.sol",
    "contracts/interfaces/IWitRandomness.sol": "project/contracts/interfaces/IWitRandomness.sol",
    "contracts/interfaces/IWitRandomnessAdmin.sol": "project/contracts/interfaces/IWitRandomnessAdmin.sol",
    "contracts/interfaces/IWitRandomnessConsumer.sol": "project/contracts/interfaces/IWitRandomnessConsumer.sol",
    "contracts/interfaces/IWitRandomnessEvents.sol": "project/contracts/interfaces/IWitRandomnessEvents.sol",
    "contracts/interfaces/IWitRandomnessTypes.sol": "project/contracts/interfaces/IWitRandomnessTypes.sol",
    "contracts/interfaces/legacy/IChainlinkAggregatorV3.sol": "project/contracts/interfaces/legacy/IChainlinkAggregatorV3.sol",
    "contracts/interfaces/legacy/IPythChainlinkAggregatorV3.sol": "project/contracts/interfaces/legacy/IPythChainlinkAggregatorV3.sol",
    "contracts/interfaces/legacy/IWitOracleConsumerLegacy.sol": "project/contracts/interfaces/legacy/IWitOracleConsumerLegacy.sol",
    "contracts/interfaces/legacy/IWitOracleLegacy.sol": "project/contracts/interfaces/legacy/IWitOracleLegacy.sol",
    "contracts/interfaces/legacy/IWitOracleRadonRegistryLegacy.sol": "project/contracts/interfaces/legacy/IWitOracleRadonRegistryLegacy.sol",
    "contracts/interfaces/legacy/IWitOracleRequest.sol": "project/contracts/interfaces/legacy/IWitOracleRequest.sol",
    "contracts/interfaces/legacy/IWitOracleRequestFactory.sol": "project/contracts/interfaces/legacy/IWitOracleRequestFactory.sol",
    "contracts/interfaces/legacy/IWitOracleRequestFactoryEvents.sol": "project/contracts/interfaces/legacy/IWitOracleRequestFactoryEvents.sol",
    "contracts/interfaces/legacy/IWitOracleRequestTemplate.sol": "project/contracts/interfaces/legacy/IWitOracleRequestTemplate.sol",
    "contracts/interfaces/legacy/IWitPriceFeedsLegacy.sol": "project/contracts/interfaces/legacy/IWitPriceFeedsLegacy.sol",
    "contracts/interfaces/legacy/IWitPriceFeedsLegacyAdmin.sol": "project/contracts/interfaces/legacy/IWitPriceFeedsLegacyAdmin.sol",
    "contracts/interfaces/legacy/IWitPriceFeedsLegacySolver.sol": "project/contracts/interfaces/legacy/IWitPriceFeedsLegacySolver.sol",
    "contracts/interfaces/legacy/IWitPriceFeedsLegacySolverFactory.sol": "project/contracts/interfaces/legacy/IWitPriceFeedsLegacySolverFactory.sol",
    "contracts/interfaces/legacy/IWitPyth.sol": "project/contracts/interfaces/legacy/IWitPyth.sol",
    "contracts/interfaces/legacy/IWitPythChainlinkAggregator.sol": "project/contracts/interfaces/legacy/IWitPythChainlinkAggregator.sol",
    "contracts/interfaces/legacy/IWitPythErrors.sol": "project/contracts/interfaces/legacy/IWitPythErrors.sol",
    "contracts/interfaces/legacy/IWitPythEvents.sol": "project/contracts/interfaces/legacy/IWitPythEvents.sol",
    "contracts/interfaces/legacy/IWitPythReporter.sol": "project/contracts/interfaces/legacy/IWitPythReporter.sol",
    "contracts/interfaces/legacy/IWitRandomnessAdminLegacy.sol": "project/contracts/interfaces/legacy/IWitRandomnessAdminLegacy.sol",
    "contracts/interfaces/legacy/IWitRandomnessLegacy.sol": "project/contracts/interfaces/legacy/IWitRandomnessLegacy.sol",
    "contracts/libs/Bech32.sol": "project/contracts/libs/Bech32.sol",
    "contracts/libs/Create3.sol": "project/contracts/libs/Create3.sol",
    "contracts/libs/Secp256k1.sol": "project/contracts/libs/Secp256k1.sol",
    "contracts/libs/Slices.sol": "project/contracts/libs/Slices.sol",
    "contracts/libs/WitOracleRadonEncodingLib.sol": "project/contracts/libs/WitOracleRadonEncodingLib.sol",
    "contracts/libs/WitOracleResultStatusLib.sol": "project/contracts/libs/WitOracleResultStatusLib.sol",
    "contracts/libs/Witnet.sol": "project/contracts/libs/Witnet.sol",
    "contracts/libs/WitnetBuffer.sol": "project/contracts/libs/WitnetBuffer.sol",
    "contracts/libs/WitnetCBOR.sol": "project/contracts/libs/WitnetCBOR.sol",
    "contracts/mockups/UsingWitOracle.sol": "project/contracts/mockups/UsingWitOracle.sol",
    "contracts/mockups/UsingWitPriceFeeds.sol": "project/contracts/mockups/UsingWitPriceFeeds.sol",
    "contracts/mockups/UsingWitRandomness.sol": "project/contracts/mockups/UsingWitRandomness.sol",
    "contracts/mockups/WitPythChainlinkAggregator.sol": "project/contracts/mockups/WitPythChainlinkAggregator.sol",
    "contracts/mockups/legacy/WitPriceFeedsSolverBase.sol": "project/contracts/mockups/legacy/WitPriceFeedsSolverBase.sol",
    "contracts/mockups/tests/TestBech32.sol": "project/contracts/mockups/tests/TestBech32.sol",
    "contracts/mockups/tests/TestSecp256k1.sol": "project/contracts/mockups/tests/TestSecp256k1.sol",
    "contracts/mockups/tests/WitRngConsumer.sol": "project/contracts/mockups/tests/WitRngConsumer.sol",
    "contracts/patterns/Clonable.sol": "project/contracts/patterns/Clonable.sol",
    "contracts/patterns/Escrowable.sol": "project/contracts/patterns/Escrowable.sol",
    "contracts/patterns/Initializable.sol": "project/contracts/patterns/Initializable.sol",
    "contracts/patterns/Ownable.sol": "project/contracts/patterns/Ownable.sol",
    "contracts/patterns/Ownable2Step.sol": "project/contracts/patterns/Ownable2Step.sol",
    "contracts/patterns/Payable.sol": "project/contracts/patterns/Payable.sol",
    "contracts/patterns/Proxiable.sol": "project/contracts/patterns/Proxiable.sol",
    "contracts/patterns/ReentrancyGuard.sol": "project/contracts/patterns/ReentrancyGuard.sol",
    "contracts/patterns/Upgradeable.sol": "project/contracts/patterns/Upgradeable.sol"
  },
  "input": {
    "language": "Solidity",
    "settings": {
      "evmVersion": "prague",
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "outputSelection": {
        "*": {
          "": [
            "ast"
          ],
          "*": [
            "abi",
            "evm.bytecode",
            "evm.deployedBytecode",
            "evm.methodIdentifiers",
            "metadata"
          ]
        }
      },
      "remappings": [
        "project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/contracts-upgradeable@5.4.0/",
        "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
        "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
        "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
        "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
        "project/:ado-contracts/=npm/ado-contracts@1.0.0/",
        "project/:ado-contracts/=npm/ado-contracts@1.0.0/",
        "project/:ado-contracts/=npm/ado-contracts@1.0.0/"
      ]
    },
    "sources": {
      "npm/@openzeppelin/contracts-upgradeable@5.4.0/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reinitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\n        }\n        $._initialized = 1;\n        if (isTopLevelCall) {\n            $._initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            $._initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\n        $._initialized = version;\n        $._initializing = true;\n        _;\n        $._initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\n        }\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.\n     *\n     * NOTE: Consider following the ERC-7201 formula to derive storage locations.\n     */\n    function _initializableStorageSlot() internal pure virtual returns (bytes32) {\n        return INITIALIZABLE_STORAGE;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        bytes32 slot = _initializableStorageSlot();\n        assembly {\n            $.slot := slot\n        }\n    }\n}\n"
      },
      "npm/@openzeppelin/contracts@5.4.0/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../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 * The initial owner is set to the address provided by the deployer. This can\n * 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    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\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        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\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        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\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"
      },
      "npm/@openzeppelin/contracts@5.4.0/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"
      },
      "npm/@openzeppelin/contracts@5.4.0/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\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    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"
      },
      "npm/@openzeppelin/contracts@5.4.0/utils/introspection/ERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165 is IERC165 {\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"
      },
      "npm/@openzeppelin/contracts@5.4.0/utils/introspection/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "npm/@openzeppelin/contracts@5.4.0/utils/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,\n * consider using {ReentrancyGuardTransient} instead.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    uint256 private _status;\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    constructor() {\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if (_status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        _status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == ENTERED;\n    }\n}\n"
      },
      "npm/ado-contracts@1.0.0/contracts/interfaces/IERC2362.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.5.0 <0.9.0;\n\n/**\n* @dev EIP2362 Interface for pull oracles\n* https://github.com/adoracles/EIPs/blob/erc-2362/EIPS/eip-2362.md\n*/\ninterface IERC2362\n{\n\t/**\n\t * @dev Exposed function pertaining to EIP standards\n\t * @param _id bytes32 ID of the query\n\t * @return int,uint,uint returns the value, timestamp, and status code of query\n\t */\n\tfunction valueFor(bytes32 _id) external view returns(int256,uint256,uint256);\n}"
      },
      "project/contracts/apps/WitPriceFeedsLegacyBypassV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {IWitOracle, IWitOracleRadonRegistry, Witnet} from \"../interfaces/IWitOracle.sol\";\r\n\r\nimport {IWitOracleLegacy} from \"../interfaces/legacy/IWitOracleLegacy.sol\";\r\nimport {IWitPriceFeeds, IWitPriceFeedsTypes, IWitPyth} from \"../interfaces/IWitPriceFeeds.sol\";\r\nimport {\r\n    IWitPriceFeedsLegacy, \r\n    IWitPriceFeedsLegacySolver,\r\n    IWitOracleRequest, \r\n    IWitOracleRequestTemplate\r\n} from \"../interfaces/legacy/IWitPriceFeedsLegacy.sol\";\r\n\r\nimport {Slices} from \"../libs/Slices.sol\";\r\nimport {Ownable, Ownable2Step} from \"../patterns/Ownable2Step.sol\";\r\nimport {WitnetUpgradableBase} from \"../core/WitnetUpgradableBase.sol\";\r\nimport {WitPriceFeedsLegacyDataLib} from \"../data/WitPriceFeedsLegacyDataLib.sol\";\r\nimport {WitPriceFeedsLegacy, IWitOracleAppliance} from \"../WitPriceFeedsLegacy.sol\";\r\n\r\n\r\n/// @title WitPriceFeeds: Price Feeds upgradable repository reliant on the Wit/Oracle blockchain.\r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\n\r\ncontract WitPriceFeedsLegacyBypassV3\r\n    is\r\n        Ownable2Step,\r\n        WitnetUpgradableBase\r\n{\r\n    using Slices for string;\r\n    using Slices for Slices.Slice;\r\n\r\n    IWitPriceFeeds immutable public surrogate;\r\n    IWitOracleRadonRegistry immutable public registry;\r\n\r\n    struct BypassV2V3 {\r\n        mapping (IWitPriceFeedsTypes.ID4 => bytes4) v2Ids;\r\n        mapping (bytes4 => IWitPriceFeedsTypes.ID4) v3Ids;\r\n    }\r\n\r\n    function class() public pure returns (string memory) {\r\n        return type(WitPriceFeedsLegacyBypassV3).name;\r\n    }\r\n    \r\n    constructor(\r\n            address _surrogate,\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        Ownable(address(msg.sender))\r\n        WitnetUpgradableBase(\r\n            _upgradable,\r\n            _versionTag,\r\n            \"io.witnet.proxiable.feeds.price\"\r\n        )\r\n    {\r\n        _require(\r\n            _surrogate != address(0)\r\n                && _surrogate.code.length > 0,\r\n            \"invalid surrogate\"\r\n        );\r\n        surrogate = IWitPriceFeeds(_surrogate);\r\n        registry = IWitOracleRadonRegistry(\r\n            IWitOracle(\r\n                IWitOracleAppliance(_surrogate).witOracle()\r\n            ).registry()\r\n        );\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'Upgradeable' ------------------------------------------------------------------------------------\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    function __initializeUpgradableData(bytes memory) virtual override internal {\r\n        uint _length = __legacy().ids.length;\r\n        for (uint _ix; _ix < _length; ++ _ix) {\r\n            // turn legacy captions 'Price-*' into 'Caption.*' ...\r\n            bytes4 _v2Id = __legacy().ids[_ix];\r\n            string memory _captionV2 = __legacy().records[_v2Id].caption;\r\n            Slices.Slice memory _slice = _captionV2.toSlice();\r\n            Slices.Slice memory _delim = string(\"-\").toSlice();\r\n            string[] memory _parts = new string[](_slice.count(_delim) + 1);\r\n            for (uint _px = 0; _px < _parts.length; _px ++) {\r\n                _parts[_px] = _slice.split(_delim).toString();\r\n            }\r\n            string memory _captionV3 = \"Crypto.\";\r\n            for (uint _px = 1; _px < _parts.length; _px ++) {\r\n                _captionV3 = string(abi.encodePacked(\r\n                    _captionV3,\r\n                    _parts[_px]\r\n                ));\r\n            }\r\n            IWitPriceFeedsTypes.ID4 _v3Id = IWitPriceFeedsTypes.ID4.wrap(bytes4(keccak256(bytes(_captionV3))));\r\n            __bypass().v2Ids[_v3Id] = _v2Id;\r\n            __bypass().v3Ids[_v2Id] = _v3Id;\r\n        }\r\n    }\r\n\r\n    /// Tells whether provided address could eventually upgrade the contract.\r\n    function isUpgradableFrom(address _from) external view override returns (bool) {\r\n        address _owner = owner();\r\n        return (\r\n            // false if the WRB is intrinsically not upgradable, or `_from` is no owner\r\n            isUpgradable()\r\n                && _owner == _from\r\n        );\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements 'IWitFeeds' -------------------------------------------------------------------------------------\r\n\r\n    function estimateUpdateBaseFee(uint256) external pure returns (uint256) {\r\n        return 0;\r\n    }\r\n\r\n    function footprint() external view returns (bytes4) {\r\n        return surrogate.footprint();\r\n    }\r\n\r\n    function hash(string memory caption) external pure returns (bytes4) {\r\n        return WitPriceFeedsLegacyDataLib.hash(caption);\r\n    }\r\n    \r\n    function lookupCaption(bytes4 feedId)\r\n        public view\r\n        returns (string memory _caption)\r\n    {\r\n        _caption = surrogate.lookupPriceFeedCaption(IWitPriceFeedsTypes.ID4.wrap(feedId));\r\n        if (bytes(_caption).length == 0) {\r\n            return __legacy().records[feedId].caption;\r\n        }\r\n    }\r\n\r\n    function supportedFeeds()\r\n        external view\r\n        returns (bytes4[] memory _ids, string[] memory _captions, bytes32[] memory _solvers)\r\n    {\r\n        IWitPriceFeeds.Info[] memory _pfs = surrogate.lookupPriceFeeds();\r\n        _ids = new bytes4[](_pfs.length);\r\n        _captions = new string[](_pfs.length);\r\n        _solvers = new bytes32[](_pfs.length);\r\n        for (uint _ix; _ix < _pfs.length; ++ _ix) {\r\n            IWitPriceFeedsTypes.ID4 _v3Id = IWitPriceFeedsTypes.ID4.wrap(bytes4((IWitPyth.ID.unwrap(_pfs[_ix].id))));\r\n            _ids[_ix] = (__bypass().v2Ids[_v3Id] == bytes4(0) ? IWitPriceFeedsTypes.ID4.unwrap(_v3Id) : __bypass().v2Ids[_v3Id]);\r\n            _captions[_ix] = _pfs[_ix].symbol;\r\n            if (_pfs[_ix].mapper.class != IWitPriceFeedsTypes.Mappers.None) {\r\n                _solvers[_ix] = (_pfs[_ix].oracle.sources != bytes32(0)\r\n                    ? _pfs[_ix].oracle.sources\r\n                    : bytes32(bytes20(_pfs[_ix].oracle.target))\r\n                );\r\n            }\r\n        }\r\n    }\r\n    \r\n    function supportsCaption(string calldata caption) external view returns (bool) {\r\n        return surrogate.supportsCaption(caption);\r\n    }\r\n\r\n    function totalFeeds() \r\n        external view\r\n        returns (uint256)\r\n    {\r\n        return surrogate.lookupPriceFeeds().length;\r\n    }\r\n\r\n    function lastValidQueryId(bytes4)\r\n        external pure\r\n        returns (uint256)\r\n    {\r\n        return 0;\r\n    }\r\n\r\n    function lastValidQueryResponse(bytes4)\r\n        external pure\r\n        returns (Witnet.QueryResponse memory)\r\n    {}\r\n\r\n    function latestUpdateQueryId(bytes4)\r\n        external pure\r\n        returns (uint256)\r\n    {\r\n        return 0;\r\n    }\r\n\r\n    function latestUpdateQueryRequest(bytes4)\r\n        external pure\r\n        returns (Witnet.QueryRequest memory _void)\r\n    {}\r\n\r\n    function lookupWitnetBytecode(bytes4 feedId)\r\n        external view\r\n        returns (bytes memory)\r\n    {\r\n        IWitPriceFeeds.Info memory _info = surrogate.lookupPriceFeed(IWitPriceFeedsTypes.ID4.wrap(feedId));\r\n        if (_info.oracle.class == IWitPriceFeedsTypes.Oracles.Witnet) {\r\n            Witnet.RadonHash _radHash = Witnet.RadonHash.wrap(_info.oracle.sources);\r\n            return registry.lookupRadonRequestBytecode(_radHash);\r\n        } else {\r\n            return new bytes(0);\r\n        }\r\n    }\r\n\r\n    function lookupWitnetRadHash(bytes4 feedId)\r\n        external view\r\n        returns (bytes32 _void)\r\n    {\r\n        IWitPriceFeeds.Info memory _info = surrogate.lookupPriceFeed(IWitPriceFeedsTypes.ID4.wrap(feedId));\r\n        if (_info.oracle.class == IWitPriceFeedsTypes.Oracles.Witnet) {\r\n            return _info.oracle.sources;\r\n        } else {\r\n            return bytes32(0);\r\n        }\r\n    }\r\n\r\n    function lookupWitnetRetrievals(bytes4 feedId)\r\n        external view\r\n        returns (Witnet.RadonRetrieval[] memory _void)\r\n    {\r\n        IWitPriceFeeds.Info memory _info = surrogate.lookupPriceFeed(IWitPriceFeedsTypes.ID4.wrap(feedId));\r\n        if (_info.oracle.class == IWitPriceFeedsTypes.Oracles.Witnet) {\r\n            Witnet.RadonHash _radHash = Witnet.RadonHash.wrap(_info.oracle.sources);\r\n            return registry.lookupRadonRequestRetrievals(_radHash);\r\n        } else {\r\n            return new Witnet.RadonRetrieval[](0);\r\n        }\r\n    }\r\n\r\n    function requestUpdate(bytes4)\r\n        external payable\r\n        returns (uint256)\r\n    {\r\n        _revertBypass();\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitFeedsLegacy -------------------------------------------------------------------------------------------\r\n    \r\n    function defaultRadonSLA() \r\n        external view \r\n        returns (IWitPriceFeedsLegacy.RadonSLAv1 memory)\r\n    {\r\n        IWitPriceFeeds.UpdateConditions memory _conditions = surrogate.defaultUpdateConditions();\r\n        uint8 _numWitnesses = uint8(_conditions.minWitnesses);\r\n        uint64 _unitaryReward = 2 * 10 ** 8; // 0.2 WIT\r\n        return IWitPriceFeedsLegacy.RadonSLAv1({\r\n            numWitnesses: _numWitnesses,\r\n            minConsensusPercentage: 51,\r\n            witnessReward: _unitaryReward,\r\n            witnessCollateral: _unitaryReward * _numWitnesses,\r\n            minerCommitRevealFee: _unitaryReward / _numWitnesses\r\n        });\r\n    }\r\n\r\n    function latestUpdateResponse(bytes4) \r\n        external view \r\n        returns (Witnet.QueryResponse memory)\r\n    {\r\n        _revertBypass();\r\n    }\r\n\r\n    function latestUpdateResponseStatus(bytes4)\r\n        external view\r\n        returns (IWitOracleLegacy.QueryResponseStatus)\r\n    {\r\n        _revertBypass();\r\n    }\r\n\r\n    function latestUpdateResultError(bytes4)\r\n        external view \r\n        returns (IWitOracleLegacy.ResultError memory)\r\n    {\r\n        _revertBypass();\r\n    }\r\n    \r\n    function requestUpdate(bytes4, IWitPriceFeedsLegacy.RadonSLAv2 calldata)\r\n        external payable\r\n        returns (uint256)\r\n    {\r\n        _revertBypass();\r\n    }\r\n\r\n    function witnet()\r\n        external view \r\n        returns (address)\r\n    {\r\n        return IWitOracleAppliance(address(surrogate)).witOracle();\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements 'IWitPriceFeedsLegacyAdmin' -----------------------------------------------------------------------------\r\n\r\n    function owner()\r\n        virtual override\r\n        public view \r\n        returns (address)\r\n    {\r\n        return Ownable.owner();\r\n    }\r\n    \r\n    function acceptOwnership()\r\n        virtual override \r\n        public\r\n    {\r\n        Ownable2Step.acceptOwnership();\r\n    }\r\n\r\n    function baseFeeOverheadPercentage() external view returns (uint16) {\r\n        _revertBypass();\r\n    }\r\n\r\n\r\n    function pendingOwner() \r\n        virtual override \r\n        public view\r\n        returns (address)\r\n    {\r\n        return Ownable2Step.pendingOwner();\r\n    }\r\n    \r\n    function transferOwnership(address _newOwner)\r\n        virtual override \r\n        public \r\n        onlyOwner\r\n    {\r\n        Ownable.transferOwnership(_newOwner);\r\n    }\r\n\r\n    function deleteFeed(string calldata) external view {\r\n        _revertBypass();\r\n    }\r\n\r\n    function deleteFeeds() external view {\r\n        _revertBypass();\r\n    }\r\n\r\n    function settleBaseFeeOverheadPercentage(uint16) external view {\r\n        _revertBypass();\r\n    }\r\n\r\n    function settleDefaultRadonSLA(IWitPriceFeedsLegacy.RadonSLAv2 calldata) external view {\r\n        _revertBypass();\r\n    }\r\n    \r\n    function settleFeedRequest(string calldata, bytes32) external view {\r\n        _revertBypass();\r\n    }\r\n\r\n    function settleFeedRequest(string calldata, IWitOracleRequest) external view {\r\n        _revertBypass();\r\n    }\r\n\r\n    function settleFeedRequest(string calldata, IWitOracleRequestTemplate, string[][] calldata) external view {\r\n        _revertBypass();\r\n    }\r\n\r\n    function settleFeedSolver(string calldata, address, string[] calldata) external view {\r\n        _revertBypass();\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements 'IWitPriceFeeds' -----------------------------------------------------------------------------\r\n\r\n    function lookupDecimals(bytes4 feedId) \r\n        external view\r\n        returns (uint8)\r\n    {\r\n        int8 _exponent = surrogate.lookupPriceFeedExponent(IWitPriceFeedsTypes.ID4.wrap(feedId));\r\n        _require(_exponent <= 0, \"uncompliant exponent\");\r\n        return uint8(-_exponent);\r\n    }\r\n    \r\n    function lookupPriceSolver(bytes4 feedId)\r\n        external view\r\n        returns (address _solverAddress, string[] memory _solverDeps)\r\n    {\r\n        IWitPriceFeeds.Info memory _info = surrogate.lookupPriceFeed(IWitPriceFeedsTypes.ID4.wrap(feedId));\r\n        if (_info.mapper.class != IWitPriceFeedsTypes.Mappers.None) {\r\n            _solverAddress = address(surrogate);\r\n            _solverDeps = _info.mapper.deps;\r\n        }\r\n    }\r\n\r\n    function latestPrice(bytes4 feedId)\r\n        public view\r\n        returns (IWitPriceFeedsLegacySolver.Price memory)\r\n    {\r\n        IWitPriceFeedsTypes.ID4 _v3Id = (\r\n            IWitPriceFeedsTypes.ID4.unwrap(__bypass().v3Ids[feedId]) != bytes4(0) \r\n                ? __bypass().v3Ids[feedId]\r\n                : IWitPriceFeedsTypes.ID4.wrap(feedId)\r\n        );\r\n        IWitPriceFeeds.Price memory _lastUpdate = surrogate.getPriceUnsafe(_v3Id);\r\n        return IWitPriceFeedsLegacySolver.Price({\r\n            value: _lastUpdate.price,\r\n            timestamp: _lastUpdate.timestamp,\r\n            drTxHash: _lastUpdate.trail,\r\n            latestStatus: IWitPriceFeedsLegacySolver.LatestUpdateStatus.Ready\r\n        });\r\n    }\r\n\r\n    function latestPrices(bytes4[] calldata feedIds)\r\n        external view\r\n        returns (IWitPriceFeedsLegacySolver.Price[] memory _prices)\r\n    {\r\n        _prices = new IWitPriceFeedsLegacySolver.Price[](feedIds.length);\r\n        for (uint _ix = 0; _ix < feedIds.length; _ix ++) {\r\n            _prices[_ix] = latestPrice(feedIds[_ix]);\r\n        }\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements 'IERC2362' --------------------------------------------------------------------------------------\r\n    \r\n    function valueFor(bytes32 feedId)\r\n        external view\r\n        returns (int256, uint256, uint256)\r\n    {\r\n        bytes4 _v2Id = bytes4(feedId);\r\n        IWitPriceFeedsTypes.ID4 _v3Id = (\r\n            IWitPriceFeedsTypes.ID4.unwrap(__bypass().v3Ids[_v2Id]) != bytes4(0) \r\n                ? __bypass().v3Ids[_v2Id]\r\n                : IWitPriceFeedsTypes.ID4.wrap(_v2Id)\r\n        );\r\n        IWitPriceFeeds.Price memory _lastUpdate = surrogate.getPriceUnsafe(_v3Id);\r\n        uint256 _timestamp = uint(Witnet.Timestamp.unwrap(_lastUpdate.timestamp));\r\n        return (\r\n            int(int64(_lastUpdate.price)),\r\n            _timestamp,\r\n            _timestamp == 0 ? 404 : 200\r\n        );\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Internal methods -------------------------------------------------------------------------------------------\r\n\r\n    function _require(bool _condition, string memory _reason) internal pure {\r\n        if (_condition) {\r\n            _revert(_reason);\r\n        }\r\n    }\r\n\r\n    function _revert(string memory _reason) internal pure {\r\n        revert(string(abi.encodePacked(\r\n            class(),\r\n            \": \",\r\n            _reason\r\n        )));\r\n    }\r\n\r\n    function _revertBypass() internal view {\r\n        _revert(\r\n            string(\r\n                abi.encodePacked(\r\n                    \"bypassed to \", \r\n                    IWitOracleAppliance(address(surrogate)).class()\r\n                )\r\n            )\r\n        );\r\n    }\r\n\r\n    bytes32 private constant _BYPASS_V2_V3_STORAGE_SLOT =    \r\n        /* keccak256(\"io.witnet.feeds.bypass\") & ~bytes32(uint256(0xff) */\r\n        0xc5354469a5d32189a18f5e79f9508d828fa089087c317bc89792b1c8dba53900;\r\n\r\n    function __bypass() internal pure returns (BypassV2V3 storage _ptr) {\r\n        assembly {\r\n            _ptr.slot := _BYPASS_V2_V3_STORAGE_SLOT       \r\n        }\r\n    }\r\n\r\n    function __legacy() internal pure returns (WitPriceFeedsLegacyDataLib.Storage storage _ptr) {\r\n        return WitPriceFeedsLegacyDataLib.data();\r\n    }\r\n\r\n}\r\n"
      },
      "project/contracts/apps/WitPriceFeedsLegacyUpgradable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../WitPriceFeedsLegacy.sol\";\r\n\r\nimport \"../core/WitnetUpgradableBase.sol\";\r\nimport \"../data/WitPriceFeedsLegacyDataLib.sol\";\r\nimport \"../interfaces/legacy/IWitOracleLegacy.sol\";\r\nimport \"../patterns/Ownable2Step.sol\";\r\n\r\n/// @title WitPriceFeeds: Price Feeds upgradable repository reliant on the Wit/Oracle blockchain.\r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\n\r\ncontract WitPriceFeedsLegacyUpgradable\r\n    is\r\n        WitPriceFeedsLegacy,\r\n        Ownable2Step,\r\n        WitnetUpgradableBase\r\n{\r\n    using Witnet for bytes;\r\n    using Witnet for Witnet.DataResult;\r\n    using Witnet for Witnet.QueryResponse;\r\n    using Witnet for Witnet.QuerySLA;\r\n    using Witnet for Witnet.ResultStatus;\r\n\r\n    function class() virtual override public view returns (string memory) {\r\n        return type(WitPriceFeedsLegacyUpgradable).name;\r\n    }\r\n\r\n    address immutable public override witOracle;\r\n    IWitOracleRadonRegistry immutable internal __registry;\r\n\r\n    Witnet.QuerySLA private __defaultQuerySLA;\r\n    uint16 private __baseFeeOverheadPercentage;\r\n    \r\n    constructor(\r\n            WitOracle _witOracle,\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        Ownable(address(msg.sender))\r\n        WitnetUpgradableBase(\r\n            _upgradable,\r\n            _versionTag,\r\n            \"io.witnet.proxiable.feeds.price\"\r\n        )\r\n    {\r\n        _require(\r\n            address(_witOracle).code.length > 0,\r\n            \"inexistent oracle\"\r\n        );\r\n        _require(\r\n            _witOracle.specs() == (\r\n                type(IWitOracle).interfaceId\r\n                    ^ type(IWitOracleQueriable).interfaceId\r\n            ), \"uncompliant oracle\"\r\n        );\r\n        witOracle = address(_witOracle);\r\n    }\r\n\r\n    function _registry() virtual internal view returns (IWitOracleRadonRegistry) {\r\n        return IWitOracle(witOracle).registry();\r\n    }\r\n\r\n    // solhint-disable-next-line payable-fallback\r\n    fallback() override external {\r\n        if (\r\n            msg.sig == IWitPriceFeedsLegacySolver.solve.selector\r\n                && msg.sender == address(this)\r\n        ) {\r\n            address _solver = WitPriceFeedsLegacyDataLib.seekRecord(bytes4(bytes8(msg.data) << 32)).solver;\r\n            _require(\r\n                _solver != address(0),\r\n                \"unsettled solver\"\r\n            );\r\n            assembly {\r\n                let ptr := mload(0x40)\r\n                calldatacopy(ptr, 0, calldatasize())\r\n                let result := delegatecall(gas(), _solver, ptr, calldatasize(), 0, 0)\r\n                let size := returndatasize()\r\n                returndatacopy(ptr, 0, size)\r\n                switch result\r\n                    case 0 { revert(ptr, size) }\r\n                    default { return(ptr, size) }\r\n            }\r\n        } else {\r\n            _revert(\"not implemented\");\r\n        }\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'Upgradeable' ------------------------------------------------------------------------------------\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    function __initializeUpgradableData(bytes memory _initData) virtual override internal {\r\n        if (__proxiable().codehash == bytes32(0)) {\r\n            __defaultQuerySLA = Witnet.QuerySLA({\r\n                witCommitteeSize: 3,\r\n                witUnitaryReward: 200_000_000, \r\n                witResultMaxSize: 16\r\n            });\r\n            // settle default base fee overhead percentage\r\n            __baseFeeOverheadPercentage = 10;\r\n        \r\n        } else {\r\n            // otherwise, store beacon read from _initData, if any\r\n            if (_initData.length > 0) {\r\n                (uint16 _baseFeeOverheadPercentage, Witnet.QuerySLA memory _defaultQuerySLA) = abi.decode(\r\n                    _initData, (uint16, Witnet.QuerySLA)\r\n                );\r\n                __baseFeeOverheadPercentage = _baseFeeOverheadPercentage;\r\n                __defaultQuerySLA = _defaultQuerySLA;\r\n            \r\n            } else if (!__defaultQuerySLA.isValid()) {\r\n                // possibly, an upgrade from a previous branch took place:\r\n                __defaultQuerySLA = Witnet.QuerySLA({\r\n                    witCommitteeSize: 3,\r\n                    witUnitaryReward: 200_000_000, \r\n                    witResultMaxSize: 16\r\n                });\r\n            }\r\n        }\r\n    }\r\n\r\n    /// Tells whether provided address could eventually upgrade the contract.\r\n    function isUpgradableFrom(address _from) external view override returns (bool) {\r\n        address _owner = owner();\r\n        return (\r\n            // false if the WRB is intrinsically not upgradable, or `_from` is no owner\r\n            isUpgradable()\r\n                && _owner == _from\r\n        );\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements 'IWitFeeds' -------------------------------------------------------------------------------------\r\n\r\n    function estimateUpdateBaseFee(uint256 _evmGasPrice) virtual override public view returns (uint256) {\r\n        return _estimateUpdateRequestFee(_evmGasPrice);\r\n    }\r\n    \r\n    function _estimateUpdateRequestFee(uint256 _evmGasPrice) internal view returns (uint) {\r\n        return (\r\n            IWitOracleQueriable(witOracle).estimateBaseFee(_evmGasPrice)\r\n                * (100 + __baseFeeOverheadPercentage)\r\n        ) / 100; \r\n    }\r\n    \r\n    /// @notice Returns unique hash determined by the combination of data sources being used\r\n    /// @notice on non-routed price feeds, and dependencies of routed price feeds.\r\n    /// @dev Ergo, `footprint()` changes if any data source is modified, or the dependecy tree\r\n    /// @dev on any routed price feed is altered.\r\n    function footprint() \r\n        virtual override\r\n        public view\r\n        returns (bytes4 _footprint)\r\n    {\r\n        if (__storage().ids.length > 0) {\r\n            _footprint = _footprintOf(__storage().ids[0]);\r\n            for (uint _ix = 1; _ix < __storage().ids.length; _ix ++) {\r\n                _footprint ^= _footprintOf(__storage().ids[_ix]);\r\n            }\r\n        }\r\n    }\r\n\r\n    function hash(string memory caption)\r\n        virtual override\r\n        public pure\r\n        returns (bytes4)\r\n    {\r\n        return WitPriceFeedsLegacyDataLib.hash(caption);\r\n    }\r\n\r\n    function lookupCaption(bytes4 feedId)\r\n        override\r\n        public view\r\n        returns (string memory)\r\n    {\r\n        return WitPriceFeedsLegacyDataLib.seekRecord(feedId).caption;\r\n    }\r\n\r\n    function supportedFeeds()\r\n        virtual override\r\n        external view\r\n        returns (bytes4[] memory _ids, string[] memory _captions, bytes32[] memory _solvers)\r\n    {\r\n        return WitPriceFeedsLegacyDataLib.supportedFeeds();\r\n    }\r\n    \r\n    function supportsCaption(string calldata caption)\r\n        virtual override\r\n        external view\r\n        returns (bool)\r\n    {\r\n        bytes4 feedId = hash(caption);\r\n        return hash(WitPriceFeedsLegacyDataLib.seekRecord(feedId).caption) == feedId;\r\n    }\r\n    \r\n    function totalFeeds() \r\n        override \r\n        external view\r\n        returns (uint256)\r\n    {\r\n        return __storage().ids.length;\r\n    }\r\n\r\n    function lastValidQueryId(bytes4 feedId)\r\n        override public view\r\n        returns (uint256)\r\n    {\r\n        return WitPriceFeedsLegacyDataLib.lastValidQueryId(IWitOracleQueriable(witOracle), feedId);\r\n    }\r\n\r\n    function lastValidQueryResponse(bytes4 feedId)\r\n        override public view\r\n        returns (Witnet.QueryResponse memory)\r\n    {\r\n        return IWitOracleQueriable(witOracle).getQueryResponse(Witnet.QueryId.wrap(uint64(\r\n            WitPriceFeedsLegacyDataLib.lastValidQueryId(IWitOracleQueriable(witOracle), feedId)\r\n        )));\r\n    }\r\n\r\n    function latestUpdateQueryId(bytes4 feedId)\r\n        override public view\r\n        returns (uint256)\r\n    {\r\n        return WitPriceFeedsLegacyDataLib.seekRecord(feedId).latestUpdateQueryId;\r\n    }\r\n\r\n    function latestUpdateQueryRequest(bytes4 feedId)\r\n        override external view \r\n        returns (Witnet.QueryRequest memory)\r\n    {\r\n        return IWitOracleQueriable(witOracle).getQueryRequest(Witnet.QueryId.wrap(uint64(\r\n            latestUpdateQueryId(feedId)\r\n        )));\r\n    }\r\n\r\n    function lookupWitnetBytecode(bytes4 feedId)\r\n        override public view\r\n        returns (bytes memory)\r\n    {\r\n        WitPriceFeedsLegacyDataLib.Record storage __record = WitPriceFeedsLegacyDataLib.seekRecord(feedId);\r\n        _require(\r\n            __record.radHash != 0,\r\n            \"no RAD hash\"\r\n        );\r\n        return _registry().lookupRadonRequestBytecode(Witnet.RadonHash.wrap(__record.radHash));\r\n    }\r\n\r\n    function lookupWitnetRadHash(bytes4 feedId)\r\n        override public view\r\n        returns (bytes32)\r\n    {\r\n        return WitPriceFeedsLegacyDataLib.seekRecord(feedId).radHash;\r\n    }\r\n\r\n    function lookupWitnetRetrievals(bytes4 feedId)\r\n        override external view\r\n        returns (Witnet.RadonRetrieval[] memory _retrievals)\r\n    {\r\n        return _registry().lookupRadonRequestRetrievals(\r\n            Witnet.RadonHash.wrap(lookupWitnetRadHash(feedId))\r\n        );\r\n    }\r\n\r\n    function requestUpdate(bytes4 feedId)\r\n        external payable\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return __requestUpdate(feedId, __defaultQuerySLA);\r\n    }\r\n    \r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitFeedsLegacy -------------------------------------------------------------------------------------------\r\n    \r\n    function defaultRadonSLA() override external view returns (IWitPriceFeedsLegacy.RadonSLAv1 memory) {\r\n        uint8 _numWitnesses = uint8(__defaultQuerySLA.witCommitteeSize);\r\n        uint64 _unitaryReward = __defaultQuerySLA.witUnitaryReward;\r\n        return IWitPriceFeedsLegacy.RadonSLAv1({\r\n            numWitnesses: _numWitnesses,\r\n            minConsensusPercentage: 51,\r\n            witnessReward: _unitaryReward,\r\n            witnessCollateral: _unitaryReward * _numWitnesses,\r\n            minerCommitRevealFee: _unitaryReward / _numWitnesses\r\n        });\r\n    }\r\n\r\n    function latestUpdateResponse(bytes4 feedId) \r\n        override external view \r\n        returns (Witnet.QueryResponse memory)\r\n    {\r\n        return IWitOracleQueriable(witOracle).getQueryResponse(Witnet.QueryId.wrap(uint64(\r\n            latestUpdateQueryId(feedId)\r\n        )));\r\n    }\r\n\r\n    function latestUpdateResponseStatus(bytes4 feedId)\r\n        override public view\r\n        returns (IWitOracleLegacy.QueryResponseStatus)\r\n    {\r\n        return IWitOracleLegacy(witOracle).getQueryResponseStatus(latestUpdateQueryId(feedId));\r\n    }\r\n\r\n    function latestUpdateResultError(bytes4 feedId)\r\n        override external view \r\n        returns (IWitOracleLegacy.ResultError memory)\r\n    {\r\n        return IWitOracleLegacy(witOracle).getQueryResultError(latestUpdateQueryId(feedId));\r\n    }\r\n    \r\n    function requestUpdate(bytes4 feedId, IWitPriceFeedsLegacy.RadonSLAv2 calldata legacySLA)\r\n        external payable\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return __requestUpdate(feedId, _intoQuerySLA(legacySLA));\r\n    }\r\n\r\n    function witnet() virtual override external view returns (address) {\r\n        return address(witOracle);\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements 'IWitPriceFeedsLegacyAdmin' -----------------------------------------------------------------------------\r\n\r\n    function owner()\r\n        virtual override (IWitPriceFeedsLegacyAdmin, Ownable)\r\n        public view \r\n        returns (address)\r\n    {\r\n        return Ownable.owner();\r\n    }\r\n    \r\n    function acceptOwnership()\r\n        virtual override (IWitPriceFeedsLegacyAdmin, Ownable2Step)\r\n        public\r\n    {\r\n        Ownable2Step.acceptOwnership();\r\n    }\r\n\r\n    function baseFeeOverheadPercentage()\r\n        virtual override\r\n        external view\r\n        returns (uint16)\r\n    {\r\n        return __baseFeeOverheadPercentage;\r\n    }\r\n\r\n    function pendingOwner() \r\n        virtual override (IWitPriceFeedsLegacyAdmin, Ownable2Step)\r\n        public view\r\n        returns (address)\r\n    {\r\n        return Ownable2Step.pendingOwner();\r\n    }\r\n    \r\n    function transferOwnership(address _newOwner)\r\n        virtual override (IWitPriceFeedsLegacyAdmin, Ownable2Step)\r\n        public \r\n        onlyOwner\r\n    {\r\n        Ownable.transferOwnership(_newOwner);\r\n    }\r\n\r\n    function deleteFeed(string calldata caption) virtual override external onlyOwner {\r\n        try WitPriceFeedsLegacyDataLib.deleteFeed(caption) {\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n\r\n        } catch (bytes memory) {\r\n            _revertWitPriceFeedsLegacyDataLibUnhandledException();\r\n        }\r\n    }\r\n\r\n    function deleteFeeds() virtual override external onlyOwner {\r\n        try WitPriceFeedsLegacyDataLib.deleteFeeds() {\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n\r\n        } catch (bytes memory) {\r\n            _revertWitPriceFeedsLegacyDataLibUnhandledException();\r\n        }\r\n    }\r\n\r\n    function settleBaseFeeOverheadPercentage(uint16 _baseFeeOverheadPercentage)\r\n        virtual override\r\n        external\r\n        onlyOwner \r\n    {\r\n        __baseFeeOverheadPercentage = _baseFeeOverheadPercentage;\r\n    }\r\n\r\n    function settleDefaultRadonSLA(RadonSLAv2 calldata radonSLAv2)\r\n        override public\r\n        onlyOwner\r\n    {\r\n        __defaultQuerySLA.witCommitteeSize = radonSLAv2.numWitnesses;\r\n        __defaultQuerySLA.witUnitaryReward = radonSLAv2.unitaryReward;\r\n        _require(\r\n            __defaultQuerySLA.isValid(), \r\n            \"invalid update SLA\"\r\n        );\r\n    }\r\n    \r\n    function settleFeedRequest(string calldata caption, bytes32 radHash)\r\n        override public\r\n        onlyOwner\r\n    {\r\n        _require(\r\n            _registry().lookupRadonRequestResultDataType(Witnet.RadonHash.wrap(radHash)) == dataType,\r\n            \"bad result data type\"\r\n        );\r\n        try WitPriceFeedsLegacyDataLib.settleFeedRequest(caption, radHash) {\r\n\r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            _revertWitPriceFeedsLegacyDataLibUnhandledException();\r\n        }\r\n    }\r\n\r\n    function settleFeedRequest(string calldata caption, IWitOracleRequest request)\r\n        override external\r\n        onlyOwner\r\n    {\r\n        settleFeedRequest(caption, Witnet.RadonHash.unwrap(request.radHash()));\r\n    }\r\n\r\n    function settleFeedRequest(\r\n            string calldata caption,\r\n            IWitOracleRequestTemplate template,\r\n            string[][] calldata args\r\n        )\r\n        override external\r\n        onlyOwner\r\n    {\r\n        settleFeedRequest(caption, Witnet.RadonHash.unwrap(template.verifyRadonRequest(args)));\r\n    }\r\n\r\n    function settleFeedSolver(\r\n            string calldata caption,\r\n            address solver,\r\n            string[] calldata deps\r\n        )\r\n        override external\r\n        onlyOwner\r\n    {\r\n        _require(\r\n            bytes6(bytes(caption)) == bytes6(__prefix),\r\n            \"bad caption prefix\"\r\n        );\r\n        _require(\r\n            solver != address(0),\r\n            \"no solver address\"\r\n        );\r\n        try WitPriceFeedsLegacyDataLib.settleFeedSolver(caption, solver, deps) {\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            _revertWitPriceFeedsLegacyDataLibUnhandledException();\r\n        }\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements 'IWitPriceFeeds' -----------------------------------------------------------------------------\r\n\r\n    function lookupDecimals(bytes4 feedId) \r\n        override \r\n        external view\r\n        returns (uint8)\r\n    {\r\n        return WitPriceFeedsLegacyDataLib.seekRecord(feedId).decimals;\r\n    }\r\n    \r\n    function lookupPriceSolver(bytes4 feedId)\r\n        override\r\n        external view\r\n        returns (address _solverAddress, string[] memory _solverDeps)\r\n    {\r\n        return WitPriceFeedsLegacyDataLib.seekPriceSolver(feedId);\r\n    }\r\n\r\n    function latestPrice(bytes4 feedId)\r\n        virtual override\r\n        public view\r\n        returns (IWitPriceFeedsLegacySolver.Price memory)\r\n    {\r\n        try WitPriceFeedsLegacyDataLib.latestPrice(\r\n            IWitOracleQueriable(witOracle), \r\n            feedId\r\n        ) returns (IWitPriceFeedsLegacySolver.Price memory _latestPrice) {\r\n            return _latestPrice;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            _revertWitPriceFeedsLegacyDataLibUnhandledException();\r\n        }\r\n    }\r\n\r\n    function latestPrices(bytes4[] calldata feedIds)\r\n        virtual override\r\n        external view\r\n        returns (IWitPriceFeedsLegacySolver.Price[] memory _prices)\r\n    {\r\n        _prices = new IWitPriceFeedsLegacySolver.Price[](feedIds.length);\r\n        for (uint _ix = 0; _ix < feedIds.length; _ix ++) {\r\n            _prices[_ix] = latestPrice(feedIds[_ix]);\r\n        }\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements 'IWitPriceFeedsLegacySolverFactory' ---------------------------------------------------------------------\r\n\r\n    function deployPriceSolver(bytes calldata initcode, bytes calldata constructorParams)\r\n        virtual override external\r\n        onlyOwner\r\n        returns (address)\r\n    {\r\n        try WitPriceFeedsLegacyDataLib.deployPriceSolver(\r\n            initcode, \r\n            constructorParams\r\n        ) returns (\r\n            address _solver\r\n        ) {\r\n            emit NewPriceFeedsSolver(\r\n                _solver, \r\n                _solver.codehash, \r\n                constructorParams\r\n            );\r\n            return _solver;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n\r\n        } catch (bytes memory) {\r\n            _revertWitPriceFeedsLegacyDataLibUnhandledException();\r\n        }\r\n    }\r\n\r\n    function determinePriceSolverAddress(bytes calldata initcode, bytes calldata constructorParams)\r\n        virtual override public view\r\n        returns (address _address)\r\n    {\r\n        return WitPriceFeedsLegacyDataLib.determinePriceSolverAddress(initcode, constructorParams);\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements 'IERC2362' --------------------------------------------------------------------------------------\r\n    \r\n    function valueFor(bytes32 feedId)\r\n        virtual override\r\n        external view\r\n        returns (int256 _value, uint256 _timestamp, uint256 _status)\r\n    {\r\n        IWitPriceFeedsLegacySolver.Price memory _latestPrice = latestPrice(bytes4(feedId));\r\n        return (\r\n            int(uint(_latestPrice.value)),\r\n            Witnet.Timestamp.unwrap(_latestPrice.timestamp),\r\n            (_latestPrice.latestStatus == IWitPriceFeedsLegacySolver.LatestUpdateStatus.Ready\r\n                ? 200\r\n                : (_latestPrice.latestStatus == IWitPriceFeedsLegacySolver.LatestUpdateStatus.Awaiting\r\n                    ? 404 \r\n                    : 400\r\n                )\r\n            )\r\n        );\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Internal methods -------------------------------------------------------------------------------------------\r\n\r\n    function _footprintOf(bytes4 _id4) virtual internal view returns (bytes4) {\r\n        if (WitPriceFeedsLegacyDataLib.seekRecord(_id4).radHash != bytes32(0)) {\r\n            return bytes4(keccak256(abi.encode(_id4, WitPriceFeedsLegacyDataLib.seekRecord(_id4).radHash)));\r\n        } else {\r\n            return bytes4(keccak256(abi.encode(_id4, WitPriceFeedsLegacyDataLib.seekRecord(_id4).solverDepsFlag)));\r\n        }\r\n    }\r\n\r\n    function _intoQuerySLA(IWitPriceFeedsLegacy.RadonSLAv2 memory _updateSLA) internal view returns (Witnet.QuerySLA memory) {\r\n        if (\r\n            _updateSLA.numWitnesses >= __defaultQuerySLA.witCommitteeSize\r\n                && _updateSLA.unitaryReward >= __defaultQuerySLA.witUnitaryReward\r\n        ) {\r\n            return Witnet.QuerySLA({\r\n                witCommitteeSize: _updateSLA.numWitnesses,\r\n                witUnitaryReward: _updateSLA.unitaryReward,\r\n                witResultMaxSize: __defaultQuerySLA.witResultMaxSize\r\n            });\r\n        \r\n        } else {\r\n            _revert(\"unsecure update request\");\r\n        }\r\n    }\r\n\r\n    function _validateCaption(string calldata caption)\r\n        internal view returns (uint8)\r\n    {\r\n        _require(\r\n            bytes6(bytes(caption)) == bytes6(__prefix),\r\n            \"bad caption prefix\"\r\n        );\r\n        try WitPriceFeedsLegacyDataLib.validateCaption(caption) returns (uint8 _decimals) {\r\n            return _decimals;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n\r\n        } catch (bytes memory) {\r\n            _revertWitPriceFeedsLegacyDataLibUnhandledException();\r\n        }\r\n    }\r\n\r\n    function _revertWitPriceFeedsLegacyDataLibUnhandledException() internal view {\r\n        _revert(_revertWitPriceFeedsLegacyDataLibUnhandledExceptionReason());\r\n    }\r\n\r\n    function _revertWitPriceFeedsLegacyDataLibUnhandledExceptionReason() internal pure returns (string memory) {\r\n        return string(abi.encodePacked(\r\n            type(WitPriceFeedsLegacyDataLib).name,\r\n            \": unhandled assertion\"\r\n        ));\r\n    }\r\n\r\n    function __requestUpdate(bytes4[] memory _deps, IWitPriceFeedsLegacy.RadonSLAv2 memory sla)\r\n        virtual internal\r\n        returns (uint256 _evmUsedFunds)\r\n    {\r\n        uint _evmUnitaryUpdateRequestFee = msg.value / _deps.length;\r\n        for (uint _ix = 0; _ix < _deps.length; _ix ++) {\r\n            _evmUsedFunds += this.requestUpdate{\r\n                value: _evmUnitaryUpdateRequestFee\r\n            }(\r\n                _deps[_ix], \r\n                sla\r\n            );\r\n        }\r\n    }\r\n\r\n    function __requestUpdate(\r\n            bytes4 feedId, \r\n            Witnet.QuerySLA memory querySLA\r\n        )\r\n        virtual internal\r\n        returns (uint256)\r\n    {\r\n        if (WitPriceFeedsLegacyDataLib.seekRecord(feedId).radHash != 0) {\r\n            uint256 _evmUpdateRequestFee = msg.value;\r\n            try WitPriceFeedsLegacyDataLib.requestUpdate(\r\n                IWitOracleQueriable(witOracle),\r\n                feedId,\r\n                querySLA,\r\n                _evmUpdateRequestFee\r\n            \r\n            ) returns (\r\n                uint256 _latestQueryId,\r\n                uint256 _evmUsedFunds\r\n            \r\n            ) {\r\n                if (_evmUsedFunds < msg.value) {\r\n                    // transfer back unused funds:\r\n                    payable(msg.sender).transfer(msg.value - _evmUsedFunds);\r\n                }\r\n                // solhint-disable avoid-tx-origin:\r\n                emit PullingUpdate(tx.origin, _msgSender(), feedId, _latestQueryId);\r\n                return _evmUsedFunds;\r\n            \r\n            } catch Error(string memory _reason) {\r\n                _revert(_reason);\r\n\r\n            } catch (bytes memory) {\r\n                _revertWitPriceFeedsLegacyDataLibUnhandledException();\r\n            }\r\n        \r\n        } else if (WitPriceFeedsLegacyDataLib.seekRecord(feedId).solver != address(0)) {\r\n            return __requestUpdate(\r\n                WitPriceFeedsLegacyDataLib.depsOf(feedId),\r\n                IWitPriceFeedsLegacy.RadonSLAv2({\r\n                    numWitnesses: uint8(querySLA.witCommitteeSize),\r\n                    unitaryReward: querySLA.witUnitaryReward\r\n                })\r\n            );\r\n\r\n        } else {\r\n            _revert(\"unknown feed\");\r\n        }\r\n    }\r\n\r\n    function __storage() internal pure returns (WitPriceFeedsLegacyDataLib.Storage storage) {\r\n        return WitPriceFeedsLegacyDataLib.data();\r\n    }\r\n}\r\n"
      },
      "project/contracts/apps/WitPriceFeedsUpgradableV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {WitPriceFeedsV3} from \"./WitPriceFeedsV3.sol\";\r\nimport {Upgradeable} from \"../patterns/Upgradeable.sol\";\r\n\r\n/// @title WitPriceFeedsUpgradableV3: On-demand Price Feeds registry for EVM-compatible L1/L2 chains, \r\n/// natively powered by the Wit/Oracle blockchain, but yet capable of aggregating price \r\n/// updates from other on-chain price-feed oracles too, if required.\r\n/// \r\n/// Price feeds purely relying on the Wit/Oracle present some advantanges, though:\r\n/// - Anyone can permissionless pull and report price updates on-chain.\r\n/// - Updating the price requires paying no extra \"update fees\".\r\n/// - Prices can be extracted from independent and highly reputed exchanges and data providers.\r\n/// - Actual data sources for each price feed can be introspected on-chain.\r\n/// - Data source traceability in the Wit/Oracle blockchain is possible for every single price update.\r\n///\r\n/// Instances of this contract may also provide support for \"routed price feeds\" (computed as the \r\n/// product or mean average of up to other 8 different price feeds), as well as \"cascade price feeds\" \r\n/// (where multiple oracles could be used as backup when preferred ones don't manage to provide \r\n/// fresh enough updates for whatever reason).\r\n///\r\n/// Also, this contract allows simple plug-and-play integration from \r\n/// smart contracts, dapps and DeFi projects currently adapted to operate with\r\n/// other price feed solutions, like Chainlink, or Pyth. \r\n///\r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\n\r\ncontract WitPriceFeedsUpgradableV3\r\n    is\r\n        Upgradeable,\r\n        WitPriceFeedsV3\r\n{\r\n    bytes32 internal immutable __VERSION;\r\n\r\n    function class() virtual override public pure returns (string memory) {\r\n        return type(WitPriceFeedsUpgradableV3).name;\r\n    }\r\n\r\n    constructor(\r\n            address _witOracle,\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        Upgradeable(_upgradable)\r\n        WitPriceFeedsV3(_witOracle, msg.sender)\r\n    {\r\n        __VERSION = _versionTag;\r\n        proxiableUUID = keccak256(bytes(\"io.witnet.pricefeeds.v3\"));\r\n    }\r\n\r\n    /// @dev Reverts if proxy delegatecalls to unexistent method.\r\n    /* solhint-disable no-complex-fallback */\r\n    fallback() virtual external { \r\n        _revert(\"unsupported method\");\r\n    }\r\n\r\n    /// ===============================================================================================================\r\n    /// --- Clonable --------------------------------------------------------------------------------------------------\r\n\r\n    function base() \r\n        virtual override (WitPriceFeedsV3, Upgradeable)\r\n        public view \r\n        returns (address)\r\n    {\r\n        return __SELF;\r\n    }\r\n\r\n    function cloned() \r\n        virtual override \r\n        public view \r\n        returns (bool)\r\n    {\r\n        return (\r\n            address(this) != __proxiable().proxy // => not an initialized WitnetProxy\r\n                && address(this) != __SELF       // => a proxy to __SELF\r\n        );\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'Proxiable' --------------------------------------------------------------------------------------\r\n\r\n    /// @dev Gets immutable \"heritage blood line\" (ie. genotype) as a Proxiable, and eventually Upgradeable, contract.\r\n    ///      If implemented as an Upgradeable touch, upgrading this contract to another one with a different \r\n    ///      `proxiableUUID()` value should fail.\r\n    bytes32 public immutable override proxiableUUID;\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Overrides 'Upgradeable' ------------------------------------------------------------------------------------\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    /// @dev Must fail when trying to upgrade to same logic contract more than once.\r\n    function initialize(bytes memory _initData) \r\n        virtual override \r\n        public \r\n    {\r\n        _require(!initialized() || !cloned(), \"not on clones\");\r\n        \r\n        address _owner = owner();\r\n        if (_owner == address(0)) {\r\n            // upon first upgrade, extract decode owner address from _intidata\r\n            (_owner, _initData) = abi.decode(_initData, (address, bytes));\r\n            _transferOwnership(_owner);\r\n        \r\n        } else {\r\n            // only owner can initialize an existing proxy:\r\n            require(msg.sender == _owner, \"not the owner\");\r\n        }\r\n        if (\r\n            __proxiable().codehash != bytes32(0)\r\n                && __proxiable().codehash == codehash()\r\n        ) {\r\n            revert(\"already initialized\");\r\n        }\r\n        if (__proxiable().proxy == address(0)) {\r\n            // a proxy is being initialized for the first time...\r\n            __proxiable().proxy = address(this);   \r\n        }\r\n        __proxiable().codehash = codehash();\r\n        __proxiable().implementation = base();\r\n        __initializeUpgradableData(_initData);\r\n        emit Upgraded(owner(), base(), codehash(), version());\r\n    }\r\n\r\n    /// Tells whether provided address could eventually upgrade the contract.\r\n    function isUpgradableFrom(address _from) \r\n        virtual override\r\n        external view  \r\n        returns (bool)\r\n    {\r\n        return (\r\n            // false if the contract is not upgradable, or `_from` is no owner\r\n            isUpgradable()\r\n                && owner() == _from\r\n        );\r\n    }\r\n\r\n    function version() public view virtual override returns (string memory) {\r\n        return _toString(__VERSION);\r\n    }\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    function __initializeUpgradableData(bytes memory)\r\n        virtual override \r\n        internal\r\n    {\r\n        if (\r\n            __proxiable().codehash == bytes32(0)\r\n                || !_validateUpdateConditions(__storage().defaultUpdateConditions)\r\n        ) {\r\n            __storage().defaultUpdateConditions = UpdateConditions({\r\n                callbackGas: 1_000_000,\r\n                computeEma: false,\r\n                cooldownSecs: 15 minutes,\r\n                heartbeatSecs: 1 days,\r\n                maxDeviation1000: 0, // oo\r\n                minWitnesses: 3\r\n            });\r\n        }\r\n    }\r\n\r\n    \r\n    /// Converts bytes32 into string.\r\n    function _toString(bytes32 _bytes32)\r\n        internal pure\r\n        returns (string memory)\r\n    {\r\n        bytes memory _bytes = new bytes(_toStringLength(_bytes32));\r\n        for (uint _i = 0; _i < _bytes.length;) {\r\n            _bytes[_i] = _bytes32[_i];\r\n            unchecked {\r\n                _i ++;\r\n            }\r\n        }\r\n        return string(_bytes);\r\n    }\r\n\r\n    // Calculate length of string-equivalent to given bytes32.\r\n    function _toStringLength(bytes32 _bytes32)\r\n        internal pure\r\n        returns (uint _length)\r\n    {\r\n        for (; _length < 32; ) {\r\n            if (_bytes32[_length] == 0) {\r\n                break;\r\n            }\r\n            unchecked {\r\n                _length ++;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/apps/WitPriceFeedsV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {\r\n    IWitAppliance,\r\n    IWitOracle,\r\n    IWitOracleAppliance,\r\n    IWitOracleQueriable,\r\n    IWitOracleRadonRegistry,\r\n    Witnet\r\n} from \"../WitOracle.sol\";\r\n\r\nimport {\r\n    IWitPriceFeeds,\r\n    IWitPriceFeedsAdmin,\r\n    IWitPriceFeedsConsumer,\r\n    WitPriceFeeds\r\n} from \"../WitPriceFeeds.sol\";\r\n\r\nimport {WitPriceFeedsDataLib} from \"../data/WitPriceFeedsDataLib.sol\";\r\nimport {WitPythChainlinkAggregator} from \"../mockups/WitPythChainlinkAggregator.sol\";\r\n\r\nimport {Clonable} from \"../patterns/Clonable.sol\";\r\nimport {Ownable, Ownable2Step} from \"../patterns/Ownable2Step.sol\";\r\n\r\n/// @title WitPriceFeedsV3: On-demand Price Feeds registry for EVM-compatible L1/L2 chains, \r\n/// natively powered by the Wit/Oracle blockchain, but yet capable of aggregating price \r\n/// updates from other on-chain price-feed oracles too, if required.\r\n/// \r\n/// Price feeds purely relying on the Wit/Oracle present some advantanges, though:\r\n/// - Anyone can permissionless pull and report price updates on-chain.\r\n/// - Updating the price requires paying no extra \"update fees\".\r\n/// - Prices can be extracted from independent and highly reputed exchanges and data providers.\r\n/// - Actual data sources for each price feed can be introspected on-chain.\r\n/// - Data source traceability in the Wit/Oracle blockchain is possible for every single price update.\r\n///\r\n/// Instances of this contract may also provide support for \"routed price feeds\" (computed as the \r\n/// product or mean average of up to other 8 different price feeds), as well as \"cascade price feeds\" \r\n/// (where multiple oracles could be used as backup when preferred ones don't manage to provide \r\n/// fresh enough updates for whatever reason).\r\n///\r\n/// Also, this contract allows simple plug-and-play integration from \r\n/// smart contracts, dapps and DeFi projects currently adapted to operate with\r\n/// other price feed solutions, like Chainlink, or Pyth. \r\n///\r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\n\r\ncontract WitPriceFeedsV3\r\n    is\r\n        Clonable,\r\n        Ownable2Step,\r\n        WitPriceFeeds\r\n{\r\n    using Witnet for Witnet.DataResult;\r\n    using Witnet for Witnet.RadonHash;\r\n    using Witnet for Witnet.Timestamp;\r\n\r\n    using WitPriceFeedsDataLib for ID4;\r\n    using WitPriceFeedsDataLib for Mappers;\r\n    using WitPriceFeedsDataLib for Oracles;\r\n    using WitPriceFeedsDataLib for UpdateConditions;\r\n    using WitPriceFeedsDataLib for WitPriceFeedsDataLib.PriceFeed;\r\n\r\n    address immutable public override witOracle;\r\n\r\n    function class() virtual override public pure returns (string memory) {\r\n        return type(WitPriceFeedsV3).name;\r\n    }\r\n\r\n    constructor(\r\n            address _witOracle,\r\n            address _operator\r\n        )\r\n        Ownable(_operator != address(0) ? _operator : msg.sender)\r\n    {\r\n        require(\r\n            _witOracle.code.length > 0,\r\n            \"inexistent wit/oracle\"\r\n        );\r\n        bytes4 _witOracleSpecs = IWitAppliance(address(_witOracle)).specs();\r\n        require(\r\n            _witOracleSpecs == type(IWitOracle).interfaceId \r\n                || _witOracleSpecs == type(IWitOracle).interfaceId ^ type(IWitOracleQueriable).interfaceId,\r\n            \"uncompliant wit/oracle\"\r\n        );\r\n        witOracle = _witOracle;\r\n        __storage().defaultUpdateConditions = UpdateConditions({\r\n            callbackGas: 1_000_000,\r\n            computeEma: false,\r\n            cooldownSecs: 15 minutes,\r\n            heartbeatSecs: 1 days,\r\n            maxDeviation1000: 0, // oo\r\n            minWitnesses: 3\r\n        });\r\n    }\r\n\r\n    function initializeClone(\r\n            address _curator, \r\n            UpdateConditions calldata _defaultUpdateConditions\r\n        )\r\n        external\r\n        onlyOnClones\r\n        initializer\r\n        returns (address)\r\n    {\r\n        _require(_curator != address(0), \"zero curator\");\r\n        _transferOwnership(_curator);\r\n        \r\n        _require(_validateUpdateConditions(_defaultUpdateConditions), \"invalid conditions\");\r\n        __storage().defaultUpdateConditions = _defaultUpdateConditions;\r\n\r\n        return address(this);\r\n    }\r\n\r\n    \r\n    /// ===============================================================================================================\r\n    /// --- Clonable --------------------------------------------------------------------------------------------------\r\n\r\n    function initialized() virtual override public view returns (bool) {\r\n        return __storage().defaultUpdateConditions.minWitnesses > 0;\r\n    }\r\n    \r\n    \r\n    /// ===============================================================================================================\r\n    /// --- IERC2362 --------------------------------------------------------------------------------------------------\r\n\r\n    function valueFor(bytes32 _id)\r\n        override\r\n        external view\r\n        returns (int256 _value, uint256 _timestamp, uint256 _status)\r\n    {\r\n        ID4 _id4 = ID4.wrap(bytes4(_id));\r\n        WitPriceFeedsDataLib.PriceFeed storage __record = __seekPriceFeed(_id4);\r\n        UpdateConditions memory _updateConditions = __record.updateConditions.coalesce();\r\n        WitPriceFeedsDataLib.PriceData memory _lastUpdate = __record.fetchLastUpdate(_id4, _updateConditions.heartbeatSecs);\r\n        _value = int(uint(_lastUpdate.emaPrice > 0 ? _lastUpdate.emaPrice : _lastUpdate.price));\r\n        _timestamp = uint(Witnet.Timestamp.unwrap(_lastUpdate.timestamp));\r\n        _status = (\r\n            _timestamp == 0 \r\n                ? 404\r\n                : (\r\n                    block.timestamp > Witnet.Timestamp.unwrap(_lastUpdate.timestamp) + _updateConditions.heartbeatSecs\r\n                        ? 400 \r\n                        : 200\r\n                )\r\n        );\r\n    }\r\n\r\n    \r\n    /// ===============================================================================================================\r\n    /// --- IWitPyth --------------------------------------------------------------------------------------------------\r\n\r\n    /// @notice Returns the exponentially-weighted moving average price.\r\n    /// @dev Reverts if the EMA price is not available, or if the price feeds is settled with a heartbeat\r\n    /// and the price was not recently updated.\r\n    /// @param _id The Price Feed ID of which to fetch the EMA price.\r\n    function getEmaPrice(ID _id)\r\n        external view override \r\n        returns (PythPrice memory)\r\n    {\r\n        return _intoPythPrice(\r\n            WitPriceFeedsDataLib.getPrice(_intoID4(_id))\r\n        );\r\n    }\r\n\r\n    /// @notice Returns the exponentially-weighted moving average price that is no older than `_age` seconds\r\n    /// of the current time.\r\n    /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in\r\n    /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently\r\n    /// recently.\r\n    function getEmaPriceNotOlderThan(ID _id, uint64 _age)\r\n        external view override\r\n        returns (PythPrice memory)\r\n    {\r\n        return _intoPythPrice(\r\n            WitPriceFeedsDataLib.getPriceNotOlderThan(_intoID4(_id), uint24(_age))\r\n        );\r\n    }\r\n\r\n    /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.\r\n    /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.\r\n    /// However, if the price is not recent this function returns the latest available price.\r\n    ///\r\n    /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that\r\n    /// the returned price is recent or useful for any particular application.\r\n    ///\r\n    /// Users of this function should check the `timestamp` in the price to ensure that the returned price is\r\n    /// sufficiently recent for their application. If you are considering using this function, it may be\r\n    /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.\r\n    function getEmaPriceUnsafe(ID _id)\r\n        external view override \r\n        returns (PythPrice memory) \r\n    {\r\n        return _intoPythPrice(\r\n            WitPriceFeedsDataLib.getPriceUnsafe(_intoID4(_id))\r\n        );\r\n    }\r\n\r\n    /// @notice Returns the price of given price feed.\r\n    /// @dev Reverts if the price has not been updated within the last `heartbeatSecs`. \r\n    /// @param _id The Price Feed ID of which to fetch the price.\r\n    function getPrice(ID _id)\r\n        external view override\r\n        returns (PythPrice memory)\r\n    {\r\n        return _intoPythPrice(\r\n            WitPriceFeedsDataLib.getPrice(_intoID4(_id))\r\n        );\r\n    }\r\n\r\n    /// @notice Returns the price that is no older than `_age` seconds of the current time.\r\n    /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in\r\n    /// applications that require a sufficiently-recent price. \r\n    /// Reverts if the price wasn't updated sufficiently\r\n    /// recently.\r\n    function getPriceNotOlderThan(ID _id, uint64 _age)\r\n        external view override \r\n        returns (PythPrice memory)\r\n    {\r\n        return _intoPythPrice(\r\n            WitPriceFeedsDataLib.getPriceNotOlderThan(_intoID4(_id), uint24(_age))\r\n        );\r\n    }\r\n\r\n    /// @notice Returns the price of a price feed without any sanity checks.\r\n    /// @dev This function returns the most recent price update in this contract without any recency checks.\r\n    /// This function is unsafe as the returned price update may be arbitrarily far in the past.\r\n    /// \r\n    /// Users of this function should check the `timestamp` in the price to ensure that the returned price is\r\n    /// sufficiently recent for their application. If you are considering using this function, it may be\r\n    /// safer / easier to use either `getPrice` or `getPriceNoOlderThan`.\r\n    function getPriceUnsafe(ID _id)\r\n        external view override\r\n        returns (PythPrice memory)\r\n    {\r\n        return _intoPythPrice(\r\n            WitPriceFeedsDataLib.getPriceUnsafe(_intoID4(_id))\r\n        );\r\n    }\r\n\r\n    /// @notice Legacy-compliant to get the required fee to update an array of price updates, which would be\r\n    /// always 0 if relying from the Wit/Oracle framework.\r\n    function getUpdateFee(bytes calldata) external override pure returns (uint256) {\r\n        return 0;\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitPriceFeeds --------------------------------------------------------------------------------------------\r\n\r\n    /// --- permissionless state-modifying methods --------------------------------------------------------------------\r\n\r\n    /// Creates a light-proxy clone to the `base()` contract address, to be owned by the specified `curator` address. \r\n    /// Curators of cloned contracts can optionally settle one single `IWitPriceFeedConsumer` consuming contract. \r\n    /// The consuming contract, if settled, will be immediately reported every time a new Witnet-certified price update\r\n    /// gets pushed into the cloned instance. Either way, price feeds data will be stored in the `WitPriceFeeds` storage. \r\n    /// @param _curator Address that will have rights to manage price feeds on the new light-proxy clone.\r\n    function clone(address _curator) \r\n        virtual override\r\n        external\r\n        returns (address)\r\n    {\r\n        return WitPriceFeedsV3(__clone()).initializeClone(\r\n            _curator,\r\n            __storage().defaultUpdateConditions\r\n        );\r\n    }\r\n\r\n    /// Creates a Chainlink Aggregator proxy to the specified symbol.\r\n    /// @dev Reverts if symbol is not supported.\r\n    function createChainlinkAggregator(string calldata symbol)\r\n        virtual override external\r\n        returns (address)\r\n    {\r\n        require(supportsCaption(symbol), PriceFeedNotFound());\r\n        bytes memory _initcode = type(WitPythChainlinkAggregator).creationCode;\r\n        bytes memory _params = abi.encodePacked(address(this), _intoID4(hash(symbol)));\r\n        address _aggregator = _determineCreate2Address(_initcode, _params);\r\n        if (_aggregator.code.length == 0) {\r\n            bytes memory _bytecode = _completeInitCode(_initcode, _params);\r\n            assembly {\r\n                _aggregator := create2(\r\n                    0,\r\n                    add(_bytecode, 0x20),\r\n                    mload(_bytecode),\r\n                    0\r\n                )\r\n            }\r\n        }\r\n        return _aggregator;\r\n    }\r\n\r\n\r\n    /// --- read-only methods -----------------------------------------------------------------------------------------\r\n\r\n    function base() virtual override (Clonable, IWitPriceFeeds) public view returns (address) {\r\n        return super.base();\r\n    }\r\n\r\n    /// Returns the consumer address where all price updates will be reported to.\r\n    /// @dev If zero, new price updates will not be reported to any other external address.\r\n    /// @dev The consumer contract must implement the `IWitPriceFeedsConsumer` interface, \r\n    /// @dev and accept this instance as source of truth.\r\n    /// @dev It can only be settled by a curator on cloned instances.\r\n    /// @dev It can only be settled by a curator, only on cloned instances.\r\n    function consumer() override external view returns (IWitPriceFeedsConsumer) {\r\n        return IWitPriceFeedsConsumer(__storage().consumer);\r\n    }\r\n\r\n    /// Returns a unique hash determined by the combination of data sources being used by \r\n    /// supported non-routed price feeds, and dependencies of all supported routed \r\n    /// price feeds. The footprint changes if any price feed is modified, added, removed \r\n    /// or if the dependency tree of any routed price feed is altered.\r\n    function footprint() external override view returns (bytes4 _footprint) {\r\n        return __storage().footprint;\r\n    }\r\n    \r\n    /// Determines unique ID for specified `symbol` string.\r\n    function hash(string memory _symbol) public pure returns (ID) {\r\n        return ID.wrap(WitPriceFeedsDataLib.hash(_symbol));\r\n    }\r\n    \r\n    /// @notice Returns last update price for the specified ID4 price feed.\r\n    /// Note: This function is sanity-checked version of `getPriceUnsafe` which is useful in applications and\r\n    /// smart contracts that require recentl updated price, and no hint of market deviation being currently excessive. \r\n    ///\r\n    /// @dev Reverts if:\r\n    /// - `StalePrice()`: the price feed has not been updated within the last `UpdateConditions.heartbeatSecs`,\r\n    /// - `DeviantPrice()`: a deviation greater than `UpdateConditions.maxDeviation1000` was detected upon last update attempt.\r\n    /// - `InvalidGovernanceTarget()`: no EMA is curretly settled to be computed for this price feed.\r\n    ///\r\n    /// @param _id4 Unique ID4 identifier of a price feed supported by this contract.\r\n    function getPrice(ID4 _id4) external view override returns (Price memory) {\r\n        return WitPriceFeedsDataLib.getPrice(_id4);\r\n    }\r\n\r\n    /// @notice Returns last known price if no older than `_age` seconds of the current time.\r\n    /// Note: This function is a sanity-checked version of `getPriceUnsafe` which is useful in applications and\r\n    /// smart contracts that require last known non-deviant price, last updated within specified time range.\r\n    ///\r\n    /// @dev Reverts if:\r\n    /// - `StalePrice()`: the price feed has not been updated within the last `_age` seconds,\r\n    /// \r\n    /// @param _id4 Unique ID4 identifier of a price feed supported by this contract.\r\n    /// @param _age Maximum age of acceptable price value.\r\n    function getPriceNotOlderThan(ID4 _id4, uint24 _age) external view override returns (Price memory) {\r\n        return WitPriceFeedsDataLib.getPriceNotOlderThan(_id4, _age);\r\n    }\r\n\r\n    /// @notice Returns last updated price without any sanity checks.\r\n    /// Note: This function is unsafe as the returned price update may be arbitrarily far in the past.\r\n    /// Users of this function should check the `timestamp` of each price feed to ensure that the returned values \r\n    /// are sufficiently recent for their application. If you need safe access to fresh data, please consider\r\n    /// using calling to either `getPrice` or `getPriceNoOlderThan` variants.\r\n    /// \r\n    /// @param _id4 Unique ID4 identifier of a price feed supported by this contract.\r\n    function getPriceUnsafe(ID4 _id4) external view override returns (Price memory) {\r\n        return WitPriceFeedsDataLib.getPriceUnsafe(_id4);\r\n    }\r\n    \r\n    function lookupPriceFeed(ID4 _id4)\r\n        override \r\n        public view \r\n        returns (Info memory)\r\n    {\r\n        WitPriceFeedsDataLib.PriceFeed storage __record = __seekPriceFeed(_id4);\r\n        Mappers _mapper = __record.mapper;\r\n        string[] memory _mapperDeps;\r\n        if (_mapper != Mappers.None) {\r\n            ID4[] memory _deps = _id4.deps();\r\n            _mapperDeps = new string[](_deps.length);\r\n            for (uint _ix = 0; _ix < _deps.length; ++ _ix) {\r\n                _mapperDeps[_ix] = __storage().records[_deps[_ix]].symbol;\r\n            }\r\n        }\r\n        Oracles _oracle = __record.oracle;\r\n        bytes32 _oracleSources = __record.oracleSources;\r\n        address _oracleAddress = __record.oracleAddress;\r\n\r\n        return Info({\r\n            id: _intoID(_id4),\r\n            exponent: __record.exponent,\r\n            symbol: __record.symbol,\r\n            mapper: Mapper({\r\n                class: _mapper,\r\n                deps: _mapperDeps\r\n            }),\r\n            oracle: Oracle({\r\n                class: _oracle,\r\n                target: _oracleAddress,\r\n                sources: _oracleSources\r\n            }),\r\n            updateConditions: __record.updateConditions.coalesce(),\r\n            lastUpdate: WitPriceFeedsDataLib.getPriceUnsafe(_id4)\r\n        });\r\n    }\r\n\r\n    function lookupPriceFeedCaption(ID4 _id4) external override view returns (string memory _symbol) {\r\n        return __seekPriceFeed(_id4).symbol;\r\n    }\r\n\r\n    function lookupPriceFeedExponent(ID4 _id4) override public view returns (int8) {\r\n        return __seekPriceFeed(_id4).exponent;\r\n    }\r\n\r\n    function lookupPriceFeedID(ID4 _id4) override public view returns (bytes32) {\r\n        return ID.unwrap(_intoID(_id4));\r\n    }\r\n    \r\n    function lookupPriceFeeds() external override view returns (Info[] memory _infos) {\r\n        ID[] storage __ids = __storage().ids;\r\n        _infos = new Info[](__ids.length);\r\n        for (uint _ix; _ix < _infos.length; ++ _ix) {\r\n            _infos[_ix] = lookupPriceFeed(_intoID4(__ids[_ix]));\r\n        }\r\n    }\r\n\r\n    function supportsCaption(string calldata _caption) public override view returns (bool) {\r\n        WitPriceFeedsDataLib.PriceFeed storage __record = __seekPriceFeed(_intoID4(hash(_caption)));\r\n        return __record.settled();\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitPriceFeedsAdmin ---------------------------------------------------------------------------------------\r\n\r\n    function acceptOwnership()\r\n        virtual override (IWitPriceFeedsAdmin, Ownable2Step)\r\n        public\r\n    {\r\n        Ownable2Step.acceptOwnership();\r\n    }\r\n\r\n    function defaultUpdateConditions()\r\n        external view override\r\n        returns (UpdateConditions memory)\r\n    {\r\n        return __storage().defaultUpdateConditions;\r\n    }\r\n\r\n    function owner()\r\n        virtual override (IWitPriceFeedsAdmin, Ownable)\r\n        public view \r\n        returns (address)\r\n    {\r\n        return Ownable.owner();\r\n    }\r\n\r\n    function pendingOwner() \r\n        virtual override (IWitPriceFeedsAdmin, Ownable2Step)\r\n        public view\r\n        returns (address)\r\n    {\r\n        return Ownable2Step.pendingOwner();\r\n    }\r\n    \r\n    function transferOwnership(address _newOwner)\r\n        virtual override (IWitPriceFeedsAdmin, Ownable2Step)\r\n        public \r\n        onlyOwner\r\n    {\r\n        Ownable.transferOwnership(_newOwner);\r\n    }\r\n\r\n    function removePriceFeed(string calldata _symbol, bool _recursively) \r\n        external override\r\n        onlyOwner\r\n        returns (bytes4 _footprint)\r\n    {\r\n        ID4 _id4 = _intoID4(hash(_symbol));\r\n        WitPriceFeedsDataLib.removePriceFeed(_id4, _recursively);\r\n        emit PriceFeedRemoved(\r\n            msg.sender, \r\n            _id4, \r\n            _symbol\r\n        );\r\n        return WitPriceFeedsDataLib.settlePriceFeedFootprint();\r\n    }\r\n\r\n    function settleConsumer(address _consumer)\r\n        external override\r\n        onlyOnClones\r\n        onlyOwner\r\n    {\r\n        _require(\r\n            _consumer != address(this)\r\n                && _consumer != base()\r\n                && _consumer.code.length > 0 // must be a contract\r\n                && address(IWitPriceFeedsConsumer(_consumer).witPriceFeeds()) == address(this),\r\n            \"invalid consumer\"\r\n        );\r\n        __storage().consumer = _consumer;\r\n    }\r\n\r\n    function settleDefaultUpdateConditions(UpdateConditions calldata _conditions)\r\n        external override\r\n        onlyOwner\r\n    {\r\n        _require(_validateUpdateConditions(_conditions), \"invalid conditions\");\r\n        __storage().defaultUpdateConditions = _conditions;\r\n    }\r\n\r\n    function settlePriceFeedMapper(\r\n            string calldata _symbol, \r\n            int8 _exponent,\r\n            Mappers _mapper,\r\n            string[] calldata _deps\r\n        ) \r\n        external override\r\n        onlyOwner\r\n        returns (bytes4)\r\n    {\r\n        try WitPriceFeedsDataLib\r\n            .settlePriceFeedMapper(\r\n                _symbol, \r\n                _exponent, \r\n                _mapper,\r\n                _deps\r\n            )\r\n        returns (bytes4 _footprint) { \r\n            emit PriceFeedMapper(\r\n                msg.sender,\r\n                _intoID4(hash(_symbol)),\r\n                _symbol,\r\n                _exponent,\r\n                _mapper,\r\n                _deps\r\n            );\r\n            return _footprint; \r\n        \r\n        } catch Error(string memory _reason) { \r\n            _revert(_reason); \r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandled(); \r\n        }\r\n    }\r\n\r\n    function settlePriceFeedOracle(\r\n            string calldata _symbol, \r\n            int8 _exponent,\r\n            Oracles _oracle,\r\n            address _oracleAddress,\r\n            bytes32 _oracleSources\r\n        ) \r\n        external override\r\n        onlyOwner\r\n        returns (bytes4)\r\n    {\r\n        return __settlePriceFeedOracle(_symbol, _exponent, _oracle, _oracleAddress, _oracleSources);\r\n    }\r\n\r\n    function settlePriceFeedRadonBytecode(\r\n            string calldata _symbol, \r\n            int8 _exponent,\r\n            bytes calldata _radonBytecode\r\n        )\r\n        external override \r\n        onlyOwner\r\n        returns (bytes4)\r\n    {\r\n        try WitPriceFeedsDataLib\r\n            .settlePriceFeedRadonBytecode(\r\n                _symbol,\r\n                _radonBytecode,\r\n                _exponent,\r\n                IWitOracle(witOracle).registry()\r\n            )\r\n        returns (bytes4 _footprint, Witnet.RadonHash _radonHash) {\r\n            emit PriceFeedOracle(\r\n                msg.sender,\r\n                _intoID4(hash(_symbol)),\r\n                _symbol,\r\n                _exponent,\r\n                Oracles.Witnet,\r\n                address(this),\r\n                Witnet.RadonHash.unwrap(_radonHash)\r\n            );\r\n            return _footprint;\r\n        \r\n        } catch Error(string memory _reason) { \r\n            _revert(_reason); \r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandled(); \r\n        }\r\n    }\r\n\r\n    function settlePriceFeedRadonHash(\r\n            string calldata _symbol, \r\n            int8 _exponent,\r\n            Witnet.RadonHash _radonHash\r\n        )\r\n        external override \r\n        onlyOwner\r\n        returns (bytes4)\r\n    {\r\n        try WitPriceFeedsDataLib\r\n            .settlePriceFeedRadonHash(\r\n                _symbol,\r\n                _radonHash,\r\n                _exponent,\r\n                IWitOracle(witOracle).registry()\r\n            )\r\n        returns (bytes4 _footprint) {\r\n            emit PriceFeedOracle(\r\n                msg.sender,\r\n                _intoID4(hash(_symbol)),\r\n                _symbol,\r\n                _exponent,\r\n                Oracles.Witnet,\r\n                address(this),\r\n                Witnet.RadonHash.unwrap(_radonHash)\r\n            );\r\n            return _footprint;\r\n        }\r\n        catch Error(string memory _reason) { \r\n            _revert(_reason); \r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandled(); \r\n        }\r\n    }\r\n\r\n    function settlePriceFeedUpdateConditions(\r\n            string calldata _symbol, \r\n            UpdateConditions calldata _conditions\r\n        )\r\n        external override\r\n        onlyOwner\r\n    {\r\n        _require(_validateUpdateConditions(_conditions), \"invalid conditions\");\r\n        __settlePriceFeedUpdateConditions(_symbol, _conditions);\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitOracleConsumer ----------------------------------------------------------------------------------------\r\n\r\n    function pushDataReport(\r\n            Witnet.DataPushReport calldata report, \r\n            bytes calldata proof\r\n        )\r\n        virtual override\r\n        public\r\n    {\r\n        ID4 _id4 = __storage().reverseIds[report.queryRadHash];\r\n        require(\r\n            !_id4.isZero(), \r\n            InvalidUpdateDataSource()\r\n        );\r\n        WitPriceFeedsDataLib.PriceFeed storage __record = __seekPriceFeed(_id4);\r\n        UpdateConditions memory _updateConditions = __record.updateConditions.coalesce();\r\n        require(\r\n            report.queryParams.witCommitteeSize >= _updateConditions.minWitnesses,\r\n            InvalidGovernanceTarget()\r\n        );\r\n        Witnet.DataResult memory _dataResult = IWitOracle(witOracle).pushDataReport(\r\n            report,\r\n            proof\r\n        );\r\n        require(\r\n            _dataResult.status == Witnet.ResultStatus.NoErrors\r\n                && _dataResult.dataType == Witnet.RadonDataTypes.Integer,\r\n            InvalidUpdateData()\r\n        );\r\n        require(\r\n            _dataResult.timestamp.gt(__record.lastUpdate.timestamp),\r\n            NoFreshUpdate()\r\n        );\r\n        require(\r\n            Witnet.Timestamp.unwrap(_dataResult.timestamp)\r\n                >= Witnet.Timestamp.unwrap(__record.lastUpdate.timestamp) + _updateConditions.cooldownSecs,\r\n            HotPrice()\r\n        );\r\n        \r\n        int8 _exponent = __record.lastUpdate.exponent;\r\n        uint64 _deltaSecs = uint24(\r\n            Witnet.Timestamp.unwrap(__record.lastUpdate.timestamp)\r\n                - Witnet.Timestamp.unwrap(_dataResult.timestamp)\r\n        );\r\n        uint64 _lastPrice = __record.lastUpdate.price;\r\n        uint64 _nextPrice = _dataResult.fetchUint();\r\n        int56 _deltaPrice = int56(int64(_nextPrice) - int64(_lastPrice));\r\n        uint64 _deviation1000 = (\r\n            _deltaPrice >= 0\r\n                ? uint56(_deltaPrice * 1000) / _lastPrice\r\n                : uint56(-_deltaPrice * 1000) / _lastPrice\r\n        );\r\n        \r\n        require(\r\n            _updateConditions.maxDeviation1000 == 0 || _deviation1000 <= _updateConditions.maxDeviation1000,\r\n            DeviantPrice()\r\n        );\r\n\r\n        __record.lastUpdate.deltaPrice = _deltaPrice;\r\n        __record.lastUpdate.price = _nextPrice;\r\n        __record.lastUpdate.timestamp = _dataResult.timestamp;\r\n        __record.lastUpdate.trail = _dataResult.drTxHash;\r\n\r\n        if (_updateConditions.computeEma) {\r\n            // TODO\r\n            // ...\r\n            /// __record.lastUpdate.emaPrice = x;\r\n        }\r\n        \r\n        if (__storage().consumer == address(0)) {\r\n            emit PriceFeedUpdate(\r\n                _id4,\r\n                _dataResult.timestamp,\r\n                _dataResult.drTxHash,\r\n                _nextPrice,\r\n                _deltaPrice,\r\n                _exponent\r\n            );\r\n        } else {\r\n            IWitPriceFeedsConsumer(__storage().consumer).reportUpdate(\r\n                _id4,\r\n                _dataResult.timestamp,\r\n                _dataResult.drTxHash,\r\n                _nextPrice,\r\n                _deltaPrice,\r\n                _deltaSecs,\r\n                _exponent\r\n            );\r\n        }\r\n    }\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Internal methods -------------------------------------------------------------------------------------------\r\n\r\n    function _completeInitCode(bytes memory initcode, bytes memory params)\r\n        private pure\r\n        returns (bytes memory)\r\n    {\r\n        return abi.encodePacked(\r\n            initcode,\r\n            params\r\n        );\r\n    }\r\n\r\n    function _determineCreate2Address(bytes memory initcode, bytes memory params)\r\n        private view\r\n        returns (address)\r\n    {\r\n        return address(\r\n            uint160(uint(keccak256(\r\n                abi.encodePacked(\r\n                    bytes1(0xff),\r\n                    address(this),\r\n                    bytes32(0),\r\n                    keccak256(_completeInitCode(initcode, params))\r\n                )\r\n            )))\r\n        );\r\n    }\r\n\r\n    function _intoID(ID4 id4) internal view returns (ID) {\r\n        return __storage().ids[__storage().records[id4].index];\r\n    }\r\n\r\n    function _intoID4(ID id) internal pure returns (ID4) {\r\n        return ID4.wrap(bytes4(ID.unwrap(id)));\r\n    }\r\n\r\n    function _intoPythPrice(Price memory _witPrice) internal pure returns (PythPrice memory) {\r\n        return PythPrice({\r\n            price: int64(_witPrice.price),\r\n            conf: 0,\r\n            expo: int32(_witPrice.exponent),\r\n            publishTime: uint(Witnet.Timestamp.unwrap(_witPrice.timestamp))\r\n        });\r\n    }\r\n\r\n    function _revertUnhandled() internal view {\r\n        _revert(\"unhandled revert\");\r\n    }\r\n\r\n    function _validateUpdateConditions(UpdateConditions memory _conditions)\r\n        internal pure\r\n        returns (bool)\r\n    {\r\n        return (\r\n            _conditions.callbackGas > 0\r\n                && _conditions.heartbeatSecs > 0\r\n                && _conditions.minWitnesses > 0\r\n        );\r\n    }\r\n\r\n    function __seekPriceFeed(ID4 _id4) internal view returns (WitPriceFeedsDataLib.PriceFeed storage) {\r\n        return WitPriceFeedsDataLib.seekPriceFeed(_id4);\r\n    }\r\n\r\n    function __settlePriceFeedOracle(\r\n            string memory _symbol, \r\n            int8 _exponent,\r\n            Oracles _oracle,\r\n            address _oracleAddress,\r\n            bytes32 _oracleSources\r\n        )\r\n        virtual internal \r\n        returns (bytes4)\r\n    {\r\n        try WitPriceFeedsDataLib\r\n            .settlePriceFeedOracle(\r\n                _symbol, \r\n                _exponent, \r\n                _oracle,\r\n                _oracleAddress,\r\n                _oracleSources\r\n            )\r\n        returns (bytes4 _footprint) { \r\n            emit PriceFeedOracle(\r\n                msg.sender,\r\n                _intoID4(hash(_symbol)),\r\n                _symbol,\r\n                _exponent,\r\n                _oracle,\r\n                _oracleAddress,\r\n                _oracleSources\r\n            );\r\n            return _footprint; \r\n        \r\n        } catch Error(string memory _reason) { \r\n            _revert(_reason); \r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandled(); \r\n        }\r\n    }\r\n\r\n    function __settlePriceFeedUpdateConditions(\r\n            string memory _symbol,\r\n            UpdateConditions memory _conditions\r\n        )\r\n        virtual internal \r\n    {\r\n        ID4 _id4 = _intoID4(hash(_symbol));\r\n        WitPriceFeedsDataLib.PriceFeed storage __pf = __seekPriceFeed(_id4);\r\n        __pf.updateConditions = _conditions;\r\n        if (!_conditions.computeEma) {\r\n            __pf.lastUpdate.emaPrice = 0;\r\n        }\r\n        emit PriceFeedUpdateConditions(\r\n            _msgSender(),\r\n            _id4,\r\n            _symbol,\r\n            _conditions\r\n        );\r\n    }\r\n\r\n    function __storage() internal pure returns (WitPriceFeedsDataLib.Storage storage) {\r\n        return WitPriceFeedsDataLib.data();\r\n    }\r\n\r\n}\r\n"
      },
      "project/contracts/apps/WitRandomnessV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {\r\n    IWitOracle, \r\n    IWitOracleAppliance,\r\n    IWitOracleQueriable,\r\n    IWitOracleRadonRegistry,\r\n    Witnet\r\n} from \"../WitOracle.sol\";\r\n\r\nimport { \r\n    IWitRandomness, \r\n    IWitRandomnessAdmin, \r\n    IWitRandomnessConsumer, \r\n    WitRandomness\r\n} from \"../WitRandomness.sol\";\r\n\r\nimport {Clonable} from \"../patterns/Clonable.sol\";\r\nimport {Ownable, Ownable2Step} from \"../patterns/Ownable2Step.sol\";\r\n\r\n/// @title WitRandomnessV3: Unbiased, EVM-agnostic and provably-fair random seeds from the Witnet blockchain. \r\n/// \r\n/// 64-bit entropy seeds can be permissionless pulled at anytime from smart contracts and externally-owned EVM accounts.\r\n/// \r\n/// Randomness provisioning is securely protected against race-condition and malleability attacks by node validators\r\n/// on both EVM and Witnet blockchains. \r\n///\r\n/// This contract acts also as a public-good registry, openly preserving all random seeds generated in the past,\r\n/// and providing after-the-fact traceability proof to the actual witnessing committees and punishable acts that took\r\n/// place on the Witnet blockchain for generating every single one of them.\r\n///\r\n/// @dev Protection against race-condition and malleability attacks requires randomness queried to this contract\r\n/// to be solved is an asynchronous way, meaning that after some randomness is requested, the result provided\r\n/// from the Wit/Oracle sidechain won't be ready until a certain amount of EVM blocks have elapsed. \r\n/// This protection also implies that eventually failing randomness requests on the Wit/Oracle sidechain \r\n/// cannot be retried but from this very same contract. Failing randomness requests will get all automatically\r\n/// and unbiasedly solved as soon as some new randomness request gets solved, even if paid by a different requester.\r\n///\r\n/// Querying for new randomness requires paying a fee in native EVM gas currency, as to cover the implicit cost of\r\n/// solving unmalleable randomness on the Wit/Oracle sidechain and report it back to the EVM storage. The actual \r\n/// randomize fee depends on the expected gas price to pay for the EVM transaction that would eventually include \r\n/// a call to any of the `randomize(..)` methods of this contract. The randomize fee can be computed by passing\r\n/// the expected gas price value to the `estimateRandomizeFee(uint256)` method.\r\n///\r\n/// > Note [1]: On highly volatile gas price markets, especially on some Layer-2 EVM chains, is highly recommended\r\n/// to estimate the randomize fee before a `randomize()` call, and pass a fresh EVM gas price value. Otherwise\r\n/// the call to `randomize()` could potentially revert with either \"insufficient reward\" or \"too much reward\".\r\n///\r\n/// > Note [2]: Contracts requiring some external entity to report Witnet-certified randomness only when required,\r\n/// would need to implement the `IWitRandomnessConsumer`. The external entity would then have to clone the \r\n/// public-domain address, attach it to the consumer contract address, and get the `randomize()` function\r\n/// called on the cloned instance as many times as required.\r\n///\r\n/// @author The Witnet Foundation.\r\ncontract WitRandomnessV3\r\n    is\r\n        Clonable,\r\n        Ownable2Step,\r\n        WitRandomness\r\n{\r\n    using Witnet for Witnet.DataResult;\r\n    \r\n    /// @notice Unique identifier of the RNG data request used on the Witnet blockchain for solving randomness.\r\n    /// @dev Can be used to track all randomness requests solved so far on the Witnet blockchain.\r\n    Witnet.RadonHash internal immutable __WIT_ORACLE_RNG_RADON_HASH;\r\n\r\n    /// @dev Default number of blocks after a randomize request to consider it delayed if not solved yet.\r\n    uint16 internal constant _DEFAULT_RANDOMIZE_WAITING_BLOCKS = 256;\r\n\r\n    /// @dev Minimum acceptable callback gas limit that can be settled by the `owner()`. \r\n    uint24 internal constant _WIT_ORACLE_MIN_CALLBACK_GAS_LIMIT = 50000;\r\n\r\n    /// @dev Size of successful CBOR-encoded randomness generated by the Witnet blockchain. \r\n    uint16 internal constant _WIT_ORACLE_RNG_MAX_RESULT_SIZE = 34;\r\n\r\n    /// @dev Storage slot pointer\r\n    bytes32 private constant _WIT_RANDOMNESS_STORAGE_SLOT = \r\n        // keccak256(\"io.witnet.apps.randomness.v3\") & ~bytes32(uint256(0xff) \r\n        0x43025ad356942e949bc1eab02ffb42d0642f59c8829febfec0169ebcda390700;\r\n\r\n    /// Randomize records\r\n    struct Randomize {\r\n        uint64 queryId;\r\n        uint64 finality;\r\n        uint64 nextBlock;\r\n        bytes8 randomness;\r\n        uint64 prevBlock;\r\n    }\r\n\r\n    /// Initialization parameters for clones\r\n    struct CloneSettings {\r\n        uint24 callbackGasLimit;\r\n        uint16 extraFeePercentage;\r\n        uint16 witCommitteeSize;\r\n        uint64 witInclusionFees;\r\n        uint16 randomizeWaitingBlocks;\r\n    }\r\n\r\n    /// Data storage layout \r\n    struct Storage {\r\n        uint24 callbackGasLimit;\r\n        uint16 extraFeePercentage;\r\n        uint64 lastRandomizeBlock;\r\n        uint16 witCommitteeSize;\r\n        uint64 witInclusionFees;\r\n        uint72 _0;\r\n        address consumer;\r\n        uint16 randomizeWaitingBlocks;\r\n        uint80 _1;\r\n        mapping (Witnet.QueryId => uint256) blocks;\r\n        mapping (uint256 => Randomize) requests;\r\n    }\r\n\r\n    /// @notice Returns the WitOracle address that this appliance is bound to.\r\n    address immutable internal __WIT_ORACLE;\r\n\r\n    /// @notice Returns the name of the actual contract implementing the logic of this Witnet appliance.\r\n    function class() virtual override public pure returns (string memory) {\r\n        return type(WitRandomnessV3).name;\r\n    }\r\n\r\n    constructor(\r\n            address _witOracle,\r\n            address _operator\r\n        )\r\n        Ownable(_operator)\r\n    {\r\n        _require(\r\n            _witOracle.code.length > 0\r\n                && IWitOracleAppliance(_witOracle).specs() == (\r\n                    type(IWitOracle).interfaceId\r\n                        ^ type(IWitOracleQueriable).interfaceId\r\n                ), \r\n            \"uncompliant WitOracle\"\r\n        );\r\n        __WIT_ORACLE = _witOracle;\r\n\r\n        // Build Witnet-compliant randomness request:\r\n        IWitOracleRadonRegistry _witOracleRadonRegistry = IWitOracle(_witOracle).registry();\r\n        __WIT_ORACLE_RNG_RADON_HASH = _witOracleRadonRegistry.verifyRadonRequest(\r\n            Witnet.intoMemArray([\r\n                _witOracleRadonRegistry.verifyRadonRetrieval(\r\n                    Witnet.RadonRetrievalMethods.RNG,\r\n                    \"\", // no request url\r\n                    \"\", // no request body\r\n                    new string[2][](0), // no request headers\r\n                    hex\"80\" // no request Radon script\r\n                )\r\n            ]),\r\n            Witnet.RadonReducer({\r\n                opcode: Witnet.RadonReduceOpcodes.Mode,\r\n                filters: new Witnet.RadonFilter[](0)\r\n            }),\r\n            Witnet.RadonReducer({\r\n                opcode: Witnet.RadonReduceOpcodes.ConcatenateAndHash,\r\n                filters: new Witnet.RadonFilter[](0)\r\n            })\r\n        );\r\n\r\n        // Initialize settings:\r\n        __storage().extraFeePercentage = 10; // 10 %\r\n        __storage().callbackGasLimit = _WIT_ORACLE_MIN_CALLBACK_GAS_LIMIT;\r\n        __storage().randomizeWaitingBlocks = _DEFAULT_RANDOMIZE_WAITING_BLOCKS;\r\n        __storage().witCommitteeSize = 3;\r\n        __storage().witInclusionFees = 0;\r\n    }\r\n\r\n    receive() virtual external payable {\r\n        _revert(\"no transfers accepted\");\r\n    }\r\n\r\n    fallback() virtual external payable { \r\n        _revert(string(abi.encodePacked(\r\n            \"not implemented: 0x\",\r\n            Witnet.toHexString(uint8(bytes1(msg.sig))),\r\n            Witnet.toHexString(uint8(bytes1(msg.sig << 8))),\r\n            Witnet.toHexString(uint8(bytes1(msg.sig << 16))),\r\n            Witnet.toHexString(uint8(bytes1(msg.sig << 24)))\r\n        )));\r\n    }\r\n\r\n    function initializeClone(address _curator, CloneSettings calldata _settings)\r\n        external\r\n        onlyOnClones\r\n        initializer\r\n        returns (IWitRandomness)\r\n    {\r\n        _require(\r\n            _curator != address(0), \r\n            \"zero curator\"\r\n        );\r\n        _transferOwnership(_curator);\r\n        \r\n        _require(\r\n            _settings.witCommitteeSize > 0\r\n                && _settings.witCommitteeSize <= 127,\r\n            \"invalid settings\"\r\n        );\r\n        __storage().callbackGasLimit = _settings.callbackGasLimit;\r\n        __storage().extraFeePercentage = _settings.extraFeePercentage;\r\n        __storage().witCommitteeSize = _settings.witCommitteeSize;\r\n        __storage().witInclusionFees = _settings.witInclusionFees;\r\n        __storage().randomizeWaitingBlocks = _settings.randomizeWaitingBlocks;\r\n\r\n        return IWitRandomness(address(this));\r\n    }\r\n\r\n    /// ===============================================================================================================\r\n    /// --- Clonable --------------------------------------------------------------------------------------------------\r\n\r\n    function initialized() virtual override public view returns (bool) {\r\n        return __storage().witCommitteeSize > 0;\r\n    }\r\n\r\n    \r\n    /// ===============================================================================================================\r\n    /// --- IWitRandomness --------------------------------------------------------------------------------------------\r\n\r\n    /// Address of the underlying logic contract that can be potentially cloned.\r\n    function base() virtual override (Clonable, IWitRandomness) public view returns (address) {\r\n        return super.base();\r\n    }\r\n\r\n    /// Creates a light-proxy clone to the `base()` logic address, to be owned by the specified `curator`address.\r\n    /// Curators of cloned instances can optionally settle one single `IWitRandomnessConsumer` consuming contract.\r\n    /// The consuming contract, if settled, will be immediately reported every time a new `randomize()` request\r\n    /// gets solved and bridged back from Witnet. Either way, randomness resolutions will be reamin stored in the \r\n    /// `WitRandomness` storage, as for future reference. \r\n    /// @param _curator Address that will have authoritative access to `IWitRandomnessAdmin` methods.\r\n    function clone(address _curator)\r\n        virtual override\r\n        external \r\n        returns (IWitRandomness)\r\n    {\r\n        return WitRandomnessV3(payable(__clone())).initializeClone(\r\n            _curator,\r\n            CloneSettings({\r\n                callbackGasLimit: __storage().callbackGasLimit,\r\n                extraFeePercentage: __storage().extraFeePercentage,\r\n                witCommitteeSize: __storage().witCommitteeSize,\r\n                witInclusionFees: __storage().witInclusionFees,\r\n                randomizeWaitingBlocks: __storage().randomizeWaitingBlocks\r\n            })\r\n        );\r\n    }\r\n\r\n    /// Returns the consumer address where all valid randomize results will be reported to.\r\n    /// @dev If zero, generated randomness will not be reported to any other external address. \r\n    /// @dev The consumer contract must implement the `IWitRandomnessConsumer` interface, \r\n    /// @dev and accept this instance as source of entropy.\r\n    /// @dev It can only be settled by a curator on cloned instances.\r\n    function consumer() \r\n        virtual override\r\n        external view \r\n        returns (IWitRandomnessConsumer)\r\n    {\r\n        \r\n        return IWitRandomnessConsumer(__storage().consumer);\r\n    }\r\n\r\n    /// Returns amount of wei required to be paid as a fee when requesting randomization with a \r\n    /// transaction gas price as the one given.\r\n    function estimateRandomizeFee(uint256 _evmGasPrice)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        uint256 _baseFee = IWitOracleQueriable(__WIT_ORACLE).estimateBaseFeeWithCallback(\r\n            _evmGasPrice, \r\n            __storage().callbackGasLimit\r\n        );\r\n        return (_baseFee * (100 + __storage().extraFeePercentage)) / 100;\r\n    }\r\n\r\n    /// Retrieves the result of keccak256-hashing the given block number with the randomness value \r\n    /// generated by the Witnet blockchain in response to the first non-failing randomize request solved \r\n    /// after such block number.\r\n    ///\r\n    /// @dev Reverts if:\r\n    ///    i.   no `randomize()` was queried on neither the given block, nor afterwards.\r\n    ///    ii.  the first non-failing `randomize()` request found on or after the given block is not solved yet.\r\n    ///    iii. all `randomize()` requests that took place on or after the given block were solved with errors.\r\n    ///\r\n    /// @param _blockNumber Block number from which the search will start.\r\n    function fetchRandomnessAfter(uint256 _blockNumber)\r\n        public view\r\n        virtual override\r\n        returns (bytes32)\r\n    {\r\n        return keccak256(\r\n            abi.encode(\r\n                _blockNumber,\r\n                _fetchRandomnessAfter(_blockNumber)\r\n            )\r\n        );\r\n    }\r\n    \r\n    /// Retrieves the actual random value, unique hash and timestamp of the witnessing commit/reveal act \r\n    /// that took place in the Witnet blockchain in response to the first non-failing randomize query\r\n    /// solved after the given block number.\r\n    ///\r\n    /// @dev Reverts if:\r\n    ///    i.   no `randomize()` was queried on neither the given block, nor afterwards.\r\n    ///    ii.  the first non-failing `randomize()` request found on or after the given block is not solved yet.\r\n    ///    iii. all `randomize()` requests that took place on or after the given block were solved with errors.\r\n    ///\r\n    /// @param _blockNumber Block number from which the search will start.\r\n    ///\r\n    /// @return _witnetQueryUUID Universal identifier of the query posted from this contract that ultimately solved randomness.\r\n    /// @return _witnetTimestamp Timestamp at which the randomness value was generated by the Witnet blockchain.\r\n    /// @return _witnetDrTxHash Hash of the witnessing commit/reveal act that took place on the Witnet blockchain.\r\n    /// @return _evmFinalityBlock EVM block number at which the generated randomness can be considered to be final.\r\n    function fetchRandomnessAfterProof(uint256 _blockNumber) \r\n        virtual override\r\n        public view \r\n        returns (\r\n            bytes32 _witnetQueryUUID,\r\n            Witnet.Timestamp _witnetTimestamp,\r\n            Witnet.TransactionHash _witnetDrTxHash,\r\n            uint256 _evmFinalityBlock\r\n        )\r\n    {\r\n        (_witnetQueryUUID, _witnetDrTxHash, _witnetTimestamp, _evmFinalityBlock) = IWitOracleQueriable(__WIT_ORACLE)\r\n            .getQueryResultTrails(\r\n                _getRandomizeQueryId(_blockNumber)\r\n            );\r\n    }\r\n\r\n    /// Returns last block number on which a randomize was requested.\r\n    function getLastRandomizeBlock()\r\n        virtual override\r\n        external view\r\n        returns (uint256)\r\n    {\r\n        return __storage().lastRandomizeBlock;\r\n    }\r\n\r\n    /// Retrieves metadata related to the randomize request that got queried to the`WitOracle` contract \r\n    /// on the specified block number, if any.\r\n    ///\r\n    /// @dev Returns zero values if no randomize request was actually queried on the specified block number.\r\n    ///\r\n    /// @param _blockNumber Block number from which the search will start.\r\n    ///\r\n    /// @return _queryId Identifier of the underlying Wit/Oracle query created on the specified block number. \r\n    /// @return _prevRandomizeBlock Block number in which a randomize request got queried just before this one. 0 if none.\r\n    /// @return _nextRandomizeBlock Block number in which a randomize request got queried just after this one, 0 if none.\r\n    function getRandomizeData(uint256 _blockNumber)\r\n        external view\r\n        virtual override\r\n        returns (\r\n            Witnet.QueryId _queryId,\r\n            uint256 _prevRandomizeBlock,\r\n            uint256 _nextRandomizeBlock\r\n        )\r\n    {\r\n        Randomize storage __request = __storage().requests[_blockNumber];\r\n        _queryId = Witnet.QueryId.wrap(__request.queryId);\r\n        _prevRandomizeBlock = __request.prevBlock != 0 ? __request.prevBlock : getRandomizePrevBlock(_blockNumber);\r\n        _nextRandomizeBlock = __request.nextBlock != 0 ? __request.nextBlock : getRandomizeNextBlock(_blockNumber);\r\n    }\r\n\r\n    /// Returns the number of the next block in which a randomize request was posted after the given one. \r\n    /// @param _blockNumber Block number from which the search will start.\r\n    /// @return Number of the first block found after the given one, or `0` otherwise.\r\n    function getRandomizeNextBlock(uint256 _blockNumber)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return (\r\n            __storage().requests[_blockNumber].queryId == 0\r\n                ? _searchNextBlock(_blockNumber, __storage().lastRandomizeBlock)\r\n                : __storage().requests[_blockNumber].nextBlock\r\n        );\r\n    }\r\n\r\n    /// Returns the number of the previous block in which a randomize request was posted before the given one.\r\n    /// @param _blockNumber Block number from which the search will start. Cannot be zero.\r\n    /// @return First block found before the given one, or `0` otherwise.\r\n    function getRandomizePrevBlock(uint256 _blockNumber)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        uint256 _latest = __storage().lastRandomizeBlock;\r\n        return (_blockNumber > _latest\r\n            ? _latest\r\n            // start search from the latest block\r\n            : _searchPrevBlock(_blockNumber, __storage().requests[_latest].prevBlock)\r\n        );\r\n    }\r\n\r\n    /// Returns the identifier of the Wit/Oracle query that has either solved randomness\r\n    /// for the specified block number, is currently attending randomness for the specified block number,\r\n    /// of the one that attempted to solve it. \r\n    /// @dev Returns zero if no randomize was request on or after the specified block number.\r\n    function getRandomizeQueryId(uint256 _blockNumber)\r\n        virtual override\r\n        public view\r\n        returns (Witnet.QueryId)\r\n    {\r\n        return Witnet.QueryId.wrap(\r\n            _getRandomizeQueryId(_blockNumber)\r\n        );\r\n    }\r\n\r\n    /// Explains why the last attempt of generating randomness for the specified block number failed.\r\n    function getRandomizeQueryErrorDescription(uint256 _blockNumber) \r\n        virtual override \r\n        public view\r\n        returns (string memory _reason)\r\n    {\r\n        RandomizeStatus _status = getRandomizeStatus(_blockNumber);\r\n        if (_status == RandomizeStatus.Error) {\r\n            _reason = IWitOracleQueriable(__WIT_ORACLE).getQueryResultStatusDescription(\r\n                _getRandomizeQueryId(_blockNumber)\r\n            );\r\n        }\r\n    }\r\n\r\n    /// Returns security and liveness parameters required to the Witnet blockchain \r\n    /// when solving randomness requests, if no others are specified.\r\n    /// @return _callbackGasLimit Max. expendable gas upon randomness delivery.\r\n    /// @return _extraFeePercentage Overhead percentage applied when estimating the randomize request fee. \r\n    /// @return _witCommitteeSize Number of Witnet witnessing nodes required to generate unbiased randomness.\r\n    /// @return _witInclusionFees Minimum amount of fees in $nanoWIT to be paid on the Witnet blockchain.\r\n    function getRandomizeQueryParams()\r\n        virtual override\r\n        public view\r\n        returns (\r\n            uint24 _callbackGasLimit,\r\n            uint16 _extraFeePercentage,\r\n            uint16 _witCommitteeSize,\r\n            uint64 _witInclusionFees\r\n        )\r\n    {\r\n        return (\r\n            __storage().callbackGasLimit,\r\n            __storage().extraFeePercentage,\r\n            __storage().witCommitteeSize,\r\n            __storage().witInclusionFees\r\n        );\r\n    }\r\n\r\n    /// Returns the immutable bytecode of the Radon Request that's being used \r\n    /// for solving randomness requests on the Witnet blockchain.\r\n    function getRandomizeRadonBytecode() virtual override external view returns (bytes memory) {\r\n        return IWitOracle(__WIT_ORACLE).registry().lookupRadonRequestBytecode(\r\n            getRandomizeRadonHash()\r\n        );\r\n    }\r\n\r\n    /// Returns the unique identifier of the Radon Request that's being used \r\n    /// for solving request randomness requests on the Witnet blockchain.\r\n    function getRandomizeRadonHash() virtual override public view returns (Witnet.RadonHash) {\r\n        return __WIT_ORACLE_RNG_RADON_HASH;\r\n    }\r\n\r\n    /// Returns status of the first non-errored randomize request queried on or after the given block number.\r\n    ///  - 0 -> Void: no randomize request was actually queried on or after the given block number.\r\n    ///  - 1 -> Awaiting: a randomize request was found but it's not yet solved by the Wit/Oracle.\r\n    ///  - 2 -> Ready: a successfull randomize value was reported and is ready to be read.\r\n    ///  - 3 -> Error: all attempted randomize requests at or after the given block were solved with errors.\r\n    ///  - 4 -> Finalizing: a randomize result was relayed already but cannot yet be considered to be final.\r\n    function getRandomizeStatus(uint256 _blockNumber)\r\n        virtual override\r\n        public view \r\n        returns (RandomizeStatus)\r\n    {\r\n        Randomize storage __request = __storage().requests[_blockNumber];\r\n        \r\n        if (_blockNumber == 0) {\r\n            return RandomizeStatus.Void;\r\n        \r\n        } else if (__request.queryId == 0) {\r\n            // if no randomize was requested on the specified block number, \r\n            // return the current status of the first randomize request after it, if any:\r\n            return getRandomizeStatus(\r\n                getRandomizeNextBlock(_blockNumber)\r\n            );\r\n        \r\n        } else if (__request.queryId == type(uint64).max) {\r\n            // if the resolution to the randomize request on the specified block number failed,\r\n            // return the current status of the randomize request after it, if any, \r\n            // or `Error` otherwise:\r\n            if (__request.nextBlock > 0) {\r\n                return getRandomizeStatus(__request.nextBlock);\r\n            } else {\r\n                return RandomizeStatus.Error;\r\n            }\r\n        \r\n        } else {\r\n            if (__request.randomness == bytes32(0)) {\r\n                // if there was a randomize request on the specified block number,\r\n                // but it hasn't been solved after some settled number of blocks,\r\n                // return the current status of the later randomize request if any,\r\n                // or still `Awaiting` otherwise:\r\n                if (\r\n                    __storage().randomizeWaitingBlocks > 0\r\n                        && block.number > _blockNumber + __storage().randomizeWaitingBlocks\r\n                        && __request.nextBlock > 0\r\n                ) {\r\n                    return getRandomizeStatus(__request.nextBlock);\r\n                } else {\r\n                    return RandomizeStatus.Awaiting;\r\n                }\r\n            \r\n            } else {\r\n                // if there was a randomize request on the specified block number,\r\n                // and it has already been resolved, return `Ready` or `Finalizing` depending \r\n                // on whether the randomness finality block has already been reached:\r\n                return (\r\n                    block.number >= __request.finality\r\n                        ? RandomizeStatus.Ready\r\n                        : RandomizeStatus.Finalizing\r\n                );\r\n            }\r\n        }\r\n    }\r\n\r\n    /// Return the number of EVM blocks after a randomize requests that have to elapse before\r\n    /// considering such request to be delayed. Results to delayed requests can potentially be\r\n    /// provided by later requests, if solved earlier. A value of zero means that randomize \r\n    /// requests will never expire. \r\n    function getRandomizeWaitingBlocks()\r\n        virtual override\r\n        external view \r\n        returns (uint16)\r\n    {\r\n        return __storage().randomizeWaitingBlocks;\r\n    }\r\n\r\n\r\n    /// Returns `true` only if a successfull resolution from the Witnet blockchain is found for the first \r\n    /// non-errored randomize request posted on or after the given block number.\r\n    function isRandomized(uint256 _blockNumber)\r\n        public view\r\n        virtual override\r\n        returns (bool)\r\n    {\r\n        return (\r\n            getRandomizeStatus(_blockNumber) == RandomizeStatus.Ready\r\n        );\r\n    }\r\n\r\n    /// Requests the Witnet blockchain to generate an unbiased 64-bit random seed.\r\n    /// @dev Only one randomize request per block will get ultimately relayed to the Witnet blockchain.\r\n    /// @return _evmUsedFunds EVM funds actually paid as randomize fee.\r\n    function randomize()\r\n        external payable\r\n        virtual override\r\n        returns (uint256 _evmUsedFunds)\r\n    {\r\n        uint256 _queryId;\r\n        uint256 _blockNumber = block.number;\r\n        if (__storage().lastRandomizeBlock < _blockNumber) {\r\n            _evmUsedFunds = msg.value;\r\n            \r\n            // Post the Witnet Randomness request:\r\n            _queryId = IWitOracleQueriable(__WIT_ORACLE).queryDataWithCallback{\r\n                value: msg.value\r\n            }(\r\n                __WIT_ORACLE_RNG_RADON_HASH,\r\n                Witnet.QuerySLA({\r\n                    witResultMaxSize: _WIT_ORACLE_RNG_MAX_RESULT_SIZE,\r\n                    witCommitteeSize: __storage().witCommitteeSize,\r\n                    witUnitaryReward: __storage().witInclusionFees\r\n                }),\r\n                Witnet.QueryCallback({\r\n                    consumer: address(this),\r\n                    gasLimit: __storage().callbackGasLimit\r\n                })\r\n            );\r\n\r\n            // Save Randomize metadata in storage:\r\n            uint256 _prevBlock = __storage().lastRandomizeBlock;\r\n            Randomize storage __request = __storage().requests[_blockNumber];\r\n            __request.queryId = uint64(_queryId);\r\n            __request.prevBlock = uint64(_prevBlock);\r\n            __storage().requests[_prevBlock].nextBlock = uint64(_blockNumber);\r\n            __storage().lastRandomizeBlock = uint64(_blockNumber);\r\n            __storage().blocks[Witnet.QueryId.wrap(uint64(_queryId))] = _blockNumber;\r\n\r\n            // Emit event only on first successful randomize within one block:\r\n            // solhint-disable-next-line avoid-tx-origin\r\n            emit Randomizing(\r\n                _msgSender(), \r\n                block.number,\r\n                Witnet.QueryId.wrap(uint64(_queryId))\r\n            );\r\n        \r\n        } else {\r\n            _queryId = __storage().requests[_blockNumber].queryId;\r\n        }\r\n\r\n        // Transfer back unused funds:\r\n        if (_evmUsedFunds < msg.value) {\r\n            payable(msg.sender).transfer(msg.value - _evmUsedFunds);\r\n        }\r\n    }\r\n\r\n    /// Verifies that the specified randomness seed was actually generated on the Witnet blockchain,\r\n    /// and was actually used for producing the randomness seed returned by `fetchRandomnessAfter`.\r\n    function verifyRandomnessAfter(uint256 blockNumber, bytes32 witnetRandomness)\r\n        external view \r\n        virtual override\r\n        returns (bool)\r\n    {\r\n        return (\r\n            isRandomized(blockNumber)\r\n                && fetchRandomnessAfter(blockNumber) == keccak256(abi.encode(\r\n                    blockNumber,\r\n                    bytes8(witnetRandomness)\r\n                ))\r\n        );\r\n    }\r\n\r\n    /// The Wit/Oracle core address accepted as source of entropy.\r\n    function witOracle() virtual override external view returns (address) {\r\n        return __WIT_ORACLE;\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitRandomnessAdmin -------------------------------------------------------------------------------------\r\n\r\n    function acceptOwnership()\r\n        virtual override (IWitRandomnessAdmin, Ownable2Step)\r\n        public\r\n    {\r\n        Ownable2Step.acceptOwnership();\r\n    }\r\n\r\n    function owner()\r\n        virtual override (IWitRandomnessAdmin, Ownable)\r\n        public view \r\n        returns (address)\r\n    {\r\n        return Ownable.owner();\r\n    }\r\n\r\n    function pendingOwner() \r\n        virtual override (IWitRandomnessAdmin, Ownable2Step)\r\n        public view\r\n        returns (address)\r\n    {\r\n        return Ownable2Step.pendingOwner();\r\n    }\r\n    \r\n    function transferOwnership(address _newOwner)\r\n        virtual override (IWitRandomnessAdmin, Ownable2Step)\r\n        public \r\n        onlyOwner\r\n    {\r\n        Ownable.transferOwnership(_newOwner);\r\n    }\r\n\r\n    function settleConsumer(address _consumer, uint24 _maxCallbackGasLimit)\r\n        virtual override\r\n        external\r\n        onlyOnClones\r\n        onlyOwner\r\n    {\r\n        if (\r\n            _consumer != address(0)\r\n                && _consumer.code.length > 0\r\n        ) {\r\n            try IWitRandomnessConsumer(_consumer).witRandomness() returns (IWitRandomness _witRandomness) {\r\n                if (address(_witRandomness) == address(this)) {\r\n                    _require(_maxCallbackGasLimit >= _WIT_ORACLE_MIN_CALLBACK_GAS_LIMIT, \"low gas limit\");\r\n                    __storage().consumer = _consumer;\r\n                    __storage().callbackGasLimit = _maxCallbackGasLimit;\r\n                    return;\r\n                }\r\n            } catch (bytes memory) {}\r\n        } \r\n        _revert(\"invalid consumer\");   \r\n    }\r\n\r\n    function settleQueryParams(\r\n            uint24 _callbackGasLimit,\r\n            uint16 _extraFeePercentage,\r\n            uint16 _minWitCommitteeSize,\r\n            uint64 _minWitInclusionFees\r\n        )\r\n        virtual override\r\n        external\r\n        onlyOwner\r\n    {\r\n        // validate ranges:\r\n        _require(\r\n            _callbackGasLimit >= _WIT_ORACLE_MIN_CALLBACK_GAS_LIMIT\r\n                && _minWitCommitteeSize > 0 \r\n                && _minWitCommitteeSize <= 127, \r\n            \"invalid params\"\r\n        );\r\n        __storage().callbackGasLimit = _callbackGasLimit;\r\n        __storage().extraFeePercentage = _extraFeePercentage;\r\n        __storage().witCommitteeSize = _minWitCommitteeSize;\r\n        __storage().witInclusionFees = _minWitInclusionFees;\r\n    }\r\n\r\n\r\n    function settleRandomizeWaitingBlocks(uint16 _randomizeWaitingBlocks)\r\n        virtual override\r\n        external\r\n        onlyOwner\r\n    {\r\n        __storage().randomizeWaitingBlocks = _randomizeWaitingBlocks;\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- IWitOracleQueriableConsumer --------------------------------------------------------------------------------\r\n\r\n    /// Method to be called from the witOracle contract as soon as the given Witnet `queryId` gets reported.\r\n    /// @dev It should revert if called from an address different to the WitOracle instance being used by consumer.\r\n    /// @param queryId The unique identifier of the Witnet query being reported.\r\n    /// @param queryResult Abi-encoded Witnet.DataResult containing the CBOR-encoded query's result, and metadata.\r\n    function reportWitOracleQueryResult(\r\n            uint256 queryId,\r\n            bytes calldata queryResult\r\n        ) \r\n        virtual override\r\n        external\r\n    {\r\n        uint256 _randomizeBlock = __storage().blocks[Witnet.QueryId.wrap(uint64(queryId))];\r\n        _require(_randomizeBlock > 0, \"invalid query\");\r\n        _require(reportableFrom(msg.sender), \"invalid oracle\");\r\n\r\n        Randomize storage __request = __storage().requests[_randomizeBlock];\r\n\r\n        Witnet.DataResult memory _queryResult = abi.decode(queryResult, (Witnet.DataResult));\r\n        if (\r\n            __request.randomness == 0\r\n                && __storage().randomizeWaitingBlocks > 0\r\n                && block.number > _randomizeBlock + __storage().randomizeWaitingBlocks\r\n                && __request.nextBlock > 0\r\n        ) {\r\n            // ignore the query result if it's provided too late and there was a later randomize attempt:\r\n            __request.queryId = type(uint64).max;\r\n\r\n        } else {\r\n            bytes8 _randomness = bytes8(0);\r\n            if (_queryResult.status == Witnet.ResultStatus.NoErrors) {\r\n                if (uint64(queryId) != __request.queryId) {\r\n                    // if a non-finalized error was disputed and eventually won:\r\n                    __request.queryId = uint64(queryId);\r\n                }\r\n                _randomness = bytes8(_queryResult.fetchBytes32());\r\n            } else {\r\n                __request.queryId = type(uint64).max;\r\n            }\r\n            __request.finality = uint64(_queryResult.finality);\r\n            __request.randomness = _randomness;\r\n\r\n            address _consumer = __storage().consumer;\r\n            if (_consumer != address(0)) {\r\n                try IWitRandomnessConsumer(_consumer).reportRandomness(\r\n                    _randomness,\r\n                    _randomizeBlock,\r\n                    _queryResult.finality,\r\n                    _queryResult.timestamp,\r\n                    _queryResult.drTxHash\r\n                \r\n                ) {} catch (bytes memory) {\r\n                    // no matter if reporting randomness to the consumer fails,\r\n                    // this transaction must prevail so already verified randomness\r\n                    // gets preserved in storage.\r\n                }\r\n            }\r\n\r\n            emit Randomized(\r\n                _randomizeBlock, \r\n                _queryResult.finality,\r\n                _randomness\r\n            );\r\n        }\r\n    }\r\n\r\n    /// Determines if Witnet queries can be reported from given address.\r\n    /// @dev In practice, must only be true on the WitOracle address that's being used by\r\n    /// @dev the consumer contract to post data queries. \r\n    function reportableFrom(address _from) \r\n        virtual override \r\n        public view \r\n        returns (bool)\r\n    {\r\n        return (\r\n            _from == address(__WIT_ORACLE)\r\n        );\r\n    }\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Internal methods -------------------------------------------------------------------------------------------\r\n\r\n    function _getRandomizeQueryId(uint256 _blockNumber)\r\n        virtual internal view \r\n        returns (uint64)\r\n    {\r\n        Randomize storage __request = __storage().requests[_blockNumber];\r\n        if (__request.queryId == 0) {\r\n            return _getRandomizeQueryId(\r\n                getRandomizeNextBlock(_blockNumber)\r\n            );\r\n\r\n        } else if (__request.queryId == type(uint64).max) {\r\n            return (\r\n                __request.nextBlock > 0 \r\n                    ? _getRandomizeQueryId(__request.nextBlock) \r\n                    : __request.queryId\r\n            );\r\n        \r\n        } else {\r\n            if (__request.randomness == bytes8(0)) {\r\n                if (\r\n                    __storage().randomizeWaitingBlocks > 0 \r\n                        && block.number > _blockNumber + __storage().randomizeWaitingBlocks\r\n                        && __request.nextBlock > 0\r\n                ) {\r\n                    return _getRandomizeQueryId(__request.nextBlock);\r\n                }\r\n            }\r\n            return __request.queryId;\r\n        }\r\n    }\r\n\r\n    function _fetchRandomnessAfter(uint256 _blockNumber)\r\n        virtual internal view \r\n        returns (bytes8 _randomness)\r\n    {\r\n        Randomize storage __request = __storage().requests[_blockNumber];\r\n        if (__request.queryId == 0) {\r\n            return _fetchRandomnessAfter(\r\n                getRandomizeNextBlock(_blockNumber)\r\n            );\r\n        \r\n        } else if (__request.queryId == type(uint64).max) {\r\n            _require(\r\n                __request.nextBlock > 0,\r\n                \"failed: retry randomize\"\r\n            );\r\n            return _fetchRandomnessAfter(\r\n                __request.nextBlock\r\n            );\r\n        \r\n        } else if (__request.randomness == bytes8(0)) {\r\n            if (\r\n                __storage().randomizeWaitingBlocks > 0 \r\n                    && block.number > _blockNumber + __storage().randomizeWaitingBlocks\r\n            ) {\r\n                _require(\r\n                    __request.nextBlock > 0,\r\n                    \"delayed: keep waiting or retry randomize\"\r\n                );\r\n                return _fetchRandomnessAfter(__request.nextBlock);\r\n            } else {\r\n                _revert(\"pending randomize\");\r\n            }\r\n        \r\n        } else {\r\n            _require(\r\n                block.number >= __request.finality,\r\n                string(abi.encodePacked(\r\n                    \"finalizing on block #\",\r\n                    Witnet.toString(uint256(__request.finality))\r\n                ))\r\n            );\r\n            return __request.randomness;\r\n        }\r\n    }\r\n\r\n    /// @dev Recursively searches for the number of the first block after the given one in which a Witnet \r\n    /// @dev randomness request was posted. Returns 0 if none found.\r\n    function _searchNextBlock(uint256 _target, uint256 _latest) internal view returns (uint256) {\r\n        return (_target >= _latest \r\n            ? __storage().requests[_latest].nextBlock\r\n            : _searchNextBlock(_target, __storage().requests[_latest].prevBlock)\r\n        );\r\n    }\r\n\r\n    /// @dev Recursively searches for the number of the first block before the given one in which a Witnet \r\n    /// @dev randomness request was posted. Returns 0 if none found.\r\n    function _searchPrevBlock(uint256 _target, uint256 _latest) internal view returns (uint256) {\r\n        return (_target > _latest\r\n            ? _latest\r\n            : _searchPrevBlock(_target, __storage().requests[_latest].prevBlock)\r\n        );\r\n    }\r\n\r\n    function __storage() internal pure returns (Storage storage _ptr) {\r\n        assembly {\r\n            _ptr.slot := _WIT_RANDOMNESS_STORAGE_SLOT\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleBasePushOnly.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../WitOraclePushOnly.sol\";\r\nimport \"../../WitOracleRadonRegistry.sol\";\r\n\r\n/// @title Push-only WitOracle base implementation.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleBasePushOnly\r\n    is \r\n        WitOraclePushOnly\r\n{\r\n    function channel() virtual override public view returns (bytes4) {\r\n        return Witnet.channel(address(this));\r\n    }\r\n\r\n    IWitOracleRadonRegistry public immutable override registry;\r\n\r\n    constructor(WitOracleRadonRegistry _registry) {\r\n        _require(\r\n            address(_registry).code.length > 0,\r\n            \"inexistent registry\"\r\n        );\r\n        _require(\r\n            _registry.specs() == (\r\n                type(IWitAppliance).interfaceId\r\n                    ^ type(IWitOracleRadonRegistry).interfaceId\r\n            ), \"uncompliant registry\"\r\n        );\r\n        registry = _registry;\r\n    }\r\n\r\n    // ================================================================================================================\r\n    // --- Internal functions -----------------------------------------------------------------------------------------\r\n\r\n    function _revertUnhandledException() virtual internal view {\r\n        _revert(_revertUnhandledExceptionReason());\r\n    }\r\n\r\n    function _revertUnhandledExceptionReason() virtual internal pure returns (string memory);\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleBasePushOnlyTrustable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleBasePushOnly.sol\";\r\nimport \"../WitnetUpgradableBase.sol\";\r\nimport \"../../data/WitOracleDataLib.sol\";\r\nimport \"../../interfaces/IWitOracleTrustableAdmin.sol\";\r\n\r\n/// @title Push-only WitOracle \"trustable\" base implementation.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleBasePushOnlyTrustable\r\n    is \r\n        WitnetUpgradableBase,\r\n        WitOracleBasePushOnly,\r\n        IWitOracleTrustableAdmin\r\n{\r\n    using Witnet for Witnet.DataPushReport;\r\n\r\n    constructor(bytes32 _versionTag)\r\n        Ownable(msg.sender)\r\n        WitnetUpgradableBase(\r\n            true, \r\n            _versionTag,\r\n            \"io.witnet.proxiable.board\"\r\n        )\r\n    {}\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Upgradeable ------------------------------------------------------------------------------------------------\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    function __initializeUpgradableData(bytes memory _initData) virtual override internal {\r\n        WitOracleDataLib.setReporters(abi.decode(_initData, (address[])));\r\n    }\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- IWitOracle -------------------------------------------------------------------------------------------------\r\n\r\n    function parseDataReport(Witnet.DataPushReport calldata _report, bytes calldata _signature)\r\n        virtual override public view\r\n        returns (Witnet.DataResult memory _result)\r\n    {\r\n        (, _result) = WitOracleDataLib.parseDataReport(_report, _signature);\r\n    }\r\n\r\n    function pushDataReport(Witnet.DataPushReport calldata _report, bytes calldata _signature)\r\n        virtual override external\r\n        returns (Witnet.DataResult memory)\r\n    {\r\n        (address _evmSigner, Witnet.DataResult memory _result) = WitOracleDataLib.parseDataReport(_report, _signature);\r\n        emit WitOracleReport(\r\n            tx.origin, \r\n            msg.sender, \r\n            _evmSigner, \r\n            _report.witDrTxHash,\r\n            _report.queryRadHash,\r\n            _report.queryParams,\r\n            _report.resultTimestamp,\r\n            _report.resultCborBytes\r\n        );\r\n        return _result;\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- IWitOracleTrustableAdmin ----------------------------------------------------------------------------------------\r\n\r\n    /// Tells whether given address is included in the active reporters control list.\r\n    /// @param _queryResponseReporter The address to be checked.\r\n    function isReporter(address _queryResponseReporter) virtual override public view returns (bool) {\r\n        return WitOracleDataLib.isReporter(_queryResponseReporter);\r\n    }\r\n\r\n    /// Adds given addresses to the active reporters control list.\r\n    /// @dev Can only be called from the owner address.\r\n    /// @dev Emits the `ReportersSet` event. \r\n    /// @param _queryResponseReporters List of addresses to be added to the active reporters control list.\r\n    function setReporters(address[] calldata _queryResponseReporters)\r\n        virtual override public\r\n        onlyOwner\r\n    {\r\n        WitOracleDataLib.setReporters(_queryResponseReporters);\r\n    }\r\n\r\n    /// Removes given addresses from the active reporters control list.\r\n    /// @dev Can only be called from the owner address.\r\n    /// @dev Emits the `ReportersUnset` event. \r\n    /// @param _exReporters List of addresses to be added to the active reporters control list.\r\n    function unsetReporters(address[] calldata _exReporters)\r\n        virtual override public\r\n        onlyOwner\r\n    {\r\n        WitOracleDataLib.unsetReporters(_exReporters);\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Internal functions -----------------------------------------------------------------------------------------\r\n\r\n    function _revertUnhandledExceptionReason() \r\n        virtual override internal pure returns (string memory)\r\n    {\r\n        return string(abi.encodePacked(\r\n            type(WitOracleDataLib).name,\r\n            \": unhandled assertion\"\r\n        ));\r\n    }\r\n\r\n    /// Returns storage pointer to contents of 'WitOracleDataLib.Storage' struct.\r\n    function __storage() virtual internal pure returns (WitOracleDataLib.Storage storage _ptr) {\r\n      return WitOracleDataLib.data();\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleBasePushOnlyTrustless.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleBasePushOnly.sol\";\r\n\r\nimport \"../../data/WitOracleTrustlessDataLib.sol\";\r\nimport \"../../data/WitOracleDataLib.sol\";\r\n\r\n/// @title Push-only WitOracle \"trustless\" base implementation.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleBasePushOnlyTrustless\r\n    is \r\n        WitOracleBasePushOnly,\r\n        IWitOracleTrustless\r\n{\r\n    using Witnet for Witnet.DataPushReport;\r\n\r\n    constructor() {\r\n        // store genesis beacon:\r\n        WitOracleTrustlessDataLib.data().beacons[\r\n            Witnet.WIT_2_GENESIS_BEACON_INDEX\r\n        ] = Witnet.Beacon({\r\n            index: Witnet.WIT_2_GENESIS_BEACON_INDEX,\r\n            prevIndex: Witnet.WIT_2_GENESIS_BEACON_PREV_INDEX,\r\n            prevRoot: Witnet.WIT_2_GENESIS_BEACON_PREV_ROOT,\r\n            ddrTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DDR_TALLIES_MERKLE_ROOT,\r\n            droTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DRO_TALLIES_MERKLE_ROOT,\r\n            nextCommitteeAggPubkey: [\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_0,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_1,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_2,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_3\r\n            ]\r\n        });\r\n    }\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- IWitOracle -------------------------------------------------------------------------------------------------\r\n\r\n    function parseDataReport(Witnet.DataPushReport calldata _report, bytes calldata _signature)\r\n        virtual override public view\r\n        returns (Witnet.DataResult memory _result)\r\n    {\r\n        (, _result) = WitOracleDataLib.parseDataReport(_report, _signature);\r\n    }\r\n\r\n    function pushDataReport(Witnet.DataPushReport calldata _report, bytes calldata _signature)\r\n        virtual override external\r\n        returns (Witnet.DataResult memory)\r\n    {\r\n        (address _evmSigner, Witnet.DataResult memory _result) = WitOracleDataLib.parseDataReport(_report, _signature);\r\n        emit WitOracleReport(\r\n            tx.origin, \r\n            msg.sender, \r\n            _evmSigner, \r\n            _report.witDrTxHash,\r\n            _report.queryRadHash,\r\n            _report.queryParams,\r\n            _report.resultTimestamp,\r\n            _report.resultCborBytes\r\n        );\r\n        return _result;\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- IWitOracleTrustless -------------------------------------------------------------------------------------------\r\n\r\n    function determineBeaconIndexFromTimestamp(Witnet.Timestamp timestamp)\r\n        virtual override\r\n        external pure\r\n        returns (uint64)\r\n    {\r\n        return Witnet.determineBeaconIndexFromTimestamp(timestamp);\r\n    }\r\n    \r\n    function determineEpochFromTimestamp(Witnet.Timestamp timestamp)\r\n        virtual override\r\n        external pure\r\n        returns (Witnet.BlockNumber)\r\n    {\r\n        return Witnet.determineEpochFromTimestamp(timestamp);\r\n    }\r\n\r\n    function getBeaconByIndex(uint32 index)\r\n        virtual override\r\n        public view\r\n        returns (Witnet.Beacon memory)\r\n    {\r\n        return WitOracleTrustlessDataLib.seekBeacon(index);\r\n    }\r\n\r\n    function getGenesisBeacon() \r\n        virtual override \r\n        external pure\r\n        returns (Witnet.Beacon memory)\r\n    {\r\n        return Witnet.Beacon({\r\n            index: Witnet.WIT_2_GENESIS_BEACON_INDEX,\r\n            prevIndex: Witnet.WIT_2_GENESIS_BEACON_PREV_INDEX,\r\n            prevRoot: Witnet.WIT_2_GENESIS_BEACON_PREV_ROOT,\r\n            ddrTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DDR_TALLIES_MERKLE_ROOT,\r\n            droTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DRO_TALLIES_MERKLE_ROOT,\r\n            nextCommitteeAggPubkey: [\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_0,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_1,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_2,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_3\r\n            ]\r\n        });\r\n    }\r\n\r\n    function getLastKnownBeacon() \r\n        virtual override\r\n        public view\r\n        returns (Witnet.Beacon memory)\r\n    {\r\n        return WitOracleTrustlessDataLib.getLastKnownBeacon();\r\n    }\r\n\r\n    function getLastKnownBeaconIndex()\r\n        virtual override\r\n        public view\r\n        returns (uint32)\r\n    {\r\n        return uint32(WitOracleTrustlessDataLib.getLastKnownBeaconIndex());\r\n    }\r\n\r\n    function rollupBeacons(Witnet.FastForward[] calldata _witOracleRollup)\r\n        virtual override public \r\n        returns (Witnet.Beacon memory)\r\n    {\r\n        try WitOracleTrustlessDataLib.rollupBeacons(\r\n            _witOracleRollup\r\n        ) returns (\r\n            Witnet.Beacon memory _witOracleHead\r\n        ) {\r\n            return _witOracleHead;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandledException();\r\n        }\r\n    }\r\n    \r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Internal functions -----------------------------------------------------------------------------------------\r\n\r\n    function _revertUnhandledExceptionReason() \r\n        virtual override internal pure returns (string memory)\r\n    {\r\n        return string(abi.encodePacked(\r\n            type(WitOracleTrustlessDataLib).name,\r\n            \": unhandled assertion\"\r\n        ));\r\n    }\r\n\r\n    // /// Returns storage pointer to contents of 'WitOracleDataLib.Storage' struct.\r\n    // function __storage() virtual internal pure returns (WitOracleDataLib.Storage storage _ptr) {\r\n    //   return WitOracleDataLib.data();\r\n    // }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleBasePushOnlyUpgradable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleBasePushOnlyTrustless.sol\";\r\nimport \"../WitnetUpgradableBase.sol\";\r\nimport \"../../data/WitOracleDataLib.sol\";\r\n\r\n/// @title Push-only WitOracle \"trustless\" but yet \"upgradable\" base implementation.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleBasePushOnlyUpgradable\r\n    is \r\n        WitnetUpgradableBase,\r\n        WitOracleBasePushOnlyTrustless\r\n{\r\n    constructor(bytes32 _versionTag, bool _upgradable)\r\n        Ownable(msg.sender)\r\n        WitnetUpgradableBase(_upgradable, _versionTag, \"io.witnet.proxiable.board\")\r\n    {}\r\n\r\n\r\n    // ================================================================================================================\r\n    // ---Upgradeable -------------------------------------------------------------------------------------------------\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    function __initializeUpgradableData(bytes memory _initData) virtual override internal {\r\n        if (__proxiable().codehash == bytes32(0)) {\r\n            // upon first initialization, store genesis beacon\r\n            WitOracleTrustlessDataLib.data().beacons[\r\n                Witnet.WIT_2_GENESIS_BEACON_INDEX\r\n            ] = Witnet.Beacon({\r\n                index: Witnet.WIT_2_GENESIS_BEACON_INDEX,\r\n                prevIndex: Witnet.WIT_2_GENESIS_BEACON_PREV_INDEX,\r\n                prevRoot: Witnet.WIT_2_GENESIS_BEACON_PREV_ROOT,\r\n                ddrTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DDR_TALLIES_MERKLE_ROOT,\r\n                droTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DRO_TALLIES_MERKLE_ROOT,\r\n                nextCommitteeAggPubkey: [\r\n                    Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_0,\r\n                    Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_1,\r\n                    Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_2,\r\n                    Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_3\r\n                ]\r\n            });\r\n        } else {\r\n            // otherwise, store beacon read from _initData, if any\r\n            if (_initData.length > 0) {\r\n                Witnet.Beacon memory _initBeacon = abi.decode(_initData, (Witnet.Beacon));\r\n                WitOracleTrustlessDataLib.data().beacons[_initBeacon.index] = _initBeacon;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleBaseQueriable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleBasePushOnly.sol\";\r\n\r\nimport \"../../WitOracle.sol\";\r\nimport \"../../data/WitOracleDataLib.sol\";\r\nimport \"../../interfaces/IWitOracleQueriableConsumer.sol\";\r\nimport \"../../libs/WitOracleResultStatusLib.sol\";\r\nimport \"../../patterns/Payable.sol\";\r\n\r\n/// @title Queriable WitOracle base implementation.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleBaseQueriable\r\n    is \r\n        Payable,\r\n        WitOracle\r\n{\r\n    using Witnet for Witnet.QuerySLA;\r\n    using WitOracleDataLib for WitOracleDataLib.Storage;\r\n\r\n    function channel() virtual override public view returns (bytes4) {\r\n        return Witnet.channel(address(this));\r\n    }\r\n\r\n    IWitOracleRadonRegistry public immutable override registry;\r\n\r\n    uint256 internal immutable __reportResultGasBase;\r\n    uint256 internal immutable __reportResultWithCallbackGasBase;\r\n    uint256 internal immutable __reportResultWithCallbackRevertGasBase;\r\n    uint256 internal immutable __sstoreFromZeroGas;\r\n\r\n    modifier checkQueryCallback(Witnet.QueryCallback memory callback) virtual {\r\n        _require(\r\n            address(callback.consumer).code.length > 0\r\n                && IWitOracleQueriableConsumer(callback.consumer).reportableFrom(address(this))\r\n                && callback.gasLimit > 0,\r\n            \"invalid callback\"\r\n        ); _;\r\n    }\r\n\r\n    modifier checkQueryReward(uint256 _msgValue, uint256 _baseFee) virtual {\r\n        _require(\r\n            _msgValue >= _baseFee, \r\n            \"insufficient reward\"\r\n        ); \r\n        _require(\r\n            _msgValue <= _baseFee * 10,\r\n            \"too much reward\"\r\n        ); _;\r\n    }\r\n\r\n    modifier checkQuerySLA(Witnet.QuerySLA memory sla) virtual {\r\n        _require(\r\n            sla.isValid(), \r\n            \"invalid SLA\"\r\n        ); _;\r\n    }\r\n\r\n    /// Asserts the given query is currently in the given status.\r\n    modifier inStatus(uint256 _queryId, Witnet.QueryStatus _status) {\r\n        if (getQueryStatus(_queryId) != _status) {\r\n            _revert(WitOracleDataLib.notInStatusRevertMessage(_status));\r\n        } else {\r\n            _;\r\n        }\r\n    }\r\n\r\n    /// Asserts the caller actually posted the referred query.\r\n    modifier onlyRequester(uint256 _queryId) {\r\n        _require(\r\n            msg.sender == WitOracleDataLib.seekQueryRequest(_queryId).requester, \r\n            \"not the requester\"\r\n        ); _;\r\n    }\r\n\r\n    struct EvmImmutables {\r\n        uint32 reportResultGasBase;\r\n        uint32 reportResultWithCallbackGasBase;\r\n        uint32 reportResultWithCallbackRevertGasBase;\r\n        uint32 sstoreFromZeroGas;\r\n    }\r\n    \r\n    constructor(\r\n            EvmImmutables memory _immutables,\r\n            WitOracleRadonRegistry _registry\r\n        )\r\n    {\r\n        _require(\r\n            address(_registry).code.length > 0,\r\n            \"inexistent registry\"\r\n        );\r\n        _require(\r\n            _registry.specs() == type(IWitOracleRadonRegistry).interfaceId, \r\n            \"uncompliant registry\"\r\n        );\r\n        registry = _registry;\r\n\r\n        __reportResultGasBase = _immutables.reportResultGasBase;\r\n        __reportResultWithCallbackGasBase = _immutables.reportResultWithCallbackGasBase;\r\n        __reportResultWithCallbackRevertGasBase = _immutables.reportResultWithCallbackRevertGasBase;\r\n        __sstoreFromZeroGas = _immutables.sstoreFromZeroGas;\r\n    }\r\n\r\n    function getQueryStatus(uint256) virtual public view returns (Witnet.QueryStatus);\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Payable ----------------------------------------------------------------------------------------------------\r\n\r\n    /// Gets current transaction price.\r\n    function _getGasPrice() internal view virtual override returns (uint256) {\r\n        return tx.gasprice;\r\n    }\r\n\r\n    /// Gets message actual sender.\r\n    function _getMsgSender() internal view virtual override returns (address) {\r\n        return msg.sender;\r\n    }\r\n    \r\n    /// Gets current payment value.\r\n    function _getMsgValue() internal view virtual override returns (uint256) {\r\n        return msg.value;\r\n    }\r\n\r\n    /// Transfers ETHs to given address.\r\n    /// @param _to Recipient address.\r\n    /// @param _amount Amount of ETHs to transfer.\r\n    function __safeTransferTo(address payable _to, uint256 _amount) virtual override internal {\r\n        payable(_to).transfer(_amount);\r\n    }\r\n    \r\n    \r\n    // ================================================================================================================\r\n    // --- IWitOracle (partial) ---------------------------------------------------------------------------------------\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @param _evmGasPrice Expected gas price to pay upon posting the data request.\r\n    function estimateBaseFee(uint256 _evmGasPrice)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return _evmGasPrice * (\r\n            __reportResultGasBase \r\n                + 4 * __sstoreFromZeroGas\r\n        );\r\n    }\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request with a callback.\r\n    /// @param _evmGasPrice Expected gas price to pay upon posting the data request.\r\n    /// @param _evmCallbackGasLimit Maximum gas to be spent when reporting the data request result.\r\n    function estimateBaseFeeWithCallback(uint256 _evmGasPrice, uint24 _evmCallbackGasLimit)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        uint _reportResultWithCallbackGasThreshold = (\r\n            __reportResultWithCallbackRevertGasBase\r\n                + 3 * __sstoreFromZeroGas\r\n        );\r\n        if (\r\n            _evmCallbackGasLimit < _reportResultWithCallbackGasThreshold\r\n                || __reportResultWithCallbackGasBase + _evmCallbackGasLimit < _reportResultWithCallbackGasThreshold\r\n        ) {\r\n            return (\r\n                _evmGasPrice\r\n                    * _reportResultWithCallbackGasThreshold\r\n            );\r\n        } else {\r\n            return (\r\n                _evmGasPrice \r\n                    * (\r\n                        __reportResultWithCallbackGasBase\r\n                            + _evmCallbackGasLimit\r\n                    )\r\n            );\r\n        }\r\n    }\r\n\r\n    /// @notice Estimate the extra reward (i.e. over the base fee) to be paid when posting a new\r\n    /// @notice data query in order to avoid getting provable \"too low incentives\" results from\r\n    /// @notice the Wit/Oracle blockchain. \r\n    /// @dev The extra fee gets calculated in proportion to:\r\n    /// @param _evmGasPrice Tentative EVM gas price at the moment the query result is ready.\r\n    /// @param _evmWitPrice Tentative nanoWit price in Wei at the moment the query is solved on the Wit/Oracle blockchain.\r\n    /// @param _querySLA The query SLA data security parameters as required for the Wit/Oracle blockchain. \r\n    function estimateExtraFee(\r\n            uint256 _evmGasPrice, \r\n            uint256 _evmWitPrice, \r\n            Witnet.QuerySLA memory _querySLA\r\n        )\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return (\r\n            _evmWitPrice * _querySLA.witUnitaryReward\r\n                + (_querySLA.witResultMaxSize > 32\r\n                    ? _evmGasPrice * __sstoreFromZeroGas * ((_querySLA.witResultMaxSize - 32) / 32)\r\n                    : 0\r\n                )\r\n        );\r\n    }\r\n\r\n    /// Gets the whole Query data contents, if any, no matter its current status.\r\n    function getQuery(Witnet.QueryId _queryId)\r\n      public view\r\n      virtual override\r\n      returns (Witnet.Query memory)\r\n    {\r\n        return WitOracleDataLib.getQuery(_queryId);\r\n    }\r\n\r\n    /// @notice Gets the current EVM reward the report can claim, if not done yet.\r\n    function getQueryEvmReward(uint256 _queryId) \r\n        external view \r\n        virtual override\r\n        returns (Witnet.QueryEvmReward)\r\n    {\r\n        return __storage().queries[_queryId].reward;\r\n    }\r\n\r\n    /// @notice Retrieves the RAD hash and SLA parameters of the given query.\r\n    /// @param _queryId The unique query identifier.\r\n    function getQueryRequest(Witnet.QueryId _queryId)\r\n        external view override\r\n        returns (Witnet.QueryRequest memory)\r\n    {\r\n        return WitOracleDataLib.getQueryRequest(_queryId);\r\n    }\r\n\r\n    /// Retrieves the Witnet-provable result, and metadata, to a previously posted request.    \r\n    /// @dev Fails if the `_queryId` is not in 'Reported' status.\r\n    /// @param _queryId The unique query identifier\r\n    function getQueryResponse(Witnet.QueryId _queryId)\r\n        virtual override public view\r\n        returns (Witnet.QueryResponse memory)\r\n    {\r\n        return WitOracleDataLib.getQueryResponse(_queryId);\r\n    }\r\n\r\n    function getQueryResult(uint256 _queryId)\r\n        virtual override public view \r\n        returns (Witnet.DataResult memory)\r\n    {\r\n        return WitOracleDataLib.getQueryResult(_queryId);\r\n    }\r\n\r\n    function getQueryResultStatus(uint256 _queryId)\r\n        virtual override public view \r\n        returns (Witnet.ResultStatus)\r\n    {\r\n        return WitOracleDataLib.getQueryResultStatus(_queryId);\r\n    }\r\n\r\n    function getQueryResultStatusDescription(uint256 _queryId)\r\n        virtual override public view\r\n        returns (string memory)\r\n    {\r\n        return WitOracleResultStatusLib.toString(\r\n            abi.encode(WitOracleDataLib.getQueryResult(_queryId))\r\n        );\r\n    }\r\n\r\n    /// @notice Gets query's result back tracing trails\r\n    function getQueryResultTrails(uint256 _queryId) \r\n        virtual override\r\n        external view returns (\r\n            bytes32 queryUUID,\r\n            Witnet.TransactionHash resultDrTxHash,\r\n            Witnet.Timestamp resultTimestamp,\r\n            uint256 resultFinalityBlock\r\n        )\r\n    {\r\n        WitOracleDataLib.Query storage __query = WitOracleDataLib.seekQuery(_queryId);\r\n        queryUUID = bytes32(Witnet.QueryUUID.unwrap(__query.uuid));\r\n        resultDrTxHash = Witnet.TransactionHash.wrap(__query.response.resultDrTxHash);\r\n        resultTimestamp = Witnet.Timestamp.wrap(__query.response.resultTimestamp);\r\n        resultFinalityBlock = Witnet.BlockNumber.unwrap(__query.checkpoint);\r\n    }\r\n\r\n    function getQueryStatusString(uint256 _queryId)\r\n        virtual override external view \r\n        returns (string memory)\r\n    {\r\n        return WitOracleDataLib.toString(\r\n            getQueryStatus(_queryId)\r\n        );\r\n    }\r\n\r\n    function getQueryStatusBatch(uint256[] calldata _queryIds)\r\n        virtual override\r\n        public view\r\n        returns (Witnet.QueryStatus[] memory _status)\r\n    {\r\n        _status = new Witnet.QueryStatus[](_queryIds.length);\r\n        for (uint _ix = 0; _ix < _queryIds.length; _ix ++) {\r\n            _status[_ix] = getQueryStatus(_queryIds[_ix]);\r\n        }\r\n    }\r\n\r\n    /// @notice Returns next query id to be generated by the Witnet Request Board.\r\n    function getNextQueryId()\r\n        external view\r\n        override\r\n        returns (Witnet.QueryId)\r\n    {\r\n        return Witnet.QueryId.wrap(__storage().nonce + 1);\r\n    }\r\n\r\n    function queryData(\r\n            Witnet.RadonHash _queryRAD, \r\n            Witnet.QuerySLA memory _querySLA\r\n        )\r\n        virtual override\r\n        public payable\r\n        checkQueryReward(\r\n            _getMsgValue(),\r\n            estimateBaseFee(_getGasPrice())\r\n        )\r\n        checkQuerySLA(_querySLA)\r\n        returns (uint256 _queryId)\r\n    {\r\n        _queryId = __queryData(\r\n            _getMsgSender(), 0,\r\n            uint72(_getMsgValue()),\r\n            _queryRAD,\r\n            _querySLA\r\n        );\r\n        // Let Web3 observers know that a new request has been posted\r\n        emit WitOracleQuery(\r\n            _getMsgSender(),\r\n            _getGasPrice(),\r\n            _getMsgValue(),\r\n            Witnet.QueryId.wrap(uint64(_queryId)),\r\n            _queryRAD, \r\n            _querySLA\r\n        );\r\n    }\r\n   \r\n    function queryDataWithCallback(\r\n            Witnet.RadonHash _queryRAD, \r\n            Witnet.QuerySLA memory _querySLA,\r\n            Witnet.QueryCallback memory _queryCallback\r\n        )\r\n        virtual override\r\n        public payable\r\n        checkQueryReward(\r\n            _getMsgValue(),\r\n            estimateBaseFeeWithCallback(\r\n                _getGasPrice(),  \r\n                _queryCallback.gasLimit\r\n            )\r\n        )\r\n        checkQuerySLA(_querySLA)\r\n        checkQueryCallback(_queryCallback)\r\n        returns (uint256 _queryId)\r\n    {\r\n        _queryId = __queryData(\r\n            _queryCallback.consumer,\r\n            _queryCallback.gasLimit,\r\n            uint72(_getMsgValue()),\r\n            _queryRAD,\r\n            _querySLA\r\n        );\r\n        emit WitOracleQuery(\r\n            _getMsgSender(),\r\n            _getGasPrice(),\r\n            _getMsgValue(),\r\n            Witnet.QueryId.wrap(uint64(_queryId)), \r\n            _queryRAD, \r\n            _querySLA\r\n        );\r\n    } \r\n\r\n    /// Increments the reward of a previously posted request by adding the transaction value to it.\r\n    /// @dev Fails if the `_queryId` is not in 'Posted' status.\r\n    /// @param _queryId The unique query identifier.\r\n    function upgradeQueryEvmReward(uint256 _queryId)\r\n        external payable\r\n        virtual override      \r\n        inStatus(_queryId, Witnet.QueryStatus.Posted)\r\n    {\r\n        WitOracleDataLib.Query storage __query = WitOracleDataLib.seekQuery(_queryId);\r\n        uint256 _newReward = (\r\n            Witnet.QueryEvmReward.unwrap(__query.reward)\r\n                + _getMsgValue()\r\n        );\r\n        __query.reward = Witnet.QueryEvmReward.wrap(uint72(_newReward));\r\n        emit WitOracleQueryUpgrade(\r\n            Witnet.QueryId.wrap(uint64(_queryId)),\r\n            _getMsgSender(),\r\n            _getGasPrice(),\r\n            _newReward\r\n        );\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Internal functions -----------------------------------------------------------------------------------------\r\n\r\n    function __queryData(\r\n            address _requester,\r\n            uint24  _callbackGas,\r\n            uint72  _evmReward,\r\n            Witnet.RadonHash _radonHash,\r\n            Witnet.QuerySLA memory _querySLA\r\n        )\r\n        virtual internal\r\n        returns (uint256 _queryId)\r\n    {\r\n        _queryId = ++ __storage().nonce;\r\n        WitOracleDataLib.Query storage __query = WitOracleDataLib.seekQuery(_queryId);\r\n        __query.checkpoint = Witnet.BlockNumber.wrap(uint64(block.number));\r\n        __query.uuid = Witnet.hashify(\r\n            Witnet.QueryId.wrap(uint64(_queryId)), \r\n            _radonHash, \r\n            _querySLA.hashify()\r\n        );\r\n        __query.reward = Witnet.QueryEvmReward.wrap(_evmReward);\r\n        __query.request.requester = _requester;\r\n        __query.request.radonHash = Witnet.RadonHash.unwrap(_radonHash);\r\n        if (_callbackGas > 0) __query.request.callbackGas = _callbackGas;\r\n        __query.slaParams = _querySLA;\r\n    }\r\n\r\n    function _revertUnhandledException() virtual internal view {\r\n        _revert(_revertUnhandledExceptionReason());\r\n    }\r\n\r\n    function _revertUnhandledExceptionReason() virtual internal pure returns (string memory) {\r\n        return string(abi.encodePacked(\r\n            type(WitOracleDataLib).name,\r\n            \": unhandled assertion\"\r\n        ));\r\n    }\r\n\r\n    /// Returns storage pointer to contents of 'WitOracleDataLib.Storage' struct.\r\n    function __storage() virtual internal pure returns (WitOracleDataLib.Storage storage _ptr) {\r\n        return WitOracleDataLib.data();\r\n    }    \r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleBaseQueriableTrustable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleBaseQueriable.sol\";\r\nimport \"../WitnetUpgradableBase.sol\";\r\nimport \"../../interfaces/IWitOracleTrustableAdmin.sol\";\r\nimport \"../../interfaces/IWitOracleQueriable.sol\";\r\nimport \"../../interfaces/IWitOracleQueriableTrustableReporter.sol\";\r\nimport \"../../interfaces/legacy/IWitOracleLegacy.sol\";\r\n\r\n/// @title Queriable WitOracle \"trustable\" base implementation.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleBaseQueriableTrustable\r\n    is\r\n        WitnetUpgradableBase,\r\n        WitOracleBaseQueriable,\r\n        IWitOracleTrustableAdmin,\r\n        IWitOracleLegacy,\r\n        IWitOracleQueriableTrustableReporter\r\n{\r\n    using Witnet for Witnet.DataPushReport;\r\n    using Witnet for Witnet.QuerySLA;\r\n    using Witnet for Witnet.Timestamp;\r\n\r\n    /// Asserts the caller is authorized as a reporter\r\n    modifier onlyReporters virtual {\r\n        _require(\r\n            WitOracleDataLib.data().reporters[msg.sender],\r\n            \"unauthorized reporter\"\r\n        ); _;\r\n    }\r\n\r\n    constructor(bytes32 _versionTag)\r\n        Ownable(msg.sender)\r\n        Payable(address(0))\r\n        WitnetUpgradableBase(\r\n            true, \r\n            _versionTag,\r\n            \"io.witnet.proxiable.board\"\r\n        )\r\n    {} \r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Upgradeable ------------------------------------------------------------------------------------------------\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    function __initializeUpgradableData(bytes memory _initData) virtual override internal {\r\n        WitOracleDataLib.setReporters(abi.decode(_initData, (address[])));\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- IWitOracle -------------------------------------------------------------------------------------------------\r\n\r\n    function parseDataReport(Witnet.DataPushReport calldata _report, bytes calldata _signature)\r\n        virtual override public view\r\n        returns (Witnet.DataResult memory _result)\r\n    {\r\n        (, _result) = WitOracleDataLib.parseDataReport(_report, _signature);\r\n    }\r\n\r\n    function pushDataReport(Witnet.DataPushReport calldata _report, bytes calldata _signature)\r\n        virtual override external\r\n        returns (Witnet.DataResult memory)\r\n    {\r\n        (address _evmSigner, Witnet.DataResult memory _result) = WitOracleDataLib.parseDataReport(_report, _signature);\r\n        emit WitOracleReport(\r\n            tx.origin, \r\n            msg.sender, \r\n            _evmSigner, \r\n            _report.witDrTxHash,\r\n            _report.queryRadHash,\r\n            _report.queryParams,\r\n            _report.resultTimestamp,\r\n            _report.resultCborBytes\r\n        );\r\n        return _result;\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- IWitOracleQueriable ----------------------------------------------------------------------------------------\r\n\r\n    /// @notice Removes all query data from storage. Pays back reward on expired queries.\r\n    /// @dev Fails if the query is not in a final status, or not called from the actual requester.\r\n    function deleteQuery(uint256 _queryId)\r\n        virtual override public\r\n        returns (Witnet.QueryEvmReward)\r\n    {\r\n        try WitOracleDataLib.deleteQuery(\r\n            _queryId\r\n        \r\n        ) returns (\r\n            Witnet.QueryEvmReward _queryReward\r\n        ) {\r\n            uint256 _evmPayback = Witnet.QueryEvmReward.unwrap(_queryReward);\r\n            if (_evmPayback > 0) {\r\n                // transfer unused reward to requester, only if the query expired:\r\n                __safeTransferTo(\r\n                    payable(msg.sender),\r\n                    _evmPayback\r\n                );\r\n            }\r\n            return _queryReward;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n\r\n        } catch (bytes memory) {\r\n            _revertUnhandledException();\r\n        }\r\n    }\r\n\r\n    /// Gets current status of given query.\r\n    function getQueryStatus(uint256 _queryId) \r\n        virtual override\r\n        public view\r\n        returns (Witnet.QueryStatus)\r\n    {\r\n        return WitOracleDataLib.getQueryStatus(_queryId);\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implements IWitOracleTrustableAdmin -----------------------------------------------------------------------------\r\n\r\n    /// Tells whether given address is included in the active reporters control list.\r\n    /// @param _queryResponseReporter The address to be checked.\r\n    function isReporter(address _queryResponseReporter) virtual override public view returns (bool) {\r\n        return WitOracleDataLib.isReporter(_queryResponseReporter);\r\n    }\r\n\r\n    /// Adds given addresses to the active reporters control list.\r\n    /// @dev Can only be called from the owner address.\r\n    /// @dev Emits the `ReportersSet` event. \r\n    /// @param _queryResponseReporters List of addresses to be added to the active reporters control list.\r\n    function setReporters(address[] calldata _queryResponseReporters)\r\n        virtual override public\r\n        onlyOwner\r\n    {\r\n        WitOracleDataLib.setReporters(_queryResponseReporters);\r\n    }\r\n\r\n    /// Removes given addresses from the active reporters control list.\r\n    /// @dev Can only be called from the owner address.\r\n    /// @dev Emits the `ReportersUnset` event. \r\n    /// @param _exReporters List of addresses to be added to the active reporters control list.\r\n    function unsetReporters(address[] calldata _exReporters)\r\n        virtual override public\r\n        onlyOwner\r\n    {\r\n        WitOracleDataLib.unsetReporters(_exReporters);\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitOracleLegacy ------------------------------------------------------------------------------------------\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @dev Underestimates if the size of returned data is greater than `_resultMaxSize`. \r\n    /// @param _gasPrice Expected gas price to pay upon posting the data request.\r\n    function estimateBaseFee(uint256 _gasPrice, uint16)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return estimateBaseFee(_gasPrice);\r\n    }\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @dev Underestimates if the size of returned data is greater than `resultMaxSize`. \r\n    /// @param gasPrice Expected gas price to pay upon posting the data request.\r\n    /// @param radHash The hash of some Witnet Data Request previously posted in the WitOracleRadonRegistry registry.\r\n    function estimateBaseFee(uint256 gasPrice, bytes32 radHash)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        // Check this rad hash is actually verified:\r\n        _require(\r\n            registry.isVerifiedRadonRequest(Witnet.RadonHash.wrap(radHash)),\r\n            \"unknown radon hash\"\r\n        );\r\n\r\n        // Base fee is actually invariant to max result size:\r\n        return estimateBaseFee(gasPrice);\r\n    }\r\n\r\n    function extractWitnetDataRequests(uint256[] calldata queryIds) external view returns (bytes[] memory) {\r\n        Witnet.QueryId[] memory _ids = new Witnet.QueryId[](queryIds.length);\r\n        for (uint _ix; _ix < _ids.length; _ix ++) {\r\n            _ids[_ix] = Witnet.QueryId.wrap(uint64(queryIds[_ix]));\r\n        }\r\n        return extractRadonBytecodes(_ids);\r\n    }\r\n\r\n    function fetchQueryResponse(uint256 queryId) virtual override external returns (bytes memory) {\r\n        deleteQuery(queryId);\r\n        return hex\"\";\r\n    }\r\n\r\n    function getQuery(uint256 queryId) \r\n        virtual override \r\n        external view \r\n        returns (IWitOracleLegacy.Query memory)\r\n    {\r\n        return IWitOracleLegacy.Query({\r\n            request: getQueryRequest(queryId),\r\n            response: getQueryResponse(queryId)\r\n        });\r\n    }\r\n\r\n    function getQueryRequest(uint256 queryId)\r\n        virtual override\r\n        public view\r\n        returns (IWitOracleLegacy.QueryRequest memory)\r\n    {\r\n        WitOracleDataLib.Query storage __query = __storage().queries[queryId];\r\n        if (__query.request.radonBytecode.length > 65535) {\r\n            // read from v1 layout\r\n            return IWitOracleLegacy.QueryRequest({\r\n                requester: address(0),\r\n                callbackGas: 0,\r\n                evmReward: 0,\r\n                radonBytecode: hex\"\",\r\n                radonHash: __query.request.radonHash,\r\n                radonParams: IWitOracleLegacy.RadonSLA({\r\n                    numWitnesses: 0,\r\n                    witnessReward: 0\r\n                })\r\n            });\r\n\r\n        } else if (__query.request._1 > 0) {\r\n            // read from v2 layout\r\n            return IWitOracleLegacy.QueryRequest({\r\n                requester: __query.request.requester,\r\n                callbackGas: __query.request.callbackGas,\r\n                evmReward: __query.request._0,\r\n                radonBytecode: __query.request.radonBytecode,\r\n                radonHash: __query.request.radonHash,\r\n                radonParams: IWitOracleLegacy.RadonSLA({\r\n                    numWitnesses: uint8(__query.slaParams.witCommitteeSize),\r\n                    witnessReward: __query.slaParams.witUnitaryReward\r\n                })\r\n            });\r\n        } else {\r\n            // read from v3 layout\r\n            return IWitOracleLegacy.QueryRequest({\r\n                requester: __query.request.requester,\r\n                callbackGas: __query.request.callbackGas,\r\n                evmReward: Witnet.QueryEvmReward.unwrap(__query.reward),\r\n                radonBytecode: __query.request.radonBytecode,\r\n                radonHash: __query.request.radonHash,\r\n                radonParams: IWitOracleLegacy.RadonSLA({\r\n                    numWitnesses: uint8(__query.slaParams.witCommitteeSize),\r\n                    witnessReward: __query.slaParams.witUnitaryReward\r\n                })\r\n            });\r\n        }\r\n    }\r\n\r\n    function getQueryResponse(uint256 queryId)\r\n        virtual override\r\n        public view\r\n        returns (IWitOracleLegacy.QueryResponse memory)\r\n    {\r\n        WitOracleDataLib.Query storage __query = __storage().queries[queryId];\r\n        if (__query.request.radonBytecode.length > 65535) {\r\n            // read from v1 layout\r\n            return IWitOracleLegacy.QueryResponse({\r\n                reporter: address(0),\r\n                finality: uint64(0),\r\n                timestamp: uint32(0),\r\n                trail: bytes32(0),\r\n                cborBytes: new bytes(0)\r\n            });\r\n\r\n        } else if (__query.request._1 > 0) {\r\n            // read from v2 layout\r\n            return IWitOracleLegacy.QueryResponse({\r\n                reporter: __query.response.reporter,\r\n                finality: uint64(__query.response._0),\r\n                timestamp: uint32(__query.response.resultTimestamp >> 32),\r\n                trail: __query.response.resultDrTxHash,\r\n                cborBytes: __query.response.resultCborBytes\r\n            });\r\n\r\n        } else {\r\n            // read from v3 layout\r\n            return IWitOracleLegacy.QueryResponse({\r\n                reporter: __query.response.reporter,\r\n                finality: Witnet.BlockNumber.unwrap(__query.checkpoint),\r\n                timestamp: uint32(__query.response.resultTimestamp),\r\n                trail: __query.response.resultDrTxHash,\r\n                cborBytes: __query.response.resultCborBytes\r\n            });\r\n        }\r\n    }\r\n\r\n    function getQueryResponseStatus(uint256 queryId) \r\n        virtual override \r\n        public view \r\n        returns (IWitOracleLegacy.QueryResponseStatus)\r\n    {\r\n        return WitOracleDataLib.getQueryResponseStatus(queryId);\r\n    }\r\n\r\n    function getQueryResultCborBytes(uint256 queryId) virtual override external view returns (bytes memory) {\r\n        return getQueryResponse(Witnet.QueryId.wrap(uint64(queryId))).resultCborBytes;\r\n    }\r\n\r\n    function getQueryResultError(uint256 queryId) virtual override external view returns (IWitOracleLegacy.ResultError memory) {\r\n        Witnet.DataResult memory _result = getQueryResult(queryId);\r\n        return IWitOracleLegacy.ResultError({\r\n            code: uint8(_result.status),\r\n            reason: WitOracleResultStatusLib.toString(abi.encode(_result))\r\n        });\r\n    }\r\n\r\n    function postRequest(\r\n            bytes32 _queryRadHash, \r\n            IWitOracleLegacy.RadonSLA calldata _querySLA\r\n        )\r\n        virtual override\r\n        external payable\r\n        returns (uint256)\r\n    {\r\n        return queryData(\r\n            Witnet.RadonHash.wrap(_queryRadHash),\r\n            Witnet.QuerySLA({\r\n                witResultMaxSize: 32,\r\n                witCommitteeSize: _querySLA.numWitnesses,\r\n                witUnitaryReward: _querySLA.witnessReward\r\n            })\r\n        );\r\n    }\r\n\r\n    function postRequestWithCallback(\r\n            bytes32 _queryRadHash,\r\n            IWitOracleLegacy.RadonSLA calldata _querySLA,\r\n            uint24 _queryCallbackGas\r\n        )\r\n        virtual override\r\n        external payable\r\n        returns (uint256)\r\n    {\r\n        return queryDataWithCallback(\r\n            Witnet.RadonHash.wrap(_queryRadHash),\r\n            Witnet.QuerySLA({\r\n                witResultMaxSize: 32,\r\n                witCommitteeSize: _querySLA.numWitnesses,\r\n                witUnitaryReward: _querySLA.witnessReward\r\n            }),\r\n            Witnet.QueryCallback({\r\n                consumer: msg.sender,\r\n                gasLimit: _queryCallbackGas\r\n            })\r\n        );\r\n    }\r\n\r\n    function reportResult(\r\n            uint256 queryId,\r\n            uint32 resultTimestamp,\r\n            bytes32 drTxHash,\r\n            bytes calldata resultCborBytes\r\n        )\r\n        external override\r\n        onlyReporters\r\n        returns (uint256)\r\n    {\r\n        return reportResult(\r\n            Witnet.QueryId.wrap(uint64(queryId)),\r\n            Witnet.Timestamp.wrap(resultTimestamp),\r\n            Witnet.TransactionHash.wrap(drTxHash),\r\n            resultCborBytes\r\n        );\r\n    }\r\n\r\n    function reportResult(\r\n            uint256 queryId,\r\n            bytes32 drTxHash,\r\n            bytes calldata resultCborBytes\r\n        )\r\n        external override\r\n        onlyReporters\r\n        returns (uint256)\r\n    {\r\n        return reportResult(\r\n            Witnet.QueryId.wrap(uint64(queryId)),\r\n            Witnet.TransactionHash.wrap(drTxHash),\r\n            resultCborBytes\r\n        );\r\n    }\r\n\r\n    function reportResultBatch(BatchResultLegacy[] calldata results)\r\n        external override\r\n        onlyReporters\r\n        returns (uint256 _batchReward)\r\n    {\r\n        IWitOracleQueriableTrustableReporter.BatchResult[] memory _results = new IWitOracleQueriableTrustableReporter.BatchResult[](results.length);\r\n        for (uint _ix = 0; _ix < results.length; _ix ++) {\r\n            _results[_ix] = BatchResult({\r\n                queryId: Witnet.QueryId.wrap(uint64(results[_ix].queryId)),\r\n                resultTimestamp: Witnet.Timestamp.wrap(results[_ix].resultTimestamp),\r\n                drTxHash: Witnet.TransactionHash.wrap(results[_ix].drTxHash),\r\n                resultCborBytes: results[_ix].resultCborBytes\r\n            });\r\n        }\r\n        return reportResultBatch(_results);\r\n    }\r\n\r\n\r\n\r\n    // =========================================================================================================================\r\n    // --- Implements IWitOracleQueriableTrustableReporter ------------------------------------------------------------------------------\r\n\r\n    /// @notice Estimates the actual earnings (or loss), in WEI, that a reporter would get by reporting result to given query,\r\n    /// @notice based on the gas price of the calling transaction. Data requesters should consider upgrading the reward on \r\n    /// @notice queries providing no actual earnings.\r\n    function estimateReportEarnings(\r\n            uint256[] calldata _queryIds, \r\n            bytes calldata,\r\n            uint256 _evmGasPrice,\r\n            uint256 _evmWitPrice\r\n        )\r\n        external view\r\n        virtual override\r\n        returns (uint256 _revenues, uint256 _expenses)\r\n    {\r\n        for (uint _ix = 0; _ix < _queryIds.length; _ix ++) {\r\n            uint256 _queryId = _queryIds[_ix];\r\n            if (\r\n                getQueryStatus(_queryId) == Witnet.QueryStatus.Posted\r\n            ) {\r\n                WitOracleDataLib.Query storage __query = WitOracleDataLib.seekQuery(_queryId);\r\n                if (__query.request.callbackGas > 0) {\r\n                    _expenses += (\r\n                        estimateBaseFeeWithCallback(_evmGasPrice, __query.request.callbackGas)\r\n                            + estimateExtraFee(_evmGasPrice, _evmWitPrice,\r\n                                Witnet.QuerySLA({\r\n                                    witResultMaxSize: uint16(0),\r\n                                    witCommitteeSize: __query.slaParams.witCommitteeSize,\r\n                                    witUnitaryReward: __query.slaParams.witUnitaryReward\r\n                                })\r\n                            )\r\n                    );\r\n                } else {\r\n                    _expenses += (\r\n                        estimateBaseFee(_evmGasPrice)\r\n                            + estimateExtraFee(_evmGasPrice, _evmWitPrice, __query.slaParams)\r\n                    );\r\n                }\r\n                _expenses +=  _evmWitPrice * __query.slaParams.witUnitaryReward;\r\n                _revenues += Witnet.QueryEvmReward.unwrap(__query.reward);\r\n            }\r\n        }\r\n    }\r\n\r\n    /// @notice Retrieves the Witnet Data Request bytecodes of previously posted queries.\r\n    /// @dev Returns empty buffer if the query does not exist.\r\n    /// @param _queryIds Query identifies.\r\n    function extractRadonBytecodes(Witnet.QueryId[] memory _queryIds)\r\n        public view \r\n        virtual override\r\n        returns (bytes[] memory _bytecodes)\r\n    {\r\n        return WitOracleDataLib.extractRadonBytecodes(registry, _queryIds);\r\n    }\r\n\r\n    /// Reports the Witnet-provable result to a previously posted request. \r\n    /// @dev Will assume `block.timestamp` as the timestamp at which the request was solved.\r\n    /// @dev Fails if:\r\n    /// @dev - the `_queryId` is not in 'Posted' status.\r\n    /// @dev - provided `_witDrTxHash` is zero;\r\n    /// @dev - length of provided `_result` is zero.\r\n    /// @param _queryId The unique identifier of the data request.\r\n    /// @param _witDrTxHash Hash of the commit/reveal witnessing act that took place in the Witnet blockahin.\r\n    /// @param _resultCborBytes The result itself as bytes.\r\n    function reportResult(\r\n            Witnet.QueryId _queryId,\r\n            Witnet.TransactionHash _witDrTxHash,\r\n            bytes calldata _resultCborBytes\r\n        )\r\n        public override\r\n        onlyReporters\r\n        returns (uint256)\r\n    {\r\n        // results cannot be empty:\r\n        _require(\r\n            _resultCborBytes.length != 0, \r\n            \"result cannot be empty\"\r\n        );\r\n        // do actual report and return reward transfered to the reproter:\r\n        // solhint-disable not-rely-on-time\r\n        return __reportResultAndReward(\r\n            Witnet.QueryId.unwrap(_queryId),\r\n            Witnet.Timestamp.wrap(uint64(block.timestamp)),\r\n            _witDrTxHash,\r\n            _resultCborBytes\r\n        );\r\n    }\r\n\r\n    /// Reports the Witnet-provable result to a previously posted request.\r\n    /// @dev Fails if:\r\n    /// @dev - called from unauthorized address;\r\n    /// @dev - the `_queryId` is not in 'Posted' status.\r\n    /// @dev - provided `_witDrTxHash` is zero;\r\n    /// @dev - length of provided `_resultCborBytes` is zero.\r\n    /// @param _queryId The unique query identifier\r\n    /// @param _resultTimestamp Timestamp at which the reported value was captured by the Witnet blockchain. \r\n    /// @param _witDrTxHash Hash of the commit/reveal witnessing act that took place in the Witnet blockahin.\r\n    /// @param _resultCborBytes The result itself as bytes.\r\n    function reportResult(\r\n            Witnet.QueryId _queryId,\r\n            Witnet.Timestamp  _resultTimestamp,\r\n            Witnet.TransactionHash _witDrTxHash,\r\n            bytes calldata _resultCborBytes\r\n        )\r\n        public \r\n        override\r\n        onlyReporters\r\n        returns (uint256)\r\n    {\r\n        // validate timestamp\r\n        _require(\r\n            !_resultTimestamp.isZero(),\r\n            \"bad timestamp\"\r\n        );\r\n        // results cannot be empty\r\n        _require(\r\n            _resultCborBytes.length != 0, \r\n            \"result cannot be empty\"\r\n        );\r\n        // do actual report and return reward transfered to the reproter:\r\n        return  __reportResultAndReward(\r\n            Witnet.QueryId.unwrap(_queryId),\r\n            _resultTimestamp,\r\n            _witDrTxHash,\r\n            _resultCborBytes\r\n        );\r\n    }\r\n\r\n    /// @notice Reports Witnet-provided results to multiple requests within a single EVM tx.\r\n    /// @notice Emits either a WitOracleQueryReport* or a BatchReportError event per batched report.\r\n    /// @dev Fails only if called from unauthorized address.\r\n    /// @param _batchResults Array of BatchResult structs, every one containing:\r\n    ///         - unique query identifier;\r\n    ///         - timestamp of the solving tally txs in Witnet. If zero is provided, EVM-timestamp will be used instead;\r\n    ///         - hash of the corresponding data request tx at the Witnet side-chain level;\r\n    ///         - data request result in raw bytes.\r\n    function reportResultBatch(IWitOracleQueriableTrustableReporter.BatchResult[] memory _batchResults)\r\n        public override\r\n        onlyReporters\r\n        returns (uint256 _batchReward)\r\n    {\r\n        for (uint _i = 0; _i < _batchResults.length; _i ++) {\r\n            uint256 _queryId = Witnet.QueryId.unwrap(_batchResults[_i].queryId);\r\n            if (\r\n                getQueryStatus(_queryId)\r\n                    != Witnet.QueryStatus.Posted\r\n            ) {\r\n                emit BatchReportError(\r\n                    Witnet.QueryId.unwrap(_batchResults[_i].queryId),\r\n                    string(abi.encodePacked(\r\n                        class(),\r\n                        \": \", WitOracleDataLib.notInStatusRevertMessage(Witnet.QueryStatus.Posted)\r\n                    ))\r\n                );\r\n            } else if (\r\n                Witnet.Timestamp.unwrap(_batchResults[_i].resultTimestamp) > uint64(block.timestamp)\r\n                    || _batchResults[_i].resultTimestamp.isZero()\r\n                    || _batchResults[_i].resultCborBytes.length == 0\r\n            ) {\r\n                emit BatchReportError(\r\n                    Witnet.QueryId.unwrap(_batchResults[_i].queryId), \r\n                    string(abi.encodePacked(\r\n                        class(),\r\n                        \": invalid report data\"\r\n                    ))\r\n                );\r\n            } else {\r\n                _batchReward += __reportResult(\r\n                    Witnet.QueryId.unwrap(_batchResults[_i].queryId),\r\n                    _batchResults[_i].resultTimestamp,\r\n                    _batchResults[_i].drTxHash,\r\n                    _batchResults[_i].resultCborBytes\r\n                );\r\n            }\r\n        }   \r\n        // Transfer rewards to all reported results in one single transfer to the reporter:\r\n        if (_batchReward > 0) {\r\n            __safeTransferTo(\r\n                payable(msg.sender),\r\n                _batchReward\r\n            );\r\n        }\r\n    }\r\n\r\n\r\n    /// ================================================================================================================\r\n    /// --- Internal methods -------------------------------------------------------------------------------------------\r\n\r\n    function __queryData(\r\n            address _requester,\r\n            uint24  _callbackGas,\r\n            uint72  _evmReward,\r\n            Witnet.RadonHash _radonHash,\r\n            Witnet.QuerySLA memory _querySLA\r\n        ) \r\n        virtual override\r\n        internal\r\n        returns (uint256 _queryId)\r\n    {\r\n        _queryId = super.__queryData(\r\n            _requester,\r\n            _callbackGas,\r\n            _evmReward,\r\n            _radonHash,\r\n            _querySLA\r\n        );\r\n        // todo: deprecate legacy events\r\n        emit IWitOracleLegacy.WitnetQuery(\r\n            _queryId, \r\n            msg.value, \r\n            IWitOracleLegacy.RadonSLA({\r\n                numWitnesses: uint8(_querySLA.witCommitteeSize),\r\n                witnessReward: _querySLA.witUnitaryReward\r\n            })\r\n        );\r\n    }\r\n\r\n    function __reportResult(\r\n            uint256 _queryId,\r\n            Witnet.Timestamp  _resultTimestamp,\r\n            Witnet.TransactionHash _witDrTxHash,\r\n            bytes memory _resultCborBytes\r\n        )\r\n        virtual internal\r\n        returns (uint256)\r\n    {\r\n        _require(\r\n            WitOracleDataLib.getQueryStatus(_queryId) == Witnet.QueryStatus.Posted,\r\n            \"not in Posted status\"\r\n        );\r\n        return WitOracleDataLib.reportResult(\r\n            msg.sender,\r\n            tx.gasprice,\r\n            uint64(block.number),\r\n            _queryId, \r\n            _resultTimestamp, \r\n            _witDrTxHash, \r\n            _resultCborBytes\r\n        );\r\n    }\r\n\r\n    function __reportResultAndReward(\r\n            uint256 _queryId,\r\n            Witnet.Timestamp  _resultTimestamp,\r\n            Witnet.TransactionHash _witDrTxHash,\r\n            bytes calldata _resultCborBytes\r\n        )\r\n        virtual internal\r\n        returns (uint256 _evmReward)\r\n    {\r\n        _evmReward = __reportResult(\r\n            _queryId, \r\n            _resultTimestamp, \r\n            _witDrTxHash, \r\n            _resultCborBytes\r\n        );\r\n        // transfer reward to reporter\r\n        __safeTransferTo(\r\n            payable(msg.sender),\r\n            _evmReward\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleBaseQueriableTrustless.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleBaseQueriable.sol\";\r\nimport \"../../data/WitOracleTrustlessDataLib.sol\";\r\nimport \"../../interfaces/IWitOracleTrustless.sol\";\r\nimport \"../../interfaces/IWitOracleQueriableTrustlessReporter.sol\";\r\nimport \"../../patterns/Escrowable.sol\";\r\n\r\n/// @title Queriable WitOracle \"trustless\" base implementation.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleBaseQueriableTrustless\r\n    is \r\n        Escrowable,\r\n        WitOracleBaseQueriable,\r\n        IWitOracleTrustless,\r\n        IWitOracleQueriableTrustlessReporter\r\n{\r\n    using Witnet for Witnet.DataPullReport;\r\n    using WitOracleTrustlessDataLib for WitOracleDataLib.Query;\r\n\r\n    /// @notice Number of blocks to await for either a dispute or a proven response to some query.\r\n    uint256 immutable public QUERY_AWAITING_BLOCKS;\r\n\r\n    /// @notice Amount in wei to be staked upon reporting or disputing some query.\r\n    uint256 immutable public QUERY_REPORTING_STAKE;\r\n\r\n    modifier checkQueryReward(uint256 _msgValue, uint256 _baseFee) virtual override {\r\n        if (_msgValue < _baseFee) {\r\n            __burn(msg.sender, _baseFee - _msgValue);\r\n        \r\n        } else if (_msgValue > _baseFee * 10) {\r\n            _revert(\"too much reward\");\r\n\r\n        } _;   \r\n    }\r\n\r\n    constructor(\r\n            uint256 _queryAwaitingBlocks,\r\n            uint256 _queryReportingStake\r\n        )\r\n        Payable(address(0))\r\n    {\r\n        _require(_queryAwaitingBlocks < 64, \"too many awaiting blocks\");\r\n        _require(_queryReportingStake > 0, \"no reporting stake?\");\r\n        \r\n        QUERY_AWAITING_BLOCKS = _queryAwaitingBlocks;\r\n        QUERY_REPORTING_STAKE = _queryReportingStake;\r\n\r\n        // store genesis beacon:\r\n        WitOracleTrustlessDataLib.data().beacons[\r\n            Witnet.WIT_2_GENESIS_BEACON_INDEX\r\n        ] = Witnet.Beacon({\r\n            index: Witnet.WIT_2_GENESIS_BEACON_INDEX,\r\n            prevIndex: Witnet.WIT_2_GENESIS_BEACON_PREV_INDEX,\r\n            prevRoot: Witnet.WIT_2_GENESIS_BEACON_PREV_ROOT,\r\n            ddrTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DDR_TALLIES_MERKLE_ROOT,\r\n            droTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DRO_TALLIES_MERKLE_ROOT,\r\n            nextCommitteeAggPubkey: [\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_0,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_1,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_2,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_3\r\n            ]\r\n        });\r\n    } \r\n    \r\n    // ================================================================================================================\r\n    // --- Escrowable -------------------------------------------------------------------------------------------------\r\n\r\n    receive() external payable virtual override {\r\n        __deposit(msg.sender, _getMsgValue());\r\n    }\r\n\r\n    function collateralOf(address tenant)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return WitOracleTrustlessDataLib.data().escrows[tenant].collateral;\r\n    }\r\n\r\n    function balanceOf(address tenant)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return WitOracleTrustlessDataLib.data().escrows[tenant].balance;\r\n    }\r\n\r\n    function withdraw()\r\n        external\r\n        virtual override\r\n        returns (uint256 _withdrawn)\r\n    {\r\n        _withdrawn = WitOracleTrustlessDataLib.withdraw(msg.sender);\r\n        __safeTransferTo(\r\n            payable(msg.sender), \r\n            _withdrawn\r\n        );\r\n    }\r\n\r\n    function __burn(address from, uint256 value) \r\n        virtual override\r\n        internal\r\n    {\r\n        WitOracleTrustlessDataLib.burn(from, value);\r\n    }\r\n\r\n    function __deposit(address from, uint256 value)\r\n        virtual override\r\n        internal\r\n    {\r\n        WitOracleTrustlessDataLib.deposit(from, value);\r\n    }\r\n\r\n    function __stake(address from, uint256 value)\r\n        virtual override\r\n        internal\r\n    {\r\n        WitOracleTrustlessDataLib.stake(from, value);\r\n    }\r\n\r\n    function __slash(address from, address to, uint256 value)\r\n        virtual override\r\n        internal\r\n    {\r\n        WitOracleTrustlessDataLib.slash(from, to, value);\r\n    }\r\n\r\n    function __unstake(address from, uint256 value)\r\n        virtual override\r\n        internal\r\n    {\r\n        WitOracleTrustlessDataLib.unstake(from, value);\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides IWitOracle (trustlessly) -------------------------------------------------------------------------\r\n\r\n    function parseDataReport(Witnet.DataPushReport calldata _dataPushReport, bytes calldata _proof)\r\n        virtual override \r\n        external view\r\n        returns (Witnet.DataResult memory)\r\n    {\r\n        (Witnet.FastForward[] memory _rollup, bytes32[] memory _merkle) = abi.decode(\r\n            _proof, \r\n            (Witnet.FastForward[], bytes32[])\r\n        );\r\n        try WitOracleTrustlessDataLib.parseDataPushReport(\r\n            _dataPushReport,\r\n            _rollup,\r\n            _merkle\r\n        \r\n        ) returns (\r\n            Witnet.DataResult memory _queryResult\r\n        ) {\r\n            return _queryResult;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            revert(\"unhandled assertion\");\r\n        }\r\n    }\r\n\r\n    function pushDataReport(Witnet.DataPushReport calldata _dataPushReport, bytes calldata _proof)\r\n        virtual override external\r\n        returns (Witnet.DataResult memory)\r\n    {\r\n        (Witnet.FastForward[] memory _rollup, bytes32[] memory _merkle) = abi.decode(\r\n            _proof, \r\n            (Witnet.FastForward[], bytes32[])\r\n        );\r\n        try WitOracleTrustlessDataLib.rollupDataPushReport(\r\n            _dataPushReport,\r\n            _rollup,\r\n            _merkle\r\n        \r\n        ) returns (\r\n            Witnet.DataResult memory _queryResult\r\n        ) {\r\n            return _queryResult;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            revert(\"unhandled assertion\");\r\n        }\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides IWitOracleQueriable (truslessly) -----------------------------------------------------------------\r\n\r\n    /// @notice Removes all query data from storage. Pays back reward on expired queries.\r\n    /// @dev Fails if the query is not in a final status, or not called from the actual requester.\r\n    function deleteQuery(uint256 _queryId)\r\n        virtual override external\r\n        returns (Witnet.QueryEvmReward)\r\n    {\r\n        try WitOracleTrustlessDataLib.deleteQueryTrustlessly(\r\n            _queryId,\r\n            QUERY_AWAITING_BLOCKS,\r\n            QUERY_REPORTING_STAKE\r\n        \r\n        ) returns (\r\n            Witnet.QueryEvmReward _queryReward\r\n        ) {\r\n            uint256 _evmPayback = Witnet.QueryEvmReward.unwrap(_queryReward);\r\n            if (_evmPayback > 0) {\r\n                // transfer unused reward to requester, only if the query expired:\r\n                __safeTransferTo(\r\n                    payable(msg.sender),\r\n                    _evmPayback\r\n                );\r\n            }\r\n            return _queryReward;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandledException();\r\n        }\r\n    }\r\n\r\n    function getQueryStatus(uint256 _queryId)\r\n        virtual override\r\n        public view\r\n        returns (Witnet.QueryStatus)\r\n    {\r\n        return WitOracleDataLib\r\n            .seekQuery(_queryId)\r\n            .getQueryStatusTrustlessly(QUERY_AWAITING_BLOCKS);\r\n    }\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- IWitOracleTrustless -------------------------------------------------------------------------------------------\r\n\r\n    function determineBeaconIndexFromTimestamp(Witnet.Timestamp timestamp)\r\n        virtual override\r\n        external pure\r\n        returns (uint64)\r\n    {\r\n        return Witnet.determineBeaconIndexFromTimestamp(timestamp);\r\n    }\r\n    \r\n    function determineEpochFromTimestamp(Witnet.Timestamp timestamp)\r\n        virtual override\r\n        external pure\r\n        returns (Witnet.BlockNumber)\r\n    {\r\n        return Witnet.determineEpochFromTimestamp(timestamp);\r\n    }\r\n\r\n    function getBeaconByIndex(uint32 index)\r\n        virtual override\r\n        public view\r\n        returns (Witnet.Beacon memory)\r\n    {\r\n        return WitOracleTrustlessDataLib.seekBeacon(index);\r\n    }\r\n\r\n    function getGenesisBeacon() \r\n        virtual override \r\n        external pure\r\n        returns (Witnet.Beacon memory)\r\n    {\r\n        return Witnet.Beacon({\r\n            index: Witnet.WIT_2_GENESIS_BEACON_INDEX,\r\n            prevIndex: Witnet.WIT_2_GENESIS_BEACON_PREV_INDEX,\r\n            prevRoot: Witnet.WIT_2_GENESIS_BEACON_PREV_ROOT,\r\n            ddrTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DDR_TALLIES_MERKLE_ROOT,\r\n            droTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DRO_TALLIES_MERKLE_ROOT,\r\n            nextCommitteeAggPubkey: [\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_0,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_1,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_2,\r\n                Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_3\r\n            ]\r\n        });\r\n    }\r\n\r\n    function getLastKnownBeacon() \r\n        virtual override\r\n        public view\r\n        returns (Witnet.Beacon memory)\r\n    {\r\n        return WitOracleTrustlessDataLib.getLastKnownBeacon();\r\n    }\r\n\r\n    function getLastKnownBeaconIndex()\r\n        virtual override\r\n        public view\r\n        returns (uint32)\r\n    {\r\n        return uint32(WitOracleTrustlessDataLib.getLastKnownBeaconIndex());\r\n    }\r\n\r\n    function rollupBeacons(Witnet.FastForward[] calldata _witOracleRollup)\r\n        virtual override public \r\n        returns (Witnet.Beacon memory)\r\n    {\r\n        try WitOracleTrustlessDataLib.rollupBeacons(\r\n            _witOracleRollup\r\n        ) returns (\r\n            Witnet.Beacon memory _witOracleHead\r\n        ) {\r\n            return _witOracleHead;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandledException();\r\n        }\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- IWitOracleQueriableTrustlessReporter --------------------------------------------------------------------------------\r\n\r\n    function claimQueryReward(Witnet.QueryId _queryId)\r\n        virtual override external\r\n        returns (uint256)\r\n    {\r\n        try WitOracleTrustlessDataLib.claimQueryReward(\r\n            Witnet.QueryId.unwrap(_queryId), \r\n            QUERY_AWAITING_BLOCKS,\r\n            QUERY_REPORTING_STAKE\r\n\r\n        ) returns (\r\n            uint256 _evmReward\r\n        ) {\r\n            return _evmReward;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandledException();\r\n        }\r\n    }\r\n\r\n    function claimQueryRewardBatch(Witnet.QueryId[] calldata _queryIds)\r\n        virtual override external\r\n        returns (uint256 _evmTotalReward)\r\n    {\r\n        for (uint _ix = 0; _ix < _queryIds.length; _ix ++) {\r\n            try WitOracleTrustlessDataLib.claimQueryReward(\r\n                Witnet.QueryId.unwrap(_queryIds[_ix]),\r\n                QUERY_AWAITING_BLOCKS,\r\n                QUERY_REPORTING_STAKE\r\n                \r\n            ) returns (uint256 _evmReward) {\r\n                _evmTotalReward += _evmReward;\r\n            \r\n            } catch Error(string memory _reason) {\r\n                emit BatchQueryError(\r\n                    _queryIds[_ix], \r\n                    _reason\r\n                );\r\n        \r\n            } catch (bytes memory) {\r\n                emit BatchQueryError(\r\n                    _queryIds[_ix], \r\n                    _revertUnhandledExceptionReason()\r\n                );\r\n            }\r\n        }\r\n    }\r\n\r\n    function disputeQueryResponse(Witnet.QueryId _queryId) \r\n        virtual override external\r\n        returns (uint256)\r\n    {\r\n        try WitOracleTrustlessDataLib.disputeQueryResponse(\r\n            Witnet.QueryId.unwrap(_queryId),\r\n            QUERY_AWAITING_BLOCKS,\r\n            QUERY_REPORTING_STAKE\r\n        ) returns (uint256 _evmPotentialReward) {\r\n            return _evmPotentialReward;\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandledException();\r\n        }\r\n    }\r\n\r\n    function reportQueryResponse(Witnet.DataPullReport calldata _responseReport)\r\n        virtual override public \r\n        returns (uint256)\r\n    {\r\n        try WitOracleTrustlessDataLib.reportQueryResponseTrustlessly(\r\n            _responseReport,\r\n            QUERY_AWAITING_BLOCKS,\r\n            QUERY_REPORTING_STAKE\r\n\r\n        ) returns (\r\n            address evmReporter,\r\n            uint256 evmGasPrice,\r\n            uint64  evmFinalityBlock,\r\n            Witnet.QueryId queryId,\r\n            Witnet.Timestamp witDrResultTimestamp,\r\n            Witnet.TransactionHash witDrTxHash,\r\n            bytes memory witDrResultCborBytes\r\n        ) {\r\n            try WitOracleDataLib\r\n                .reportResult(\r\n                    evmReporter,\r\n                    evmGasPrice,\r\n                    evmFinalityBlock,\r\n                    Witnet.QueryId.unwrap(queryId),\r\n                    witDrResultTimestamp,\r\n                    witDrTxHash,\r\n                    witDrResultCborBytes\r\n            ) returns (\r\n                uint256 _evmReward\r\n            ) {\r\n                return _evmReward;\r\n            \r\n            } catch Error(string memory _reason) {\r\n                _revert(_reason);\r\n            \r\n            } catch (bytes memory) {\r\n                _revertUnhandledException();    \r\n            }\r\n        \r\n        } catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        \r\n        } catch (bytes memory) {\r\n            _revertUnhandledException();\r\n        }\r\n    }\r\n    \r\n    function reportQueryResponseBatch(Witnet.DataPullReport[] calldata _responseReports)\r\n        virtual override external \r\n        returns (uint256 _evmTotalReward)\r\n    {\r\n        for (uint _ix = 0; _ix < _responseReports.length; _ix ++) {\r\n            Witnet.DataPullReport calldata _responseReport = _responseReports[_ix];\r\n            try WitOracleTrustlessDataLib.reportQueryResponseTrustlessly(\r\n                _responseReport,\r\n                QUERY_AWAITING_BLOCKS,\r\n                QUERY_REPORTING_STAKE\r\n            ) returns (\r\n                address evmReporter,\r\n                uint256 evmGasPrice,\r\n                uint64  evmFinalityBlock,\r\n                Witnet.QueryId queryId,\r\n                Witnet.Timestamp witDrResultTimestamp,\r\n                Witnet.TransactionHash witDrTxHash,\r\n                bytes memory witDrResultCborBytes\r\n            ) {\r\n                try WitOracleDataLib.reportResult(\r\n                    evmReporter,\r\n                    evmGasPrice,\r\n                    evmFinalityBlock,\r\n                    Witnet.QueryId.unwrap(queryId),\r\n                    witDrResultTimestamp,\r\n                    witDrTxHash,\r\n                    witDrResultCborBytes\r\n                ) returns (\r\n                    uint256 _evmPartialReward\r\n                ) {\r\n                    _evmTotalReward += _evmPartialReward;\r\n                \r\n                } catch Error(string memory _reason) {\r\n                    emit BatchQueryError(\r\n                        _responseReport.queryId,\r\n                        _reason\r\n                    );\r\n                \r\n                } catch (bytes memory) {\r\n                    emit BatchQueryError(\r\n                        _responseReport.queryId,\r\n                        _revertUnhandledExceptionReason()\r\n                    );\r\n                }\r\n            \r\n            } catch Error(string memory _reason) {\r\n                emit BatchQueryError(\r\n                    _responseReport.queryId,\r\n                    _reason\r\n                );\r\n    \r\n            } catch (bytes memory) {\r\n                emit BatchQueryError(\r\n                    _responseReport.queryId,\r\n                    _revertUnhandledExceptionReason()\r\n                );\r\n            }\r\n        }\r\n    }\r\n\r\n    function rollupQueryResponseProof(\r\n            Witnet.FastForward[] calldata _witOracleRollup, \r\n            Witnet.DataPullReport calldata _responseReport,\r\n            bytes32[] calldata _queryResponseReportMerkleProof\r\n        ) \r\n        virtual override external\r\n        returns (uint256)\r\n    {\r\n        try WitOracleTrustlessDataLib.rollupQueryResponseProof(\r\n            _witOracleRollup,\r\n            _responseReport,\r\n            _queryResponseReportMerkleProof,\r\n            QUERY_AWAITING_BLOCKS,\r\n            QUERY_REPORTING_STAKE\r\n            \r\n        ) returns (\r\n            uint256 _evmReward\r\n        ) {\r\n            return _evmReward;\r\n        }\r\n        catch Error(string memory _reason) {\r\n            _revert(_reason);\r\n        }\r\n        catch (bytes memory) {\r\n            _revertUnhandledException();\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleBaseQueriableUpgradable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleBaseQueriableTrustless.sol\";\r\nimport \"../WitnetUpgradableBase.sol\";\r\n\r\n/// @title Queriable WitOracle \"trustless\" but yet \"upgradable\" base implementation.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleBaseQueriableUpgradable\r\n    is \r\n        WitOracleBaseQueriableTrustless,\r\n        WitnetUpgradableBase\r\n{    \r\n    constructor(\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        Ownable(msg.sender)\r\n        WitnetUpgradableBase(\r\n            _upgradable,\r\n            _versionTag,\r\n            \"io.witnet.proxiable.board\"\r\n        )\r\n    {}\r\n\r\n\r\n    // ================================================================================================================\r\n    // ---Upgradeable -------------------------------------------------------------------------------------------------\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    function __initializeUpgradableData(bytes memory _initData) virtual override internal {\r\n        if (__proxiable().codehash == bytes32(0)) {\r\n            // upon first initialization, store genesis beacon\r\n            WitOracleTrustlessDataLib.data().beacons[\r\n                Witnet.WIT_2_GENESIS_BEACON_INDEX\r\n            ] = Witnet.Beacon({\r\n                index: Witnet.WIT_2_GENESIS_BEACON_INDEX,\r\n                prevIndex: Witnet.WIT_2_GENESIS_BEACON_PREV_INDEX,\r\n                prevRoot: Witnet.WIT_2_GENESIS_BEACON_PREV_ROOT,\r\n                ddrTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DDR_TALLIES_MERKLE_ROOT,\r\n                droTalliesMerkleRoot: Witnet.WIT_2_GENESIS_BEACON_DRO_TALLIES_MERKLE_ROOT,\r\n                nextCommitteeAggPubkey: [\r\n                    Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_0,\r\n                    Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_1,\r\n                    Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_2,\r\n                    Witnet.WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_3\r\n                ]\r\n            });\r\n        } else {\r\n            // otherwise, store beacon read from _initData, if any\r\n            if (_initData.length > 0) {\r\n                Witnet.Beacon memory _initBeacon = abi.decode(_initData, (Witnet.Beacon));\r\n                WitOracleTrustlessDataLib.data().beacons[_initBeacon.index] = _initBeacon;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleRadonRegistryBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.4 <0.9.0;\r\n\r\nimport \"../../WitOracleRadonRegistry.sol\";\r\nimport \"../../data/WitOracleRadonRegistryData.sol\";\r\nimport \"../../interfaces/legacy/IWitOracleRadonRegistryLegacy.sol\";\r\nimport \"../../libs/WitOracleRadonEncodingLib.sol\";\r\n\r\n/// @title Witnet Request Board EVM-default implementation contract.\r\n/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.\r\n/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.\r\n/// The result of the requests will be posted back to this contract by the bridge nodes too.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleRadonRegistryBase\r\n    is \r\n        WitOracleRadonRegistry,\r\n        WitOracleRadonRegistryData,\r\n        IWitOracleRadonRegistryLegacy\r\n{   \r\n    using Witnet for bytes;\r\n    using Witnet for string;\r\n    using Witnet for Witnet.QuerySLA;\r\n    using Witnet for Witnet.RadonHash;\r\n    \r\n    using WitOracleRadonEncodingLib for Witnet.RadonDataTypes;\r\n    using WitOracleRadonEncodingLib for Witnet.RadonReducer;\r\n    using WitOracleRadonEncodingLib for Witnet.RadonRetrieval;\r\n    using WitOracleRadonEncodingLib for Witnet.RadonRetrieval[];\r\n    using WitOracleRadonEncodingLib for Witnet.RadonRetrievalMethods;\r\n    using WitOracleRadonEncodingLib for Witnet.RadonSLAv1;\r\n\r\n    modifier radonRequestExists(Witnet.RadonHash _radHash) {\r\n        _require(\r\n            __database().radsBytecode[_radHash].length > 0,\r\n            \"unverified data request\"\r\n        ); _;\r\n    }\r\n    \r\n    modifier radonRetrievalExists(bytes32 _hash) {\r\n        _require(\r\n            __database().retrievals[_hash].method != Witnet.RadonRetrievalMethods.Unknown,\r\n            \"unverified data source\"\r\n        ); _;\r\n    }\r\n\r\n    function _witOracleHash(bytes memory chunk) virtual internal pure returns (Witnet.RadonHash) {\r\n        return Witnet.RadonHash.wrap(sha256(chunk));\r\n    }\r\n\r\n    receive() external payable {\r\n        _revert(\"no transfers\");\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Implementation of 'IWitOracleRadonRegistry' -----------------------------------------------------------------------\r\n\r\n    function bytecodeOf(Witnet.RadonHash _radHash, Witnet.QuerySLA calldata _sla)\r\n        override external view \r\n        returns (bytes memory)\r\n    {\r\n        bytes memory _radBytecode = lookupRadonRequestBytecode(_radHash);\r\n        return abi.encodePacked(\r\n            WitOracleRadonEncodingLib.encode(uint64(_radBytecode.length), 0x0a),\r\n            _radBytecode,\r\n            _sla.toV1().encode()\r\n        );\r\n    }\r\n\r\n    function bytecodeOf(bytes calldata _radBytecode, Witnet.QuerySLA calldata _sla)\r\n        override external pure\r\n        returns (bytes memory)\r\n    {\r\n        return abi.encodePacked(\r\n            WitOracleRadonEncodingLib.encode(uint64(_radBytecode.length), 0x0a),\r\n            _radBytecode,\r\n            _sla.toV1().encode()\r\n        );\r\n    }\r\n\r\n    function isVerifiedRadonReducer(bytes32 _radonReducerHash) external view override returns (bool) {\r\n        return (\r\n            uint8(__database().reducers[_radonReducerHash].opcode) != uint8(0)\r\n        );\r\n    }\r\n\r\n    function isVerifiedRadonRequest(Witnet.RadonHash _radonRequestHash) external view override returns (bool) {\r\n        return (\r\n            __database().radsBytecode[_radonRequestHash].length > 0\r\n        );\r\n    }\r\n\r\n    function isVerifiedRadonRetrieval(bytes32 _radonRetrievalHash) external view override returns (bool) {\r\n        return (\r\n            __database().retrievals[_radonRetrievalHash].method != Witnet.RadonRetrievalMethods.Unknown\r\n        );\r\n    }\r\n\r\n    function hashOf(bytes calldata _radBytecode) external pure override returns (Witnet.RadonHash) {\r\n        return _witOracleHash(_radBytecode);\r\n    }\r\n\r\n    function lookupRadonReducer(bytes32 _hash)\r\n        virtual override \r\n        public view\r\n        returns (Witnet.RadonReducer memory _reducer)\r\n    {   \r\n        _reducer = __database().reducers[_hash];\r\n        _require(uint8(_reducer.opcode) != 0, \"unverified data reducer\");\r\n    }\r\n\r\n    function lookupRadonRequestBytecode(Witnet.RadonHash _radHash)\r\n        public view override\r\n        radonRequestExists(_radHash)\r\n        returns (bytes memory)\r\n    {\r\n        return __database().radsBytecode[_radHash];\r\n    }\r\n\r\n    function lookupRadonRequestCrowdAttestationTally(Witnet.RadonHash _radHash)\r\n        override external view\r\n        radonRequestExists(_radHash)\r\n        returns (Witnet.RadonReducer memory)\r\n    {\r\n        return lookupRadonReducer(__database().radsInfo[_radHash].crowdAttestationTallyHash);\r\n    }\r\n\r\n    function lookupRadonRequestRetrievals(Witnet.RadonHash _radHash)\r\n        override public view \r\n        radonRequestExists(_radHash)\r\n        returns (Witnet.RadonRetrieval[] memory _retrievals)\r\n    {\r\n        // TODO: disassemble radon request's bytecode into array of Radon Retrievals,\r\n        // data structs need not to be saved in storage.\r\n        _retrievals = new Witnet.RadonRetrieval[](__requests(_radHash).retrievals.length);\r\n        for (uint _ix = 0; _ix < _retrievals.length; _ix ++) {\r\n            _retrievals[_ix] = __database().retrievals[\r\n                __requests(_radHash).retrievals[_ix]\r\n            ];\r\n        }\r\n    }\r\n\r\n    function lookupRadonRequestRetrievalsAggregator(Witnet.RadonHash _radHash)\r\n        override external view\r\n        radonRequestExists(_radHash)\r\n        returns (Witnet.RadonReducer memory)\r\n    {\r\n        return lookupRadonReducer(__database().radsInfo[_radHash].dataSourcesAggregatorHash);\r\n    }\r\n\r\n    function lookupRadonRequestRetrievalsCount(Witnet.RadonHash _radHash)\r\n        override external view\r\n        returns (uint8)\r\n    {\r\n        return __database().radsInfo[_radHash].dataSourcesCount;\r\n    }\r\n\r\n    function lookupRadonRetrieval(bytes32 _hash)\r\n        override public view\r\n        radonRetrievalExists(_hash)\r\n        returns (Witnet.RadonRetrieval memory _source)\r\n    {\r\n        return __database().retrievals[_hash];\r\n    }\r\n\r\n    function lookupRadonRetrievalArgsCount(bytes32 _hash)\r\n        override external view\r\n        radonRetrievalExists(_hash)\r\n        returns (uint8)\r\n    {\r\n        return __database().retrievals[_hash].argsCount;\r\n    }\r\n\r\n    function lookupRadonRetrievalResultDataType(bytes32 _hash)\r\n        override public view\r\n        radonRetrievalExists(_hash)\r\n        returns (Witnet.RadonDataTypes)\r\n    {\r\n        return __database().retrievals[_hash].dataType;\r\n    }\r\n\r\n    function lookupRadonRequestResultDataType(Witnet.RadonHash _radHash)\r\n        override external view\r\n        radonRequestExists(_radHash)\r\n        returns (Witnet.RadonDataTypes _resultDataType)\r\n    {\r\n        _resultDataType = __database().radsInfo[_radHash].resultDataType;\r\n        if (uint8(_resultDataType) == 0) {\r\n            _resultDataType = lookupRadonRetrievalResultDataType(\r\n                __database().legacyRequests[_radHash].retrievals[0]\r\n            );\r\n        }\r\n    }\r\n\r\n    function verifyRadonReducer(Witnet.RadonReducer memory _reducer)\r\n        virtual override public\r\n        returns (bytes32 hash)\r\n    {\r\n        hash = bytes32(bytes15(keccak256(abi.encode(_reducer))));\r\n        Witnet.RadonReducer storage __reducer = __database().reducers[hash];\r\n        if (\r\n            uint8(__reducer.opcode) == 0\r\n                // && __reducer.filters.length == 0\r\n        ) {\r\n            _reducer.validate();\r\n            __reducer.opcode = _reducer.opcode;\r\n            __pushRadonReducerFilters(__reducer, _reducer.filters);\r\n            emit NewRadonReducer(hash);\r\n        }\r\n    }\r\n    \r\n    function verifyRadonRequest(\r\n            bytes32[] calldata _retrieveHashes,\r\n            Witnet.RadonReducer calldata _aggregateReducer,\r\n            Witnet.RadonReducer calldata _tallyReducer\r\n        ) \r\n        override external \r\n        returns (Witnet.RadonHash radHash)\r\n    {\r\n        return __verifyRadonRequest(\r\n            _retrieveHashes,\r\n            new string[][](_retrieveHashes.length),\r\n            verifyRadonReducer(_aggregateReducer),\r\n            verifyRadonReducer(_tallyReducer)\r\n        );\r\n    }\r\n\r\n    function verifyRadonRequest(\r\n            bytes32[] calldata _retrieveHashes,\r\n            bytes32 _aggregateReducerHash,\r\n            bytes32 _tallyReducerHash\r\n        )\r\n        override external\r\n        returns (Witnet.RadonHash radHash)\r\n    {\r\n        return __verifyRadonRequest(\r\n            _retrieveHashes,\r\n            new string[][](_retrieveHashes.length),\r\n            _aggregateReducerHash,\r\n            _tallyReducerHash\r\n        );\r\n    }\r\n\r\n    function verifyRadonRequest(\r\n            bytes32[] calldata _retrieveHashes,\r\n            string[][] calldata _retrieveArgsValues,\r\n            Witnet.RadonReducer calldata _aggregateReducer,\r\n            Witnet.RadonReducer calldata _tallyReducer\r\n        ) \r\n        override external \r\n        returns (Witnet.RadonHash)\r\n    {\r\n        return __verifyRadonRequest(\r\n            _retrieveHashes, \r\n            _retrieveArgsValues, \r\n            verifyRadonReducer(_aggregateReducer), \r\n            verifyRadonReducer(_tallyReducer)\r\n        );\r\n    }\r\n\r\n    function verifyRadonRequest(\r\n            bytes32[] calldata _retrieveHashes,\r\n            string[][] calldata _retrieveArgsValues,\r\n            bytes32 _aggregateReducerHash,\r\n            bytes32 _tallyReducerHash\r\n        )\r\n        override external\r\n        returns (Witnet.RadonHash)\r\n    {\r\n        return __verifyRadonRequest(\r\n            _retrieveHashes,\r\n            _retrieveArgsValues,\r\n            _aggregateReducerHash,\r\n            _tallyReducerHash\r\n        );\r\n    }\r\n\r\n    function verifyRadonRequest(\r\n            bytes32 modalRetrieveHash,\r\n            string[] calldata modalArgs,\r\n            string[] calldata modalUrls,\r\n            bytes32 dataSourcesAggregatorHash,\r\n            bytes32 crowdAttestationTallyHash\r\n        )\r\n        override external \r\n        returns (Witnet.RadonHash _radHash)\r\n    {\r\n        bytes32 hash = keccak256(abi.encode(\r\n            modalRetrieveHash,\r\n            modalUrls,\r\n            modalArgs,\r\n            dataSourcesAggregatorHash,\r\n            crowdAttestationTallyHash\r\n        ));\r\n        _radHash = __database().rads[hash];\r\n        if (__database().rads[hash].isZero()) {\r\n            Witnet.RadonRetrieval[] memory _retrievals = new Witnet.RadonRetrieval[](modalUrls.length);\r\n            for (uint _ix = 0; _ix < modalUrls.length; ++ _ix) {\r\n                if (_ix == 0) {\r\n                    _retrievals[0] = lookupRadonRetrieval(modalRetrieveHash);\r\n                } else {\r\n                    _retrievals[_ix] = _retrievals[0];\r\n                }\r\n                _retrievals[_ix].url = modalUrls[_ix];\r\n            }\r\n\r\n            // Compose radon request bytecode:\r\n            bytes memory _radBytecode = _retrievals.encode(\r\n                modalArgs,\r\n                __database().reducers[dataSourcesAggregatorHash].encode(),\r\n                __database().reducers[crowdAttestationTallyHash].encode()\r\n            );\r\n            _require(\r\n                _radBytecode.length <= 65535,\r\n                \"too big request\"\r\n            );\r\n            \r\n            // Compute radhash \r\n            _radHash = _witOracleHash(_radBytecode);\r\n            __database().rads[hash] = _radHash;\r\n            // Add request metadata and rad bytecode to storage:\r\n            __database().radsBytecode[_radHash] = _radBytecode;\r\n            __database().radsInfo[_radHash] = RadonRequestInfo({\r\n                crowdAttestationTallyHash: bytes15(crowdAttestationTallyHash),\r\n                dataSourcesCount: uint8(modalUrls.length),\r\n                dataSourcesAggregatorHash: bytes15(dataSourcesAggregatorHash),\r\n                resultDataType: _retrievals[0].dataType\r\n            });\r\n            \r\n            // Emit event\r\n            emit NewRadonRequest(_radHash);\r\n        }\r\n    }\r\n\r\n    function verifyRadonRetrieval(\r\n            Witnet.RadonRetrievalMethods _requestMethod,\r\n            string memory _requestURL,\r\n            string memory _requestBody,\r\n            string[2][] memory  _requestHeaders,\r\n            bytes memory _requestRadonScript\r\n        )\r\n        virtual override public\r\n        returns (bytes32 hash)\r\n    {\r\n        // validate data source params\r\n        hash = _requestMethod.validate(\r\n            _requestURL, \r\n            _requestBody, \r\n            _requestHeaders, \r\n            _requestRadonScript\r\n        );\r\n\r\n        // should it be a new data source:\r\n        if (\r\n            __database().retrievals[hash].method == Witnet.RadonRetrievalMethods.Unknown\r\n        ) {\r\n            // compose data source and save it in storage:\r\n            __database().retrievals[hash] = Witnet.RadonRetrieval({\r\n                argsCount:\r\n                    WitnetBuffer.argsCountOf(\r\n                        abi.encode(\r\n                            _requestURL, bytes(\" \"),\r\n                            _requestBody, bytes(\" \"),\r\n                            _requestHeaders, bytes(\" \"),\r\n                            _requestRadonScript\r\n                        )\r\n                    ),\r\n\r\n                method:\r\n                    _requestMethod,\r\n\r\n                dataType:\r\n                    WitOracleRadonEncodingLib.verifyRadonScriptResultDataType(_requestRadonScript),\r\n\r\n                url:\r\n                    _requestURL,\r\n\r\n                body:\r\n                    _requestBody,\r\n\r\n                headers:\r\n                    _requestHeaders,\r\n\r\n                radonScript:\r\n                    _requestRadonScript\r\n            });\r\n            emit NewRadonRetrieval(hash);\r\n        }\r\n    }\r\n\r\n    // function verifyRadonRetrieval(\r\n    //         bytes32 _baseRetrieveHash,\r\n    //         string calldata _lastArgValue\r\n    //     )\r\n    //     override external\r\n    //     returns (bytes32)\r\n    // {\r\n    //     Witnet.RadonRetrieval memory _retrieval = lookupRadonRetrieval(_baseRetrieveHash);\r\n    //     _require(\r\n    //         _retrieval.argsCount > 0,\r\n    //         \"non-parameterized radon retrieval\"\r\n    //     );\r\n    //     _retrieval = _retrieval.replaceWildcards(\r\n    //         _retrieval.argsCount - 1, \r\n    //         _lastArgValue\r\n    //     );\r\n    //     return verifyRadonRetrieval(\r\n    //         _retrieval.method,\r\n    //         _retrieval.url,\r\n    //         _retrieval.body,\r\n    //         _retrieval.headers,\r\n    //         _retrieval.radonScript\r\n    //     );\r\n    // }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- IWitOracleRadonRegistryLegacy ---------------------------------------------------------------------------------\r\n\r\n    function bytecodeOf(Witnet.RadonHash _radHash)\r\n        external view override\r\n        radonRequestExists(_radHash)\r\n        returns (bytes memory)\r\n    {\r\n        return lookupRadonRequestBytecode(_radHash);\r\n    }\r\n\r\n    function lookupRadonRequest(Witnet.RadonHash _radHash)\r\n        override external view\r\n        returns (Witnet.RadonRequest memory)\r\n    {\r\n        return Witnet.RadonRequest({\r\n            retrieve:  lookupRadonRequestRetrievals(_radHash),\r\n            aggregate: lookupRadonRequestAggregator(_radHash),\r\n            tally:     lookupRadonRequestTally(_radHash)\r\n        });\r\n    }\r\n\r\n    function lookupRadonRequestAggregator(Witnet.RadonHash _radHash)\r\n        override public view\r\n        radonRequestExists(_radHash)\r\n        returns (Witnet.RadonReducer memory)\r\n    {\r\n        if (__requests(_radHash).legacyTallyHash != bytes32(0)) {\r\n            return lookupRadonReducer(__requests(_radHash).aggregateTallyHashes);\r\n        } else {\r\n            return lookupRadonReducer(bytes16(__requests(_radHash).aggregateTallyHashes));\r\n        }\r\n    }\r\n\r\n    function lookupRadonRequestResultMaxSize(bytes32 _radHash) \r\n        override external view\r\n        radonRequestExists(Witnet.RadonHash.wrap(_radHash)) \r\n        returns (uint16)\r\n    {\r\n        return 32;\r\n    }\r\n\r\n    // function lookupRadonRequestRetrievalByIndex(Witnet.RadonHash _radHash, uint256 _index) \r\n    //     override external view \r\n    //     radonRequestExists(_radHash)\r\n    //     returns (Witnet.RadonRetrieval memory)\r\n    // {\r\n    //     _require(_index < __requests(_radHash).retrievals.length, \"out of range\");\r\n    //     return __database().retrievals[\r\n    //         __requests(_radHash).retrievals[_index]\r\n    //     ];\r\n    // }\r\n\r\n    function lookupRadonRequestSources(bytes32 _radHash) \r\n        override external view \r\n        radonRequestExists(Witnet.RadonHash.wrap(_radHash))\r\n        returns (bytes32[] memory)\r\n    {\r\n        return __requests(Witnet.RadonHash.wrap(_radHash)).retrievals;\r\n    }\r\n\r\n    function lookupRadonRequestSourcesCount(bytes32 _radHash)\r\n        override external view \r\n        radonRequestExists(Witnet.RadonHash.wrap(_radHash))\r\n        returns (uint)\r\n    {\r\n        return __requests(Witnet.RadonHash.wrap(_radHash)).retrievals.length;\r\n    }\r\n\r\n    function verifyRadonRequest(\r\n            bytes32[] calldata _retrieveHashes,\r\n            bytes32 _aggregateReducerHash,\r\n            bytes32 _tallyReducerHash,\r\n            uint16,\r\n            string[][] calldata _retrieveArgsValues\r\n        )\r\n        virtual override public\r\n        returns (bytes32)\r\n    {\r\n        return Witnet.RadonHash.unwrap(__verifyRadonRequest(\r\n            _retrieveHashes,\r\n            _retrieveArgsValues,\r\n            _aggregateReducerHash,\r\n            _tallyReducerHash\r\n        ));\r\n    }\r\n\r\n    function lookupRadonRequestTally(Witnet.RadonHash _radHash)\r\n        override public view\r\n        radonRequestExists(_radHash)\r\n        returns (Witnet.RadonReducer memory)\r\n    {\r\n        if (__requests(_radHash).legacyTallyHash != bytes32(0)) {\r\n            return lookupRadonReducer(__requests(_radHash).legacyTallyHash);\r\n        } else {\r\n            return lookupRadonReducer(bytes16(__requests(_radHash).aggregateTallyHashes << 128));\r\n        }\r\n    }\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Internal methods -------------------------------------------------------------------------------------------\r\n\r\n    function __verifyRadonRequest(\r\n            bytes32[] calldata _retrieveHashes,\r\n            string[][] memory _retrieveArgsValues,\r\n            bytes32 _aggregateReducerHash,\r\n            bytes32 _tallyReducerHash\r\n        )\r\n        virtual internal\r\n        returns (Witnet.RadonHash _radHash)\r\n    {\r\n        // calculate unique hash:\r\n        bytes32 hash = keccak256(abi.encode(\r\n            _retrieveHashes,\r\n            _retrieveArgsValues,\r\n            _aggregateReducerHash, \r\n            _tallyReducerHash\r\n        ));\r\n        \r\n        // verify, compose and register only if hash is not yet known:\r\n        _radHash = __database().rads[hash];\r\n        if (__database().rads[hash].isZero()) {\r\n        \r\n            // Check that at least one source is provided;\r\n            _require(\r\n                _retrieveHashes.length > 0 && _retrieveHashes.length < 256,\r\n                \"no retrievals\"\r\n            );\r\n            \r\n            // Check that number of args arrays matches the number of sources:\r\n            _require(\r\n                _retrieveHashes.length == _retrieveArgsValues.length,\r\n                \"args mismatch\"\r\n            );\r\n            \r\n            // Check result type consistency among all sources:\r\n            Witnet.RadonDataTypes _resultDataType;\r\n            Witnet.RadonRetrieval[] memory _retrievals = new Witnet.RadonRetrieval[](_retrieveHashes.length);\r\n            for (uint _ix = 0; _ix < _retrieveHashes.length; _ix ++) {\r\n                _retrievals[_ix] = __database().retrievals[_retrieveHashes[_ix]];\r\n                _require(\r\n                    _retrievals[_ix].method != Witnet.RadonRetrievalMethods.Unknown,\r\n                    \"unknown retrieval\"\r\n                );\r\n                // Check all sources return same Radon data type:\r\n                if (_ix == 0) {\r\n                    _resultDataType = _retrievals[0].dataType;\r\n                } else if (_resultDataType != _retrievals[_ix].dataType) {\r\n                    _revert(\"mismatching retrievals\");\r\n                }\r\n                // check enough args are provided for each source\r\n                if (_retrieveArgsValues[_ix].length != uint(_retrievals[_ix].argsCount)) {\r\n                    _revert(string(abi.encodePacked(\r\n                        \"mismatching args count on retrieval #\",\r\n                        Witnet.toString(_ix + 1)\r\n                    )));\r\n                }\r\n            }\r\n            \r\n            // Compose radon request bytecode:\r\n            bytes memory _bytecode = _retrievals.encode(\r\n                _retrieveArgsValues, \r\n                __database().reducers[_aggregateReducerHash].encode(),\r\n                __database().reducers[_tallyReducerHash].encode(),\r\n                0\r\n            );\r\n            _require(\r\n                _bytecode.length <= 65535,\r\n                \"too big request\"\r\n            );\r\n        \r\n            // Calculate radhash and add request metadata and rad bytecode to storage:\r\n            _radHash = _witOracleHash(_bytecode);\r\n            __database().rads[hash] = _radHash;\r\n            __database().radsBytecode[_radHash] = _bytecode;\r\n            __database().radsInfo[_radHash] = RadonRequestInfo({\r\n                crowdAttestationTallyHash: bytes15(_tallyReducerHash),\r\n                dataSourcesCount: uint8(_retrieveHashes.length),\r\n                dataSourcesAggregatorHash: bytes15(_aggregateReducerHash),\r\n                resultDataType: _resultDataType\r\n            });\r\n\r\n            // Emit event\r\n            emit NewRadonRequest(_radHash);\r\n        }\r\n    }\r\n\r\n    function __pushRadonReducerFilters(\r\n            Witnet.RadonReducer storage __reducer,\r\n            Witnet.RadonFilter[] memory _filters\r\n        )\r\n        internal\r\n    {\r\n        for (uint _ix = 0; _ix < _filters.length; _ix ++) {\r\n            __reducer.filters.push(_filters[_ix]);\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleRadonRegistryBaseUpgradable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.4 <0.9.0;\r\n\r\nimport \"../WitnetUpgradableBase.sol\";\r\nimport \"../base/WitOracleRadonRegistryBase.sol\";\r\n\r\n/// @title Witnet Request Board EVM-default implementation contract.\r\n/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.\r\n/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.\r\n/// The result of the requests will be posted back to this contract by the bridge nodes too.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleRadonRegistryBaseUpgradable\r\n    is \r\n        WitOracleRadonRegistryBase,\r\n        WitnetUpgradableBase\r\n{    \r\n    constructor(\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        Ownable(address(msg.sender))\r\n        WitnetUpgradableBase(\r\n            _upgradable,\r\n            _versionTag,\r\n            \"io.witnet.proxiable.bytecodes\"\r\n        )\r\n    {}\r\n    \r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'Upgradeable' ------------------------------------------------------------------------------------\r\n\r\n    function __initializeUpgradableData(bytes memory) virtual override internal {}\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Overrides 'Ownable2Step' -----------------------------------------------------------------------------------\r\n\r\n    /// Returns the address of the pending owner.\r\n    function pendingOwner()\r\n        public view\r\n        virtual override\r\n        returns (address)\r\n    {\r\n        return __bytecodes().pendingOwner;\r\n    }\r\n\r\n    /// Returns the address of the current owner.\r\n    function owner()\r\n        public view\r\n        virtual override\r\n        returns (address)\r\n    {\r\n        return __bytecodes().owner;\r\n    }\r\n\r\n    /// Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\r\n    /// @dev Can only be called by the current owner.\r\n    function transferOwnership(address _newOwner)\r\n        public\r\n        virtual override\r\n        onlyOwner\r\n    {\r\n        __bytecodes().pendingOwner = _newOwner;\r\n        emit OwnershipTransferStarted(owner(), _newOwner);\r\n    }\r\n\r\n    /// @dev Transfers ownership of the contract to a new account (`_newOwner`) and deletes any pending owner.\r\n    /// @dev Internal function without access restriction.\r\n    function _transferOwnership(address _newOwner)\r\n        internal\r\n        virtual override\r\n    {\r\n        delete __bytecodes().pendingOwner;\r\n        address _oldOwner = owner();\r\n        if (_newOwner != _oldOwner) {\r\n            __bytecodes().owner = _newOwner;\r\n            emit OwnershipTransferred(_oldOwner, _newOwner);\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleRadonRequestFactoryBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../WitOracleRadonRequestFactory.sol\";\r\n\r\nimport \"./WitOracleRadonRequestFactoryModals.sol\";\r\nimport \"./WitOracleRadonRequestFactoryTemplates.sol\";\r\n\r\nabstract contract WitOracleRadonRequestFactoryBase\r\n    is\r\n        WitOracleRadonRequestFactory\r\n{\r\n    using Witnet for Witnet.RadonHash;\r\n\r\n    /// @notice Reference to the Witnet Request Board that all templates built out from this factory will refer to.\r\n    address immutable public override witOracle;\r\n    \r\n    IWitOracleRadonRegistry immutable internal __witOracleRadonRegistry;\r\n    \r\n    WitOracleRadonRequestFactoryModals immutable public witOracleRadonRequestModalsBuilder;\r\n    WitOracleRadonRequestFactoryTemplates immutable public witOracleRadonRequestTemplatesBuilder;\r\n\r\n    constructor(\r\n            address _witOracleRadonRequestModalsBuilder,\r\n            address _witOracleRadonRequestTemplatesBuilder\r\n        )\r\n    {\r\n        witOracle = IWitOracleAppliance(_witOracleRadonRequestModalsBuilder).witOracle();\r\n        _require(\r\n            witOracle != address(0) \r\n                && witOracle.code.length > 0\r\n                && witOracle == IWitOracleAppliance(_witOracleRadonRequestTemplatesBuilder).witOracle(),\r\n            \"invalid builders\"\r\n        );\r\n        __witOracleRadonRegistry = IWitOracle(witOracle).registry();\r\n        witOracleRadonRequestModalsBuilder = WitOracleRadonRequestFactoryModals(_witOracleRadonRequestModalsBuilder);\r\n        witOracleRadonRequestTemplatesBuilder = WitOracleRadonRequestFactoryTemplates(_witOracleRadonRequestTemplatesBuilder);\r\n    }\r\n\r\n    /// ===============================================================================================================\r\n    /// --- Implementation of IWitOracleRadonRequestFactory -----------------------------------------------------------\r\n\r\n    function buildRadonRequestModal(\r\n            DataSourceRequest calldata commonDataRequest,\r\n            Witnet.RadonReducer memory crowdAttestationTally\r\n        )\r\n        virtual override\r\n        external \r\n        returns (IWitOracleRadonRequestModal)\r\n    {\r\n        bytes32 _commonRetrievalHash = __witOracleRadonRegistry.verifyRadonRetrieval(\r\n            commonDataRequest.method,\r\n            \"\",\r\n            commonDataRequest.body,\r\n            commonDataRequest.headers,\r\n            commonDataRequest.script\r\n        );\r\n        bytes15 _crowdAttestationTallyHash = bytes15(__witOracleRadonRegistry.verifyRadonReducer(\r\n            crowdAttestationTally\r\n        ));\r\n        address _modal = witOracleRadonRequestModalsBuilder.determineAddress(\r\n            _commonRetrievalHash,\r\n            _crowdAttestationTallyHash\r\n        );\r\n        if (_modal.code.length == 0) {\r\n            witOracleRadonRequestModalsBuilder.buildRadonRequestModal(\r\n                _commonRetrievalHash,\r\n                _crowdAttestationTallyHash\r\n            );\r\n            _checkCloneWasDeployed(_modal);\r\n            emit NewRadonRequestModal(_modal);\r\n        }\r\n        return IWitOracleRadonRequestModal(_modal);\r\n    }\r\n\r\n    function buildRadonRequestTemplate(\r\n            bytes32[] memory radonRetrieveHashes,\r\n            Witnet.RadonReducer memory dataSourcesAggregator,\r\n            Witnet.RadonReducer memory crowdAttestationTally\r\n        )\r\n        virtual override\r\n        public\r\n        returns (IWitOracleRadonRequestTemplate)\r\n    {\r\n        bytes15 _dataSourcesAggregatorHash = bytes15(__witOracleRadonRegistry.verifyRadonReducer(dataSourcesAggregator));\r\n        bytes15 _crowdAttestationTallyHash = bytes15(__witOracleRadonRegistry.verifyRadonReducer(crowdAttestationTally));\r\n        address _template = witOracleRadonRequestTemplatesBuilder.determineAddress(\r\n            radonRetrieveHashes,\r\n            _dataSourcesAggregatorHash,\r\n            _crowdAttestationTallyHash\r\n        );\r\n        if (_template.code.length == 0) {\r\n            witOracleRadonRequestTemplatesBuilder.buildRadonRequestTemplate(\r\n                radonRetrieveHashes,\r\n                _dataSourcesAggregatorHash,\r\n                _crowdAttestationTallyHash\r\n            );\r\n            _checkCloneWasDeployed(_template);\r\n            emit NewRadonRequestTemplate(_template);\r\n        }\r\n        return IWitOracleRadonRequestTemplate(_template);\r\n    }\r\n\r\n    function buildRadonRequestTemplate(\r\n            DataSource[] calldata dataSources,\r\n            Witnet.RadonReducer calldata dataSourcesAggregator,\r\n            Witnet.RadonReducer calldata crowdAttestationTally\r\n        )\r\n        virtual override\r\n        external \r\n        returns (IWitOracleRadonRequestTemplate)\r\n    {\r\n        bytes32[] memory _radonRetrieveHashes = new bytes32[](dataSources.length);\r\n        for (uint _ix; _ix < dataSources.length; ++ _ix) {\r\n            DataSourceRequest memory _request = dataSources[_ix].request;\r\n            _radonRetrieveHashes[_ix] = __witOracleRadonRegistry.verifyRadonRetrieval(\r\n                _request.method,\r\n                dataSources[_ix].url,\r\n                _request.body,\r\n                _request.headers,\r\n                _request.script\r\n            );\r\n        }\r\n        return buildRadonRequestTemplate(\r\n            _radonRetrieveHashes,\r\n            dataSourcesAggregator,\r\n            crowdAttestationTally\r\n        );\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- Internal virtual methods ----------------------------------------------------------------------------------\r\n\r\n    function _checkCloneWasDeployed(address _clone) virtual internal view {\r\n        _require(\r\n            _clone.code.length > 0,\r\n            \"cannot clone\"\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleRadonRequestFactoryBaseUpgradable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.4 <0.9.0;\r\n\r\nimport \"./WitOracleRadonRequestFactoryBase.sol\";\r\nimport \"../WitnetUpgradableBase.sol\";\r\n\r\n/// @title Witnet Request Board EVM-default implementation contract.\r\n/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.\r\n/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.\r\n/// The result of the requests will be posted back to this contract by the bridge nodes too.\r\n/// @author The Witnet Foundation\r\nabstract contract WitOracleRadonRequestFactoryBaseUpgradable\r\n    is \r\n        WitOracleRadonRequestFactoryBase,\r\n        WitnetUpgradableBase\r\n{   \r\n    // modifier onlyDelegateCalls override(Clonable, Upgradeable) {\r\n    //     _require(\r\n    //         address(this) != _BASE,\r\n    //         \"not a delegate call\"\r\n    //     ); _;\r\n    // }\r\n\r\n    // modifier notOnFactory virtual override {\r\n    //     _require(\r\n    //         address(this) != __proxy()\r\n    //             && address(this) != base(),\r\n    //         \"not on factory\"\r\n    //     ); _;\r\n    // }\r\n\r\n    // modifier onlyOnFactory virtual override {\r\n    //     _require(\r\n    //         address(this) == __proxy()\r\n    //             || address(this) == base(),\r\n    //         \"not the factory\"\r\n    //     ); _;\r\n    // }\r\n\r\n    constructor(\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        Ownable(address(msg.sender))\r\n        WitnetUpgradableBase(\r\n            _upgradable,\r\n            _versionTag,\r\n            \"io.witnet.radon.factory\"\r\n        )\r\n    {\r\n        // // let logic contract be used as a factory, while avoiding further initializations:\r\n        // __proxiable().proxy = address(this);\r\n        // __proxiable().implementation = address(this);\r\n        // __witOracleRequestFactory().owner = address(0);\r\n    }\r\n\r\n    // function version()\r\n    //     virtual override(WitOracleRequestFactoryBase, WitnetUpgradableBase)\r\n    //     public view\r\n    //     returns (string memory)\r\n    // {\r\n    //     return WitnetUpgradableBase.version();\r\n    // }\r\n    \r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'Upgradeable' ------------------------------------------------------------------------------------\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    function __initializeUpgradableData(bytes memory) virtual override internal {\r\n        if (__proxiable().codehash == bytes32(0)) {\r\n            __proxiable().proxy = address(this);\r\n        }\r\n        __proxiable().implementation = base();\r\n    }\r\n\r\n\r\n    // // ================================================================================================================\r\n    // // --- Overrides 'Ownable2Step' -----------------------------------------------------------------------------------\r\n\r\n    // /// @notice Returns the address of the pending owner.\r\n    // function pendingOwner()\r\n    //     public view\r\n    //     virtual override\r\n    //     returns (address)\r\n    // {\r\n    //     return __witOracleRequestFactory().pendingOwner;\r\n    // }\r\n\r\n    // /// @notice Returns the address of the current owner.\r\n    // function owner()\r\n    //     virtual override\r\n    //     public view\r\n    //     returns (address)\r\n    // {\r\n    //     return __witOracleRequestFactory().owner;\r\n    // }\r\n\r\n    // /// @notice Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\r\n    // /// @dev Can only be called by the current owner.\r\n    // function transferOwnership(address _newOwner)\r\n    //     virtual override public\r\n    //     onlyOwner\r\n    // {\r\n    //     __witOracleRequestFactory().pendingOwner = _newOwner;\r\n    //     emit OwnershipTransferStarted(owner(), _newOwner);\r\n    // }\r\n\r\n    // /// @dev Transfers ownership of the contract to a new account (`_newOwner`) and deletes any pending owner.\r\n    // /// @dev Internal function without access restriction.\r\n    // function _transferOwnership(address _newOwner)\r\n    //     internal\r\n    //     virtual override\r\n    // {\r\n    //     delete __witOracleRequestFactory().pendingOwner;\r\n    //     address _oldOwner = owner();\r\n    //     if (_newOwner != _oldOwner) {\r\n    //         __witOracleRequestFactory().owner = _newOwner;\r\n    //         emit OwnershipTransferred(_oldOwner, _newOwner);\r\n    //     }\r\n    // }\r\n\r\n    // // ================================================================================================================\r\n    // /// --- Overrides Clonable ----------------------------------------------------------------------------------------\r\n\r\n    // /// @notice Tells whether a WitOracleRequest or a WitOracleRequestTemplate has been properly initialized.\r\n    // function initialized() virtual override public view returns (bool) {\r\n    //     return (\r\n    //         super.initialized()\r\n    //             || __implementation() == base()\r\n    //     );\r\n    // }\r\n\r\n    // /// @notice Contract address to which clones will be re-directed.\r\n    // function self()\r\n    //     virtual override\r\n    //     public view\r\n    //     returns (address)\r\n    // {\r\n    //     return (__proxy() != address(0)\r\n    //         ? __implementation()\r\n    //         : base()\r\n    //     );\r\n    // }\r\n\r\n    // function _determineWitOracleRequestAddressAndSalt(Witnet.RadonHash _radHash)\r\n    //     virtual override internal view\r\n    //     returns (address, bytes32)\r\n    // {\r\n    //     bytes32 _salt = keccak256(\r\n    //         abi.encodePacked(\r\n    //             Witnet.RadonHash.unwrap(_radHash), \r\n    //             bytes4(_WITNET_UPGRADABLE_VERSION)\r\n    //         )\r\n    //     );\r\n    //     return (\r\n    //         address(uint160(uint256(keccak256(\r\n    //             abi.encodePacked(\r\n    //                 bytes1(0xff),\r\n    //                 address(this),\r\n    //                 _salt,\r\n    //                 keccak256(_cloneBytecode())\r\n    //             )\r\n    //         )))), _salt\r\n    //     );\r\n    // }\r\n\r\n    // function _determineWitOracleRequestTemplateAddressAndSalt(\r\n    //         bytes32[] memory _retrieveHashes,\r\n    //         bytes16 _aggregateReducerHash,\r\n    //         bytes16 _tallyReducerHash\r\n    //     )\r\n    //     virtual override internal view\r\n    //     returns (address, bytes32)\r\n    // {\r\n    //     bytes32 _salt = keccak256(\r\n    //         // As to avoid template address collisions from:\r\n    //         abi.encodePacked( \r\n    //             // - different factory major or mid versions:\r\n    //             bytes4(_WITNET_UPGRADABLE_VERSION),\r\n    //             // - different templates params:\r\n    //             _retrieveHashes,\r\n    //             _aggregateReducerHash,\r\n    //             _tallyReducerHash\r\n    //         )\r\n    //     );\r\n    //     return (\r\n    //         address(uint160(uint256(keccak256(\r\n    //             abi.encodePacked(\r\n    //                 bytes1(0xff),\r\n    //                 address(this),\r\n    //                 _salt,\r\n    //                 keccak256(_cloneBytecode())\r\n    //             )\r\n    //         )))), _salt\r\n    //     );\r\n    // }\r\n}\r\n"
      },
      "project/contracts/core/base/WitOracleRadonRequestFactoryModals.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../interfaces/IWitOracle.sol\";\r\nimport \"../../interfaces/IWitOracleAppliance.sol\";\r\nimport \"../../interfaces/IWitOracleRadonRequestModal.sol\";\r\n\r\nimport \"../../patterns/Clonable.sol\";\r\n\r\nabstract contract WitOracleRadonRequestFactoryModals\r\n    is\r\n        Clonable,\r\n        IWitOracleAppliance,\r\n        IWitOracleRadonRequestModal \r\n{\r\n    function specs() virtual override public view returns (bytes4) {\r\n        return (\r\n            initialized()\r\n                ? type(IWitOracleRadonRequestModal).interfaceId\r\n                : bytes4(0xebb91556) // bytes4(keccak256(abi.encodePacked(\"buildRadonRequestModal(bytes32,bytes15)\")))\r\n                    ^ bytes4(0xa646ccc1) // bytes4(keccak256(abi.encodePacked(\"determineAddress(bytes32,bytes15)\")))\r\n        );\r\n    }\r\n\r\n    /// @notice Reference to the Witnet Request Board that all templates built out from this factory will refer to.\r\n    address immutable public override(IWitOracleAppliance, IWitOracleRadonRequestModal) witOracle;\r\n\r\n    IWitOracleRadonRegistry internal immutable __witOracleRadonRegistry;\r\n    bytes16 internal immutable __radonAggregateHash;\r\n    \r\n    struct Storage {\r\n        /// @notice  Radon retrieval common to all data providers.\r\n        bytes32 radonRetrieveHash;\r\n        /// @notice Crowd attestation tally.\r\n        bytes16 radonTallyHash;\r\n    }\r\n    Storage private __storage;\r\n\r\n    constructor(address _witOracle) {\r\n        _require(_witOracle != address(0) && _witOracle.code.length > 0, \"inexistent Wit/Oracle\");\r\n        witOracle = _witOracle;\r\n        __witOracleRadonRegistry = IWitOracle(witOracle).registry();\r\n        __radonAggregateHash = bytes16(__witOracleRadonRegistry.verifyRadonReducer(\r\n            Witnet.RadonReducer({\r\n                opcode: Witnet.RadonReduceOpcodes.Mode,\r\n                filters: new Witnet.RadonFilter[](0)\r\n            })\r\n        ));\r\n    }\r\n\r\n    function buildRadonRequestModal(\r\n            bytes32 _commonRetrievalHash, \r\n            bytes15 _crowdAttestationTallyHash\r\n        ) \r\n        virtual\r\n        external\r\n        notOnClones\r\n        returns (IWitOracleRadonRequestModal)\r\n    {\r\n        return WitOracleRadonRequestFactoryModals(\r\n            __cloneDeterministic(_determineSaltAndPepper(\r\n                _commonRetrievalHash,\r\n                _crowdAttestationTallyHash\r\n            ))\r\n        ).initialize(\r\n            _commonRetrievalHash,\r\n            _crowdAttestationTallyHash\r\n        );\r\n    }\r\n\r\n    function determineAddress(\r\n            bytes32 _commonRetrievalHash,\r\n            bytes15 _crowdAttestationTallyHash\r\n        )\r\n        virtual //override\r\n        external view\r\n        notOnClones\r\n        returns (address)\r\n    {\r\n        return address(uint160(uint256(keccak256(\r\n            abi.encodePacked(\r\n                bytes1(0xff),\r\n                address(this),\r\n                _determineSaltAndPepper(\r\n                    _commonRetrievalHash,\r\n                    _crowdAttestationTallyHash\r\n                ),\r\n                keccak256(_cloneBytecode())\r\n            )\r\n        ))));\r\n    }\r\n\r\n    function initialize(\r\n            bytes32 _commonRetrievalHash,\r\n            bytes15 _crowdAttestationTallyHash\r\n        )\r\n        virtual\r\n        public \r\n        initializer\r\n        returns (IWitOracleRadonRequestModal)\r\n    {   \r\n        assert(__witOracleRadonRegistry.lookupRadonRetrievalArgsCount(_commonRetrievalHash) >= 1);\r\n        __witOracleRadonRegistry.isVerifiedRadonReducer(_crowdAttestationTallyHash);\r\n        __storage.radonRetrieveHash = _commonRetrievalHash;\r\n        __storage.radonTallyHash = _crowdAttestationTallyHash;\r\n        return IWitOracleRadonRequestModal(address(this));\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    /// --- Clonable implementation and override ----------------------------------------------------------------------\r\n\r\n    /// @notice Tells whether a WitOracleRequest or a WitOracleRequestTemplate has been properly initialized.\r\n    function initialized()\r\n        virtual override(Clonable)\r\n        public view\r\n        returns (bool)\r\n    {\r\n        return __storage.radonRetrieveHash != bytes32(0);\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitOracleRadonRequestModal -------------------------------------------------------------------------------\r\n    \r\n    function getCrowdAttestationTally()\r\n        virtual override\r\n        external view \r\n        onlyOnClones\r\n        returns (Witnet.RadonReducer memory)\r\n    {\r\n        return __witOracleRadonRegistry.lookupRadonReducer(\r\n            __storage.radonTallyHash\r\n        );\r\n    }\r\n\r\n    function getDataResultType()\r\n        virtual override\r\n        external view \r\n        onlyOnClones\r\n        returns (Witnet.RadonDataTypes)\r\n    {\r\n        return __witOracleRadonRegistry.lookupRadonRetrievalResultDataType(\r\n            __storage.radonRetrieveHash\r\n        );\r\n    }\r\n\r\n    function getDataSourceArgsCount(string calldata url)\r\n        virtual override\r\n        external view\r\n        onlyOnClones\r\n        returns (uint8)\r\n    {\r\n        return _max(\r\n            WitnetBuffer.argsCountOf(abi.encode(url)),\r\n            __witOracleRadonRegistry.lookupRadonRetrievalArgsCount(__storage.radonRetrieveHash)\r\n        );\r\n    }\r\n\r\n    function getDataSourcesAggregator() \r\n        virtual override\r\n        external view\r\n        onlyOnClones\r\n        returns (Witnet.RadonReducer memory)\r\n    {\r\n        return __witOracleRadonRegistry.lookupRadonReducer(\r\n            __radonAggregateHash\r\n        );\r\n    }\r\n\r\n    function getRadonModalRetrieval() \r\n        virtual override\r\n        external view \r\n        onlyOnClones\r\n        returns (Witnet.RadonRetrieval memory)\r\n    {\r\n        return __witOracleRadonRegistry.lookupRadonRetrieval(\r\n            __storage.radonRetrieveHash\r\n        );\r\n    }\r\n\r\n    function verifyRadonRequest(\r\n            string[] calldata modalArgs,\r\n            string[] calldata modalUrls\r\n        ) \r\n        virtual override\r\n        external \r\n        onlyOnClones\r\n        returns (Witnet.RadonHash)\r\n    {\r\n        bytes32 _retrieveHash = __storage.radonRetrieveHash;\r\n        uint8 _commonRetrieveArgsCount = __witOracleRadonRegistry.lookupRadonRetrievalArgsCount(__storage.radonRetrieveHash);\r\n        for (uint _ix; _ix < modalUrls.length; _ix ++) {\r\n            _require(\r\n                _max(WitnetBuffer.argsCountOf(abi.encode(modalUrls[_ix])), _commonRetrieveArgsCount) == modalArgs.length,\r\n                \"mismatching args\"\r\n            );\r\n        }\r\n        return __witOracleRadonRegistry.verifyRadonRequest(\r\n            _retrieveHash,\r\n            modalArgs,\r\n            modalUrls,\r\n            __radonAggregateHash,\r\n            __storage.radonTallyHash\r\n        );\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- Internal methods ------------------------------------------------------------------------------------------\r\n\r\n    function _determineSaltAndPepper(\r\n            bytes32 _commonRetrievalHash, \r\n            bytes15 _crowdAttestationTally\r\n        )\r\n        virtual internal view\r\n        returns (bytes32)\r\n    {\r\n        return keccak256(\r\n            abi.encodePacked(\r\n                __SELF,\r\n                _commonRetrievalHash,\r\n                _crowdAttestationTally\r\n            )\r\n        );\r\n    }\r\n\r\n    function _max(uint8 a, uint8 b) internal pure returns (uint8) {\r\n        return (a >= b ? a : b);\r\n    }\r\n}"
      },
      "project/contracts/core/base/WitOracleRadonRequestFactoryTemplates.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../interfaces/IWitOracle.sol\";\r\nimport \"../../interfaces/IWitOracleAppliance.sol\";\r\nimport \"../../interfaces/IWitOracleRadonRequestTemplate.sol\";\r\n\r\nimport \"../../patterns/Clonable.sol\";\r\n\r\nabstract contract WitOracleRadonRequestFactoryTemplates\r\n    is\r\n        Clonable,\r\n        IWitOracleAppliance,\r\n        IWitOracleRadonRequestTemplate \r\n{\r\n    function specs() virtual override public view returns (bytes4) {\r\n        return (\r\n            initialized()\r\n                ? type(IWitOracleRadonRequestTemplate).interfaceId\r\n                : bytes4(0xdccf450a) // bytes4(keccak256(abi.encodePacked(\"buildRadonRequestTemplate(bytes32[],bytes15,bytes15)\")))\r\n                    ^ bytes4(0x5613166e) // bytes4(keccak256(abi.encodePacked(\"determineAddress(bytes32[],bytes15,bytes15)\")))\r\n        );\r\n    }\r\n\r\n    /// @notice Reference to the Witnet Request Board that all templates built out from this factory will refer to.\r\n    address immutable public override(IWitOracleAppliance, IWitOracleRadonRequestTemplate) witOracle;\r\n\r\n    IWitOracleRadonRegistry internal immutable __witOracleRadonRegistry;\r\n    \r\n    struct Storage {\r\n        /// @notice Expected data result for all Radon Requests built out from this template.abi\r\n        Witnet.RadonDataTypes resultDataType;\r\n        /// @notice Parameters count for each data source.\r\n        uint8[] radonRetrieveArgsCount;\r\n        /// @notice Parameterized Radon retrievals.\r\n        bytes32[] radonRetrieveHashes;\r\n        /// @notice Data sources aggregator.\r\n        bytes16 radonAggregateHash;\r\n        /// @notice Crowd attestation tally.\r\n        bytes16 radonTallyHash;\r\n    }\r\n    Storage private __storage;\r\n\r\n    constructor(address _witOracle) {\r\n        _require(\r\n            _witOracle != address(0)\r\n                && _witOracle.code.length > 0, \r\n            \"inexistent Wit/Oracle\"\r\n        );\r\n        witOracle = _witOracle;\r\n        __witOracleRadonRegistry = IWitOracle(witOracle).registry();\r\n    }\r\n\r\n    function buildRadonRequestTemplate(\r\n            bytes32[] calldata _dataRetrieveHashes,\r\n            bytes15 _dataSourcesAggregatorHash,\r\n            bytes15 _crowdAttestationTallyHash\r\n        ) \r\n        virtual //override\r\n        external\r\n        notOnClones\r\n        returns (IWitOracleRadonRequestTemplate)\r\n    {\r\n        return WitOracleRadonRequestFactoryTemplates(\r\n            __cloneDeterministic(_determineSaltAndPepper(\r\n                _dataRetrieveHashes,\r\n                _dataSourcesAggregatorHash,\r\n                _crowdAttestationTallyHash\r\n            ))\r\n        ).initialize(\r\n            _dataRetrieveHashes,\r\n            _dataSourcesAggregatorHash,\r\n            _crowdAttestationTallyHash\r\n        );\r\n    }\r\n\r\n    function determineAddress(\r\n            bytes32[] calldata _dataRetrieveHashes,\r\n            bytes15 _dataSourcesAggregatorHash,\r\n            bytes15 _crowdAttestationTallyHash\r\n        )\r\n        virtual //override\r\n        external view \r\n        notOnClones\r\n        returns (address)\r\n    {\r\n        return address(uint160(uint256(keccak256(\r\n            abi.encodePacked(\r\n                bytes1(0xff),\r\n                address(this),\r\n                _determineSaltAndPepper(\r\n                    _dataRetrieveHashes,\r\n                    _dataSourcesAggregatorHash,\r\n                    _crowdAttestationTallyHash\r\n                ),\r\n                keccak256(_cloneBytecode())\r\n            )\r\n        ))));\r\n    }\r\n\r\n    function initialize(\r\n            bytes32[] calldata _dataRetrieveHashes,\r\n            bytes15 _dataSourcesAggregatorHash,\r\n            bytes15 _crowdAttestationTallyHash\r\n        )\r\n        virtual\r\n        public \r\n        initializer\r\n        returns (IWitOracleRadonRequestTemplate)\r\n    {\r\n        __witOracleRadonRegistry.isVerifiedRadonReducer(_dataSourcesAggregatorHash);\r\n        __witOracleRadonRegistry.isVerifiedRadonReducer(_crowdAttestationTallyHash);\r\n        uint _totalArgs;\r\n        Witnet.RadonDataTypes _resultDataType;\r\n        for (uint _ix = 0; _ix < _dataRetrieveHashes.length; ++ _ix) {\r\n            uint8 _argsCount = __witOracleRadonRegistry.lookupRadonRetrievalArgsCount(_dataRetrieveHashes[_ix]);\r\n            __storage.radonRetrieveArgsCount.push(_argsCount);\r\n            _totalArgs += _argsCount;\r\n            if (_ix == 0) {\r\n                _resultDataType = __witOracleRadonRegistry.lookupRadonRetrievalResultDataType(_dataRetrieveHashes[0]);\r\n            } else {\r\n                if (_resultDataType != __witOracleRadonRegistry.lookupRadonRetrievalResultDataType(_dataRetrieveHashes[_ix])) {\r\n                    _revert(\"mistyped data sources\");\r\n                }\r\n            }\r\n        }\r\n        _require(_totalArgs >= 1, \"unparameterized data sources\");\r\n        __storage.radonRetrieveHashes = _dataRetrieveHashes;\r\n        __storage.radonAggregateHash = _dataSourcesAggregatorHash;\r\n        __storage.radonTallyHash = _crowdAttestationTallyHash;\r\n        __storage.resultDataType = _resultDataType;\r\n        return IWitOracleRadonRequestTemplate(address(this));\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    /// --- Clonable implementation and override ----------------------------------------------------------------------\r\n\r\n    /// @notice Tells whether a WitOracleRequest or a WitOracleRequestTemplate has been properly initialized.\r\n    function initialized()\r\n        virtual override(Clonable)\r\n        public view\r\n        returns (bool)\r\n    {\r\n        return __storage.radonRetrieveHashes.length > 0;\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitOracleRadonRequestTemplate -------------------------------------------------------------------------------\r\n\r\n    function getArgsCount()\r\n        virtual override\r\n        external view\r\n        onlyOnClones\r\n        returns (uint8[] memory)\r\n    {\r\n        return __storage.radonRetrieveArgsCount;\r\n    }\r\n    \r\n    function getCrowdAttestationTally()\r\n        virtual override\r\n        external view \r\n        onlyOnClones\r\n        returns (Witnet.RadonReducer memory)\r\n    {\r\n        return __witOracleRadonRegistry.lookupRadonReducer(\r\n            __storage.radonTallyHash\r\n        );\r\n    }\r\n\r\n    function getDataResultType()\r\n        virtual override\r\n        external view \r\n        onlyOnClones\r\n        returns (Witnet.RadonDataTypes)\r\n    {\r\n        return __storage.resultDataType;\r\n    }\r\n\r\n    function getDataSources()\r\n        virtual override\r\n        external view\r\n        onlyOnClones\r\n        returns (Witnet.RadonRetrieval[] memory _dataSources)\r\n    {\r\n        _dataSources = new Witnet.RadonRetrieval[](__storage.radonRetrieveHashes.length);\r\n        for (uint _ix = 0; _ix < _dataSources.length; ++ _ix) {\r\n            _dataSources[_ix] = __witOracleRadonRegistry.lookupRadonRetrieval(\r\n                __storage.radonRetrieveHashes[_ix]\r\n            );\r\n        }\r\n    }\r\n\r\n    function getDataSourcesAggregator() \r\n        virtual override\r\n        external view\r\n        onlyOnClones\r\n        returns (Witnet.RadonReducer memory)\r\n    {\r\n        return __witOracleRadonRegistry.lookupRadonReducer(\r\n            __storage.radonAggregateHash\r\n        );\r\n    }\r\n\r\n    function verifyRadonRequest(string[][] calldata args)\r\n        virtual override\r\n        external \r\n        onlyOnClones\r\n        returns (Witnet.RadonHash)\r\n    {\r\n        return __witOracleRadonRegistry.verifyRadonRequest(\r\n            __storage.radonRetrieveHashes,\r\n            args,\r\n            __storage.radonAggregateHash,\r\n            __storage.radonTallyHash\r\n        );\r\n    }\r\n\r\n    \r\n    /// ===============================================================================================================\r\n    /// --- Internal methods ------------------------------------------------------------------------------------------\r\n\r\n    function _determineSaltAndPepper(\r\n            bytes32[] calldata _dataRetrieveHashes,\r\n            bytes15 _dataSourcesAggregatorHash,\r\n            bytes15 _crowdAttestationTallyHash\r\n        )\r\n        virtual internal view\r\n        returns (bytes32)\r\n    {\r\n        return keccak256(\r\n            abi.encodePacked(\r\n                __SELF,\r\n                _dataRetrieveHashes,\r\n                _dataSourcesAggregatorHash,\r\n                _crowdAttestationTallyHash\r\n            )\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/trustable/WitOracleTrustableDefault.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleBaseQueriableTrustable.sol\";\r\n\r\n/// @title Queriable WitOracle \"trustable\" implementation.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleTrustableDefault\r\n    is \r\n        WitOracleBaseQueriableTrustable\r\n{\r\n    function class() virtual override public view returns (string memory) {\r\n        return type(WitOracleTrustableDefault).name;\r\n    }\r\n\r\n    constructor(\r\n            EvmImmutables memory _immutables,\r\n            WitOracleRadonRegistry _registry,\r\n            bytes32 _versionTag\r\n        )\r\n        WitOracleBaseQueriable(\r\n            _immutables,\r\n            _registry\r\n        )\r\n        WitOracleBaseQueriableTrustable(_versionTag)\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/trustable/WitOracleTrustableExperimental.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleBaseQueriableTrustable.sol\";\r\nimport \"../../interfaces/IWitOracleQueriableExperimental.sol\";\r\n\r\n/// @title WitOracle \"experimental\" implementation contract.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleTrustableExperimental\r\n    is \r\n        IWitOracleQueriableExperimental,\r\n        WitOracleBaseQueriableTrustable\r\n{\r\n    using WitOracleDataLib for WitOracleDataLib.Committee;\r\n\r\n    function class() virtual override public view returns (string memory) {\r\n        return type(WitOracleTrustableExperimental).name;\r\n    }\r\n\r\n    constructor(\r\n            EvmImmutables memory _immutables,\r\n            WitOracleRadonRegistry _registry,\r\n            bytes32 _versionTag\r\n        )\r\n        WitOracleBaseQueriable(\r\n            _immutables,\r\n            _registry\r\n        )\r\n        WitOracleBaseQueriableTrustable(_versionTag)\r\n    {}\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- IWitOracleQueriableExperimental -------------------------------------------------------------------------------------\r\n\r\n    function extractDelegatedDataRequest(Witnet.QueryId _queryId)\r\n        virtual override public view\r\n        returns (IWitOracleQueriableExperimental.DDR memory _dr)\r\n    {\r\n        Witnet.QueryStatus _queryStatus = getQueryStatus(Witnet.QueryId.unwrap(_queryId));\r\n        if (\r\n            _queryStatus == Witnet.QueryStatus.Posted\r\n                || _queryStatus == Witnet.QueryStatus.Delayed\r\n        ) {\r\n            _dr = WitOracleDataLib.extractDelegatedDataRequest(registry, _queryId);\r\n        }\r\n    }\r\n\r\n    function extractDelegatedDataRequestBatch(Witnet.QueryId[] calldata _queryIds)\r\n        virtual override external view\r\n        returns (IWitOracleQueriableExperimental.DDR[] memory _drs)\r\n    {\r\n        _drs = new DDR[](_queryIds.length);\r\n        for (uint _ix = 0; _ix < _queryIds.length; _ix ++) {\r\n            _drs[_ix] = extractDelegatedDataRequest(_queryIds[_ix]);\r\n        }\r\n    }\r\n\r\n    /// @notice Enables data requesters to settle the actual validators in the Wit/Oracle\r\n    /// @notice sidechain that will be entitled whatsover to solve \r\n    /// @notice data requests, as presumed to be capable of supporting some given `Wit2.Capability`.\r\n    function settleMyOwnServiceCommittee(\r\n            bytes32 _radonHash,\r\n            Witnet.ServiceProvider[] calldata _providers\r\n        )\r\n        virtual override external\r\n    {\r\n        __storage().committees[msg.sender][Witnet.RadonHash.wrap(_radonHash)].settle(_providers);\r\n        emit WitOracleServiceCommittee(\r\n            msg.sender, \r\n            _radonHash, \r\n            _providers\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/trustable/WitOracleTrustableObscuro.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleBaseQueriableTrustable.sol\";\r\n\r\n/// @title Queriable WitOracle \"trustable\" implementation for Obscuro/TEN chains.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleTrustableObscuro\r\n    is \r\n        WitOracleBaseQueriableTrustable\r\n{\r\n    function class() virtual override public view returns (string memory) {\r\n        return type(WitOracleBaseQueriableTrustable).name;\r\n    }\r\n\r\n    constructor(\r\n            EvmImmutables memory _immutables,\r\n            WitOracleRadonRegistry _registry,\r\n            bytes32 _versionTag\r\n        )\r\n        WitOracleBaseQueriable(\r\n            _immutables,\r\n            _registry\r\n        )\r\n        WitOracleBaseQueriableTrustable(_versionTag)\r\n    {}\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'IWitOracle' -------------------------------------------------------------------------------------\r\n\r\n    /// @notice Gets the whole Query data contents, if any, no matter its current status.\r\n    /// @dev Fails if or if `msg.sender` is not the actual requester.\r\n    function getQuery(Witnet.QueryId _queryId)\r\n        public view\r\n        virtual override\r\n        onlyRequester(Witnet.QueryId.unwrap(_queryId))\r\n        returns (Witnet.Query memory)\r\n    {\r\n        return super.getQuery(_queryId);\r\n    }\r\n\r\n    /// @notice Retrieves the whole `Witnet.QueryResponse` record referred to a previously posted Witnet Data Request.\r\n    /// @dev Fails if the `_queryId` is not in 'Reported' status, or if `msg.sender` is not the actual requester.\r\n    /// @param _queryId The unique query identifier\r\n    function getQueryResponse(Witnet.QueryId _queryId)\r\n        public view\r\n        virtual override\r\n        onlyRequester(Witnet.QueryId.unwrap(_queryId))\r\n        returns (Witnet.QueryResponse memory _response)\r\n    {\r\n        return super.getQueryResponse(_queryId);\r\n    }\r\n\r\n    function getQueryResult(uint256 _queryId)\r\n        virtual override\r\n        public view\r\n        onlyRequester(_queryId)\r\n        returns (Witnet.DataResult memory)\r\n    {\r\n        return WitOracleBaseQueriable.getQueryResult(_queryId);\r\n    }\r\n\r\n    function getQueryResultStatus(uint256 _queryId)\r\n        virtual override\r\n        public view\r\n        onlyRequester(_queryId)\r\n        returns (Witnet.ResultStatus)\r\n    {\r\n        return super.getQueryResultStatus(_queryId);\r\n    }\r\n\r\n    function getQueryResultStatusDescription(uint256 _queryId)\r\n        virtual override\r\n        public view\r\n        onlyRequester(_queryId)\r\n        returns (string memory)\r\n    {\r\n        return WitOracleBaseQueriable.getQueryResultStatusDescription(_queryId);\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/trustable/WitOracleTrustableOvm2.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleBaseQueriableTrustable.sol\";\r\n\r\n// solhint-disable-next-line\r\ninterface OVM_GasPriceOracle {\r\n    function getL1Fee(bytes calldata _data) external view returns (uint256);\r\n}\r\n\r\n/// @title Queriable WitOracle \"trustable\" implementation contract for OVM2 chains. \r\n/// @author The Witnet Foundation\r\ncontract WitOracleTrustableOvm2\r\n    is \r\n        WitOracleBaseQueriableTrustable\r\n{\r\n    function class() virtual override public view returns (string memory) {\r\n        return type(WitOracleTrustableOvm2).name;\r\n    }\r\n\r\n    constructor(\r\n            EvmImmutables memory _immutables,\r\n            WitOracleRadonRegistry _registry,\r\n            bytes32 _versionTag\r\n        )\r\n        WitOracleBaseQueriable(\r\n            _immutables,\r\n            _registry\r\n        )\r\n        WitOracleBaseQueriableTrustable(_versionTag)\r\n    {\r\n        __gasPriceOracleL1 = OVM_GasPriceOracle(0x420000000000000000000000000000000000000F);\r\n    }\r\n\r\n    OVM_GasPriceOracle immutable internal __gasPriceOracleL1;\r\n\r\n    function _getCurrentL1Fee(uint16 _resultMaxSize) virtual internal view returns (uint256) {\r\n        return __gasPriceOracleL1.getL1Fee(\r\n            abi.encodePacked(\r\n                hex\"06eb2c42000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000ffffffffff00000000000000000000000000000000000000000000000000000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000ff\",\r\n                _resultMaxBuffer(_resultMaxSize)\r\n            )\r\n        );\r\n    }\r\n\r\n    function _resultMaxBuffer(uint16 _resultMaxSize) private pure returns (bytes memory) {\r\n        unchecked {\r\n            uint256[] memory _buffer = new uint256[](_resultMaxSize / 32);\r\n            for (uint _ix = 0; _ix < _buffer.length; _ix ++) {\r\n                _buffer[_ix] = type(uint256).max;\r\n            }\r\n            return abi.encodePacked(\r\n                _buffer,\r\n                uint256((1 << (_resultMaxSize % 32)) - 1)\r\n            );\r\n        }\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'IWitOracle' -------------------------------------------------------------------------------------\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @param _evmGasPrice Expected gas price to pay upon posting the data request.\r\n    function estimateBaseFee(uint256 _evmGasPrice)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return _getCurrentL1Fee(32) + WitOracleBaseQueriable.estimateBaseFee(_evmGasPrice);\r\n    }\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request with a callback.\r\n    /// @param _gasPrice Expected gas price to pay upon posting the data request.\r\n    /// @param _callbackGas Maximum gas to be spent when reporting the data request result.\r\n    function estimateBaseFeeWithCallback(uint256 _gasPrice, uint24 _callbackGas)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return _getCurrentL1Fee(32) + WitOracleBaseQueriable.estimateBaseFeeWithCallback(_gasPrice, _callbackGas);\r\n    }\r\n\r\n    /// @notice Estimate the extra reward (i.e. over the base fee) to be paid when posting a new\r\n    /// @notice data query in order to avoid getting provable \"too low incentives\" results from\r\n    /// @notice the Wit/Oracle blockchain. \r\n    /// @dev The extra fee gets calculated in proportion to:\r\n    /// @param _evmGasPrice Tentative EVM gas price at the moment the query result is ready.\r\n    /// @param _evmWitPrice Tentative nanoWit price in Wei at the moment the query is solved on the Wit/Oracle blockchain.\r\n    /// @param _querySLA The query SLA data security parameters as required for the Wit/Oracle blockchain. \r\n    function estimateExtraFee(\r\n            uint256 _evmGasPrice, \r\n            uint256 _evmWitPrice, \r\n            Witnet.QuerySLA memory _querySLA\r\n        )\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return (\r\n            _getCurrentL1Fee(_querySLA.witResultMaxSize)\r\n                + WitOracleBaseQueriable.estimateExtraFee(\r\n                    _evmGasPrice,\r\n                    _evmWitPrice,\r\n                    _querySLA\r\n                )\r\n        );\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'IWitOracleLegacy' -------------------------------------------------------------------------------\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @dev Underestimates if the size of returned data is greater than `_resultMaxSize`. \r\n    /// @param _gasPrice Expected gas price to pay upon posting the data request.\r\n    /// @param _resultMaxSize Maximum expected size of returned data (in bytes).\r\n    function estimateBaseFee(uint256 _gasPrice, uint16 _resultMaxSize)\r\n        public view \r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return _getCurrentL1Fee(_resultMaxSize) + WitOracleBaseQueriableTrustable.estimateBaseFee(_gasPrice, _resultMaxSize);\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'IWitOracleQueriableTrustableReporter' --------------------------------------------------------------------------\r\n\r\n    /// @notice Estimates the actual earnings (or loss), in WEI, that a reporter would get by reporting result to given query,\r\n    /// @notice based on the gas price of the calling transaction. Data requesters should consider upgrading the reward on \r\n    /// @notice queries providing no actual earnings.\r\n    function estimateReportEarnings(\r\n            uint256[] calldata _queryIds, \r\n            bytes calldata _evmMsgData,\r\n            uint256 _evmGasPrice, \r\n            uint256 _evmWitPrice\r\n        )\r\n        external view\r\n        virtual override\r\n        returns (uint256 _revenues, uint256 _expenses)\r\n    {\r\n        for (uint _ix = 0; _ix < _queryIds.length; _ix ++) {\r\n            uint256 _queryId = _queryIds[_ix];\r\n            if (\r\n                getQueryStatus(_queryId) == Witnet.QueryStatus.Posted\r\n            ) {\r\n                WitOracleDataLib.Query storage __query = WitOracleDataLib.seekQuery(_queryId);\r\n                if (__query.request.callbackGas > 0) {\r\n                    _expenses += (\r\n                        WitOracleBaseQueriable.estimateBaseFeeWithCallback(_evmGasPrice, __query.request.callbackGas)\r\n                            + WitOracleBaseQueriable.estimateExtraFee(\r\n                                _evmGasPrice, _evmWitPrice,\r\n                                Witnet.QuerySLA({\r\n                                    witResultMaxSize: uint16(0),\r\n                                    witCommitteeSize: __query.slaParams.witCommitteeSize,\r\n                                    witUnitaryReward: __query.slaParams.witUnitaryReward\r\n                                })\r\n                            )\r\n                    );\r\n                } else {\r\n                    _expenses += (\r\n                        WitOracleBaseQueriable.estimateBaseFee(_evmGasPrice)\r\n                            + WitOracleBaseQueriable.estimateExtraFee(\r\n                                _evmGasPrice, _evmWitPrice,\r\n                                __query.slaParams\r\n                            )\r\n                    );\r\n                }\r\n                _expenses += __query.slaParams.witUnitaryReward * _evmWitPrice;\r\n                _revenues += Witnet.QueryEvmReward.unwrap(__query.reward);\r\n            }\r\n        }\r\n        _expenses += __gasPriceOracleL1.getL1Fee(_evmMsgData);\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/trustable/WitOracleTrustablePushOnly.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleBasePushOnlyTrustable.sol\";\r\n\r\n/// @title Push-only WitOracle \"trustable\" contract.\r\n/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.\r\n/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.\r\n/// The result of the requests will be posted back to this contract by the bridge nodes too.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleTrustablePushOnly\r\n    is \r\n        WitOracleBasePushOnlyTrustable\r\n{\r\n    function class() virtual override public view returns (string memory) {\r\n        return type(WitOracleTrustablePushOnly).name;\r\n    }\r\n\r\n    constructor(\r\n            WitOracleRadonRegistry _registry, \r\n            bytes32 _versionTag\r\n        )\r\n        WitOracleBasePushOnly(_registry)\r\n        WitOracleBasePushOnlyTrustable(_versionTag)\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/trustable/WitOracleTrustableReef.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\n/* solhint-disable var-name-mixedcase */\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleBaseQueriableTrustable.sol\";\r\n\r\n/// @title Queriable WitOracle \"trustable\" implementation for Reef ecosystem.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleTrustableReef\r\n    is\r\n        WitOracleBaseQueriableTrustable\r\n{\r\n    function class() virtual override public view  returns (string memory) {\r\n        return type(WitOracleTrustableReef).name;\r\n    }\r\n    \r\n    constructor(\r\n            EvmImmutables memory _immutables,\r\n            WitOracleRadonRegistry _registry,\r\n            bytes32 _versionTag\r\n        )\r\n        WitOracleBaseQueriable(\r\n            _immutables,\r\n            _registry\r\n        )\r\n        WitOracleBaseQueriableTrustable(_versionTag)\r\n    {}\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'Payable' ----------------------------------------------------------------------------------------\r\n\r\n    /// Gets current transaction price.\r\n    function _getGasPrice()\r\n        internal pure\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return 1;\r\n    }\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'IWitOracle' ----------------------------------------------------------------------------\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @dev Underestimates if the size of returned data is greater than `_resultMaxSize`. \r\n    /// @param _resultMaxSize Maximum expected size of returned data (in bytes).\r\n    function estimateBaseFee(uint256, uint16 _resultMaxSize)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return WitOracleBaseQueriableTrustable.estimateBaseFee(1, _resultMaxSize);\r\n    }\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request with a callback.\r\n    /// @param _callbackGas Maximum gas to be spent when reporting the data request result.\r\n    function estimateBaseFeeWithCallback(uint256, uint24 _callbackGas)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return WitOracleBaseQueriable.estimateBaseFeeWithCallback(1, _callbackGas);\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/trustable/WitOracleTrustableZkSync.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\n/* solhint-disable var-name-mixedcase */\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleBaseQueriableTrustable.sol\";\r\n\r\n/// @title Queriable WitOracle \"trustable\" implementation for zkSync-Era chains.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleTrustableZkSync\r\n    is\r\n        WitOracleBaseQueriableTrustable\r\n{\r\n    function class() virtual override public view returns (string memory) {\r\n        return type(WitOracleTrustableZkSync).name;\r\n    }\r\n\r\n    uint256 internal immutable __reportResultGasPerPubData = 50000;\r\n    \r\n    constructor(WitOracleRadonRegistry _registry)\r\n        WitOracleBaseQueriable(\r\n            EvmImmutables({\r\n                reportResultGasBase: 50000,\r\n                reportResultWithCallbackGasBase: 60000,\r\n                reportResultWithCallbackRevertGasBase: 70000, \r\n                sstoreFromZeroGas: 22100\r\n            }),\r\n            _registry\r\n        )\r\n        WitOracleBaseQueriableTrustable(\"zksync-experimental\")\r\n    {}\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Overrides 'Payable' ----------------------------------------------------------------------------------------\r\n\r\n    /// Transfers ETHs to given address.\r\n    /// @param _to Recipient address.\r\n    /// @param _amount Amount of ETHs to transfer.\r\n    function __safeTransferTo(address payable _to, uint256 _amount) virtual override internal {\r\n        (bool _success,) = payable(_to).call{value: _amount}(\"\");\r\n        if (!_success) revert(\"cannot transfer back\");\r\n    }\r\n    \r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'IWitOracle' ----------------------------------------------------------------------------\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @param _evmGasPrice Expected gas price to pay upon posting the data request.\r\n    function estimateBaseFee(uint256 _evmGasPrice)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return (\r\n            WitOracleBaseQueriable.estimateBaseFee(_evmGasPrice) + (\r\n                _evmGasPrice\r\n                    * __reportResultGasPerPubData * (\r\n                        4    // heuristic: 1x contracts storage roots get modified\r\n                        + 8  // heuristic: 1x evm events get emitted\r\n                    )\r\n            )\r\n        );\r\n    }\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request with a callback.\r\n    /// @param _callbackGas Maximum gas to be spent when reporting the data request result.\r\n    function estimateBaseFeeWithCallback(uint256 _evmGasPrice, uint24 _callbackGas)\r\n        public view\r\n        virtual override\r\n        returns (uint256)\r\n    {\r\n        return (\r\n            WitOracleBaseQueriable.estimateBaseFeeWithCallback(_evmGasPrice, _callbackGas) + (\r\n                _evmGasPrice\r\n                    * __reportResultGasPerPubData * (\r\n                        8   // heuristic: 2x contracts storage roots get modified\r\n                        + 8  // heuristic: 1x evm events get emitted\r\n                    )\r\n            )\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/trustless/WitOracleRadonRegistryDefaultV21.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleRadonRegistryBase.sol\";\r\n\r\n/// @title Witnet Request Board \"trustless\" implementation contract for regular EVM-compatible chains.\r\n/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.\r\n/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.\r\n/// The result of the requests will be posted back to this contract by the bridge nodes too.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleRadonRegistryDefaultV21\r\n    is \r\n        WitOracleRadonRegistryBase\r\n{\r\n    function class() virtual override public view  returns (string memory) {\r\n        return type(WitOracleRadonRegistryDefaultV21).name;\r\n    }\r\n}\r\n"
      },
      "project/contracts/core/trustless/WitOracleRadonRequestFactoryModalsDefault.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleRadonRequestFactoryModals.sol\";\r\n\r\n/// @title Factory contract for building IWitOracleRadonRequestModal contracts as light-weight proxies.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleRadonRequestFactoryModalsDefault\r\n    is \r\n        WitOracleRadonRequestFactoryModals\r\n{\r\n    function class() virtual override public view returns (string memory) {\r\n        return (\r\n            initialized() \r\n                ? type(IWitOracleRadonRequestModal).name  \r\n                : type(WitOracleRadonRequestFactoryModalsDefault).name\r\n        );\r\n    }\r\n\r\n    constructor(address _witOracle)\r\n        WitOracleRadonRequestFactoryModals(_witOracle)\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/trustless/WitOracleRadonRequestFactoryTemplatesDefault.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleRadonRequestFactoryTemplates.sol\";\r\n\r\n/// @title Factory contract for building IWitOracleRadonRequestTemplate contracts as light-weight proxies.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleRadonRequestFactoryTemplatesDefault\r\n    is \r\n        WitOracleRadonRequestFactoryTemplates\r\n{\r\n    function class() virtual override public view  returns (string memory) {\r\n        return (\r\n            initialized() \r\n                ? type(IWitOracleRadonRequestTemplate).name  \r\n                : type(WitOracleRadonRequestFactoryTemplatesDefault).name\r\n        );\r\n    }\r\n\r\n    constructor(address _witOracle)\r\n        WitOracleRadonRequestFactoryTemplates(_witOracle)\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/trustless/WitOracleTrustlessDefaultV22.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleBaseQueriableTrustless.sol\";\r\n\r\n/// @title Witnet Request Board \"trustless\" implementation contract for regular EVM-compatible chains.\r\n/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.\r\n/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.\r\n/// The result of the requests will be posted back to this contract by the bridge nodes too.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleTrustlessDefaultV22\r\n    is \r\n        WitOracleBaseQueriableTrustless\r\n{\r\n    function class() virtual override public view  returns (string memory) {\r\n        return type(WitOracleTrustlessDefaultV22).name;\r\n    }\r\n\r\n    constructor(\r\n            EvmImmutables memory _immutables,\r\n            uint256 _queryAwaitingBlocks,\r\n            uint256 _queryReportingStake,\r\n            WitOracleRadonRegistry _registry\r\n        )\r\n        WitOracleBaseQueriable(\r\n            _immutables,\r\n            _registry\r\n        )\r\n        WitOracleBaseQueriableTrustless(\r\n            _queryAwaitingBlocks,\r\n            _queryReportingStake\r\n        )\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/upgradable/WitOracleRadonRegistryUpgradableDefault.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleRadonRegistryBaseUpgradable.sol\";\r\n\r\n/// @title Witnet Request Board \"trustless\" implementation contract for regular EVM-compatible chains.\r\n/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.\r\n/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.\r\n/// The result of the requests will be posted back to this contract by the bridge nodes too.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleRadonRegistryUpgradableDefault\r\n    is \r\n        WitOracleRadonRegistryBaseUpgradable\r\n{\r\n    function class() virtual override public view  returns (string memory) {\r\n        return type(WitOracleRadonRegistryUpgradableDefault).name;\r\n    }\r\n\r\n    constructor(\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        WitOracleRadonRegistryBaseUpgradable(\r\n            _versionTag,\r\n            _upgradable\r\n        )\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/upgradable/WitOracleRadonRegistryUpgradableNoSha256.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleRadonRegistryBaseUpgradable.sol\";\r\n\r\ncontract WitOracleRadonRegistryUpgradableNoSha256\r\n    is\r\n        WitOracleRadonRegistryBaseUpgradable\r\n{\r\n    function class() virtual override public view returns (string memory) {\r\n        return type(WitOracleRadonRegistryUpgradableNoSha256).name;\r\n    }\r\n    \r\n    function _witOracleHash(bytes memory chunk) virtual override internal pure returns (Witnet.RadonHash) {\r\n        return Witnet.RadonHash.wrap(keccak256(chunk));\r\n    }\r\n\r\n    constructor(\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        WitOracleRadonRegistryBaseUpgradable(\r\n            _versionTag,\r\n            _upgradable\r\n        )\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/upgradable/WitOracleRadonRegistryUpgradableZkSync.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleRadonRegistryUpgradableDefault.sol\";\r\n\r\n/// @title Witnet Request Board \"trustless\" implementation contract for regular EVM-compatible chains.\r\n/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.\r\n/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.\r\n/// The result of the requests will be posted back to this contract by the bridge nodes too.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleRadonRegistryUpgradableZkSync\r\n    is \r\n        WitOracleRadonRegistryUpgradableDefault\r\n{\r\n    function class() virtual override public view  returns (string memory) {\r\n        return type(WitOracleRadonRegistryUpgradableZkSync).name;\r\n    }\r\n\r\n    constructor()\r\n        WitOracleRadonRegistryUpgradableDefault(\r\n            bytes32(\"zksync-experimental\"),\r\n            true\r\n        )\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/upgradable/WitOracleRadonRequestFactoryUpgradableConfluxCore.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleRadonRequestFactoryUpgradableDefault.sol\";\r\n\r\ncontract WitOracleRadonRequestFactoryUpgradableConfluxCore\r\n    is\r\n        WitOracleRadonRequestFactoryUpgradableDefault  \r\n{\r\n    function class() virtual override public view  returns (string memory) {\r\n        return type(WitOracleRadonRequestFactoryUpgradableConfluxCore).name;\r\n    }\r\n\r\n    constructor(\r\n            address _witOracleRadonRequestModalsBuilder,\r\n            address _witOracleRadonRequestTemplatesBuilder,\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        WitOracleRadonRequestFactoryUpgradableDefault(\r\n            _witOracleRadonRequestModalsBuilder,\r\n            _witOracleRadonRequestTemplatesBuilder,\r\n            _versionTag,\r\n            _upgradable\r\n        )\r\n    {}\r\n\r\n    function _checkCloneWasDeployed(address _clone) virtual override internal pure {}\r\n}\r\n"
      },
      "project/contracts/core/upgradable/WitOracleRadonRequestFactoryUpgradableDefault.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleRadonRequestFactoryBaseUpgradable.sol\";\r\n\r\ncontract WitOracleRadonRequestFactoryUpgradableDefault\r\n    is\r\n        WitOracleRadonRequestFactoryBaseUpgradable  \r\n{\r\n    function class() virtual override public view  returns (string memory) {\r\n        return type(WitOracleRadonRequestFactoryUpgradableDefault).name;\r\n    }\r\n\r\n    constructor(\r\n            address _witOracleRadonRequestModalsBuilder,\r\n            address _witOracleRadonRequestTemplatesBuilder,\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        WitOracleRadonRequestFactoryBase(\r\n            _witOracleRadonRequestModalsBuilder,\r\n            _witOracleRadonRequestTemplatesBuilder\r\n        )\r\n        WitOracleRadonRequestFactoryBaseUpgradable(\r\n            _versionTag,\r\n            _upgradable\r\n        )\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/upgradable/WitOracleTrustlessUpgradableDefault.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../base/WitOracleBaseQueriableUpgradable.sol\";\r\n\r\n/// @title Witnet Request Board \"trustless\" implementation contract for regular EVM-compatible chains.\r\n/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.\r\n/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.\r\n/// The result of the requests will be posted back to this contract by the bridge nodes too.\r\n/// @author The Witnet Foundation\r\ncontract WitOracleTrustlessUpgradableDefault\r\n    is \r\n        WitOracleBaseQueriableUpgradable\r\n{\r\n    function class() virtual override public view  returns (string memory) {\r\n        return type(WitOracleTrustlessUpgradableDefault).name;\r\n    }\r\n\r\n    constructor(\r\n            EvmImmutables memory _immutables,\r\n            uint256 _queryAwaitingBlocks,\r\n            uint256 _queryReportingStake,\r\n            WitOracleRadonRegistry _registry,\r\n            bytes32 _versionTag,\r\n            bool _upgradable\r\n        )\r\n        WitOracleBaseQueriable(\r\n            _immutables,\r\n            _registry\r\n        )\r\n        WitOracleBaseQueriableTrustless(\r\n            _queryAwaitingBlocks,\r\n            _queryReportingStake\r\n        )\r\n        WitOracleBaseQueriableUpgradable(\r\n            _versionTag,\r\n            _upgradable\r\n        )\r\n    {}\r\n}\r\n"
      },
      "project/contracts/core/WitnetDeployer.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitnetProxy.sol\";\r\nimport \"../libs/Create3.sol\";\r\n\r\n/// @notice WitnetDeployer contract used both as CREATE2 (EIP-1014) factory for Witnet artifacts, \r\n/// @notice and CREATE3 (EIP-3171) factory for Witnet proxies.\r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\n\r\ncontract WitnetDeployer {\r\n\r\n    /// @notice Use given `_initCode` and `_salt` to deploy a contract into a deterministic address. \r\n    /// @dev The address of deployed address will be determined by both the `_initCode` and the `_salt`, but not the address\r\n    /// @dev nor the nonce of the caller (i.e. see EIP-1014). \r\n    /// @param _initCode Creation code, including construction logic and input parameters.\r\n    /// @param _salt Arbitrary value to modify resulting address.\r\n    /// @return _deployed Just deployed contract address.\r\n    function deploy(bytes memory _initCode, bytes32 _salt)\r\n        virtual public\r\n        returns (address _deployed)\r\n    {\r\n        _deployed = determineAddr(_initCode, _salt);\r\n        if (_deployed.code.length == 0) {\r\n            assembly {\r\n                _deployed := create2(0, add(_initCode, 0x20), mload(_initCode), _salt)\r\n            }\r\n            require(_deployed != address(0), \"WitnetDeployer: deployment failed\");\r\n        }\r\n    }\r\n\r\n    /// @notice Determine counter-factual address of the contract that would be deployed by the given `_initCode` and a `_salt`.\r\n    /// @param _initCode Creation code, including construction logic and input parameters.\r\n    /// @param _salt Arbitrary value to modify resulting address.\r\n    /// @return Deterministic contract address.\r\n    function determineAddr(bytes memory _initCode, bytes32 _salt)\r\n        virtual public view\r\n        returns (address)\r\n    {\r\n        return address(\r\n            uint160(uint(keccak256(\r\n                abi.encodePacked(\r\n                    bytes1(0xff),\r\n                    address(this),\r\n                    _salt,\r\n                    keccak256(_initCode)\r\n                )\r\n            )))\r\n        );\r\n    }\r\n\r\n    function determineProxyAddr(bytes32 _salt) \r\n        virtual public view\r\n        returns (address)\r\n    {\r\n        return Create3.determineAddr(_salt);\r\n    }\r\n\r\n    function proxify(bytes32 _proxySalt, address _firstImplementation, bytes memory _initData)\r\n        virtual external \r\n        returns (WitnetProxy)\r\n    {\r\n        address _proxyAddr = determineProxyAddr(_proxySalt);\r\n        if (_proxyAddr.code.length == 0) {\r\n            // deploy the WitnetProxy\r\n            Create3.deploy(_proxySalt, type(WitnetProxy).creationCode);\r\n            // settle first implementation address,\r\n            WitnetProxy(payable(_proxyAddr)).upgradeTo(\r\n                _firstImplementation, \r\n                // and initialize it, providing\r\n                abi.encode(\r\n                    // the owner (i.e. the caller of this function)\r\n                    msg.sender,\r\n                    // and some (optional) initialization data\r\n                     _initData\r\n                )\r\n            );\r\n            return WitnetProxy(payable(_proxyAddr));\r\n        } else {\r\n            revert(\"WitnetDeployer: already proxified\");\r\n        }\r\n    }\r\n\r\n}"
      },
      "project/contracts/core/WitnetDeployerConfluxCore.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitnetDeployer.sol\";\r\n\r\n/// @notice WitnetDeployerConfluxCore contract used both as CREATE2 factory (EIP-1014) for Witnet artifacts, \r\n/// @notice and CREATE3 factory (EIP-3171) for Witnet proxies, on the Conflux Core Ecosystem.\r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\n\r\ncontract WitnetDeployerConfluxCore is WitnetDeployer {\r\n\r\n    /// @notice Determine counter-factual address of the contract that would be deployed by the given `_initCode` and a `_salt`.\r\n    /// @param _initCode Creation code, including construction logic and input parameters.\r\n    /// @param _salt Arbitrary value to modify resulting address.\r\n    /// @return Deterministic contract address.\r\n    function determineAddr(bytes memory _initCode, bytes32 _salt)\r\n        virtual override\r\n        public view\r\n        returns (address)\r\n    {\r\n        return address(\r\n            (uint160(uint(keccak256(\r\n                abi.encodePacked(\r\n                    bytes1(0xff),\r\n                    address(this),\r\n                    _salt,\r\n                    keccak256(_initCode)\r\n                )\r\n            ))) & uint160(0x0fffFFFFFfFfffFfFfFFffFffFffFFfffFfFFFFf)\r\n            ) | uint160(0x8000000000000000000000000000000000000000)\r\n        );\r\n    }\r\n\r\n    function determineProxyAddr(bytes32 _salt) \r\n        virtual override\r\n        public view\r\n        returns (address)\r\n    {\r\n        return determineAddr(type(WitnetProxy).creationCode, _salt);\r\n    }\r\n\r\n    function proxify(bytes32 _proxySalt, address _firstImplementation, bytes memory _initData)\r\n        virtual override external \r\n        returns (WitnetProxy)\r\n    {\r\n        address _proxyAddr = determineProxyAddr(_proxySalt);\r\n        if (_proxyAddr.code.length == 0) {\r\n            // deploy the WitnetProxy\r\n            deploy(type(WitnetProxy).creationCode, _proxySalt);\r\n            // settle first implementation address,\r\n            WitnetProxy(payable(_proxyAddr)).upgradeTo(\r\n                _firstImplementation, \r\n                // and initialize it, providing\r\n                abi.encode(\r\n                    // the owner (i.e. the caller of this function)\r\n                    msg.sender,\r\n                    // and some (optional) initialization data\r\n                     _initData\r\n                )\r\n            );\r\n            return WitnetProxy(payable(_proxyAddr));\r\n        } else {\r\n            revert(\"WitnetDeployerConfluxCore: already proxified\");\r\n        }\r\n    }\r\n\r\n}"
      },
      "project/contracts/core/WitnetDeployerDeferred.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitnetProxy.sol\";\r\nimport \"../libs/Create3.sol\";\r\n\r\n/// @notice WitnetDeployerNoChecks contract used both as CREATE2 (EIP-1014) factory for Witnet artifacts, \r\n/// @notice and CREATE3 (EIP-3171) factory for Witnet proxies. \r\n/// @dev To be used on EVM chains where contract deployment takes place in a deferred way: \r\n/// @dev - after the deployment tx gets mined, and not while it gets executed.\r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\n\r\ncontract WitnetDeployerDeferred {\r\n\r\n    /// @notice Use given `_initCode` and `_salt` to deploy a contract into a deterministic address. \r\n    /// @dev The address of deployed address will be determined by both the `_initCode` and the `_salt`, but not the address\r\n    /// @dev nor the nonce of the caller (i.e. see EIP-1014). \r\n    /// @param _initCode Creation code, including construction logic and input parameters.\r\n    /// @param _salt Arbitrary value to modify resulting address.\r\n    /// @return _deployed Just deployed contract address.\r\n    function deploy(bytes memory _initCode, bytes32 _salt)\r\n        virtual public\r\n        returns (address _deployed)\r\n    {\r\n        _deployed = determineAddr(_initCode, _salt);\r\n        if (_deployed.code.length == 0) {\r\n            assembly {\r\n                _deployed := create2(0, add(_initCode, 0x20), mload(_initCode), _salt)\r\n            }\r\n        }\r\n    }\r\n\r\n    /// @notice Determine counter-factual address of the contract that would be deployed by the given `_initCode` and a `_salt`.\r\n    /// @param _initCode Creation code, including construction logic and input parameters.\r\n    /// @param _salt Arbitrary value to modify resulting address.\r\n    /// @return Deterministic contract address.\r\n    function determineAddr(bytes memory _initCode, bytes32 _salt)\r\n        virtual public view\r\n        returns (address)\r\n    {\r\n        return address(\r\n            uint160(uint(keccak256(\r\n                abi.encodePacked(\r\n                    bytes1(0xff),\r\n                    address(this),\r\n                    _salt,\r\n                    keccak256(_initCode)\r\n                )\r\n            )))\r\n        );\r\n    }\r\n\r\n    function determineProxyAddr(bytes32 _salt) \r\n        virtual public view\r\n        returns (address)\r\n    {\r\n        return Create3.determineAddr(_salt);\r\n    }\r\n\r\n    function proxify(bytes32 _proxySalt, address _firstImplementation, bytes memory _initData)\r\n        virtual external \r\n        returns (WitnetProxy)\r\n    {\r\n        address _proxyAddr = determineProxyAddr(_proxySalt);\r\n        if (_proxyAddr.code.length == 0) {\r\n            // deploy the WitnetProxy\r\n            Create3.deploy(_proxySalt, type(WitnetProxy).creationCode);\r\n            // settle first implementation address,\r\n            WitnetProxy(payable(_proxyAddr)).upgradeTo(\r\n                _firstImplementation, \r\n                // and initialize it, providing\r\n                abi.encode(\r\n                    // the owner (i.e. the caller of this function)\r\n                    msg.sender,\r\n                    // and some (optional) initialization data\r\n                     _initData\r\n                )\r\n            );\r\n            return WitnetProxy(payable(_proxyAddr));\r\n        } else {\r\n            revert(\"WitnetDeployerDeferred: already proxified\");\r\n        }\r\n    }\r\n\r\n}"
      },
      "project/contracts/core/WitnetDeployerMeter.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitnetDeployer.sol\";\r\n\r\n/// @notice WitnetDeployerMeter contract used both as CREATE2 factory (EIP-1014) for Witnet artifacts, \r\n/// @notice and CREATE3 factory (EIP-3171) for Witnet proxies, on the Meter Ecosystem.\r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\n\r\ncontract WitnetDeployerMeter is WitnetDeployer {\r\n\r\n    function determineProxyAddr(bytes32 _salt) \r\n        virtual override\r\n        public view\r\n        returns (address)\r\n    {\r\n        return determineAddr(type(WitnetProxy).creationCode, _salt);\r\n    }\r\n\r\n    function proxify(bytes32 _proxySalt, address _firstImplementation, bytes memory _initData)\r\n        virtual override\r\n        external \r\n        returns (WitnetProxy)\r\n    {\r\n        address _proxyAddr = determineProxyAddr(_proxySalt);\r\n        if (_proxyAddr.code.length == 0) {\r\n            // deploy the WitnetProxy\r\n            deploy(type(WitnetProxy).creationCode, _proxySalt);\r\n            // settle first implementation address,\r\n            WitnetProxy(payable(_proxyAddr)).upgradeTo(\r\n                _firstImplementation, \r\n                // and initialize it, providing\r\n                abi.encode(\r\n                    // the owner (i.e. the caller of this function)\r\n                    msg.sender,\r\n                    // and some (optional) initialization data\r\n                     _initData\r\n                )\r\n            );\r\n            return WitnetProxy(payable(_proxyAddr));\r\n        } else {\r\n            revert(\"WitnetDeployerMeter: already proxified\");\r\n        }\r\n    }\r\n\r\n}"
      },
      "project/contracts/core/WitnetProxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.7.0 <0.9.0;\r\npragma experimental ABIEncoderV2;\r\n\r\nimport \"../patterns/Upgradeable.sol\";\r\n\r\n/// @title WitnetProxy: upgradable delegate-proxy contract. \r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\ncontract WitnetProxy {\r\n\r\n    /// Event emitted every time the implementation gets updated.\r\n    event Upgraded(address indexed implementation);  \r\n\r\n    /// Constructor with no params as to ease eventual support of Singleton pattern (i.e. ERC-2470).\r\n    constructor () {}\r\n\r\n    receive() virtual external payable {}\r\n\r\n    /// Payable fallback accepts delegating calls to payable functions.  \r\n    fallback() external payable { /* solhint-disable no-complex-fallback */\r\n        address _implementation = implementation();\r\n        assembly { /* solhint-disable avoid-low-level-calls */\r\n            // Gas optimized delegate call to 'implementation' contract.\r\n            // Note: `msg.data`, `msg.sender` and `msg.value` will be passed over \r\n            //       to actual implementation of `msg.sig` within `implementation` contract.\r\n            let ptr := mload(0x40)\r\n            calldatacopy(ptr, 0, calldatasize())\r\n            let result := delegatecall(gas(), _implementation, ptr, calldatasize(), 0, 0)\r\n            let size := returndatasize()\r\n            returndatacopy(ptr, 0, size)\r\n            switch result\r\n                case 0  { \r\n                    // pass back revert message:\r\n                    revert(ptr, size) \r\n                }\r\n                default {\r\n                  // pass back same data as returned by 'implementation' contract:\r\n                  return(ptr, size) \r\n                }\r\n        }\r\n    }\r\n\r\n    /// Returns proxy's current implementation address.\r\n    function implementation() public view returns (address) {\r\n        return __proxySlot().implementation;\r\n    }\r\n\r\n    /// Upgrades the `implementation` address.\r\n    /// @param _newImplementation New implementation address.\r\n    /// @param _initData Raw data with which new implementation will be initialized.\r\n    /// @return Returns whether new implementation would be further upgradable, or not.\r\n    function upgradeTo(address _newImplementation, bytes memory _initData)\r\n        public returns (bool)\r\n    {\r\n        // New implementation cannot be null:\r\n        require(_newImplementation != address(0), \"WitnetProxy: null implementation\");\r\n\r\n        address _oldImplementation = implementation();\r\n        if (_oldImplementation != address(0)) {\r\n            // New implementation address must differ from current one:\r\n            require(_newImplementation != _oldImplementation, \"WitnetProxy: nothing to upgrade\");\r\n\r\n            // Assert whether current implementation is intrinsically upgradable:\r\n            try Upgradeable(_oldImplementation).isUpgradable() returns (bool _isUpgradable) {\r\n                require(_isUpgradable, \"WitnetProxy: not upgradable\");\r\n            } catch {\r\n                revert(\"WitnetProxy: unable to check upgradability\");\r\n            }\r\n\r\n            // Assert whether current implementation allows `msg.sender` to upgrade the proxy:\r\n            (bool _wasCalled, bytes memory _result) = _oldImplementation.delegatecall(\r\n                abi.encodeWithSignature(\r\n                    \"isUpgradableFrom(address)\",\r\n                    msg.sender\r\n                )\r\n            );\r\n            require(_wasCalled, \"WitnetProxy: uncompliant implementation\");\r\n            require(abi.decode(_result, (bool)), \"WitnetProxy: not authorized\");\r\n            require(\r\n                Upgradeable(_oldImplementation).proxiableUUID() == Upgradeable(_newImplementation).proxiableUUID(),\r\n                \"WitnetProxy: proxiableUUIDs mismatch\"\r\n            );\r\n        }\r\n\r\n        // Initialize new implementation within proxy-context storage:\r\n        (bool _wasInitialized, bytes memory _returnData) = _newImplementation.delegatecall(\r\n            abi.encodeWithSignature(\r\n                \"initialize(bytes)\",\r\n                _initData\r\n            )\r\n        );\r\n        if (!_wasInitialized) {\r\n            if (_returnData.length < 68) {\r\n                revert(\"WitnetProxy: initialization failed\");\r\n            } else {\r\n                assembly {\r\n                    _returnData := add(_returnData, 0x04)\r\n                }\r\n                revert(abi.decode(_returnData, (string)));\r\n            }\r\n        }\r\n\r\n        // If all checks and initialization pass, update implementation address:\r\n        __proxySlot().implementation = _newImplementation;\r\n    \r\n        emit Upgraded(_newImplementation);\r\n\r\n        // Asserts new implementation complies w/ minimal implementation of Upgradeable interface:\r\n        try Upgradeable(_newImplementation).isUpgradable() returns (bool _isUpgradable) {\r\n            return _isUpgradable;\r\n        }\r\n        catch {\r\n            revert (\"WitnetProxy: uncompliant implementation\");\r\n        }\r\n    }\r\n\r\n    /// @dev Complying with EIP-1967, retrieves storage struct containing proxy's current implementation address.\r\n    function __proxySlot() private pure returns (Proxiable.ProxiableSlot storage _slot) {\r\n        assembly {\r\n            // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)\r\n            _slot.slot := 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc\r\n        }\r\n    }\r\n\r\n}\r\n"
      },
      "project/contracts/core/WitnetUpgradableBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n// solhint-disable var-name-mixedcase\r\n// solhint-disable payable-fallback\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../patterns/Ownable2Step.sol\";\r\nimport \"../patterns/ReentrancyGuard.sol\";\r\nimport \"../patterns/Upgradeable.sol\";\r\n\r\nimport \"./WitnetProxy.sol\";\r\n\r\n/// @title Witnet Request Board base contract, with an Upgradeable (and Destructible) touch.\r\n/// @author Guillermo Díaz <guillermo@witnet.io>\r\nabstract contract WitnetUpgradableBase\r\n    is\r\n        Ownable2Step,\r\n        Upgradeable, \r\n        ReentrancyGuard\r\n{\r\n    bytes32 internal immutable _WITNET_UPGRADABLE_VERSION;\r\n\r\n    address public immutable deployer = msg.sender;\r\n\r\n    constructor(\r\n            bool _upgradable,\r\n            bytes32 _versionTag,\r\n            string memory _proxiableUUID\r\n        )\r\n        Upgradeable(_upgradable)\r\n    {\r\n        _WITNET_UPGRADABLE_VERSION = _versionTag;\r\n        proxiableUUID = keccak256(bytes(_proxiableUUID));\r\n    }\r\n    \r\n    /// @dev Reverts if proxy delegatecalls to unexistent method.\r\n    /* solhint-disable no-complex-fallback */\r\n    fallback() virtual external { \r\n        revert(string(abi.encodePacked(\r\n            \"WitnetUpgradableBase: not implemented: 0x\",\r\n            _toHexString(uint8(bytes1(msg.sig))),\r\n            _toHexString(uint8(bytes1(msg.sig << 8))),\r\n            _toHexString(uint8(bytes1(msg.sig << 16))),\r\n            _toHexString(uint8(bytes1(msg.sig << 24)))\r\n        )));\r\n    }\r\n   \r\n    \r\n    // ================================================================================================================\r\n    // --- Overrides 'Proxiable' --------------------------------------------------------------------------------------\r\n\r\n    /// @dev Gets immutable \"heritage blood line\" (ie. genotype) as a Proxiable, and eventually Upgradeable, contract.\r\n    ///      If implemented as an Upgradeable touch, upgrading this contract to another one with a different \r\n    ///      `proxiableUUID()` value should fail.\r\n    bytes32 public immutable override proxiableUUID;\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Overrides 'Upgradeable' ------------------------------------------------------------------------------------\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.\r\n    /// @dev Must fail when trying to upgrade to same logic contract more than once.\r\n    function initialize(bytes memory _initData) virtual override public {\r\n        address _owner = owner();\r\n        if (_owner == address(0)) {\r\n            // upon first upgrade, extract decode owner address from _intidata\r\n            (_owner, _initData) = abi.decode(_initData, (address, bytes));\r\n            _transferOwnership(_owner);\r\n        \r\n        } else {\r\n            // only owner can initialize an existing proxy:\r\n            require(msg.sender == _owner, \"not the owner\");\r\n        }\r\n        __initializeUpgradableData(_initData);\r\n        if (\r\n            __proxiable().codehash != bytes32(0)\r\n                && __proxiable().codehash == codehash()\r\n        ) {\r\n            revert(\"already initialized codehash\");\r\n        }\r\n        __proxiable().codehash = codehash();\r\n        emit Upgraded(owner(), base(), codehash(), version());\r\n    }\r\n\r\n    /// Tells whether provided address could eventually upgrade the contract.\r\n    function isUpgradableFrom(address _from) external view virtual override returns (bool) {\r\n        return (\r\n            // false if the WRB is intrinsically not upgradable, or `_from` is no owner\r\n            isUpgradable()\r\n                && owner() == _from\r\n        );\r\n    }\r\n\r\n    /// Retrieves human-readable version tag of current implementation.\r\n    function version() public view virtual override returns (string memory) {\r\n        return _toString(_WITNET_UPGRADABLE_VERSION);\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Internal methods -------------------------------------------------------------------------------------------\r\n\r\n    function _toHexString(uint8 _u)\r\n        internal pure\r\n        returns (string memory)\r\n    {\r\n        bytes memory b2 = new bytes(2);\r\n        uint8 d0 = uint8(_u / 16) + 48;\r\n        uint8 d1 = uint8(_u % 16) + 48;\r\n        if (d0 > 57)\r\n            d0 += 7;\r\n        if (d1 > 57)\r\n            d1 += 7;\r\n        b2[0] = bytes1(d0);\r\n        b2[1] = bytes1(d1);\r\n        return string(b2);\r\n    }\r\n\r\n    /// Converts bytes32 into string.\r\n    function _toString(bytes32 _bytes32)\r\n        internal pure\r\n        returns (string memory)\r\n    {\r\n        bytes memory _bytes = new bytes(_toStringLength(_bytes32));\r\n        for (uint _i = 0; _i < _bytes.length;) {\r\n            _bytes[_i] = _bytes32[_i];\r\n            unchecked {\r\n                _i ++;\r\n            }\r\n        }\r\n        return string(_bytes);\r\n    }\r\n\r\n    // Calculate length of string-equivalent to given bytes32.\r\n    function _toStringLength(bytes32 _bytes32)\r\n        internal pure\r\n        returns (uint _length)\r\n    {\r\n        for (; _length < 32; ) {\r\n            if (_bytes32[_length] == 0) {\r\n                break;\r\n            }\r\n            unchecked {\r\n                _length ++;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/data/WitOracleDataLib.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../interfaces/IWitOracleQueriableConsumer.sol\";\r\nimport \"../interfaces/IWitOracleQueriableEvents.sol\";\r\nimport \"../interfaces/IWitOracleQueriableExperimental.sol\";\r\nimport \"../interfaces/IWitOracleRadonRegistry.sol\";\r\nimport \"../interfaces/IWitOracleTrustableAdmin.sol\";\r\nimport \"../interfaces/IWitOracleQueriableTrustableReporter.sol\";\r\n\r\nimport \"../interfaces/legacy/IWitOracleLegacy.sol\";\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\n/// @title Witnet Request Board base data model library\r\n/// @author The Witnet Foundation.\r\nlibrary WitOracleDataLib {  \r\n\r\n    using Witnet for Witnet.DataPushReport;\r\n    using Witnet for Witnet.QuerySLA;\r\n    using Witnet for Witnet.RadonHash;\r\n    using Witnet for Witnet.Timestamp;\r\n    \r\n    using WitnetCBOR for WitnetCBOR.CBOR;\r\n\r\n    bytes32 internal constant _WIT_ORACLE_DATA_SLOTHASH =\r\n        /* keccak256(\"io.witnet.boards.data\") */\r\n        0xf595240b351bc8f951c2f53b26f4e78c32cb62122cf76c19b7fdda7d4968e183;\r\n\r\n    struct Storage {\r\n        uint64 nonce;\r\n        mapping (uint256 => Query) queries;\r\n        mapping (address => bool) reporters;\r\n        mapping (address => mapping (Witnet.RadonHash => Committee)) committees;\r\n    }\r\n\r\n    struct Query {\r\n        QueryRequest request;\r\n        QueryResponse response;\r\n        Witnet.QuerySLA slaParams;\r\n        Witnet.QueryUUID uuid;\r\n        Witnet.QueryEvmReward reward;\r\n        Witnet.BlockNumber checkpoint;\r\n    }\r\n\r\n    struct QueryRequest {\r\n        address requester; uint24 callbackGas; uint72 _0;\r\n        bytes radonBytecode;\r\n        bytes32 radonHash; \r\n        uint256 _1;\r\n    }\r\n\r\n    struct QueryResponse {\r\n        address reporter; uint32 _0; uint64 resultTimestamp;\r\n        bytes32 resultDrTxHash;\r\n        bytes resultCborBytes;\r\n        address disputer;\r\n    }\r\n\r\n    struct Committee {\r\n        bytes32 hash;\r\n        Witnet.ServiceProvider[] members;\r\n    }\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Internal functions -----------------------------------------------------------------------------------------\r\n\r\n    /// Returns storage pointer to contents of 'WitnetBoardState' struct.\r\n    function data() internal pure returns (Storage storage _ptr)\r\n    {\r\n        assembly {\r\n            _ptr.slot := _WIT_ORACLE_DATA_SLOTHASH\r\n        }\r\n    }\r\n\r\n    function hashify(\r\n            Witnet.QuerySLA memory querySLA, \r\n            address evmRequester, \r\n            Witnet.RadonHash radonHash\r\n        ) \r\n        internal view\r\n        returns (bytes32)\r\n    {\r\n        return (\r\n            data().committees[evmRequester][radonHash].hash != bytes32(0)\r\n                ? querySLA.hashify()\r\n                : keccak256(abi.encode(\r\n                    querySLA.hashify(),\r\n                    data().committees[evmRequester][radonHash].hash\r\n                )\r\n            )\r\n        );\r\n    }\r\n\r\n    /// Gets query storage by query id.\r\n    function seekQuery(uint256 queryId) internal view returns (Query storage) {\r\n      return data().queries[queryId];\r\n    }\r\n\r\n    /// Gets the Witnet.QueryRequest part of a given query.\r\n    function seekQueryRequest(uint256 queryId) internal view returns (QueryRequest storage) {\r\n        return data().queries[queryId].request;\r\n    }   \r\n\r\n    /// Gets the Witnet.Result part of a given query.\r\n    function seekQueryResponse(uint256 queryId) internal view returns (QueryResponse storage) {\r\n        return data().queries[queryId].response;\r\n    }\r\n\r\n    function intoDataResult(\r\n            QueryResponse memory queryResponse, \r\n            Witnet.QueryStatus queryStatus,\r\n            uint64 finalityBlock\r\n        )\r\n        internal pure\r\n        returns (Witnet.DataResult memory _result)\r\n    {\r\n        _result.drTxHash = Witnet.TransactionHash.wrap(queryResponse.resultDrTxHash);\r\n        if (queryResponse._0 > 0) {\r\n            _result.finality = (\r\n                queryResponse._0 | uint64(\r\n                    (queryResponse.resultTimestamp & 0xffffffff) << 32\r\n                )\r\n            );\r\n            _result.timestamp = Witnet.Timestamp.wrap(queryResponse.resultTimestamp >> 32);\r\n        } else {\r\n            _result.finality = finalityBlock;\r\n            _result.timestamp = Witnet.Timestamp.wrap(queryResponse.resultTimestamp);\r\n        }\r\n        if (queryResponse.resultCborBytes.length > 0) {\r\n            _result.value = WitnetCBOR.fromBytes(queryResponse.resultCborBytes);\r\n            _result.dataType = Witnet.peekRadonDataType(_result.value);\r\n        }\r\n        if (queryStatus == Witnet.QueryStatus.Finalized) {\r\n            if (queryResponse.resultCborBytes.length > 0) {\r\n                // determine whether stored result is an error by peeking the first byte\r\n                if (queryResponse.resultCborBytes[0] == bytes1(0xd8)) {\r\n                    if (\r\n                        _result.dataType == Witnet.RadonDataTypes.Array\r\n                            && WitnetCBOR.readLength(_result.value.buffer, _result.value.additionalInformation) >= 1\r\n                    ) {\r\n                        if (Witnet.peekRadonDataType(_result.value) == Witnet.RadonDataTypes.Integer) {\r\n                            _result.status = Witnet.ResultStatus(_result.value.readInt());\r\n                        \r\n                        } else {\r\n                            _result.status = Witnet.ResultStatus.UnhandledIntercept;\r\n                        }\r\n                    } else {\r\n                        _result.status = Witnet.ResultStatus.UnhandledIntercept;\r\n                    }            \r\n                } else {\r\n                    _result.status = Witnet.ResultStatus.NoErrors;\r\n                }\r\n            } else {\r\n                // the result is final but was delivered to some consuming contract:\r\n                _result.status = Witnet.ResultStatus.NoErrors;\r\n            }\r\n        \r\n        } else if (queryStatus == Witnet.QueryStatus.Reported) {\r\n            _result.status = Witnet.ResultStatus.BoardFinalizingResult;\r\n\r\n        } else if (\r\n            queryStatus == Witnet.QueryStatus.Posted\r\n                || queryStatus == Witnet.QueryStatus.Delayed\r\n        ) {\r\n            _result.status = Witnet.ResultStatus.BoardAwaitingResult;\r\n        \r\n        } else if (\r\n            queryStatus == Witnet.QueryStatus.Expired\r\n                || queryStatus == Witnet.QueryStatus.Disputed\r\n        ) {\r\n            _result.status = Witnet.ResultStatus.BoardResolutionTimeout;\r\n        \r\n        } else {\r\n            _result.status = Witnet.ResultStatus.UnhandledIntercept;\r\n        }\r\n    }\r\n\r\n    function intoString(Witnet.QueryStatus _status) internal pure returns (string memory) {\r\n        if (_status == Witnet.QueryStatus.Posted) {\r\n            return \"Posted\";\r\n        } else if (_status == Witnet.QueryStatus.Reported) {\r\n            return \"Reported\";\r\n        } else if (_status == Witnet.QueryStatus.Finalized) {\r\n            return \"Finalized\";\r\n        } else if (_status == Witnet.QueryStatus.Delayed) {\r\n            return \"Delayed\";\r\n        } else if (_status == Witnet.QueryStatus.Expired) {\r\n            return \"Expired\";\r\n        } else if (_status == Witnet.QueryStatus.Disputed) {\r\n            return \"Disputed\";\r\n        } else {\r\n            return \"Unknown\";\r\n        }\r\n    }\r\n\r\n\r\n    /// =======================================================================\r\n    /// --- IWitOracleTrustableAdmin -----------------------------------------------\r\n\r\n    function isReporter(address addr) internal view returns (bool) {\r\n        return data().reporters[addr];\r\n    }\r\n\r\n    function setReporters(address[] calldata reporters) public {\r\n        for (uint ix = 0; ix < reporters.length; ix ++) {\r\n            data().reporters[reporters[ix]] = true;\r\n        }\r\n        emit IWitOracleTrustableAdmin.ReportersSet(reporters);\r\n    }\r\n\r\n    function unsetReporters(address[] calldata reporters) public {\r\n        for (uint ix = 0; ix < reporters.length; ix ++) {\r\n            data().reporters[reporters[ix]] = false;\r\n        }\r\n        emit IWitOracleTrustableAdmin.ReportersUnset(reporters);\r\n    }\r\n\r\n    \r\n    /// =======================================================================\r\n    /// --- IWitOracle --------------------------------------------------------\r\n\r\n    function extractDataResult(\r\n            QueryResponse memory queryResponse, \r\n            Witnet.QueryStatus queryStatus,\r\n            uint64 finalityBlock\r\n        )\r\n        public pure \r\n        returns (Witnet.DataResult memory)\r\n    {\r\n        return intoDataResult(queryResponse, queryStatus, finalityBlock);\r\n    }\r\n\r\n    function parseDataReport(\r\n            Witnet.DataPushReport calldata _dataPushReport, \r\n            bytes calldata _signature\r\n        )\r\n        public view\r\n        returns (\r\n            address _evmReporter, \r\n            Witnet.DataResult memory _data\r\n        )\r\n    {\r\n        _evmReporter = Witnet.recoverEvmAddr(_signature, _dataPushReport.digest());\r\n        require(data().reporters[_evmReporter], \"WitOracleDataLib: invalid signature\");\r\n        _data = extractDataResult(\r\n            QueryResponse({\r\n                reporter: _evmReporter, \r\n                resultCborBytes: _dataPushReport.resultCborBytes,\r\n                resultDrTxHash: Witnet.TransactionHash.unwrap(_dataPushReport.witDrTxHash),\r\n                resultTimestamp: Witnet.Timestamp.unwrap(_dataPushReport.resultTimestamp),\r\n                disputer: address(0), _0: 0\r\n            }), \r\n            Witnet.QueryStatus.Finalized,\r\n            uint64(block.number)\r\n        );\r\n    }\r\n\r\n    /// =======================================================================\r\n    /// --- IWitOracleQueriable -----------------------------------------------\r\n\r\n    function deleteQuery(uint256 queryId) \r\n        public \r\n        returns (Witnet.QueryEvmReward _evmPayback) \r\n    {\r\n        WitOracleDataLib.Query storage __query = seekQuery(queryId);\r\n        require(\r\n            msg.sender == __query.request.requester,\r\n            \"not the requester\"\r\n        );\r\n        Witnet.QueryStatus _queryStatus = getQueryStatus(queryId);\r\n        if (\r\n            _queryStatus != Witnet.QueryStatus.Expired\r\n                && _queryStatus != Witnet.QueryStatus.Finalized\r\n        ) {\r\n            revert(string(abi.encodePacked(\r\n                \"invalid query status: \",\r\n                toString(_queryStatus)\r\n            )));\r\n        }\r\n        _evmPayback = __query.reward;\r\n        delete data().queries[queryId];\r\n    }\r\n\r\n    function getQuery(Witnet.QueryId queryId) public view returns (Witnet.Query memory) {\r\n        WitOracleDataLib.Query storage __query = data().queries[Witnet.QueryId.unwrap(queryId)];\r\n        Witnet.QueryUUID _uuid;\r\n        Witnet.QueryEvmReward _reward;\r\n        Witnet.BlockNumber _checkpoint;\r\n        if (__query.request._1 > 0) {\r\n            // read from v2 layout\r\n            _checkpoint = Witnet.BlockNumber.wrap(__query.response._0);\r\n            _reward = Witnet.QueryEvmReward.wrap(__query.request._0);\r\n\r\n        } else if (__query.request.radonBytecode.length <= 65535) {\r\n            // read from v3 layout\r\n            _checkpoint = __query.checkpoint;\r\n            _reward = __query.reward;\r\n            _uuid = __query.uuid;\r\n        }\r\n        return Witnet.Query({\r\n            request: getQueryRequest(queryId),\r\n            response: getQueryResponse(queryId),\r\n            slaParams: __query.slaParams,\r\n            uuid: __query.uuid,\r\n            reward: __query.reward,\r\n            checkpoint: __query.checkpoint\r\n        });\r\n    }\r\n\r\n    function getQueryRequest(Witnet.QueryId queryId) public view returns (Witnet.QueryRequest memory) {\r\n        WitOracleDataLib.Query storage __query = data().queries[Witnet.QueryId.unwrap(queryId)];\r\n        if (__query.request.radonBytecode.length > 65535) {\r\n            // read from v1 layout\r\n            return Witnet.QueryRequest({\r\n                requester: address(0),\r\n                callbackGas: 0,\r\n                radonBytecode: hex\"\",\r\n                radonHash: Witnet.RadonHash.wrap(__query.request.radonHash)\r\n            });\r\n        } else {\r\n            return Witnet.QueryRequest({\r\n                requester: __query.request.requester,\r\n                callbackGas: __query.request.callbackGas,\r\n                radonBytecode: __query.request.radonBytecode,\r\n                radonHash: Witnet.RadonHash.wrap(__query.request.radonHash)\r\n            });\r\n        }\r\n    }\r\n\r\n    function getQueryResponse(Witnet.QueryId queryId) public view returns (Witnet.QueryResponse memory) {\r\n        WitOracleDataLib.Query storage __query = data().queries[Witnet.QueryId.unwrap(queryId)];\r\n        if (__query.request.radonBytecode.length > 65535) {\r\n            // read from v1 layout\r\n            return Witnet.QueryResponse({\r\n                reporter: address(0),\r\n                resultTimestamp: Witnet.Timestamp.wrap(0),\r\n                resultDrTxHash: Witnet.TransactionHash.wrap(0),\r\n                resultCborBytes: __query.response.resultCborBytes,\r\n                disputer: address(0)\r\n            });\r\n        } else if (__query.request._1 > 0) {\r\n            // read from v2 layout\r\n            return Witnet.QueryResponse({\r\n                reporter: __query.response.reporter,\r\n                resultTimestamp: Witnet.Timestamp.wrap(__query.response.resultTimestamp >> 32),\r\n                resultDrTxHash: Witnet.TransactionHash.wrap(__query.response.resultDrTxHash),\r\n                resultCborBytes: __query.response.resultCborBytes,\r\n                disputer: address(0)\r\n            });\r\n        } else {\r\n            return Witnet.QueryResponse({\r\n                reporter: __query.response.reporter,\r\n                resultTimestamp: Witnet.Timestamp.wrap(__query.response.resultTimestamp),\r\n                resultDrTxHash: Witnet.TransactionHash.wrap(__query.response.resultDrTxHash),\r\n                resultCborBytes: __query.response.resultCborBytes,\r\n                disputer: __query.response.disputer\r\n            });\r\n        }\r\n    }\r\n\r\n    function getQueryStatus(uint256 queryId) public view returns (Witnet.QueryStatus) {\r\n        WitOracleDataLib.Query storage __query = seekQuery(queryId);\r\n        if (__query.response.resultTimestamp != 0) {\r\n            return Witnet.QueryStatus.Finalized;\r\n            \r\n        } else if (__query.request.requester != address(0)) {\r\n            return Witnet.QueryStatus.Posted;\r\n        \r\n        } else {\r\n            return Witnet.QueryStatus.Unknown;\r\n        }\r\n    }\r\n\r\n    function getQueryResult(uint256 queryId) public view returns (Witnet.DataResult memory _result) {\r\n        Witnet.QueryStatus _queryStatus = getQueryStatus(queryId);\r\n        WitOracleDataLib.Query storage __query = seekQuery(queryId);\r\n        return intoDataResult(\r\n            __query.response,\r\n            _queryStatus,\r\n            Witnet.BlockNumber.unwrap(__query.checkpoint)\r\n        );\r\n    }\r\n    \r\n    function getQueryResultStatus(uint256 queryId) public view returns (Witnet.ResultStatus) {\r\n        Witnet.QueryStatus _queryStatus = getQueryStatus(queryId);\r\n        QueryResponse storage __response = seekQueryResponse(queryId);\r\n        if (_queryStatus == Witnet.QueryStatus.Finalized) {\r\n            if (__response.resultCborBytes.length > 0) {\r\n                // determine whether stored result is an error by peeking the first byte\r\n                if (__response.resultCborBytes[0] == bytes1(0xd8)) {\r\n                    WitnetCBOR.CBOR[] memory _error = WitnetCBOR.fromBytes(__response.resultCborBytes).readArray();\r\n                    if (_error.length < 2) {\r\n                        return Witnet.ResultStatus.UnhandledIntercept;\r\n                    } else {\r\n                        return Witnet.ResultStatus(_error[0].readUint());\r\n                    }\r\n                }\r\n            }\r\n            return Witnet.ResultStatus.NoErrors;\r\n        \r\n        } else if (_queryStatus == Witnet.QueryStatus.Reported) {\r\n            return Witnet.ResultStatus.BoardFinalizingResult;\r\n\r\n        } else if (\r\n            _queryStatus == Witnet.QueryStatus.Posted\r\n                || _queryStatus == Witnet.QueryStatus.Delayed\r\n        ) {\r\n            return Witnet.ResultStatus.BoardAwaitingResult;\r\n        \r\n        } else if (\r\n            _queryStatus == Witnet.QueryStatus.Expired\r\n                || _queryStatus == Witnet.QueryStatus.Disputed\r\n        ) {\r\n            return Witnet.ResultStatus.BoardResolutionTimeout;\r\n        \r\n        } else {\r\n            return Witnet.ResultStatus.UnhandledIntercept;\r\n        }\r\n    }\r\n\r\n    function getQueryResponseStatus(uint256 queryId)\r\n        public view \r\n        returns (IWitOracleLegacy.QueryResponseStatus)\r\n    {\r\n        Witnet.QueryStatus _queryStatus = getQueryStatus(queryId);\r\n        if (_queryStatus == Witnet.QueryStatus.Finalized) {\r\n            bytes storage __cborValues = WitOracleDataLib.seekQueryResponse(queryId).resultCborBytes;\r\n            if (__cborValues.length > 0) {\r\n                // determine whether stored result is an error by peeking the first byte\r\n                return (__cborValues[0] == bytes1(0xd8)\r\n                    ? IWitOracleLegacy.QueryResponseStatus.Error \r\n                    : IWitOracleLegacy.QueryResponseStatus.Ready\r\n                );\r\n            \r\n            } else {\r\n                // the result is final but delivered to the requesting address\r\n                return IWitOracleLegacy.QueryResponseStatus.Delivered;\r\n            }\r\n        \r\n        } else if (_queryStatus == Witnet.QueryStatus.Posted) {\r\n            return IWitOracleLegacy.QueryResponseStatus.Awaiting;\r\n        \r\n        } else if (_queryStatus == Witnet.QueryStatus.Expired) {\r\n            return IWitOracleLegacy.QueryResponseStatus.Expired;\r\n        \r\n        } else {\r\n            return IWitOracleLegacy.QueryResponseStatus.Void;\r\n        }\r\n    }\r\n\r\n    \r\n    /// ================================================================================\r\n    /// --- IWitOracleQueriableTrustableReporter ---------------------------------------\r\n\r\n    function extractRadonBytecodes(\r\n            IWitOracleRadonRegistry registry, \r\n            Witnet.QueryId[] calldata queryIds\r\n        )\r\n        public view\r\n        returns (bytes[] memory bytecodes)\r\n    {\r\n        bytecodes = new bytes[](queryIds.length);\r\n        for (uint _ix = 0; _ix < queryIds.length; _ix ++) {\r\n            uint256 _queryId = Witnet.QueryId.unwrap(queryIds[_ix]);\r\n            WitOracleDataLib.Query storage __query = seekQuery(_queryId);\r\n            bytecodes[_ix] = (__query.request.radonHash != bytes32(0)\r\n                ? registry.bytecodeOf(Witnet.RadonHash.wrap(__query.request.radonHash), __query.slaParams)\r\n                : registry.bytecodeOf(__query.request.radonBytecode, __query.slaParams)\r\n            );\r\n        }\r\n    }\r\n\r\n    function reportResult(\r\n            address evmReporter,\r\n            uint256 evmGasPrice,\r\n            uint64  evmFinalityBlock,\r\n            uint256 queryId,\r\n            Witnet.Timestamp resultTimestamp,\r\n            Witnet.TransactionHash witDrTxHash,\r\n            bytes calldata resultCborBytes\r\n        )\r\n        public returns (uint256 evmReward)\r\n    {\r\n        // read requester address and whether a callback was requested:\r\n        WitOracleDataLib.Query storage __query = seekQuery(queryId);\r\n\r\n        // read query EVM reward:\r\n        evmReward = Witnet.QueryEvmReward.unwrap(__query.reward);\r\n\r\n        // set EVM reward right now as to avoid re-entrancy attacks:\r\n        __query.reward = Witnet.QueryEvmReward.wrap(0);\r\n\r\n        // determine whether a callback is required\r\n        if (__query.request.callbackGas > 0) {\r\n            (\r\n                uint256 _evmCallbackActualGas, \r\n                bool _evmCallbackSuccess, \r\n                string memory _evmCallbackRevertMessage\r\n            ) = __reportResultCallback(\r\n                evmReporter,\r\n                __query.request.requester,\r\n                __query.request.callbackGas,\r\n                evmFinalityBlock,\r\n                Witnet.QueryId.wrap(uint64(queryId)),\r\n                resultTimestamp,\r\n                witDrTxHash,\r\n                resultCborBytes\r\n            );\r\n            if (_evmCallbackSuccess) {\r\n                // => the callback run successfully\r\n                emit IWitOracleQueriableEvents.WitOracleQueryReportDelivery(\r\n                    Witnet.QueryId.wrap(uint64(queryId)),\r\n                    __query.request.requester,\r\n                    evmGasPrice,\r\n                    _evmCallbackActualGas\r\n                );\r\n            } else {\r\n                // => the callback reverted\r\n                emit IWitOracleQueriableEvents.WitOracleResportDeliveryFailed(\r\n                    Witnet.QueryId.wrap(uint64(queryId)),\r\n                    __query.request.requester,\r\n                    evmGasPrice,\r\n                    _evmCallbackActualGas,\r\n                    bytes(_evmCallbackRevertMessage).length > 0 \r\n                        ? _evmCallbackRevertMessage\r\n                        : \"WitOracleDataLib: callback exceeded gas limit\",\r\n                    resultCborBytes\r\n                );\r\n            }\r\n            // upon delivery, successfull or not, the audit trail is saved into storage, \r\n            // but not the actual result which was intended to be passed over to the requester:\r\n            __saveQueryResponse(\r\n                evmReporter,\r\n                evmFinalityBlock,\r\n                queryId,\r\n                resultTimestamp, \r\n                witDrTxHash,\r\n                hex\"\"\r\n            );\r\n        } else {\r\n            // => no callback is involved\r\n            emit IWitOracleQueriableEvents.WitOracleQueryReport(\r\n                Witnet.QueryId.wrap(uint64(queryId)),\r\n                evmGasPrice\r\n            );\r\n            // write query result and audit trail data into storage \r\n            __saveQueryResponse(\r\n                evmReporter,\r\n                evmFinalityBlock,\r\n                queryId,\r\n                resultTimestamp,\r\n                witDrTxHash,\r\n                resultCborBytes\r\n            );\r\n        }\r\n    }\r\n\r\n    function __reportResultCallback(\r\n            address evmReporter,\r\n            address evmRequester,\r\n            uint24  evmCallbackGasLimit,\r\n            uint64  evmFinalityBlock,\r\n            Witnet.QueryId queryId,\r\n            Witnet.Timestamp resultTimestamp,\r\n            Witnet.TransactionHash witDrTxHash,\r\n            bytes calldata resultCborBytes\r\n        )\r\n        private returns (\r\n            uint256 evmCallbackActualGas, \r\n            bool evmCallbackSuccess, \r\n            string memory evmCallbackRevertMessage\r\n        )\r\n    {\r\n        evmCallbackActualGas = gasleft();\r\n        Witnet.DataResult memory _result = intoDataResult(\r\n            QueryResponse({\r\n                reporter: evmReporter,\r\n                resultTimestamp: Witnet.Timestamp.unwrap(resultTimestamp),\r\n                resultDrTxHash: Witnet.TransactionHash.unwrap(witDrTxHash),\r\n                resultCborBytes: resultCborBytes,\r\n                disputer: address(0), _0: 0\r\n            }),\r\n            evmFinalityBlock <= block.number ? Witnet.QueryStatus.Finalized : Witnet.QueryStatus.Reported,\r\n            evmFinalityBlock\r\n        );\r\n        try IWitOracleQueriableConsumer(evmRequester).reportWitOracleQueryResult{\r\n            gas: evmCallbackGasLimit\r\n        } (\r\n            Witnet.QueryId.unwrap(queryId),\r\n            abi.encode(_result)\r\n        ) {\r\n            evmCallbackSuccess = true;\r\n        \r\n        } catch Error(string memory err) {\r\n            evmCallbackRevertMessage = err;\r\n        \r\n        } catch (bytes memory) {\r\n            evmCallbackRevertMessage = \"callback revert\";\r\n        }\r\n        evmCallbackActualGas -= gasleft();\r\n    }\r\n\r\n    /// Saves query response into storage.\r\n    function __saveQueryResponse(\r\n            address evmReporter,\r\n            uint64  evmFinalityBlock,\r\n            uint256 queryId,\r\n            Witnet.Timestamp resultTimestamp,\r\n            Witnet.TransactionHash witDrTxHash,\r\n            bytes memory resultCborBytes\r\n        ) private\r\n    {\r\n        WitOracleDataLib.Query storage __query = seekQuery(queryId);\r\n        __query.checkpoint = Witnet.BlockNumber.wrap(evmFinalityBlock);\r\n        __query.response.reporter = evmReporter; \r\n        __query.response.resultTimestamp = Witnet.Timestamp.unwrap(resultTimestamp);\r\n        __query.response.resultDrTxHash = Witnet.TransactionHash.unwrap(witDrTxHash);\r\n        __query.response.resultCborBytes = resultCborBytes;\r\n    }\r\n\r\n\r\n    /// =======================================================================\r\n    /// --- IWitOracleQueriableExperimental -----------------------------------\r\n\r\n    function extractDelegatedDataRequest(\r\n            IWitOracleRadonRegistry registry,\r\n            Witnet.QueryId queryId\r\n        )\r\n        public view\r\n        returns (IWitOracleQueriableExperimental.DDR memory)\r\n    {\r\n        WitOracleDataLib.Query storage __query = seekQuery(Witnet.QueryId.unwrap(queryId));\r\n        \r\n        bytes memory _radonBytecode;\r\n        Witnet.RadonHash _radonHash = Witnet.RadonHash.wrap(__query.request.radonHash);\r\n        if (_radonHash.isZero()) {\r\n            _radonBytecode = __query.request.radonBytecode;\r\n            _radonHash = registry.hashOf(_radonBytecode);\r\n        } else {\r\n            _radonBytecode = registry.lookupRadonRequestBytecode(_radonHash);\r\n        }\r\n        \r\n        Witnet.ServiceProvider[] memory _providers = data().committees\r\n            [__query.request.requester]\r\n            [_radonHash]\r\n            .members;\r\n\r\n        Witnet.QuerySLA memory _querySLA = __query.slaParams;\r\n        \r\n        return IWitOracleQueriableExperimental.DDR({\r\n            queryId: queryId,\r\n            queryUUID: __query.uuid,\r\n            queryEvmReward: __query.reward,\r\n            queryParams: IWitOracleQueriableExperimental.QueryParams({\r\n                witResultMaxSize: _querySLA.witResultMaxSize,\r\n                witCommitteeSize: _querySLA.witCommitteeSize,\r\n                witUnitaryReward: _querySLA.witUnitaryReward,\r\n                providers: _providers\r\n            }),\r\n            radonBytecode: _radonBytecode\r\n        });\r\n    }\r\n\r\n    \r\n    /// =======================================================================\r\n    /// --- Other public helper methods ---------------------------------------\r\n\r\n    function notInStatusRevertMessage(Witnet.QueryStatus self) public pure returns (string memory) {\r\n        if (self == Witnet.QueryStatus.Posted) {\r\n            return \"not in Posted status\";\r\n        } else if (self == Witnet.QueryStatus.Reported) {\r\n            return \"not in Reported status\";\r\n        } else if (self == Witnet.QueryStatus.Finalized) {\r\n            return \"not in Finalized status\";\r\n        } else {\r\n            return \"bad mood\";\r\n        }\r\n    }\r\n\r\n    function settle(Committee storage self, Witnet.ServiceProvider[] calldata members) public returns (bytes32 hash) {\r\n        if (members.length > 0) {\r\n            hash = keccak256(abi.encodePacked(members));\r\n            self.hash = hash;\r\n            self.members = members;\r\n        } else {\r\n            delete self.members;\r\n            self.hash = bytes32(0);\r\n        }\r\n    }\r\n\r\n    function toString(Witnet.QueryStatus _status) public pure returns (string memory) {\r\n        return intoString(_status);\r\n    }\r\n\r\n}\r\n"
      },
      "project/contracts/data/WitOracleRadonRegistryData.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\n/// @title Witnet Request Board base data model. \r\n/// @author The Witnet Foundation.\r\nabstract contract WitOracleRadonRegistryData {\r\n    \r\n    bytes32 private constant _WIT_BYTECODES_DATA_SLOTHASH =\r\n        /* keccak256(\"io.witnet.bytecodes.data\") */\r\n        0x673359bdfd0124f9962355e7aed2d07d989b0d4bc4cbe2c94c295e0f81427dec;\r\n\r\n    struct Storage {\r\n        address base;\r\n        address owner;\r\n        address pendingOwner;\r\n        Database db;\r\n    }\r\n\r\n    struct DataProvider {\r\n        string  authority;\r\n        uint256 totalEndpoints;\r\n        mapping (uint256 => bytes32) endpoints;\r\n    }\r\n\r\n    struct RadonRequestLegacyPacked {\r\n        string[][] _args;\r\n        bytes32 aggregateTallyHashes;\r\n        bytes32 _radHash;\r\n        Witnet.RadonDataTypes _resultDataType;\r\n        uint16 _resultMaxSize;\r\n        bytes32[] retrievals;\r\n        bytes32 legacyTallyHash;\r\n    }\r\n\r\n    struct RadonRequestInfo {\r\n        bytes15 crowdAttestationTallyHash;\r\n        uint8   dataSourcesCount;\r\n        bytes15 dataSourcesAggregatorHash;\r\n        Witnet.RadonDataTypes resultDataType;\r\n    }\r\n\r\n    struct Database {\r\n        bytes32 _reservedSlot0;\r\n        bytes32 _reservedSlot1;\r\n        mapping (bytes32 => Witnet.RadonReducer) reducers;\r\n        mapping (bytes32 => Witnet.RadonRetrieval) retrievals;\r\n        mapping (Witnet.RadonHash => RadonRequestLegacyPacked) legacyRequests;\r\n        mapping (bytes32 => Witnet.RadonHash) rads;\r\n        mapping (Witnet.RadonHash => bytes) radsBytecode;\r\n        mapping (Witnet.RadonHash => RadonRequestInfo) radsInfo;\r\n    }\r\n\r\n    constructor() {\r\n        // auto-initialize upon deployment\r\n        __bytecodes().base = address(this);\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Internal state-modifying functions -------------------------------------------------------------------------\r\n    \r\n    /// @dev Returns storage pointer to contents of 'Storage' struct.\r\n    function __bytecodes()\r\n      internal pure\r\n      returns (Storage storage _ptr)\r\n    {\r\n        assembly {\r\n            _ptr.slot := _WIT_BYTECODES_DATA_SLOTHASH\r\n        }\r\n    }\r\n\r\n    /// @dev Returns storage pointer to contents of 'Database' struct.\r\n    function __database()\r\n      internal view\r\n      returns (Database storage _ptr)\r\n    {\r\n        return __bytecodes().db;\r\n    }\r\n\r\n    function __requests(Witnet.RadonHash _radHash)\r\n        internal view\r\n        returns (RadonRequestLegacyPacked storage _ptr)\r\n    {\r\n        return __database().legacyRequests[_radHash];\r\n    }\r\n}"
      },
      "project/contracts/data/WitOracleTrustlessDataLib.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitOracleDataLib.sol\";\r\nimport \"../interfaces/IWitOracleTrustless.sol\";\r\nimport \"../libs/Witnet.sol\";\r\nimport \"../patterns/Escrowable.sol\";\r\n\r\n\r\n/// @title Trustless Witnet Request Board data library extension\r\n/// @author The Witnet Foundation.\r\nlibrary WitOracleTrustlessDataLib {  \r\n\r\n    using Witnet for Witnet.Beacon;\r\n    using Witnet for Witnet.BlockNumber;\r\n    using Witnet for Witnet.DataPullReport;\r\n    using Witnet for Witnet.DataPushReport;\r\n    using Witnet for Witnet.QuerySLA;\r\n    using Witnet for Witnet.Timestamp;\r\n\r\n    bytes32 internal constant _WIT_ORACLE_BLOCKS_SLOTHASH =\r\n        /* keccak256(\"io.witnet.boards.blocks\") & ~bytes32(uint256(0xff) */\r\n        0xf595240b351bc8f951c2f53b26f4e78c32cb62122cf76c19b7fdda7d4968e100;\r\n\r\n    struct Storage {\r\n        uint256 lastKnownBeaconIndex;\r\n        mapping (uint256 => Witnet.Beacon) beacons;\r\n        mapping (address => Escrowable.Escrow) escrows;\r\n    }\r\n    \r\n    // ================================================================================================================\r\n    // --- Internal functions -----------------------------------------------------------------------------------------\r\n\r\n    /// Returns storage pointer to contents of 'WitnetBoardState' struct.\r\n    function data() internal pure returns (Storage storage _ptr)\r\n    {\r\n        assembly {\r\n            _ptr.slot := _WIT_ORACLE_BLOCKS_SLOTHASH\r\n        }\r\n    }\r\n\r\n\r\n    /// =======================================================================\r\n    /// --- Escrowable --------------------------------------------------------\r\n\r\n    function burn(address from, uint256 value) public {\r\n        require(\r\n            data().escrows[from].balance >= value,\r\n            \"Escrowable: insufficient balance\"\r\n        );\r\n        data().escrows[from].balance -= value;\r\n        emit Escrowable.Burnt(from, value);\r\n    }\r\n    \r\n    function deposit(address to, uint256 value) public {\r\n        data().escrows[to].balance += value;\r\n        emit Payable.Received(to, value);\r\n    }\r\n\r\n    function stake(address from, uint256 value) public {\r\n        Escrowable.Escrow storage __escrow = data().escrows[from];\r\n        require(\r\n            __escrow.balance >= value,\r\n            \"Escrowable: insufficient balance\"\r\n        );\r\n        __escrow.balance -= value;\r\n        __escrow.collateral += value;\r\n        emit Escrowable.Staked(from, value);\r\n    }\r\n\r\n    function slash(address from, address to, uint256 value) public {\r\n        Escrowable.Escrow storage __escrowFrom = data().escrows[from];\r\n        Escrowable.Escrow storage __escrowTo = data().escrows[to];\r\n        require(\r\n            __escrowFrom.collateral >= value,\r\n            \"Escrowable: insufficient collateral\"\r\n        );\r\n        __escrowTo.balance += value;\r\n        __escrowFrom.collateral -= value;\r\n        emit Escrowable.Slashed(from, value);\r\n        emit Payable.Received(to, value);\r\n    }\r\n\r\n    function unstake(address from, uint256 value) public {\r\n        Escrowable.Escrow storage __escrow = data().escrows[from];\r\n        require(\r\n            __escrow.collateral >= value,\r\n            \"Escrowable: insufficient collateral\"\r\n        );\r\n        __escrow.collateral -= value;\r\n        __escrow.balance += value;\r\n        emit Escrowable.Unstaked(from, value);\r\n    }\r\n\r\n    function withdraw(address from) public returns (uint256 _withdrawn) {\r\n        Escrowable.Escrow storage __escrow = data().escrows[from];\r\n        _withdrawn = __escrow.balance;\r\n        __escrow.balance = 0;\r\n        emit Escrowable.Withdrawn(from, _withdrawn);\r\n    }\r\n\r\n\r\n    /// =======================================================================\r\n    /// --- IWitOracleTrustless --------------------------------------------------\r\n\r\n    function getLastKnownBeacon() internal view returns (Witnet.Beacon storage) {\r\n        return data().beacons[data().lastKnownBeaconIndex];\r\n    }\r\n\r\n    function getLastKnownBeaconIndex() internal view returns (uint256) {\r\n        return data().lastKnownBeaconIndex;\r\n    }\r\n\r\n    function rollupBeacons(Witnet.FastForward[] calldata rollup) \r\n        public \r\n        returns (Witnet.Beacon memory head)\r\n    {\r\n        head = verifyBeacons(rollup);\r\n        data().beacons[head.index] = head;\r\n        data().lastKnownBeaconIndex = head.index;\r\n        emit IWitOracleTrustless.Rollup(head);\r\n    }\r\n\r\n    function verifyBeacons(Witnet.FastForward[] calldata rollup)\r\n        public view\r\n        returns (Witnet.Beacon memory head)\r\n    {\r\n        require(\r\n            data().beacons[rollup[0].beacon.index].equals(rollup[0].beacon),\r\n            \"fast-forwarding from unmatching beacon\"\r\n        );\r\n        return _verifyFastForwards(rollup);\r\n    }\r\n\r\n    function seekBeacon(uint256 _index) internal view returns (Witnet.Beacon storage) {\r\n        return data().beacons[_index];\r\n    }\r\n\r\n\r\n    /// =======================================================================\r\n    /// --- IWitOracle --------------------------------------------------------\r\n\r\n    function deleteQueryTrustlessly(\r\n            uint256 queryId,\r\n            uint256 evmQueryAwaitingBlocks,\r\n            uint256 evmQueryReportingStake\r\n        )\r\n        public returns (Witnet.QueryEvmReward _evmPayback)\r\n    {\r\n        WitOracleDataLib.Query storage self = WitOracleDataLib.seekQuery(queryId);\r\n        require(\r\n            msg.sender == self.request.requester,\r\n            \"not the requester\"\r\n        );\r\n        _evmPayback = self.reward;\r\n        Witnet.QueryStatus _queryStatus = getQueryStatusTrustlessly(self, evmQueryAwaitingBlocks);\r\n        // TODO: properly handle QueryStatus.Disputed .....\r\n        // TODO: should pending reward be transferred to requester ??\r\n        if (_queryStatus == Witnet.QueryStatus.Expired) {\r\n            if (Witnet.QueryEvmReward.unwrap(_evmPayback) > 0) {\r\n                if (self.response.disputer != address(0)) {\r\n                    // transfer reporter's stake to the disputer\r\n                    slash(\r\n                        self.response.reporter,\r\n                        self.response.disputer,\r\n                        evmQueryReportingStake\r\n                    );\r\n                    // transfer back disputer's stake\r\n                    unstake(\r\n                        self.response.disputer,\r\n                        evmQueryReportingStake\r\n                    );\r\n                }\r\n            }\r\n        \r\n        } else if (_queryStatus != Witnet.QueryStatus.Finalized) {\r\n            revert(string(abi.encodePacked(\r\n                \"invalid query status: \",\r\n                WitOracleDataLib.intoString(_queryStatus)\r\n            )));\r\n        }\r\n\r\n        // completely delete query metadata from storage:\r\n        delete WitOracleDataLib.data().queries[queryId];\r\n    }\r\n\r\n    function getQueryResponseStatusTrustlessly(\r\n            WitOracleDataLib.Query storage self,\r\n            uint256 evmQueryAwaitingBlocks\r\n        )\r\n        public view returns (IWitOracleLegacy.QueryResponseStatus)\r\n    {\r\n        Witnet.QueryStatus _queryStatus = getQueryStatusTrustlessly(\r\n            self,\r\n            evmQueryAwaitingBlocks\r\n        );\r\n        if (_queryStatus == Witnet.QueryStatus.Finalized) {\r\n            bytes storage __cborValues = self.response.resultCborBytes;\r\n            if (__cborValues.length > 0) {\r\n                // determine whether stored result is an error by peeking the first byte\r\n                return (__cborValues[0] == bytes1(0xd8)\r\n                    ? IWitOracleLegacy.QueryResponseStatus.Error \r\n                    : IWitOracleLegacy.QueryResponseStatus.Ready\r\n                );\r\n            \r\n            } else {\r\n                // the result is final but delivered to the requesting address\r\n                return IWitOracleLegacy.QueryResponseStatus.Delivered;\r\n            }\r\n        } else if (_queryStatus == Witnet.QueryStatus.Reported) {\r\n            return IWitOracleLegacy.QueryResponseStatus.Finalizing;\r\n        \r\n        } else if (\r\n            _queryStatus == Witnet.QueryStatus.Posted\r\n                || _queryStatus == Witnet.QueryStatus.Delayed\r\n        ) {\r\n            return IWitOracleLegacy.QueryResponseStatus.Awaiting;\r\n        \r\n        } else if (\r\n            _queryStatus == Witnet.QueryStatus.Expired\r\n                || _queryStatus == Witnet.QueryStatus.Disputed\r\n        ) {\r\n            return IWitOracleLegacy.QueryResponseStatus.Expired;\r\n        \r\n        } else {\r\n            return IWitOracleLegacy.QueryResponseStatus.Void;\r\n        }\r\n    }\r\n\r\n    function getQueryResultTrustlessly(\r\n            WitOracleDataLib.Query storage self,\r\n            uint256 evmQueryAwaitingBlocks\r\n        ) \r\n        public view \r\n        returns (Witnet.DataResult memory _result)\r\n    {\r\n        Witnet.QueryStatus _queryStatus = getQueryStatusTrustlessly(\r\n            self,\r\n            evmQueryAwaitingBlocks\r\n        );\r\n        return _getQueryResult(self, _queryStatus);\r\n    }\r\n\r\n    function getQueryStatusTrustlessly(\r\n            WitOracleDataLib.Query storage self,\r\n            uint256 evmQueryAwaitingBlocks\r\n        )\r\n        public view returns (Witnet.QueryStatus)\r\n    {\r\n        if (self.response.resultTimestamp != 0) {\r\n            if (block.number >= Witnet.BlockNumber.unwrap(self.checkpoint)) {\r\n                if (self.response.disputer != address(0)) {\r\n                    return Witnet.QueryStatus.Disputed;\r\n\r\n                } else {\r\n                    return Witnet.QueryStatus.Finalized;\r\n                }\r\n            } else {\r\n                return Witnet.QueryStatus.Reported;\r\n            }\r\n        } else {\r\n            uint256 _checkpoint = Witnet.BlockNumber.unwrap(self.checkpoint);\r\n            if (_checkpoint == 0) {\r\n                return Witnet.QueryStatus.Unknown;\r\n            \r\n            } else if (block.number > _checkpoint + evmQueryAwaitingBlocks * 2) {\r\n                return Witnet.QueryStatus.Expired;\r\n\r\n            } else if (block.number > _checkpoint + evmQueryAwaitingBlocks) {\r\n                return Witnet.QueryStatus.Delayed;\r\n            \r\n            } else {\r\n                return Witnet.QueryStatus.Posted;\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n    /// =======================================================================\r\n    /// --- IWitOracleQueriableTrustlessReporter ---------------------------------------\r\n\r\n    function claimQueryReward(\r\n            uint256 queryId,\r\n            uint256 evmQueryAwaitingBlocks,\r\n            uint256 evmQueryReportingStake\r\n        ) \r\n        public returns (uint256 _evmReward)\r\n    {    \r\n        WitOracleDataLib.Query storage self = WitOracleDataLib.seekQuery(queryId);\r\n        \r\n        _evmReward = Witnet.QueryEvmReward.unwrap(self.reward);\r\n        self.reward = Witnet.QueryEvmReward.wrap(0);\r\n\r\n        // revert if already claimed:\r\n        require(\r\n            _evmReward > 0,\r\n            \"already claimed\"\r\n        );\r\n\r\n        // deposit query's reward into the caller's balance (if proven to be legitimate):\r\n        deposit(\r\n            msg.sender,\r\n            _evmReward\r\n        );\r\n\r\n        Witnet.QueryStatus _queryStatus = getQueryStatusTrustlessly(\r\n            self,\r\n            evmQueryAwaitingBlocks\r\n        );\r\n        if (_queryStatus == Witnet.QueryStatus.Finalized) {\r\n            // only the reporter can claim, \r\n            require(\r\n                msg.sender == self.request.requester,\r\n                \"not the requester\"\r\n            );\r\n            // recovering also the report stake\r\n            unstake(\r\n                msg.sender, \r\n                evmQueryReportingStake\r\n            );\r\n\r\n        // TODO: properly handle QueryStatus.Disputed .... \r\n        } else if (_queryStatus == Witnet.QueryStatus.Expired) {\r\n            if (self.response.disputer != address(0)) {\r\n                // only the disputer can claim,\r\n                require(\r\n                    msg.sender == self.response.disputer,\r\n                    \"not the disputer\"\r\n                );\r\n                // receiving the reporter's stake,\r\n                slash(\r\n                    self.response.reporter,\r\n                    msg.sender, \r\n                    evmQueryReportingStake\r\n                );\r\n                // and recovering the dispute stake,\r\n                unstake(\r\n                    msg.sender,\r\n                    evmQueryReportingStake\r\n                );\r\n                // TODO: should reward be transferred back to requester ??\r\n                _evmReward += evmQueryReportingStake;\r\n\r\n            } else {\r\n                // only the requester can claim,\r\n                require(\r\n                    msg.sender == self.request.requester,\r\n                    \"not the requester\"\r\n                );\r\n\r\n            }\r\n        } else {\r\n            revert(string(abi.encodePacked(\r\n                \"invalid query status: \",\r\n                WitOracleDataLib.intoString(_queryStatus)\r\n            )));\r\n        }\r\n    }\r\n\r\n    function disputeQueryResponse(\r\n            uint256 queryId,\r\n            uint256 evmQueryAwaitingBlocks,\r\n            uint256 evmQueryReportingStake\r\n        )\r\n        public returns (uint256 evmPotentialReward) \r\n    {\r\n        WitOracleDataLib.Query storage self = WitOracleDataLib.seekQuery(queryId);\r\n        require(\r\n            getQueryStatusTrustlessly(\r\n                self,\r\n                evmQueryAwaitingBlocks\r\n            ) == Witnet.QueryStatus.Reported, \"not in Reported status\"\r\n        );\r\n        stake(\r\n            msg.sender, \r\n            evmQueryReportingStake\r\n        );\r\n        self.checkpoint = Witnet.BlockNumber.wrap(uint64(block.number + evmQueryAwaitingBlocks));\r\n        self.response.disputer = msg.sender;\r\n        emit IWitOracleQueriableEvents.WitOracleQueryReportDispute(\r\n            Witnet.QueryId.wrap(uint64(queryId)),\r\n            msg.sender\r\n        );\r\n        return (\r\n            Witnet.QueryEvmReward.unwrap(self.reward)\r\n                + evmQueryReportingStake\r\n        );\r\n    }\r\n\r\n    function reportQueryResponseTrustlessly(\r\n            Witnet.DataPullReport calldata responseReport,\r\n            uint256 evmQueryAwaitingBlocks,\r\n            uint256 evmQueryReportingStake\r\n        )\r\n        public returns (\r\n            address _evmReporter,\r\n            uint256 _evmGasPrice,\r\n            uint64  _evmFinalityBlock,\r\n            Witnet.QueryId _queryId,\r\n            Witnet.Timestamp _witDrTxTimestamp,\r\n            Witnet.TransactionHash _witDrTxHash,\r\n            bytes memory _witResultCborBytes\r\n        )\r\n    {\r\n        WitOracleDataLib.Query storage self = WitOracleDataLib.seekQuery(Witnet.QueryId.unwrap(responseReport.queryId));\r\n        (bool _isValidReport, string memory _queryResponseReportInvalidError) = _isValidDataPullReport(\r\n            self,\r\n            responseReport\r\n        );\r\n        require(\r\n            _isValidReport,\r\n            _queryResponseReportInvalidError\r\n        );\r\n        \r\n        Witnet.QueryStatus _queryStatus = getQueryStatusTrustlessly(self, evmQueryAwaitingBlocks);\r\n        if (_queryStatus == Witnet.QueryStatus.Posted) {\r\n            _evmReporter = responseReport.queryRelayer();\r\n            require(\r\n                _evmReporter == msg.sender,\r\n                \"unauthorized query reporter\"\r\n            );\r\n        }\r\n\r\n        else if (_queryStatus == Witnet.QueryStatus.Delayed) {\r\n            _evmReporter = msg.sender;\r\n        \r\n        } else {\r\n            revert(string(abi.encodePacked(\r\n                \"invalid query status: \",\r\n                WitOracleDataLib.intoString(_queryStatus)\r\n            )));\r\n        }\r\n\r\n        // stake from caller's balance:\r\n        stake(msg.sender, evmQueryReportingStake);\r\n\r\n        // save query response into storage:\r\n        _evmGasPrice = tx.gasprice;\r\n        _evmFinalityBlock = uint64(block.number + evmQueryAwaitingBlocks);\r\n        _queryId = responseReport.queryId;\r\n        _witDrTxTimestamp = Witnet.determineTimestampFromEpoch(responseReport.witDrResultEpoch);\r\n        _witDrTxHash = responseReport.witDrTxHash;\r\n        _witResultCborBytes = responseReport.witDrResultCborBytes;\r\n    }\r\n\r\n    function rollupQueryResponseProof(\r\n            Witnet.FastForward[] calldata witOracleRollup,\r\n            Witnet.DataPullReport calldata responseReport,\r\n            bytes32[] calldata ddrTalliesMerkleTrie,\r\n            uint256 evmQueryAwaitingBlocks,\r\n            uint256 evmQueryReportingStake\r\n        )\r\n        public returns (uint256 evmTotalReward)\r\n    {\r\n        WitOracleDataLib.Query storage self = WitOracleDataLib.seekQuery(Witnet.QueryId.unwrap(responseReport.queryId));\r\n        // validate query response report\r\n        (bool _isValidReport, string memory _queryResponseReportInvalidError) = _isValidDataPullReport(\r\n            self,\r\n            responseReport\r\n        );\r\n        require(_isValidReport, _queryResponseReportInvalidError);\r\n\r\n        // validate rollup proofs\r\n        Witnet.Beacon memory _witOracleHead = rollupBeacons(witOracleRollup);\r\n        require(\r\n            _witOracleHead.index == Witnet.determineBeaconIndexFromEpoch(\r\n                responseReport.witDrResultEpoch\r\n            ) + 1, \"misleading head beacon\"\r\n        );\r\n\r\n        // validate merkle proof\r\n        require(\r\n            _witOracleHead.ddrTalliesMerkleRoot == Witnet.merkleRoot(\r\n                ddrTalliesMerkleTrie, \r\n                responseReport.tallyHash()\r\n            ), \"invalid merkle proof\"\r\n        );\r\n\r\n        // process query response report depending on query's current status ...\r\n        {    \r\n            Witnet.QueryStatus _queryStatus = getQueryStatusTrustlessly(\r\n                self,\r\n                evmQueryAwaitingBlocks\r\n            );\r\n            if (_queryStatus == Witnet.QueryStatus.Reported) {                \r\n                // check that proven report actually differs from what was formerly reported\r\n                require(\r\n                    keccak256(abi.encode(\r\n                        responseReport.witDrTxHash, \r\n                        responseReport.witDrResultEpoch,\r\n                        responseReport.witDrResultCborBytes\r\n                    )) != keccak256(abi.encode(\r\n                        self.response.resultDrTxHash,\r\n                        Witnet.determineEpochFromTimestamp(Witnet.Timestamp.wrap(self.response.resultTimestamp)),\r\n                        self.response.resultCborBytes\r\n                    )),\r\n                    \"proving no fake report\"\r\n                );\r\n\r\n                // transfer fake reporter's stake into caller's balance:\r\n                slash(\r\n                    self.response.reporter,\r\n                    msg.sender,\r\n                    evmQueryReportingStake\r\n                );\r\n\r\n                // transfer query's reward into caller's balance\r\n                deposit(msg.sender, Witnet.QueryEvmReward.unwrap(self.reward));\r\n\r\n                // update query's response data into storage:\r\n                self.response.reporter = msg.sender;\r\n                self.response.resultCborBytes = responseReport.witDrResultCborBytes;\r\n                self.response.resultDrTxHash = Witnet.TransactionHash.unwrap(responseReport.witDrTxHash);\r\n                self.response.resultTimestamp = Witnet.Timestamp.unwrap(Witnet.determineTimestampFromEpoch(responseReport.witDrResultEpoch));\r\n        \r\n            } else if (_queryStatus == Witnet.QueryStatus.Disputed) {\r\n                // check that proven report actually matches what was formerly reported\r\n                require(\r\n                    keccak256(abi.encode(\r\n                        responseReport.witDrTxHash, \r\n                        responseReport.witDrResultEpoch,\r\n                        responseReport.witDrResultCborBytes\r\n                    )) == keccak256(abi.encode(\r\n                        self.response.resultDrTxHash,\r\n                        Witnet.determineEpochFromTimestamp(Witnet.Timestamp.wrap(self.response.resultTimestamp)),\r\n                        self.response.resultCborBytes\r\n                    )),\r\n                    \"proving disputed fake report\"\r\n                );\r\n\r\n                // transfer fake disputer's stake into reporter's balance:\r\n                slash(\r\n                    self.response.disputer,\r\n                    self.response.reporter,\r\n                    evmQueryReportingStake\r\n                );\r\n\r\n                // transfer query's reward into reporter's balance:\r\n                deposit(self.response.reporter, Witnet.QueryEvmReward.unwrap(self.reward));\r\n                \r\n                // clear query's disputer\r\n                self.response.disputer = address(0);\r\n\r\n            } else {\r\n                revert(string(abi.encodePacked(\r\n                    \"invalid query status: \",\r\n                    WitOracleDataLib.intoString(_queryStatus)\r\n                )));\r\n            }\r\n            \r\n            // finalize query:\r\n            evmTotalReward = Witnet.QueryEvmReward.unwrap(self.reward) + evmQueryReportingStake;\r\n            self.reward = Witnet.QueryEvmReward.wrap(0); // no claimQueryReward(.) will be required (nor accepted whatsoever)\r\n            self.checkpoint = Witnet.BlockNumber.wrap(uint64(block.number)); // set query status to Finalized\r\n        }\r\n    }\r\n\r\n    function parseDataPushReport(\r\n            Witnet.DataPushReport calldata report,\r\n            Witnet.FastForward[] calldata rollup,\r\n            bytes32[] calldata droMerkleTrie\r\n        )\r\n        public view returns (Witnet.DataResult memory)\r\n    {\r\n        // validate query report\r\n        require(\r\n            Witnet.RadonHash.unwrap(report.queryRadHash) != bytes32(0)\r\n                && report.resultCborBytes.length > 0\r\n                && !report.resultTimestamp.isZero()\r\n                && Witnet.TransactionHash.unwrap(report.witDrTxHash) != bytes32(0)\r\n                && report.queryParams.isValid()\r\n            , \"invalid query report\"\r\n        );\r\n\r\n        // validate rollup proofs\r\n        Witnet.Beacon memory _witOracleHead = verifyBeacons(rollup);\r\n        require(\r\n            _witOracleHead.index >= Witnet.determineBeaconIndexFromTimestamp(report.resultTimestamp) + 1, \r\n            \"misleading head beacon\"\r\n        );\r\n\r\n        // validate merkle proof\r\n        require(\r\n            _witOracleHead.droTalliesMerkleRoot == Witnet.merkleRoot(\r\n                droMerkleTrie, \r\n                report.digest()\r\n            ), \"invalid merkle proof\"\r\n        );\r\n\r\n        return WitOracleDataLib.intoDataResult(\r\n            WitOracleDataLib.QueryResponse({\r\n                reporter: address(0), disputer: address(0), _0: 0,\r\n                resultCborBytes: report.resultCborBytes,\r\n                resultDrTxHash: Witnet.TransactionHash.unwrap(report.witDrTxHash),\r\n                resultTimestamp: Witnet.Timestamp.unwrap(report.resultTimestamp)\r\n            }),\r\n            Witnet.QueryStatus.Finalized,\r\n            uint64(block.number)\r\n        );\r\n    }\r\n\r\n    function rollupDataPushReport(\r\n            Witnet.DataPushReport calldata report,\r\n            Witnet.FastForward[] calldata rollup,\r\n            bytes32[] calldata droMerkleTrie\r\n        )\r\n        public returns (Witnet.DataResult memory)\r\n    {\r\n        // validate query report\r\n        require(\r\n            Witnet.RadonHash.unwrap(report.queryRadHash) != bytes32(0)\r\n                && report.resultCborBytes.length > 0\r\n                && !report.resultTimestamp.isZero()\r\n                && Witnet.TransactionHash.unwrap(report.witDrTxHash) != bytes32(0)\r\n                && report.queryParams.isValid()\r\n            , \"invalid query report\"\r\n        );\r\n\r\n        // validate rollup proofs\r\n        Witnet.Beacon memory _witOracleHead = rollupBeacons(rollup);\r\n        require(\r\n            _witOracleHead.index >= Witnet.determineBeaconIndexFromTimestamp(report.resultTimestamp) + 1, \r\n            \"misleading head beacon\"\r\n        );\r\n\r\n        // validate merkle proof\r\n        require(\r\n            _witOracleHead.droTalliesMerkleRoot == Witnet.merkleRoot(\r\n                droMerkleTrie, \r\n                report.digest()\r\n            ), \"invalid merkle proof\"\r\n        );\r\n\r\n        return WitOracleDataLib.intoDataResult(\r\n            WitOracleDataLib.QueryResponse({\r\n                reporter: address(0), disputer: address(0), _0: 0,\r\n                resultCborBytes: report.resultCborBytes,\r\n                resultDrTxHash: Witnet.TransactionHash.unwrap(report.witDrTxHash),\r\n                resultTimestamp: Witnet.Timestamp.unwrap(report.resultTimestamp)\r\n            }),\r\n            Witnet.QueryStatus.Finalized,\r\n            uint64(block.number)\r\n        );\r\n    }\r\n\r\n    \r\n    /// =======================================================================\r\n    /// --- Private library methods -------------------------------------------\r\n\r\n    function _getQueryResult(WitOracleDataLib.Query storage self, Witnet.QueryStatus queryStatus)\r\n        private view\r\n        returns (Witnet.DataResult memory)\r\n    {\r\n        return WitOracleDataLib.intoDataResult(\r\n            self.response, \r\n            queryStatus,\r\n            Witnet.BlockNumber.unwrap(self.checkpoint)\r\n        );\r\n    }\r\n\r\n    function _isValidDataPullReport(\r\n            WitOracleDataLib.Query storage self,\r\n            Witnet.DataPullReport calldata report\r\n        )\r\n        private view\r\n        returns (bool, string memory)\r\n    {\r\n        if (\r\n            Witnet.QueryUUID.unwrap(report.queryHash)\r\n                != Witnet.QueryUUID.unwrap(self.uuid)\r\n        ) {\r\n            return (false, \"invalid query hash\");\r\n        \r\n        } else if (report.witDrResultEpoch.isZero()) {\r\n            return (false, \"invalid result epoch\");\r\n        \r\n        } else if (report.witDrResultCborBytes.length == 0) {\r\n            return (false, \"invalid empty result\");\r\n        \r\n        } else {\r\n            return (true, new string(0));\r\n        \r\n        }\r\n    }\r\n\r\n    function _verifyFastForwards(Witnet.FastForward[] calldata ff)\r\n        private pure \r\n        returns (Witnet.Beacon calldata)\r\n    {\r\n        for (uint _ix = 1; _ix < ff.length; _ix ++) {\r\n            require(\r\n                ff[_ix].beacon.prevIndex == ff[_ix - 1].beacon.index\r\n                    && ff[_ix].beacon.prevRoot == ff[_ix - 1].beacon.root(),\r\n                string(abi.encodePacked(\r\n                    \"mismatching beacons on fast-forward step #\",\r\n                    Witnet.toString(_ix)\r\n                ))\r\n            );\r\n            require(\r\n                ff[_ix].committeeMissingPubkeys.length <= (\r\n                    Witnet.WIT_2_FAST_FORWARD_COMMITTEE_SIZE / 3\r\n                ), string(abi.encodePacked(\r\n                    \"too many missing pubkeys on fast-forward step #\",\r\n                    Witnet.toString(_ix)\r\n                ))\r\n            );\r\n            // TODO:\r\n            // uint256[4] memory _committeePubkey = ff[_ix - 1].beacon.nextCommitteePubkey;\r\n            // for (uint _mx = 0; _mx < ff[_ix].committeeMissingPubKeys.length; _mx ++) {\r\n            //     require(\r\n            //         0 < (\r\n            //             ff[_ix].committeeMissingPubkey[_mx][0]\r\n            //                 + ff[_ix].committeeMissingPubkey[_mx][1]\r\n            //                 + ff[_ix].committeeMissingPubkey[_mx][2]\r\n            //                 + ff[_ix].committeeMissingPubkey[_mx][3]\r\n\r\n            //         ), string(abi.encodePacked(\r\n            //             \"null missing pubkey on fast-forward step #\",\r\n            //             Witnet.toString(_ix),\r\n            //             \" index #\",\r\n            //             Witnet.toString(_mx)\r\n            //         ))\r\n            //     );\r\n            //     _committeePubkey -= ff[_ix].committeeMissingPubkey[_mx];\r\n            // }\r\n            // require(\r\n            //     _verifySignature(\r\n            //         ff[_ix].beacon.committeeSignature,\r\n            //         _committeePubkey,\r\n            //         ff[_ix].beacon.root()\r\n\r\n            //     ), string(abi.encodedPacked(\r\n            //         \"invalid signature on fast-forward step #\",\r\n            //         Witnet.toString(_ix)\r\n            //     ))\r\n            // );\r\n        }\r\n        return ff[ff.length - 1].beacon;\r\n    }\r\n}\r\n"
      },
      "project/contracts/data/WitPriceFeedsDataLib.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {IChainlinkAggregatorV3} from \"../interfaces/legacy/IChainlinkAggregatorV3.sol\";\r\nimport {IERC2362} from \"ado-contracts/contracts/interfaces/IERC2362.sol\";\r\nimport {IWitPriceFeeds, IWitPriceFeedsTypes, IWitPyth} from \"../interfaces/IWitPriceFeeds.sol\";\r\nimport {IWitPythErrors} from \"../interfaces/legacy/IWitPythErrors.sol\";\r\n\r\nimport {\r\n    IWitOracle,\r\n    IWitOracleRadonRegistry,\r\n    Witnet\r\n} from \"../WitOracle.sol\";\r\n\r\nimport \"../libs/Slices.sol\";\r\n\r\n/// @title WitPriceFeeds data model.\r\n/// @author The Witnet Foundation.\r\nlibrary WitPriceFeedsDataLib {\r\n\r\n    using Slices for string;\r\n    using Slices for Slices.Slice;\r\n\r\n    using Witnet for Witnet.DataResult;\r\n    using Witnet for Witnet.QueryId;\r\n    using Witnet for Witnet.RadonHash;\r\n    using Witnet for Witnet.ResultStatus;\r\n    using Witnet for Witnet.Timestamp;\r\n\r\n    using WitPriceFeedsDataLib for IWitPriceFeedsTypes.ID4;\r\n    using WitPriceFeedsDataLib for PriceFeed;\r\n    \r\n    bytes32 private constant _WIT_FEEDS_DATA_SLOTHASH =\r\n        /* keccak256(\"io.witnet.feeds.data.v3\") & ~bytes32(uint256(0xff) */\r\n        0xc5354469a5d32189a18f5e79f9508d828fa089087c317bc89792b1c8dba53900;\r\n\r\n    struct Storage {\r\n        IWitPyth.ID[] ids;\r\n        mapping (IWitPriceFeedsTypes.ID4 => PriceFeed) records;\r\n        mapping (IWitPriceFeedsTypes.ID4 => IWitPriceFeedsTypes.ID4[]) reverseDeps;\r\n        mapping (Witnet.RadonHash => IWitPriceFeedsTypes.ID4) reverseIds;\r\n        IWitPriceFeedsTypes.UpdateConditions defaultUpdateConditions;\r\n        address consumer;\r\n        bytes4  footprint;\r\n    }\r\n\r\n    struct PriceData {\r\n        /// @dev Exponentially moving average proportional to actual time since previous update.\r\n        uint64 emaPrice;\r\n        \r\n        /// @dev Price attested on the Witnet blockchain.\r\n        uint64 price;\r\n        \r\n        /// @dev How much the price varied since previous update.\r\n        int56 deltaPrice;\r\n        \r\n        /// @dev Base-10 exponent to compute actual price.\r\n        int8 exponent;\r\n\r\n        /// @dev Timestamp at which the price was attested on the Witnet blockchain.\r\n        Witnet.Timestamp timestamp;\r\n\r\n        /// @dev Auditory trail: price witnessing act on the Witnet blockchain.\r\n        Witnet.TransactionHash trail;\r\n    }\r\n\r\n    // struct Price {\r\n    //     /// @dev Price data point to be read is just one single SLOAD.\r\n    //     PriceData data;\r\n        \r\n    //     /// @dev Auditory trail: price witnessing act on the Witnet blockchain.\r\n    //     Witnet.TransactionHash trail;\r\n    // }\r\n\r\n    struct PriceFeed {\r\n        /// @dev Human-readable symbol for this price feed.\r\n        string symbol;\r\n        \r\n        /// @dev (Required for removing price-feed settlements from storage)\r\n        uint32 index;\r\n\r\n        /// @dev Base-10 exponent to compute actual price.\r\n        int8 exponent;\r\n\r\n        /// @dev (40-bit reserve)\r\n        int40 _reserved;\r\n        \r\n        /// @dev Price feed's mapping algorithm, if any.        \r\n        IWitPriceFeedsTypes.Mappers mapper;\r\n\r\n        /// @dev Price feed's aggregator oracle type, if other than the Wit/Oracle.\r\n        IWitPriceFeedsTypes.Oracles oracle;\r\n\r\n        /// @dev Price feed's aggregator oracle address, if other than the Wit/Oracle.\r\n        address oracleAddress;\r\n\r\n        /// @dev Unique ID identifying actual data sources and off-chain computations performed by \r\n        /// the selected oracle when retrieving a fresh update for this price feed \r\n        /// (e.g. Radon Request hash if oracle is the Wit/Oracle).\r\n        bytes32 oracleSources;\r\n\r\n        /// @dev 256-bit flag containing references up to 8x existing price feeds.\r\n        bytes32 mapperDeps;\r\n\r\n        /// @dev Price-feed specific update conditions, if other than defaults.\r\n        IWitPriceFeedsTypes.UpdateConditions updateConditions;\r\n\r\n        /// @dev Last valid update data retrieved from the Wit/Oracle, if any.\r\n        PriceData lastUpdate;\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Public methods ---------------------------------------------------------------------------------------------\r\n\r\n    function fetchLastUpdate(PriceFeed storage self, IWitPriceFeedsTypes.ID4 id4, uint24 heartbeat)\r\n        public view \r\n        returns (PriceData memory _lastUpdate)\r\n    {\r\n        IWitPriceFeedsTypes.Mappers _mapper = self.mapper;\r\n        if (_mapper == IWitPriceFeedsTypes.Mappers.None) {\r\n            \r\n            IWitPriceFeedsTypes.Oracles _oracle = self.oracle;\r\n            if (_oracle == IWitPriceFeedsTypes.Oracles.Witnet) {\r\n                if (self.oracleAddress == address(0) || self.oracleAddress == address(this)) {\r\n                    return self.lastUpdate;\r\n                \r\n                } else {\r\n                    return (\r\n                        self.updateConditions.computeEma\r\n                            ? _intoEmaPriceData(IWitPriceFeeds(self.oracleAddress).getPriceNotOlderThan(\r\n                                IWitPriceFeedsTypes.ID4.wrap(bytes4(self.oracleSources)), \r\n                                heartbeat\r\n                            ))\r\n                            : _intoPriceData(IWitPriceFeeds(self.oracleAddress).getPriceNotOlderThan(\r\n                                IWitPriceFeedsTypes.ID4.wrap(bytes4(self.oracleSources)), \r\n                                heartbeat\r\n                            ))\r\n                    );\r\n                }\r\n\r\n            } else if (_oracle == IWitPriceFeedsTypes.Oracles.ERC2362) {\r\n                (int _value, uint _timestamp,) = IERC2362(self.oracleAddress).valueFor(self.oracleSources);\r\n                _lastUpdate.price = uint64(int64(_value));\r\n                _lastUpdate.timestamp = Witnet.Timestamp.wrap(uint64(_timestamp));\r\n                _lastUpdate.exponent = self.exponent;\r\n\r\n            } else if (_oracle == IWitPriceFeedsTypes.Oracles.Chainlink) {\r\n                (, int _value,, uint _timestamp,) = IChainlinkAggregatorV3(self.oracleAddress).latestRoundData();\r\n                _lastUpdate.price = uint64(int64(_value));\r\n                _lastUpdate.timestamp = Witnet.Timestamp.wrap(uint64(_timestamp));\r\n                _lastUpdate.exponent = self.exponent;\r\n            \r\n            } else if (_oracle == IWitPriceFeedsTypes.Oracles.Pyth) {\r\n                IWitPyth.PythPrice memory _price;\r\n                if (self.updateConditions.computeEma) {\r\n                    _price = IWitPyth(self.oracleAddress).getEmaPriceUnsafe(IWitPyth.ID.wrap(self.oracleSources));\r\n                    _lastUpdate.emaPrice = uint64(_price.price);\r\n                } else {\r\n                    _price = IWitPyth(self.oracleAddress).getPriceUnsafe(IWitPyth.ID.wrap(self.oracleSources));\r\n                    _lastUpdate.price = uint64(_price.price);\r\n                }\r\n                _lastUpdate.timestamp = Witnet.Timestamp.wrap(uint64(_price.publishTime));\r\n                _lastUpdate.exponent = int8(_price.expo);\r\n\r\n            } else {\r\n                revert(\"unsupported oracle\");\r\n            }\r\n        \r\n        } else {    \r\n            if (\r\n                _mapper == IWitPriceFeedsTypes.Mappers.Product \r\n                    || _mapper == IWitPriceFeedsTypes.Mappers.Inverse\r\n            ) {\r\n                return fetchLastUpdateFromProduct(\r\n                    id4, \r\n                    heartbeat, \r\n                    self.exponent, \r\n                    _mapper == IWitPriceFeedsTypes.Mappers.Inverse\r\n                );\r\n\r\n            } else if (_mapper == IWitPriceFeedsTypes.Mappers.Hottest) {\r\n                return fetchLastUpdateFromHottest(\r\n                    id4, \r\n                    heartbeat,\r\n                    self.exponent\r\n                );\r\n            \r\n            } else if (_mapper == IWitPriceFeedsTypes.Mappers.Fallback) {\r\n                return fetchLastUpdateFromFallback(\r\n                    id4, \r\n                    heartbeat,\r\n                    self.exponent\r\n                );\r\n\r\n            } else {\r\n                revert(\"unsupported mapper\");\r\n            }\r\n        }\r\n    }\r\n\r\n    function getPrice(IWitPriceFeedsTypes.ID4 id4)\r\n        public view \r\n        returns (IWitPriceFeedsTypes.Price memory)\r\n    {\r\n        PriceFeed storage __record = seekPriceFeed(id4);\r\n        IWitPriceFeedsTypes.UpdateConditions memory _conditions = coalesce(__record.updateConditions);\r\n\r\n        PriceData memory _lastUpdate = fetchLastUpdate(__record, id4, _conditions.heartbeatSecs);\r\n        \r\n        require(\r\n            !_lastUpdate.timestamp.isZero(), \r\n            IWitPythErrors.PriceFeedNotFound()\r\n        );\r\n        \r\n        require(\r\n            _conditions.heartbeatSecs == 0\r\n                || block.timestamp <= Witnet.Timestamp.unwrap(_lastUpdate.timestamp) + _conditions.heartbeatSecs,\r\n            IWitPythErrors.StalePrice()\r\n        );\r\n\r\n        return IWitPriceFeedsTypes.Price({\r\n            exponent: _lastUpdate.exponent,\r\n            deltaPrice: _lastUpdate.deltaPrice,\r\n            price: _lastUpdate.emaPrice > 0 ? _lastUpdate.emaPrice : _lastUpdate.price,\r\n            timestamp: _lastUpdate.timestamp,\r\n            trail: _lastUpdate.trail\r\n        });\r\n    }\r\n\r\n    function getPriceNotOlderThan(IWitPriceFeedsTypes.ID4 id4, uint24 age)\r\n        public view \r\n        returns (IWitPriceFeedsTypes.Price memory)\r\n    {\r\n        PriceFeed storage __record = seekPriceFeed(id4);\r\n        PriceData memory _lastUpdate = fetchLastUpdate(__record, id4, age);\r\n\r\n        require(\r\n            !_lastUpdate.timestamp.isZero(), \r\n            IWitPythErrors.PriceFeedNotFound()\r\n        );\r\n\r\n        require(\r\n            block.timestamp <= Witnet.Timestamp.unwrap(_lastUpdate.timestamp) + age,\r\n            IWitPythErrors.StalePrice()\r\n        );\r\n\r\n        return IWitPriceFeedsTypes.Price({\r\n            exponent: _lastUpdate.exponent,\r\n            deltaPrice: _lastUpdate.deltaPrice,\r\n            price: _lastUpdate.emaPrice > 0 ? _lastUpdate.emaPrice : _lastUpdate.price,\r\n            timestamp: _lastUpdate.timestamp,\r\n            trail: _lastUpdate.trail\r\n        });\r\n    }\r\n\r\n    function getPriceUnsafe(IWitPriceFeedsTypes.ID4 id4)\r\n        public view \r\n        returns (IWitPriceFeedsTypes.Price memory)\r\n    {\r\n        PriceFeed storage __record = seekPriceFeed(id4);\r\n        PriceData memory _lastUpdate = fetchLastUpdate(__record, id4, 0);\r\n\r\n        return IWitPriceFeedsTypes.Price({\r\n            exponent: _lastUpdate.exponent,\r\n            deltaPrice: _lastUpdate.deltaPrice,\r\n            price: _lastUpdate.emaPrice > 0 ? _lastUpdate.emaPrice : _lastUpdate.price,\r\n            timestamp: _lastUpdate.timestamp,\r\n            trail: _lastUpdate.trail\r\n        });\r\n    }\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Price-feed admin methods -----------------------------------------------------------------------------------\r\n\r\n    function removePriceFeed(IWitPriceFeedsTypes.ID4 id4, bool recursively) public {\r\n        PriceFeed storage self = seekPriceFeed(id4);\r\n        if (self.settled()) {\r\n            IWitPriceFeedsTypes.ID4[] memory _reverseDeps = data().reverseDeps[id4];\r\n            require(\r\n                recursively\r\n                    || _reverseDeps.length == 0,\r\n                \"cannot remove if mapped from others\"  \r\n            );\r\n\r\n            // recursively remove reverse dependencies, if any\r\n            // (i.e. other price feeds that rely directly or indirectly on this one)\r\n            for (uint _ix; _ix < _reverseDeps.length; ++ _ix) {\r\n                removePriceFeed(_reverseDeps[_ix], recursively);\r\n            }\r\n            delete data().reverseDeps[id4];\r\n\r\n            // remove from array of supported price feeds\r\n            uint _popIndex = data().ids.length - 1;\r\n            if (self.index < _popIndex) {\r\n                IWitPyth.ID _popID = data().ids[_popIndex];\r\n                PriceFeed storage __last = seekPriceFeed(_intoID4(_popID));\r\n                __last.index = self.index;\r\n                data().ids[self.index] = _popID;\r\n            }\r\n            data().ids.pop();\r\n\r\n            // delete all metadata, but the update conditions\r\n            Witnet.RadonHash _radonHash = Witnet.RadonHash.wrap(self.oracleSources);       \r\n            if (!_radonHash.isZero()) {\r\n                if (id4.equals(data().reverseIds[_radonHash])) {\r\n                    data().reverseIds[_radonHash] = IWitPriceFeedsTypes.ID4.wrap(0);\r\n                }\r\n            }\r\n            delete data().records[id4].lastUpdate;\r\n            delete data().records[id4];\r\n        }\r\n    }\r\n\r\n    function settlePriceFeedFootprint() public returns (bytes4 _footprint) {\r\n        _footprint = _computePriceFeedsFootprint();\r\n        data().footprint = _footprint;\r\n    }\r\n\r\n    function settlePriceFeedMapper(\r\n            string calldata symbol,\r\n            int8 exponent,\r\n            IWitPriceFeedsTypes.Mappers mapper,\r\n            string[] calldata mapperDeps\r\n        )\r\n        public\r\n        returns (bytes4)\r\n    {\r\n        require(\r\n            uint8(mapper) > uint8(IWitPriceFeedsTypes.Mappers.None)\r\n                && uint8(mapper) <= uint8(IWitPriceFeedsTypes.Mappers.Inverse), \r\n            \"invalid mapper\"\r\n        );\r\n        IWitPriceFeedsTypes.ID4 id4 = _settlePriceFeedSymbol(symbol);\r\n        PriceFeed storage __record = seekPriceFeed(id4);\r\n        require(!__record.settled(), \"already settled\");\r\n        bytes32 _mapperDeps;\r\n        for (uint _ix; _ix < mapperDeps.length; _ix ++) {\r\n            bytes4 _id4 = bytes4(hash(mapperDeps[_ix]));\r\n            PriceFeed storage __depsFeed = seekPriceFeed(IWitPriceFeedsTypes.ID4.wrap(_id4));\r\n            require(__depsFeed.settled(), string(abi.encodePacked(\r\n                \"unsupported dependency: \",\r\n                mapperDeps[_ix]\r\n            )));\r\n            _mapperDeps |= (bytes32(_id4) >> (32 * _ix));\r\n            data().reverseDeps[IWitPriceFeedsTypes.ID4.wrap(_id4)].push(id4);\r\n        }\r\n        __record.settleMapper(\r\n            exponent, \r\n            mapper, \r\n            _mapperDeps\r\n        );\r\n        \r\n        // smoke test: force the transaction to revert, should there be any dependency loopback:\r\n        getPriceUnsafe(id4);\r\n\r\n        // recompute and return the new price feeds footprint:\r\n        return settlePriceFeedFootprint();\r\n    }\r\n\r\n    function settlePriceFeedOracle(\r\n            string calldata symbol,\r\n            int8 exponent,\r\n            IWitPriceFeedsTypes.Oracles oracle,\r\n            address oracleAddress,\r\n            bytes32 oracleSources\r\n        )\r\n        public\r\n        returns (bytes4)\r\n    {\r\n        require(\r\n            uint8(oracle) >= uint8(IWitPriceFeedsTypes.Oracles.Witnet)\r\n                && uint8(oracle) <= uint8(IWitPriceFeedsTypes.Oracles.Pyth), \r\n            \"invalid oracle\"\r\n        );\r\n        IWitPriceFeedsTypes.ID4 id4 = _settlePriceFeedSymbol(symbol);\r\n        PriceFeed storage __record = seekPriceFeed(id4);\r\n        require(!__record.settled(), \"already settled\");\r\n        require(oracleAddress.code.length > 0, \"inexistent oracle\");\r\n        __record.settleOracle(\r\n            exponent,\r\n            oracle,\r\n            oracleAddress,\r\n            oracleSources\r\n        );\r\n\r\n        // smoke test: force the transaction to revert, if providing bad sources or target address\r\n        getPriceUnsafe(id4);\r\n\r\n        // recompute and return the new price feeds footprint:\r\n        return settlePriceFeedFootprint();\r\n    }\r\n\r\n    function settlePriceFeedRadonBytecode(\r\n            string calldata symbol,\r\n            bytes calldata radonBytecode,\r\n            int8 exponent,\r\n            IWitOracleRadonRegistry registry\r\n        )\r\n        public\r\n        returns (bytes4 _footprint, Witnet.RadonHash _radonHash)\r\n    {\r\n        IWitPriceFeedsTypes.ID4 id4 = _settlePriceFeedSymbol(symbol);\r\n        PriceFeed storage __record = seekPriceFeed(id4);\r\n        require(address(registry) != address(0), \"no radon registry\");\r\n        _radonHash = registry.hashOf(radonBytecode);\r\n        __record.settleOracle(\r\n            exponent, \r\n            IWitPriceFeedsTypes.Oracles.Witnet,\r\n            address(this),\r\n            Witnet.RadonHash.unwrap(_radonHash)\r\n        );\r\n        _footprint = settlePriceFeedFootprint();\r\n    }\r\n\r\n    function settlePriceFeedRadonHash(\r\n            string calldata symbol,\r\n            Witnet.RadonHash radonHash,\r\n            int8 exponent,\r\n            IWitOracleRadonRegistry registry\r\n        )\r\n        public\r\n        returns (bytes4)\r\n    {\r\n        IWitPriceFeedsTypes.ID4 id4 = _settlePriceFeedSymbol(symbol);\r\n        PriceFeed storage __record = seekPriceFeed(id4);\r\n        require(address(registry) != address(0), \"no radon registry\");\r\n        require(registry.isVerifiedRadonRequest(radonHash), \"unverified sources\");\r\n        __record.settleOracle(\r\n            exponent, \r\n            IWitPriceFeedsTypes.Oracles.Witnet,\r\n            address(this),\r\n            Witnet.RadonHash.unwrap(radonHash)\r\n        );\r\n        return settlePriceFeedFootprint();\r\n    }\r\n\r\n    function toString(IWitPriceFeedsTypes.Mappers mapper) public pure returns (string memory) {\r\n        if (mapper == IWitPriceFeedsTypes.Mappers.None) {\r\n            return \"None\";\r\n        } else if (mapper == IWitPriceFeedsTypes.Mappers.Product) {\r\n            return \"Product\";\r\n        } else if (mapper == IWitPriceFeedsTypes.Mappers.Fallback) {\r\n            return \"Fallback\";\r\n        } else if (mapper == IWitPriceFeedsTypes.Mappers.Hottest) {\r\n            return \"Hottest\";\r\n        } \r\n        revert(\"unsupported mapper\");\r\n    }\r\n\r\n    function toString(IWitPriceFeedsTypes.Oracles oracle) public pure returns (string memory) {\r\n        if (oracle == IWitPriceFeedsTypes.Oracles.Witnet) {\r\n            return \"Wit/Oracle\";\r\n        } else if (oracle == IWitPriceFeedsTypes.Oracles.ERC2362) {\r\n            return \"ADO/ERC2362\";\r\n        } else if (oracle == IWitPriceFeedsTypes.Oracles.Chainlink) {\r\n            return \"ChainlinkAggregatorV3\";\r\n        } else if (oracle == IWitPriceFeedsTypes.Oracles.Pyth) {\r\n            return \"IPyth\";\r\n        }\r\n        revert(\"unsupported oracle\");\r\n    }\r\n\r\n    \r\n    // ================================================================================================================\r\n    // --- Internal methods -------------------------------------------------------------------------------------------\r\n\r\n    function coalesce(IWitPriceFeedsTypes.UpdateConditions storage self) \r\n        internal view \r\n        returns (IWitPriceFeedsTypes.UpdateConditions memory)\r\n    {\r\n        IWitPriceFeedsTypes.UpdateConditions storage __default = data().defaultUpdateConditions;\r\n        return IWitPriceFeedsTypes.UpdateConditions({\r\n            callbackGas: self.callbackGas == 0 ? __default.callbackGas : self.callbackGas,\r\n            computeEma: self.computeEma || __default.computeEma,\r\n            cooldownSecs:  self.cooldownSecs == 0 ? __default.cooldownSecs : self.cooldownSecs,\r\n            heartbeatSecs: self.heartbeatSecs == 0 ? __default.heartbeatSecs : self.heartbeatSecs,\r\n            maxDeviation1000: self.maxDeviation1000 == 0 ? __default.maxDeviation1000 : self.maxDeviation1000,\r\n            minWitnesses: self.minWitnesses == 0 ? __default.minWitnesses : self.minWitnesses                \r\n        });\r\n    }\r\n\r\n    function coalesce(\r\n            IWitPriceFeedsTypes.UpdateConditions storage self, \r\n            IWitPriceFeedsTypes.UpdateConditions memory _default\r\n        ) \r\n        internal pure\r\n        returns (IWitPriceFeedsTypes.UpdateConditions memory)\r\n    {\r\n        IWitPriceFeedsTypes.UpdateConditions memory _self = self;\r\n        return IWitPriceFeedsTypes.UpdateConditions({\r\n            callbackGas: _self.callbackGas == 0 ? _default.callbackGas : _self.callbackGas,\r\n            computeEma: _self.computeEma || _default.computeEma,\r\n            cooldownSecs:  _self.cooldownSecs == 0 ? _default.cooldownSecs : _self.cooldownSecs,\r\n            heartbeatSecs: _self.heartbeatSecs == 0 ? _default.heartbeatSecs : _self.heartbeatSecs,\r\n            maxDeviation1000: _self.maxDeviation1000 == 0 ? _default.maxDeviation1000 : _self.maxDeviation1000,\r\n            minWitnesses: _self.minWitnesses == 0 ? _default.minWitnesses : _self.minWitnesses\r\n        });\r\n    }\r\n\r\n    /// @notice Returns storage pointer to where Storage data is located. \r\n    function data() internal pure returns (Storage storage _ptr) {\r\n        assembly {\r\n            _ptr.slot := _WIT_FEEDS_DATA_SLOTHASH\r\n        }\r\n    }\r\n\r\n    /// @notice Returns array of price feed ids from which given feed's value depends.\r\n    /// @dev Returns empty array on either unsupported or not-routed feeds.\r\n    /// @dev The maximum number of dependencies is hard-limited to 8, as to limit number\r\n    /// @dev of SSTORE operations (`__storage().records[feedId].solverDepsFlag`), \r\n    /// @dev no matter the actual number of depending feeds involved.\r\n    function deps(IWitPriceFeedsTypes.ID4 self) internal view returns (IWitPriceFeedsTypes.ID4[] memory _deps) {\r\n        bytes32 _solverDepsFlag = data().records[self].mapperDeps;\r\n        _deps = new IWitPriceFeedsTypes.ID4[](8);\r\n        uint _len;\r\n        for (_len; _len < 8; ++ _len) {\r\n            bytes4 _id4 = bytes4(_solverDepsFlag);\r\n            if (_id4 == 0) {\r\n                break;\r\n            } else {\r\n                _deps[_len] = IWitPriceFeedsTypes.ID4.wrap(_id4);\r\n                _solverDepsFlag <<= 32;\r\n            }\r\n        }\r\n        assembly {\r\n            // reset length to actual number of dependencies:\r\n            mstore(_deps, _len)\r\n        }\r\n    }\r\n\r\n    function equals(IWitPriceFeedsTypes.ID4 a, IWitPriceFeedsTypes.ID4 b) internal pure returns (bool) {\r\n        return (\r\n            IWitPriceFeedsTypes.ID4.unwrap(a)\r\n                == IWitPriceFeedsTypes.ID4.unwrap(b)\r\n        );\r\n    }\r\n\r\n    function fetchLastUpdateFromProduct(\r\n            IWitPriceFeedsTypes.ID4 id4, \r\n            uint24 heartbeat, \r\n            int8 exponent, \r\n            bool inverse\r\n        )\r\n        internal view \r\n        returns (PriceData memory _lastUpdate)\r\n    {\r\n        IWitPriceFeedsTypes.ID4[] memory _deps = deps(id4);\r\n        int[3] memory _regs;\r\n        // _regs[0] -> _lastPrice\r\n        // _regs[1] -> _lastEmaPrice\r\n        // _regs[2] -> _exponent\r\n        unchecked {\r\n            for (uint _ix; _ix < _deps.length; ++ _ix) {\r\n                PriceData memory _depLastUpdate = fetchLastUpdate(seekPriceFeed(_deps[_ix]), _deps[_ix], heartbeat);\r\n                if (_ix == 0) {\r\n                    if (_depLastUpdate.emaPrice > 0) {\r\n                        _regs[1] = int64(_depLastUpdate.emaPrice);\r\n                    } else {\r\n                        _regs[0] = int64(_depLastUpdate.price);\r\n                    }\r\n                    _lastUpdate.timestamp = _depLastUpdate.timestamp;\r\n                    _lastUpdate.trail = _depLastUpdate.trail;\r\n                    \r\n                } else {\r\n                    if (_regs[1] > 0) {\r\n                        _regs[1] *= int64(_depLastUpdate.emaPrice);\r\n                    } else {\r\n                        _regs[0] *= int64(_depLastUpdate.price);\r\n                    }\r\n                    if (_lastUpdate.timestamp.gt(_depLastUpdate.timestamp)) {\r\n                        // on Product: timestamp belong to oldest of all deps\r\n                        _lastUpdate.timestamp = _depLastUpdate.timestamp;\r\n                        _lastUpdate.trail = _depLastUpdate.trail;\r\n                    }\r\n                }\r\n                _regs[2] += inverse ? _depLastUpdate.exponent : - _depLastUpdate.exponent;\r\n            }\r\n        }\r\n        _regs[2] += exponent;\r\n        if (_regs[2] <= 0) {\r\n            if (inverse) {\r\n                uint _factor = 10 ** uint(-_regs[2]);\r\n                if (_regs[1] > 0) {\r\n                    _lastUpdate.emaPrice = uint64(_factor / uint(_regs[1]));\r\n                } else if (_regs[0] > 0) {\r\n                    _lastUpdate.price = uint64(_factor / uint(_regs[0]));\r\n                } else {\r\n                    _lastUpdate.price = 0; // avoid unhandled reverts\r\n                }\r\n            } else {\r\n                uint _divisor = 10 ** uint(-_regs[2]);\r\n                if (_regs[1] > 0) {\r\n                    _lastUpdate.emaPrice = uint64(uint(_regs[1]) / _divisor);\r\n                } else {\r\n                    _lastUpdate.price = uint64(uint(_regs[0]) / _divisor);\r\n                }\r\n            }\r\n        } else {\r\n            uint _factor = 10 ** uint(_regs[2]);\r\n            if (_regs[1] > 0) {\r\n                _lastUpdate.emaPrice = uint64(uint(_regs[1]) * _factor);\r\n            } else {\r\n                _lastUpdate.price = uint64(uint(_regs[0]) * _factor);\r\n            }\r\n        }\r\n        _lastUpdate.exponent = exponent;\r\n    }\r\n\r\n    function fetchLastUpdateFromHottest(IWitPriceFeedsTypes.ID4 id4, uint24 heartbeat, int8 exponent)\r\n        internal view \r\n        returns (PriceData memory _lastUpdate)\r\n    {\r\n        IWitPriceFeedsTypes.ID4[] memory _deps = deps(id4);\r\n        for (uint _ix; _ix < _deps.length; ++ _ix) {\r\n            PriceData memory _depLastUpdate = fetchLastUpdate(seekPriceFeed(_deps[_ix]),  _deps[_ix], heartbeat);\r\n            if (\r\n                _ix == 0\r\n                    || _depLastUpdate.timestamp.gt(_lastUpdate.timestamp)\r\n            ) {\r\n                _lastUpdate = _depLastUpdate;\r\n            }\r\n        }\r\n        if (exponent < _lastUpdate.exponent) {\r\n            _lastUpdate.price *= uint64(10 ** uint8(_lastUpdate.exponent - exponent));\r\n            _lastUpdate.exponent = exponent;\r\n        } else if (exponent > _lastUpdate.exponent) {\r\n            _lastUpdate.price /= uint64(10 ** uint8(exponent - _lastUpdate.exponent));\r\n            _lastUpdate.exponent = exponent;\r\n        }\r\n    }\r\n\r\n    function fetchLastUpdateFromFallback(IWitPriceFeedsTypes.ID4 id4, uint24 heartbeat, int8 exponent)\r\n        internal view \r\n        returns (PriceData memory _lastUpdate)\r\n    {\r\n        IWitPriceFeedsTypes.ID4[] memory _deps = deps(id4);\r\n        for (uint _ix; _ix < _deps.length; ++ _ix) {\r\n            PriceData memory _depLastUpdate = fetchLastUpdate(seekPriceFeed(_deps[_ix]), _deps[_ix], heartbeat);\r\n            if (\r\n                heartbeat == 0\r\n                    || Witnet.Timestamp.unwrap(_depLastUpdate.timestamp) > uint64(block.timestamp - heartbeat)\r\n            ) {\r\n                return _depLastUpdate;\r\n            }\r\n        }\r\n        if (exponent < _lastUpdate.exponent) {\r\n            _lastUpdate.price *= uint64(10 ** uint8(_lastUpdate.exponent - exponent));\r\n            _lastUpdate.exponent = exponent;\r\n        } else if (exponent > _lastUpdate.exponent) {\r\n            _lastUpdate.price /= uint64(10 ** uint8(exponent - _lastUpdate.exponent));\r\n            _lastUpdate.exponent = exponent;\r\n        }\r\n    }\r\n\r\n    function hash(string memory symbol) internal pure returns (bytes32) {\r\n        return keccak256(abi.encode(symbol));\r\n    }\r\n\r\n    function isZero(IWitPriceFeedsTypes.ID4 id4) internal pure returns (bool) {\r\n        return IWitPriceFeedsTypes.ID4.unwrap(id4) == 0;\r\n    }\r\n\r\n    // function pushDataResult(\r\n    //         Witnet.DataResult memory result,\r\n    //         IWitPriceFeedsTypes.UpdateConditions memory defaultUpdateConditions,\r\n    //         IWitPriceFeedsTypes.ID4 id4\r\n    //     )\r\n    //     internal\r\n    // {\r\n    //     PriceFeed storage __record = seekPriceFeed(id4);\r\n    //     PriceData memory _lastUpdate = __record.lastUpdate.data;\r\n    //     IWitPriceFeedsTypes.UpdateConditions memory _updateConditions = coalesce(\r\n    //         __record.updateConditions, \r\n    //         defaultUpdateConditions\r\n    //     );\r\n        \r\n    //     // consider updating price-feed's last update only if reported value is more recent:\r\n    //     if (\r\n    //         Witnet.Timestamp.unwrap(_lastUpdate.timestamp) + _updateConditions.cooldownSecs\r\n    //             < Witnet.Timestamp.unwrap(result.timestamp)\r\n    //     ) {\r\n    //         // revert if any of the allegedly fresh updates actually contains \r\n    //         // no integer value:\r\n    //         require(\r\n    //             result.dataType == Witnet.RadonDataTypes.Integer\r\n    //                 && result.status == Witnet.ResultStatus.NoErrors,\r\n    //             IWitPythErrors.InvalidUpdateData()\r\n    //         );\r\n\r\n    //         // compute next data point based on `_result` and `_lastUpdate`\r\n    //         __record.lastUpdate = _computeNextPrice(\r\n    //             result, \r\n    //             _lastUpdate, \r\n    //             _updateConditions\r\n    //         );\r\n    //     }\r\n    // }\r\n\r\n    function seekPriceFeed(IWitPriceFeedsTypes.ID4 id4) internal view returns (PriceFeed storage) {\r\n        return data().records[id4];\r\n    }\r\n\r\n    function settled(PriceFeed storage self) internal view returns (bool) {\r\n        return(\r\n            self.oracleSources != bytes32(0)\r\n                || uint8(self.mapper) != 0\r\n                || self.oracleAddress != address(0)\r\n        );\r\n    }\r\n\r\n    function settleMapper(\r\n            PriceFeed storage self, \r\n            int8 exponent,\r\n            IWitPriceFeedsTypes.Mappers mapper, \r\n            bytes32 mapperDeps\r\n        )\r\n        internal\r\n    {\r\n        require(!self.settled(), \"already settled\");\r\n        self.exponent = exponent;\r\n        self.mapper = mapper;\r\n        self.mapperDeps = mapperDeps;\r\n    }\r\n\r\n    function settleOracle(\r\n            PriceFeed storage self,\r\n            int8 exponent,\r\n            IWitPriceFeedsTypes.Oracles oracle,\r\n            address oracleAddress,\r\n            bytes32 oracleSources\r\n        )\r\n        internal\r\n    {\r\n        require(!self.settled(), \"already settled\");\r\n        self.exponent = exponent;\r\n        self.oracle = oracle;\r\n        self.oracleAddress = oracleAddress;\r\n        self.oracleSources = oracleSources;\r\n    }\r\n\r\n    // function settleWitOracle(\r\n    //         PriceFeed storage self, \r\n    //         int8 exponent,\r\n    //         Witnet.RadonHash radonHash\r\n    //     )\r\n    //     internal\r\n    // {\r\n    //     require(!self.settled(), \"already settled\");\r\n    //     self.exponent = exponent;\r\n    //     self.oracle = IWitPriceFeedsTypes.Oracles.Witnet;\r\n    //     self.oracleAddress = address(this);\r\n    //     self.oracleSources = Witnet.RadonHash.unwrap(radonHash);\r\n    //     self.lastUpdate.data.exponent = exponent;\r\n    // }\r\n\r\n    function toERC165Id(IWitPriceFeedsTypes.Oracles oracle) public pure returns (bytes4) {\r\n        if (oracle == IWitPriceFeedsTypes.Oracles.Witnet) {\r\n            return type(IWitOracle).interfaceId;\r\n        \r\n        } else if (oracle == IWitPriceFeedsTypes.Oracles.ERC2362) {\r\n            return type(IERC2362).interfaceId;\r\n        \r\n        } else if (oracle == IWitPriceFeedsTypes.Oracles.Chainlink) {\r\n            return type(IChainlinkAggregatorV3).interfaceId;\r\n        \r\n        } else if (oracle == IWitPriceFeedsTypes.Oracles.Pyth) {\r\n            return type(IWitPyth).interfaceId;\r\n        \r\n        } else {\r\n            return 0x0;\r\n        }\r\n    }\r\n\r\n\r\n    // ================================================================================================================\r\n    // --- Private methods --------------------------------------------------------------------------------------------\r\n\r\n    function _computePriceFeedsFootprint() private view returns (bytes4 _footprint) {\r\n        uint _totalIds = data().ids.length;\r\n        if (_totalIds > 0) {\r\n            _footprint = _footprintOf(_intoID4(data().ids[0]));\r\n            for (uint _ix = 1; _ix < _totalIds; ++ _ix) {\r\n                _footprint ^= _footprintOf(_intoID4(data().ids[_ix]));\r\n            }\r\n        }\r\n    }\r\n\r\n    function _footprintOf(IWitPriceFeedsTypes.ID4 id4) private view returns (bytes4) {\r\n        WitPriceFeedsDataLib.PriceFeed storage self = seekPriceFeed(id4);\r\n        if (self.oracleSources == bytes32(0)) {\r\n            return self.mapper != IWitPriceFeedsTypes.Mappers.None ? (\r\n                bytes4(keccak256(abi.encodePacked(\r\n                    IWitPriceFeedsTypes.ID4.unwrap(id4), \r\n                    self.mapperDeps\r\n                )))\r\n            ) : (\r\n                bytes4(keccak256(abi.encodePacked(\r\n                    IWitPriceFeedsTypes.ID4.unwrap(id4), \r\n                    self.oracleAddress\r\n                )))\r\n            );\r\n\r\n        } else {\r\n            return bytes4(keccak256(abi.encodePacked(\r\n                IWitPriceFeedsTypes.ID4.unwrap(id4), \r\n                self.oracleSources\r\n            )));\r\n        }\r\n    }\r\n\r\n    function _intoID4(IWitPyth.ID id) private pure returns (IWitPriceFeedsTypes.ID4) {\r\n        return IWitPriceFeedsTypes.ID4.wrap(bytes4(IWitPyth.ID.unwrap(id)));\r\n    }\r\n\r\n    function _intoWitPythID(IWitPriceFeedsTypes.ID4 id4) private view returns (IWitPyth.ID) {\r\n        return data().ids[data().records[id4].index];\r\n    }\r\n\r\n        function _intoPriceData(IWitPriceFeedsTypes.Price memory _price) internal pure returns (PriceData memory) {\r\n        return PriceData({\r\n            emaPrice: 0,\r\n            price: _price.price,\r\n            deltaPrice: _price.deltaPrice,\r\n            timestamp: _price.timestamp,\r\n            trail: _price.trail,\r\n            exponent: _price.exponent\r\n        });\r\n    }\r\n\r\n    function _intoEmaPriceData(IWitPriceFeedsTypes.Price memory _price) internal pure returns (PriceData memory) {\r\n        return PriceData({\r\n            emaPrice: _price.price,\r\n            price: 0,\r\n            deltaPrice: _price.deltaPrice,\r\n            timestamp: _price.timestamp,\r\n            trail: _price.trail,\r\n            exponent: _price.exponent\r\n        });\r\n    }\r\n\r\n    // function _intoWitPythPriceFeed(\r\n    //         IWitPriceFeeds.ID priceId,\r\n    //         Witnet.DataResult memory result,\r\n    //         PriceData memory prevData,\r\n    //         IWitPriceFeedsTypes.UpdateConditions memory updateConditions\r\n    //     )\r\n    //     private pure\r\n    //     returns (IWitPyth.PriceFeed memory)\r\n    // {\r\n    //     Price memory _next = _computeNextPrice(result, prevData, updateConditions);\r\n    //     uint64 _nextDeviation1000 = uint64(\r\n    //         _next.data.deltaPrice >= 0 \r\n    //             ? int64(_next.data.deltaPrice) \r\n    //             : int64(-_next.data.deltaPrice)\r\n    //     );\r\n    //     return IWitPyth.PriceFeed({\r\n    //         id: priceId,\r\n    //         price: IWitPyth.Price({\r\n    //             price: _next.data.price,\r\n    //             conf: _nextDeviation1000,\r\n    //             expo: _next.data.exponent,\r\n    //             publishTime: _next.data.timestamp,\r\n    //             track: _next.trail\r\n    //         }),\r\n    //         emaPrice: IWitPyth.Price({\r\n    //             price: _next.data.emaPrice,\r\n    //             conf: _nextDeviation1000,\r\n    //             expo: _next.data.exponent,\r\n    //             publishTime: _next.data.timestamp,\r\n    //             track: _next.trail\r\n    //         })\r\n    //     });\r\n    // }\r\n\r\n    function _settlePriceFeedSymbol(string calldata symbol) private returns (IWitPriceFeedsTypes.ID4 id4) {\r\n        bytes32 _id = hash(symbol);\r\n        id4 = IWitPriceFeedsTypes.ID4.wrap(bytes4(_id));\r\n        PriceFeed storage __record = seekPriceFeed(id4);\r\n        if (\r\n            keccak256(abi.encode(symbol))\r\n                != keccak256(abi.encode(__record.symbol))\r\n        ) {\r\n            require(\r\n                data().reverseDeps[id4].length == 0,\r\n                \"cannot refactor exisitng symbol if mapped by others\"\r\n            );\r\n            __record.symbol = symbol;\r\n            __record.index = uint32(data().ids.length);\r\n            delete __record.lastUpdate;\r\n        }\r\n        if (!__record.settled()) {\r\n            // add id to the list of supported price feeds, if not currently settled\r\n            data().ids.push(IWitPyth.ID.wrap(_id));\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/data/WitPriceFeedsLegacyDataLib.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../WitOracle.sol\";\r\n\r\nimport \"../interfaces/legacy/IWitPriceFeedsLegacy.sol\";\r\nimport \"../interfaces/legacy/IWitPriceFeedsLegacyAdmin.sol\";\r\nimport \"../interfaces/legacy/IWitPriceFeedsLegacySolver.sol\";\r\nimport \"../libs/Slices.sol\";\r\n\r\n/// @title WitPriceFeedsLegacy data model.\r\n/// @author The Witnet Foundation.\r\nlibrary WitPriceFeedsLegacyDataLib {\r\n\r\n    using Slices for string;\r\n    using Slices for Slices.Slice;\r\n\r\n    using Witnet for Witnet.DataResult;\r\n    using Witnet for Witnet.QueryId;\r\n    using Witnet for Witnet.ResultStatus;\r\n    \r\n    bytes32 private constant _WIT_FEEDS_DATA_SLOTHASH =\r\n        /* keccak256(\"io.witnet.feeds.data\") */\r\n        0xe36ea87c48340f2c23c9e1c9f72f5c5165184e75683a4d2a19148e5964c1d1ff;\r\n\r\n    struct Storage {\r\n        bytes32 reserved;\r\n        bytes4[] ids;\r\n        mapping (bytes4 => Record) records;\r\n    }\r\n\r\n    struct Record {\r\n        string  caption;\r\n        uint8   decimals;\r\n        uint256 index;\r\n        uint256 lastValidQueryId;\r\n        uint256 latestUpdateQueryId;\r\n        bytes32 radHash;\r\n        address solver;         // logic contract address for reducing values on routed feeds.\r\n        int256  solverReductor; // as to reduce resulting number of decimals on routed feeds.\r\n        bytes32 solverDepsFlag; // as to store ids of up to 8 depending feeds.\r\n    }\r\n\r\n    \r\n    // ================================================================================================\r\n    // --- Internal functions -------------------------------------------------------------------------\r\n    \r\n    /// @notice Returns array of feed ids from which given feed's value depends.\r\n    /// @dev Returns empty array on either unsupported or not-routed feeds.\r\n    /// @dev The maximum number of dependencies is hard-limited to 8, as to limit number\r\n    /// @dev of SSTORE operations (`__storage().records[feedId].solverDepsFlag`), \r\n    /// @dev no matter the actual number of depending feeds involved.\r\n    function depsOf(bytes4 feedId) internal view returns (bytes4[] memory _deps) {\r\n        bytes32 _solverDepsFlag = data().records[feedId].solverDepsFlag;\r\n        _deps = new bytes4[](8);\r\n        uint _len;\r\n        for (_len = 0; _len < 8; _len ++) {\r\n            _deps[_len] = bytes4(_solverDepsFlag);\r\n            if (_deps[_len] == 0) {\r\n                break;\r\n            } else {\r\n                _solverDepsFlag <<= 32;\r\n            }\r\n        }\r\n        assembly {\r\n            // reset length to actual number of dependencies:\r\n            mstore(_deps, _len)\r\n        }\r\n    }\r\n\r\n    /// @notice Returns storage pointer to where Storage data is located. \r\n    function data()\r\n      internal pure\r\n      returns (Storage storage _ptr)\r\n    {\r\n        assembly {\r\n            _ptr.slot := _WIT_FEEDS_DATA_SLOTHASH\r\n        }\r\n    }\r\n\r\n    function hash(string memory caption) internal pure returns (bytes4) {\r\n        return bytes4(keccak256(bytes(caption)));\r\n    }\r\n\r\n    function lastValidQueryId(IWitOracleQueriable witOracle, bytes4 feedId)\r\n        internal view \r\n        returns (uint256 _queryId)\r\n    {\r\n        _queryId = seekRecord(feedId).latestUpdateQueryId;\r\n        if (\r\n            _queryId == 0\r\n                || witOracle.getQueryResultStatus(_queryId) != Witnet.ResultStatus.NoErrors\r\n        ) {\r\n            _queryId = seekRecord(feedId).lastValidQueryId;\r\n        }\r\n    }\r\n\r\n    function latestUpdateQueryResultStatus(IWitOracleQueriable witOracle, bytes4 feedId)\r\n        internal view\r\n        returns (Witnet.ResultStatus)\r\n    {\r\n        uint256 _queryId = seekRecord(feedId).latestUpdateQueryId;\r\n        if (_queryId != 0) {\r\n            return witOracle.getQueryResultStatus(_queryId);\r\n        } else {\r\n            return Witnet.ResultStatus.NoErrors;\r\n        }\r\n    }\r\n\r\n    /// @notice Returns storage pointer to where Record for given feedId is located.\r\n    function seekRecord(bytes4 feedId) internal view returns (Record storage) {\r\n        return data().records[feedId];\r\n    }\r\n\r\n    function seekPriceSolver(bytes4 feedId) internal view returns (\r\n            address _solverAddress,\r\n            string[] memory _solverDeps\r\n        )\r\n    {\r\n        _solverAddress = seekRecord(feedId).solver;\r\n        bytes4[] memory _deps = depsOf(feedId);\r\n        _solverDeps = new string[](_deps.length);\r\n        for (uint _ix = 0; _ix < _deps.length; _ix ++) {\r\n            _solverDeps[_ix] = seekRecord(_deps[_ix]).caption;\r\n        }\r\n    }\r\n\r\n\r\n    // ================================================================================================\r\n    // --- Public functions ---------------------------------------------------------------------------\r\n\r\n    function deleteFeed(string calldata caption) public {\r\n        bytes4 feedId = hash(caption);\r\n        bytes4[] storage __ids = data().ids;\r\n        Record storage __record = seekRecord(feedId);\r\n        uint _index = __record.index;\r\n        require(_index != 0, \"unknown feed\");\r\n        bytes4 _lastFeedId = __ids[__ids.length - 1];\r\n        __ids[_index - 1] = _lastFeedId;\r\n        __ids.pop();\r\n        seekRecord(_lastFeedId).index = _index;\r\n        delete data().records[feedId];\r\n        emit IWitPriceFeedsLegacyAdmin.WitFeedDeleted(caption, feedId);\r\n    }\r\n\r\n    function deleteFeeds() public {\r\n        bytes4[] storage __ids = data().ids;\r\n        for (uint _ix = __ids.length; _ix > 0; _ix --) {\r\n            bytes4 _feedId = __ids[_ix - 1];\r\n            string memory _caption = data().records[_feedId].caption;\r\n            delete data().records[_feedId]; __ids.pop();\r\n            emit IWitPriceFeedsLegacyAdmin.WitFeedDeleted(_caption, _feedId);\r\n        }\r\n    }\r\n\r\n    function latestPrice(\r\n            IWitOracleQueriable witOracle,\r\n            bytes4 feedId\r\n        ) \r\n        public view \r\n        returns (IWitPriceFeedsLegacySolver.Price memory)\r\n    {\r\n        uint256 _queryId = lastValidQueryId(witOracle, feedId);\r\n        if (_queryId != 0) {\r\n            Witnet.DataResult memory _lastValidResult = witOracle.getQueryResult(_queryId);\r\n            return IWitPriceFeedsLegacySolver.Price({\r\n                value: _lastValidResult.fetchUint(),\r\n                timestamp: _lastValidResult.timestamp,\r\n                drTxHash: _lastValidResult.drTxHash,\r\n                latestStatus: _intoLatestUpdateStatus(latestUpdateQueryResultStatus(witOracle, feedId))\r\n            });\r\n        \r\n        } else {\r\n            address _solver = seekRecord(feedId).solver;\r\n            if (_solver != address(0)) {\r\n                // solhint-disable-next-line avoid-low-level-calls\r\n                (bool _success, bytes memory _result) = address(this).staticcall(abi.encodeWithSelector(\r\n                    IWitPriceFeedsLegacySolver.solve.selector,\r\n                    feedId\r\n                ));\r\n                if (!_success) {\r\n                    assembly {\r\n                        _result := add(_result, 4)\r\n                    }\r\n                    revert(string(abi.decode(_result, (string))));\r\n                } else {\r\n                    return abi.decode(_result, (IWitPriceFeedsLegacySolver.Price));\r\n                }\r\n            } else {\r\n                return IWitPriceFeedsLegacySolver.Price({\r\n                    value: 0,\r\n                    timestamp: Witnet.Timestamp.wrap(0),\r\n                    drTxHash: Witnet.TransactionHash.wrap(0),\r\n                    latestStatus: _intoLatestUpdateStatus(latestUpdateQueryResultStatus(witOracle, feedId))\r\n                });\r\n            }\r\n        }\r\n    }\r\n\r\n    function requestUpdate(\r\n            IWitOracleQueriable witOracle, \r\n            bytes4 feedId, \r\n            Witnet.QuerySLA memory querySLA,\r\n            uint256 evmUpdateRequestFee\r\n        )\r\n        public\r\n        returns (\r\n            uint256 _latestQueryId,\r\n            uint256 _evmUsedFunds\r\n        )\r\n    {\r\n        Record storage __feed = seekRecord(feedId);\r\n        _latestQueryId = __feed.latestUpdateQueryId;\r\n        \r\n        Witnet.ResultStatus _latestStatus = latestUpdateQueryResultStatus(witOracle, feedId);   \r\n        if (_latestStatus.keepWaiting()) {\r\n            uint72 _evmUpdateRequestCurrentFee = Witnet.QueryEvmReward.unwrap(\r\n                witOracle.getQueryEvmReward(_latestQueryId)\r\n            );\r\n            if (evmUpdateRequestFee > _evmUpdateRequestCurrentFee) {\r\n                // latest update is still pending, so just increase the reward\r\n                // accordingly to current tx gasprice:\r\n                _evmUsedFunds = (evmUpdateRequestFee - _evmUpdateRequestCurrentFee);\r\n                witOracle.upgradeQueryEvmReward{\r\n                    value: _evmUsedFunds\r\n                }(\r\n                    _latestQueryId\r\n                );\r\n            \r\n            } else {\r\n                _evmUsedFunds = 0;\r\n            }\r\n        \r\n        } else {\r\n            // Check if latest update ended successfully:\r\n            if (_latestStatus == Witnet.ResultStatus.NoErrors) {\r\n                // If so, remove previous last valid query from the WRB:\r\n                if (__feed.lastValidQueryId != 0) {\r\n                    try witOracle.deleteQuery(__feed.lastValidQueryId) returns (Witnet.QueryEvmReward _unusedReward) {\r\n                        evmUpdateRequestFee += Witnet.QueryEvmReward.unwrap(_unusedReward);\r\n\r\n                    } catch {}\r\n                }\r\n                __feed.lastValidQueryId = _latestQueryId;\r\n            } else {\r\n                // Otherwise, try to delete latest query, as it was faulty\r\n                // and we are about to post a new update request:\r\n                try witOracle.deleteQuery(_latestQueryId) returns (Witnet.QueryEvmReward _unsedReward) {\r\n                    evmUpdateRequestFee += Witnet.QueryEvmReward.unwrap(_unsedReward);\r\n                \r\n                } catch {}\r\n            }\r\n            // Post update request to the WRB:\r\n            _evmUsedFunds = evmUpdateRequestFee;\r\n            _latestQueryId = witOracle.queryData{\r\n                value: _evmUsedFunds\r\n            }(\r\n                Witnet.RadonHash.wrap(__feed.radHash),\r\n                querySLA\r\n            );\r\n            // Update latest query id:\r\n            __feed.latestUpdateQueryId = _latestQueryId;\r\n        }\r\n    }\r\n\r\n    function settleFeedRequest(\r\n            string calldata caption,\r\n            bytes32 radHash\r\n        )\r\n        public\r\n    {\r\n        bytes4 feedId = hash(caption);\r\n        Record storage __record = seekRecord(feedId);\r\n        if (__record.index == 0) {\r\n            // settle new feed:\r\n            __record.caption = caption;\r\n            __record.decimals = validateCaption(caption);\r\n            __record.index = data().ids.length + 1;\r\n            __record.radHash = radHash;\r\n            data().ids.push(feedId);\r\n        } else if (__record.radHash != radHash) {\r\n            // update radHash on existing feed:\r\n            __record.radHash = radHash;\r\n            __record.solver = address(0);\r\n        }\r\n        emit IWitPriceFeedsLegacyAdmin.WitFeedSettled(caption, feedId, radHash);\r\n    }\r\n\r\n    function settleFeedSolver(\r\n            string calldata caption, \r\n            address solver, \r\n            string[] calldata deps\r\n        )\r\n        public\r\n    {\r\n        bytes4 feedId = hash(caption);        \r\n        Record storage __record = seekRecord(feedId);\r\n        if (__record.index == 0) {\r\n            // settle new feed:\r\n            __record.caption = caption;\r\n            __record.decimals = validateCaption(caption);\r\n            __record.index = data().ids.length + 1;\r\n            __record.solver = solver;\r\n            data().ids.push(feedId);\r\n            \r\n        } else if (__record.solver != solver) {\r\n            // update radHash on existing feed:\r\n            __record.radHash = 0;\r\n            __record.solver = solver;\r\n        }\r\n        // validate solver first-level dependencies\r\n        {\r\n            // solhint-disable-next-line avoid-low-level-calls\r\n            (bool _success, bytes memory _reason) = solver.delegatecall(abi.encodeWithSelector(\r\n                IWitPriceFeedsLegacySolver.validate.selector,\r\n                feedId,\r\n                deps\r\n            ));\r\n            if (!_success) {\r\n                assembly {\r\n                    _reason := add(_reason, 4)\r\n                }\r\n                revert(string(abi.encodePacked(\r\n                    \"solver validation failed: \",\r\n                    string(abi.decode(_reason,(string)))\r\n                )));\r\n            }\r\n        }\r\n        // smoke-test the solver \r\n        {   \r\n            // solhint-disable-next-line avoid-low-level-calls\r\n            (bool _success, bytes memory _reason) = address(this).staticcall(abi.encodeWithSelector(\r\n                IWitPriceFeedsLegacySolver.solve.selector,\r\n                feedId\r\n            ));\r\n            if (!_success) {\r\n                assembly {\r\n                    _reason := add(_reason, 4)\r\n                }\r\n                revert(string(abi.encodePacked(\r\n                    \"smoke-test failed: \",\r\n                    string(abi.decode(_reason,(string)))\r\n                )));\r\n            }\r\n        }\r\n        emit IWitPriceFeedsLegacyAdmin.WitFeedSolverSettled(caption, feedId, solver);\r\n    }\r\n\r\n    function supportedFeeds() public view returns (\r\n            bytes4[] memory _ids,\r\n            string[] memory _captions,\r\n            bytes32[] memory _solvers\r\n        )\r\n    {\r\n        _ids = data().ids;\r\n        _captions = new string[](_ids.length);\r\n        _solvers = new bytes32[](_ids.length);\r\n        for (uint _ix = 0; _ix < _ids.length; _ix ++) {\r\n            Record storage __record = seekRecord(_ids[_ix]);\r\n            _captions[_ix] = __record.caption;\r\n            _solvers[_ix] = (\r\n                address(__record.solver) == address(0) \r\n                    ? __record.radHash \r\n                    : bytes32(bytes20(__record.solver))\r\n            );\r\n        }\r\n    }\r\n\r\n    // --- IWitPriceFeedsLegacySolver public functions -------------------------------------------------------------\r\n\r\n    function deployPriceSolver(\r\n            bytes calldata initcode,\r\n            bytes calldata constructorParams\r\n        )\r\n        public\r\n        returns (address _solver)\r\n    {\r\n        _solver = determinePriceSolverAddress(initcode, constructorParams);\r\n        if (_solver.code.length == 0) {\r\n            bytes memory _bytecode = _completeInitCode(initcode, constructorParams);\r\n            address _createdContract;\r\n            assembly {\r\n                _createdContract := create2(\r\n                    0, \r\n                    add(_bytecode, 0x20),\r\n                    mload(_bytecode), \r\n                    0\r\n                )\r\n            }\r\n            // assert(_solver == _createdContract); // fails on TEN chains\r\n            _solver = _createdContract;\r\n            require(\r\n                IWitPriceFeedsLegacySolver(_solver).specs() == type(IWitPriceFeedsLegacySolver).interfaceId,\r\n                \"uncompliant solver implementation\"\r\n            );\r\n        }\r\n    }\r\n\r\n    function determinePriceSolverAddress(\r\n            bytes calldata initcode,\r\n            bytes calldata constructorParams\r\n        )\r\n        public view\r\n        returns (address)\r\n    {\r\n        return address(\r\n            uint160(uint(keccak256(\r\n                abi.encodePacked(\r\n                    bytes1(0xff),\r\n                    address(this),\r\n                    bytes32(0),\r\n                    keccak256(_completeInitCode(initcode, constructorParams))\r\n                )\r\n            )))\r\n        );\r\n    }\r\n\r\n    function validateCaption(string calldata caption) public pure returns (uint8) {\r\n        Slices.Slice memory _caption = caption.toSlice();\r\n        Slices.Slice memory _delim = string(\"-\").toSlice();\r\n        string[] memory _parts = new string[](_caption.count(_delim) + 1);\r\n        for (uint _ix = 0; _ix < _parts.length; _ix ++) {\r\n            _parts[_ix] = _caption.split(_delim).toString();\r\n        }\r\n        (uint _decimals, bool _success) = Witnet.tryUint(_parts[_parts.length - 1]);\r\n        require(_success, \"bad decimals\");\r\n        return uint8(_decimals);\r\n    }\r\n\r\n    \r\n    // ================================================================================================\r\n    // --- Private functions --------------------------------------------------------------------------\r\n\r\n    function _completeInitCode(bytes calldata initcode, bytes calldata constructorParams)\r\n        private pure\r\n        returns (bytes memory)\r\n    {\r\n        return abi.encodePacked(\r\n            initcode,\r\n            constructorParams\r\n        );\r\n    }\r\n\r\n    function _intoLatestUpdateStatus(Witnet.ResultStatus _resultStatus)\r\n        private pure \r\n        returns (IWitPriceFeedsLegacySolver.LatestUpdateStatus)\r\n    {\r\n        return (_resultStatus.keepWaiting() \r\n            ? IWitPriceFeedsLegacySolver.LatestUpdateStatus.Awaiting\r\n            : (_resultStatus.hasErrors()\r\n                ? IWitPriceFeedsLegacySolver.LatestUpdateStatus.Error\r\n                : IWitPriceFeedsLegacySolver.LatestUpdateStatus.Ready\r\n            )\r\n        );\r\n    }\r\n\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitAppliance.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\nabstract contract IWitAppliance {\r\n\r\n    /// @notice Returns the name of the actual contract implementing the logic of this Witnet appliance.\r\n    function class() virtual public view returns (string memory);\r\n\r\n    /// @notice Returns the ERC-165 id of the minimal functionality expected for this appliance.\r\n    function specs() virtual external view returns (bytes4);\r\n\r\n    function _require(bool _condition, string memory _message) virtual internal view {\r\n        if (!_condition) {\r\n            _revert(_message);\r\n        }\r\n    }\r\n\r\n    function _revert(string memory _message) virtual internal view {\r\n        revert(\r\n            string(abi.encodePacked(\r\n                class(),\r\n                \": \",\r\n                _message\r\n            ))\r\n        );\r\n    }\r\n\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracle.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {IWitOracleRadonRegistry, Witnet} from \"./IWitOracleRadonRegistry.sol\";\r\n\r\ninterface IWitOracle {\r\n\r\n    error InvalidDataReport();\r\n    \r\n    event WitOracleReport(\r\n            address indexed evmOrigin, \r\n            address indexed evmConsumer, \r\n            address evmReporter,\r\n            Witnet.TransactionHash witDrTxHash,\r\n            Witnet.RadonHash queryRadHash,\r\n            Witnet.QuerySLA  queryParams,\r\n            Witnet.Timestamp resultTimestamp,\r\n            bytes resultCborBytes\r\n        );\r\n\r\n    /// @notice Uniquely identifies the WitOracle instance and the chain on which it's deployed.\r\n    function channel() external view returns (bytes4);\r\n\r\n    /// @notice Verify the data report (as provided by Wit/Kermit API) is well-formed and authentic,\r\n    /// returning the parsed Witnet.DataResult if so, or reverting otherwise.\r\n    function parseDataReport(Witnet.DataPushReport calldata report, bytes calldata proof) external view returns (Witnet.DataResult memory);\r\n\r\n    /// @notice Same as `parseDataReport` but on certain implementations it may store roll-up information \r\n    /// that will contribute to reduce the cost of verifying and/or rolling-up future data reports.\r\n    /// Emits `DataReport` if report is authentic. \r\n    function pushDataReport(Witnet.DataPushReport calldata report, bytes calldata proof) external returns (Witnet.DataResult memory);\r\n\r\n    /// @notice Returns the WitOracleRadonRegistry in which Witnet-compliant Radon requests\r\n    /// @notice can be formally verified and forever registered as a away to let smart contracts\r\n    /// and users to track actual data sources and offchain computations applied on data updates\r\n    /// safely reported from the Wit/Oracle blockchain. \r\n    function registry() external view returns (IWitOracleRadonRegistry);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleAppliance.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./IWitAppliance.sol\";\r\n\r\nabstract contract IWitOracleAppliance\r\n    is\r\n        IWitAppliance\r\n{\r\n    /// @notice Returns the WitOracle address that this appliance is bound to.\r\n    function witOracle() virtual external view returns (address);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleConsumer.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IWitOracle.sol\";\r\n\r\ninterface IWitOracleConsumer {\r\n\r\n    /// @notice Accepts a data report from the Wit/oracle blockchain that ought to be\r\n    /// verified by the WitOracle contract pointed out by `witOracle()`. \r\n    /// @dev The referred `witOracle()` contract emits a `IWitOracle.DataReport` for\r\n    /// every `Witnet.DataPushReport` proven to be authentic. \r\n    function pushDataReport(Witnet.DataPushReport calldata report, bytes calldata proof) external;\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleQueriable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleQueriable {\r\n    \r\n    /// @notice Removes all query data from storage. Pays back reward on expired queries.\r\n    /// @dev Fails if the query is not in a final status, or not called from the actual requester.\r\n    /// @param queryId The unique query identifier.\r\n    function deleteQuery(uint256 queryId) external returns (Witnet.QueryEvmReward);\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @param evmGasPrice Expected gas price to pay upon posting the data request.\r\n    function estimateBaseFee(uint256 evmGasPrice) external view returns (uint256);\r\n    \r\n    /// @notice Estimate the minimum reward required for posting a data request with a callback.\r\n    /// @param evmGasPrice Expected gas price to pay upon posting the data request.\r\n    /// @param callbackGas Maximum gas to be spent when reporting the data request result.\r\n    function estimateBaseFeeWithCallback(uint256 evmGasPrice, uint24 callbackGas) external view returns (uint256);\r\n\r\n    /// @notice Estimate the extra reward (i.e. over the base fee) to be paid when posting a new\r\n    /// @notice data query in order to avoid getting provable \"too low incentives\" results from\r\n    /// @notice the Wit/Oracle blockchain. \r\n    /// @dev The extra fee gets calculated in proportion to:\r\n    /// @param evmGasPrice Tentative EVM gas price at the moment the query result is ready.\r\n    /// @param evmWitPrice  Tentative nanoWit price in Wei at the moment the query is solved on the Wit/Oracle blockchain.\r\n    /// @param querySLA The query SLA data security parameters as required for the Wit/Oracle blockchain. \r\n    function estimateExtraFee(uint256 evmGasPrice, uint256 evmWitPrice, Witnet.QuerySLA calldata querySLA) external view returns (uint256);\r\n\r\n    /// @notice Returns next query id to be generated by the Witnet Request Board.\r\n    function getNextQueryId() external view returns (Witnet.QueryId);\r\n\r\n    /// @notice Gets the whole Query data contents, if any, no matter its current status.\r\n    function getQuery(Witnet.QueryId queryId) external view returns (Witnet.Query memory);\r\n\r\n    /// @notice Gets the current EVM reward the reporter can claim, if not done yet.\r\n    function getQueryEvmReward(uint256) external view returns (Witnet.QueryEvmReward);\r\n\r\n    /// @notice Retrieves the RAD hash and SLA parameters of the given query.\r\n    function getQueryRequest(Witnet.QueryId) external view returns (Witnet.QueryRequest memory);\r\n\r\n    /// @notice Retrieves the whole `Witnet.QueryResponse` record referred to a previously posted Witnet Data Request.\r\n    function getQueryResponse(Witnet.QueryId) external view returns (Witnet.QueryResponse memory);\r\n\r\n    function getQueryResult(uint256) external view returns (Witnet.DataResult memory);\r\n    function getQueryResultStatus(uint256) external view returns (Witnet.ResultStatus);\r\n    function getQueryResultStatusDescription(uint256) external view returns (string memory);\r\n    \r\n    /// @notice Gets query's result back tracing trails\r\n    function getQueryResultTrails(uint256) \r\n        external view returns (\r\n            bytes32 queryUUID,\r\n            Witnet.TransactionHash resultDrTxHash,\r\n            Witnet.Timestamp resultTimestamp,\r\n            uint256 resultFinalityBlock\r\n        );\r\n\r\n    /// @notice Gets current status of given query.\r\n    function getQueryStatus(uint256) external view returns (Witnet.QueryStatus);\r\n    function getQueryStatusString(uint256) external view returns (string memory);\r\n    \r\n    /// @notice Get current status of all given query ids.\r\n    function getQueryStatusBatch(uint256[] calldata) external view returns (Witnet.QueryStatus[] memory);\r\n\r\n    /// @notice Request real world data from the Wit/Oracle sidechain. \r\n    /// @notice The paid fee is escrowed as a reward for the reporter that eventually relays back \r\n    /// @notice a valid query result from the Wit/Oracle sidechain.\r\n    /// @notice Query results are CBOR-encoded, and can contain either some     data, or an error.\r\n    /// @dev Reasons to revert:\r\n    /// @dev - the data request's RAD hash was not previously verified into the WitOracleRadonRegistry contract;\r\n    /// @dev - invalid query SLA parameters were provided;\r\n    /// @dev - insufficient value is paid as reward.\r\n    /// @param radonHash The unique hash of the Radon Request to be solved by Wit/Oracle sidechain. \r\n    function queryData(\r\n            Witnet.RadonHash radonHash,\r\n            Witnet.QuerySLA calldata\r\n        )\r\n        external payable returns (uint256);\r\n\r\n    /// @notice Request real world data from the Wit/Oracle sidechain. \r\n    /// @notice The paid fee is escrowed as a reward for the reporter that eventually relays back \r\n    /// @notice a valid query result from the Wit/Oracle sidechain.\r\n    /// @notice The Witnet-provable result will be reported directly to the requesting contract. \r\n    /// @notice Query results are CBOR-encoded, and can contain either some data, or an error.\r\n    /// @dev Reasons to revert:\r\n    /// @dev - the data request's RAD hash was not previously verified into the Radon Registry;\r\n    /// @dev - invalid query SLA parameters were provided;\r\n    /// @dev - insufficient value is paid as reward.\r\n    /// @dev - passed `consumer` is not a contract implementing the IWitOracleQueriableConsumer interface;\r\n    /// @param radonHash The unique hash of the Radon Request to be solved by Wit/Oracle sidechain. \r\n    function queryDataWithCallback(\r\n            Witnet.RadonHash radonHash, \r\n            Witnet.QuerySLA calldata, \r\n            Witnet.QueryCallback calldata\r\n        )\r\n        external payable returns (uint256);\r\n\r\n    /// @notice Increments the reward of a previously posted request by adding the transaction value to it.\r\n    function upgradeQueryEvmReward(uint256) external payable;\r\n}"
      },
      "project/contracts/interfaces/IWitOracleQueriableConsumer.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./IWitOracleQueriable.sol\";\r\n\r\ninterface IWitOracleQueriableConsumer {\r\n\r\n    /// Method to be called from the WitOracle contract as soon as the given Witnet `queryId` gets reported.\r\n    /// @dev It should revert if called from an address different to the WitOracle instance being used by consumer.\r\n    /// @param queryId The unique identifier of the Witnet query being reported.\r\n    /// @param queryResult Abi-encoded Witnet.DataResult containing the CBOR-encoded query's result, and metadata.\r\n    function reportWitOracleQueryResult(\r\n            uint256 queryId,\r\n            bytes calldata queryResult\r\n        ) external;\r\n\r\n    /// @notice Determines if Witnet queries can be reported from given address.\r\n    /// @dev In practice, must only be true on the WitOracle address that's being used by\r\n    /// @dev the WitOracleQueriableConsumer to post queries. \r\n    function reportableFrom(address) external view returns (bool);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleQueriableEvents.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleQueriableEvents {\r\n\r\n    /// Emitted every time a new query containing some verified data request is posted to the WitOracle.\r\n    event WitOracleQuery(\r\n        address indexed evmRequester,\r\n        uint256 evmGasPrice,\r\n        uint256 evmReward,\r\n        Witnet.QueryId queryId, \r\n        Witnet.RadonHash radonHash,\r\n        Witnet.QuerySLA radonParams\r\n    );\r\n\r\n    /// Emitted when the reward of some not-yet reported query gets upgraded.\r\n    event WitOracleQueryUpgrade(\r\n        Witnet.QueryId queryId,\r\n        address evmSender,\r\n        uint256 evmGasPrice,\r\n        uint256 evmReward\r\n    );\r\n\r\n\r\n    /// Emitted when a query with no callback gets reported into the WRB.\r\n    event WitOracleQueryReport(\r\n        Witnet.QueryId queryId, \r\n        uint256 evmGasPrice\r\n    );\r\n\r\n    event WitOracleQueryReportDispute(\r\n        Witnet.QueryId queryId,\r\n        address evmDisputer\r\n    );\r\n\r\n    /// Emitted when a query with a callback gets successfully reported into the WRB.\r\n    event WitOracleQueryReportDelivery(\r\n        Witnet.QueryId queryId, \r\n        address evmConsumer,\r\n        uint256 evmGasPrice, \r\n        uint256 evmCallbackGas\r\n    );\r\n\r\n    /// Emitted when a query with a callback cannot get reported into the WRB.\r\n    event WitOracleResportDeliveryFailed(\r\n        Witnet.QueryId queryId, \r\n        address evmConsumer,\r\n        uint256 evmGasPrice, \r\n        uint256 evmCallbackActualGas, \r\n        string  evmCallbackRevertReason,\r\n        bytes   resultCborBytes\r\n    );\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleQueriableExperimental.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleQueriableExperimental {\r\n    \r\n    event WitOracleServiceCommittee(\r\n        address indexed evmSubscriber,\r\n        bytes32 indexed witRadHash,\r\n        Witnet.ServiceProvider[] witServiceCommittee\r\n    );\r\n\r\n    /// @notice Enables data requesters to settle the actual validators in the Wit/Oracle\r\n    /// @notice sidechain that will be entitled to solve data requests requiring to\r\n    /// @notice support the specified Radon Request hash (i.e. RAD hash).\r\n    function settleMyOwnServiceCommittee(bytes32 radHash, Witnet.ServiceProvider[] calldata) external;\r\n\r\n    /// Structure containing extra query params for Delegated Data Requests and optional Service Committees\r\n    struct QueryParams {\r\n        uint16 witResultMaxSize;\r\n        uint16 witCommitteeSize;\r\n        uint64 witUnitaryReward;\r\n        Witnet.ServiceProvider[] providers;\r\n    }\r\n\r\n    /// Delegated Data Requests\r\n    struct DDR {\r\n        Witnet.QueryId queryId;\r\n        Witnet.QueryUUID queryUUID;\r\n        Witnet.QueryEvmReward queryEvmReward;\r\n        QueryParams queryParams;\r\n        bytes radonBytecode;\r\n    }\r\n\r\n    function extractDelegatedDataRequest(Witnet.QueryId queryId) external view returns (DDR memory);\r\n    function extractDelegatedDataRequestBatch(Witnet.QueryId[] calldata queryIds) external view returns (DDR[] memory);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleQueriableTrustableReporter.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\n/// @title The Witnet Request Board Reporter interface.\r\n/// @author The Witnet Foundation.\r\ninterface IWitOracleQueriableTrustableReporter {\r\n\r\n    /// @notice Estimates the actual earnings in WEI, that a reporter would get by reporting result to given query,\r\n    /// @notice based on the gas price of the calling transaction. Data requesters should consider upgrading the reward on \r\n    /// @notice queries providing no actual earnings.\r\n    function estimateReportEarnings(\r\n            uint256[] calldata queryIds, \r\n            bytes calldata evmReportTxMsgData,\r\n            uint256 evmReportTxGasPrice,\r\n            uint256 witEthPrice9\r\n        ) external view returns (uint256 evmRevenues, uint256 evmExpenses);\r\n\r\n    /// @notice Retrieves the Witnet Data Request bytecodes of previously posted queries.\r\n    /// @dev Returns empty buffer if the query does not exist.\r\n    /// @param queryIds Query identifiers.\r\n    function extractRadonBytecodes(Witnet.QueryId[] calldata queryIds) \r\n        external view returns (bytes[] memory drBytecodes);\r\n\r\n    /// @notice Reports the Witnet-provided result to a previously posted request. \r\n    /// @dev Will assume `block.timestamp` as the timestamp at which the request was solved.\r\n    /// @dev Fails if:\r\n    /// @dev - the `_queryId` is not in 'Posted' status.\r\n    /// @dev - provided `_tallyHash` is zero;\r\n    /// @dev - length of provided `_result` is zero.\r\n    /// @param queryId The unique identifier of the data request.\r\n    /// @param witDrTxHash The hash of the corresponding data request transaction in Witnet.\r\n    /// @param resultCborBytes The result itself as bytes.\r\n    function reportResult(\r\n            Witnet.QueryId queryId,\r\n            Witnet.TransactionHash witDrTxHash,\r\n            bytes calldata resultCborBytes\r\n        ) external returns (uint256);\r\n\r\n    /// @notice Reports the Witnet-provided result to a previously posted request.\r\n    /// @dev Fails if:\r\n    /// @dev - called from unauthorized address;\r\n    /// @dev - the `_queryId` is not in 'Posted' status.\r\n    /// @dev - provided `_tallyHash` is zero;\r\n    /// @dev - length of provided `_result` is zero.\r\n    /// @param queryId The unique query identifier\r\n    /// @param resultTimestamp The timestamp of the solving tally transaction in Witnet.\r\n    /// @param witDrTxHash The hash of the corresponding data request transaction in Witnet.\r\n    /// @param resultCborBytes The result itself as bytes.\r\n    function reportResult(\r\n            Witnet.QueryId queryId,\r\n            Witnet.Timestamp resultTimestamp,\r\n            Witnet.TransactionHash witDrTxHash,\r\n            bytes calldata resultCborBytes\r\n        ) external returns (uint256);\r\n\r\n    /// @notice Reports Witnet-provided results to multiple requests within a single EVM tx.\r\n    /// @notice Emits either a WitOracleQueryReport* or a BatchReportError event per batched report.\r\n    /// @dev Fails only if called from unauthorized address.\r\n    /// @param _batchResults Array of BatchResult structs, every one containing:\r\n    ///         - unique query identifier;\r\n    ///         - timestamp of the solving tally txs in Witnet. If zero is provided, EVM-timestamp will be used instead;\r\n    ///         - hash of the corresponding data request tx at the Witnet side-chain level;\r\n    ///         - data request result in raw bytes.\r\n    function reportResultBatch(BatchResult[] calldata _batchResults) external returns (uint256);\r\n        \r\n        struct BatchResult {\r\n            Witnet.QueryId queryId;\r\n            Witnet.Timestamp resultTimestamp;\r\n            Witnet.TransactionHash drTxHash;\r\n            bytes resultCborBytes;\r\n        }\r\n\r\n        event BatchReportError(uint256 queryId, string reason);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleQueriableTrustlessReporter.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\n/// @title The Witnet Request Board Reporter trustless interface.\r\n/// @author The Witnet Foundation.\r\ninterface IWitOracleQueriableTrustlessReporter {\r\n    \r\n    event BatchQueryError(Witnet.QueryId queryId, string reason);    \r\n    \r\n    function claimQueryReward(Witnet.QueryId queryId) external returns (uint256);\r\n    function claimQueryRewardBatch(Witnet.QueryId[] calldata queryIds) external returns (uint256);\r\n    \r\n    function disputeQueryResponse (Witnet.QueryId queryId) external returns (uint256);\r\n\r\n    function reportQueryResponse(Witnet.DataPullReport calldata report) external returns (uint256);\r\n    function reportQueryResponseBatch(Witnet.DataPullReport[] calldata reports) external returns (uint256);\r\n    \r\n    function rollupQueryResponseProof(\r\n            Witnet.FastForward[] calldata witOracleRollup, \r\n            Witnet.DataPullReport calldata queryResponseReport, \r\n            bytes32[] calldata witOracleDdrTalliesProof\r\n        ) external returns (\r\n            uint256 evmTotalReward\r\n        );    \r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleRadonRegistry.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleRadonRegistry {\r\n\r\n    /// @notice Returns the Witnet-compliant DRO bytecode for some data request object \r\n    /// made out of the given Radon Request and Radon SLA security parameters. \r\n    function bytecodeOf(\r\n            Witnet.RadonHash radonRequestHash, \r\n            Witnet.QuerySLA calldata queryParams\r\n        ) external view returns (bytes memory);\r\n    \r\n    /// @notice Returns the Witnet-compliant DRO bytecode for some data request object \r\n    /// made out of the given RAD bytecode and Radon SLA security parameters. \r\n    function bytecodeOf(\r\n            bytes calldata radonRequestBytecode, \r\n            Witnet.QuerySLA calldata queryParams\r\n        ) external view returns (bytes memory);\r\n\r\n    /// @notice Returns the hash of the given Witnet-compliant bytecode. Returned value\r\n    /// can be used to trace back in the Witnet blockchain all past resolutions \r\n    /// of the given data request payload.\r\n    function hashOf(bytes calldata) external view returns (Witnet.RadonHash);\r\n\r\n    /// @notice Tells whether the specified Radon Reducer has been formally verified into the registry.\r\n    function isVerifiedRadonReducer(bytes32) external view returns (bool);\r\n    \r\n    /// @notice Tells whether the given Radon Hash has been formally verified into the registry.\r\n    function isVerifiedRadonRequest(Witnet.RadonHash) external view returns (bool);\r\n    \r\n    /// @notice Tells whether the specified Radon Retrieval has been formally verified into the registry.\r\n    function isVerifiedRadonRetrieval(bytes32) external view returns (bool);\r\n    \r\n    /// @notice Returns the whole Witnet.RadonReducer metadata struct for the given hash.\r\n    /// @dev Reverts if unknown.\r\n    function lookupRadonReducer(bytes32 hash) external view returns (Witnet.RadonReducer memory);\r\n\r\n    // /// @notice Returns the whole Witnet.RadonRequest metadata struct for the given RAD hash value. \r\n    // /// @dev Reverts if unknown.\r\n    // function lookupRadonRequest(Witnet.RadonHash radonRequestHash) external view returns (Witnet.RadonRequest memory);\r\n\r\n    /// @notice Returns the Witnet-compliant RAD bytecode for some Radon Request \r\n    /// identified by its unique RAD hash. \r\n    function lookupRadonRequestBytecode(Witnet.RadonHash radonRequestHash) external view returns (bytes memory);\r\n\r\n    /// @notice Returns the Tally reducer that is applied to aggregated values revealed by the witnessing nodes on the \r\n    /// Witnet blockchain. \r\n    /// @dev Reverts if unknown.\r\n    function lookupRadonRequestCrowdAttestationTally(Witnet.RadonHash radonRequestHash) external view returns (Witnet.RadonReducer memory);\r\n    \r\n    /// @notice Returns the deterministic data type returned by successful resolutions of the given Radon Request. \r\n    /// @dev Reverts if unknown.\r\n    function lookupRadonRequestResultDataType(Witnet.RadonHash radonRequestHash) external view returns (Witnet.RadonDataTypes);\r\n\r\n    /// @notice Returns introspective metadata for the index-th data source of some pre-verified Radon Request. \r\n    /// @dev Reverts if out of range.\r\n    // function lookupRadonRequestRetrievalByIndex(Witnet.RadonHash radonRequestHash, uint256 index) external view returns (Witnet.RadonRetrieval memory);\r\n\r\n    /// @notice Returns an array (one or more items) containing the introspective metadata of the given Radon Request's \r\n    /// data sources (i.e. Radon Retrievals). \r\n    /// @dev Reverts if unknown.\r\n    function lookupRadonRequestRetrievals(Witnet.RadonHash radonRequestHash) external view returns (Witnet.RadonRetrieval[] memory);\r\n\r\n    /// @notice Returns the Aggregate reducer that is applied to the data extracted from the data sources \r\n    /// (i.e. Radon Retrievals) whenever the given Radon Request gets solved on the Witnet blockchain. \r\n    /// @dev Reverts if unknown.\r\n    function lookupRadonRequestRetrievalsAggregator(Witnet.RadonHash radonRequestHash) external view returns (Witnet.RadonReducer memory);\r\n\r\n    function lookupRadonRequestRetrievalsCount(Witnet.RadonHash radonRequestHash) external view returns (uint8);\r\n\r\n    /// @notice Returns introspective metadata of some previously verified Radon Retrieval (i.e. public data source). \r\n    ///@dev Reverts if unknown.\r\n    function lookupRadonRetrieval(bytes32 hash) external view returns (Witnet.RadonRetrieval memory);\r\n    \r\n    /// @notice Returns the number of indexed parameters required to be fulfilled when \r\n    /// eventually using the given Radon Retrieval. \r\n    /// @dev Reverts if unknown.\r\n    function lookupRadonRetrievalArgsCount(bytes32 hash) external view returns (uint8);\r\n\r\n    /// @notice Returns the type of the data that would be retrieved by the given Radon Retrieval \r\n    /// (i.e. public data source). \r\n    /// @dev Reverts if unknown.\r\n    function lookupRadonRetrievalResultDataType(bytes32 hash) external view returns (Witnet.RadonDataTypes);\r\n\r\n    /// @notice Verifies and registers the given sequence of dataset filters and reducing function to be \r\n    /// potentially used as either Aggregate or Tally reducers within the resolution workflow\r\n    /// of Radon Requests in the Wit/Oracle blockchain. Returns a unique hash that identifies the \r\n    /// given Radon Reducer in the registry. \r\n    /// @dev Reverts if unsupported reducing or filtering methods are specified.\r\n    function verifyRadonReducer(Witnet.RadonReducer calldata reducer) external returns (bytes32 hash);\r\n    \r\n    /// @notice Verifies and registers the specified Radon Request out of the given data sources (i.e. retrievals)\r\n    /// and the aggregate and tally Radon Reducers. Returns a unique RAD hash that identifies the \r\n    /// verified Radon Request. \r\n    /// @dev Reverts if:\r\n    /// - unverified retrievals are passed;\r\n    /// - retrievals return different data types;\r\n    /// - any of passed retrievals is parameterized;\r\n    /// - unsupported reducers are passed.\r\n    function verifyRadonRequest(\r\n            bytes32[] calldata radonRetrieveHashes,\r\n            Witnet.RadonReducer calldata dataSourcesAggregator,\r\n            Witnet.RadonReducer calldata crowsAttestationTally\r\n        ) external returns (Witnet.RadonHash radonRequestHash);\r\n\r\n    /// @notice Verifies and registers the specified Radon Request out of the given data sources (i.e. retrievals), \r\n    /// data sources parameters (if required), and some pre-verified aggregate and tally Radon Reducers. \r\n    /// Returns a unique RAD hash that identifies the verified Radon Request.\r\n    /// @dev Reverts if:\r\n    /// - unverified retrievals are passed;\r\n    /// - retrievals return different data types;\r\n    /// - ranks of passed args don't match with those required by each given retrieval;\r\n    /// - unverified reducers are passed.\r\n    function verifyRadonRequest(\r\n            bytes32[] calldata retrieveHashes,\r\n            bytes32 aggregateReducerHash,\r\n            bytes32 tallyReducerHash\r\n        ) external returns (Witnet.RadonHash radonRequestHash);\r\n\r\n    /// @notice Verifies and registers the specified Radon Request out of the given data sources (i.e. retrievals), \r\n    /// data sources parameters (if required), and the aggregate and tally Radon Reducers. Returns a unique \r\n    /// RAD hash that identifies the verified Radon Request.\r\n    /// @dev Reverts if:\r\n    /// - unverified retrievals are passed;\r\n    /// - retrievals return different data types;\r\n    /// - ranks of passed args don't match with those required by each given retrieval;\r\n    /// - unsupported reducers are passed.\r\n    function verifyRadonRequest(\r\n            bytes32[] calldata radonRetrieveHashes,\r\n            string[][] calldata radonRetrieveArgs,\r\n            Witnet.RadonReducer calldata dataSourcesAggregator,\r\n            Witnet.RadonReducer calldata crowdAttestationTally\r\n        ) external returns (Witnet.RadonHash radonRequestHash);\r\n\r\n    /// @notice Verifies and registers the specified Radon Request out of a single modal retrieval where first \r\n    /// parameter corresponds to data provider's URL, an array of data providers (i.e. URLs), and an array\r\n    /// of parmeter values common to all data providers. Some pre-verified aggregate and tally Radon Reducers\r\n    /// must also be provided. Returns a unique RAD hash that identifies the verified Radon Request.\r\n    /// @dev Reverts if:\r\n    /// - unverified retrieval is passed;\r\n    /// - ranks of passed args don't match with those expected by given retrieval, after replacing the data provider URL.\r\n    /// - unverified reducers are passed.\r\n    function verifyRadonRequest(\r\n            bytes32[] calldata radonRetrieveHashes,\r\n            string[][] calldata radonRetrieveArgs,\r\n            bytes32 dataSourcesAggregatorHash,\r\n            bytes32 crowdAttestationTallyHash\r\n        ) external returns (Witnet.RadonHash radonRequestHash);\r\n\r\n    function verifyRadonRequest(\r\n            bytes32 commonRetrieveHash,\r\n            string[] calldata commonRetrieveArgs,\r\n            string[] calldata dataProviders,\r\n            bytes32 dataSourcesAggregatorHash,\r\n            bytes32 crowdAttestationTallyHash\r\n        ) external returns (Witnet.RadonHash radonRequestHash);\r\n\r\n    /// @notice Verifies and registers the specified Radon Retrieval (i.e. public data source) into this registry contract. \r\n    /// Returns a unique retrieval hash that identifies the verified Radon Retrieval.\r\n    /// All parameters but the retrieval method are parameterizable by using embedded wildcard \\x\\ substrings (with x='0'..'9').\r\n    /// @dev Reverts if:\r\n    /// - unsupported retrieval method is given;\r\n    /// - no URL is provided Http/* requests;\r\n    /// - non-empty strings given on RNG reqs.\r\n    function verifyRadonRetrieval(\r\n            Witnet.RadonRetrievalMethods requestMethod,\r\n            string calldata requestURL,\r\n            string calldata requestBody,\r\n            string[2][] calldata requestHeaders,\r\n            bytes calldata requestRadonScript\r\n        ) external returns (bytes32 hash);\r\n\r\n//     /// Verifies a new Radon Retrieval by specifying the value to the highest indexed parameter of an already existing one.\r\n//     /// Returns the unique hash that identifies the resulting Radon Retrieval.\r\n//     /// Reverts if an unverified retrieval hash is passed.\r\n//     function verifyRadonRetrieval(\r\n//             bytes32 retrieveHash,\r\n//             string calldata lastArgValue\r\n//         ) external returns (bytes32 hash);\r\n// }\r\n}"
      },
      "project/contracts/interfaces/IWitOracleRadonRegistryEvents.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleRadonRegistryEvents {\r\n\r\n    /// Emitted every time a new Radon Reducer gets successfully verified and\r\n    /// stored into the WitOracleRadonRegistry.\r\n    event NewRadonReducer(bytes32 hash);\r\n\r\n    /// Emitted every time a new Radon Retrieval gets successfully verified and\r\n    /// stored into the WitOracleRadonRegistry.\r\n    event NewRadonRetrieval(bytes32 hash);\r\n\r\n    /// Emitted every time a new Radon Request gets successfully verified and\r\n    /// stored into the WitOracleRadonRegistry.\r\n    event NewRadonRequest(Witnet.RadonHash radonHash);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleRadonRequestFactory.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IWitOracleRadonRequestModal.sol\";\r\nimport \"./IWitOracleRadonRequestTemplate.sol\";\r\n\r\ninterface IWitOracleRadonRequestFactory {\r\n\r\n    event NewRadonRequestModal(address witOracleRadonRequestModal);\r\n    event NewRadonRequestTemplate(address witOracleRadonRequestTemplate);\r\n\r\n    struct DataSource {\r\n        string url;\r\n        DataSourceRequest request;\r\n    }\r\n\r\n    struct DataSourceRequest {\r\n        Witnet.RadonRetrievalMethods method;\r\n        string body;\r\n        string[2][] headers;\r\n        bytes script;\r\n    }\r\n\r\n    function buildRadonRequestModal(\r\n            DataSourceRequest calldata commonDataRequest,\r\n            Witnet.RadonReducer calldata crowdAttestationTally\r\n        )\r\n        external returns (IWitOracleRadonRequestModal);\r\n\r\n    function buildRadonRequestTemplate(\r\n            bytes32[] calldata dataRetrieveHashes,\r\n            Witnet.RadonReducer calldata dataSourcesAggregator,\r\n            Witnet.RadonReducer calldata crowdAttestationTally\r\n        ) external returns (IWitOracleRadonRequestTemplate);\r\n        \r\n    function buildRadonRequestTemplate(\r\n            DataSource[] calldata dataSources,\r\n            Witnet.RadonReducer calldata dataSourcesAggregator,\r\n            Witnet.RadonReducer calldata crowdAttestationTally\r\n        )\r\n        external returns (IWitOracleRadonRequestTemplate);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleRadonRequestModal.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleRadonRequestModal {\r\n\r\n    function getCrowdAttestationTally() external view returns (Witnet.RadonReducer memory);\r\n    function getDataResultType() external view returns (Witnet.RadonDataTypes); \r\n    function getDataSourceArgsCount(string calldata url) external view returns (uint8);\r\n    function getDataSourcesAggregator() external view returns (Witnet.RadonReducer memory);\r\n    \r\n    function getRadonModalRetrieval() external view returns (Witnet.RadonRetrieval memory);\r\n\r\n    function verifyRadonRequest(string[] calldata commonRetrievalArgs, string[] calldata dataProviders) external returns (Witnet.RadonHash);\r\n    function witOracle() external view returns (address);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleRadonRequestTemplate.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleRadonRequestTemplate {\r\n\r\n    function getArgsCount() external view returns (uint8[] memory);\r\n    function getCrowdAttestationTally() external view returns (Witnet.RadonReducer memory);\r\n    function getDataResultType() external view returns (Witnet.RadonDataTypes); \r\n    function getDataSources() external view returns (Witnet.RadonRetrieval[] memory);\r\n    function getDataSourcesAggregator() external view returns (Witnet.RadonReducer memory);\r\n    \r\n    /// Verifies into the bounded WitOracle's registry the actual bytecode \r\n    /// and RAD hash of the Witnet-compliant Radon Request that gets provably \r\n    /// made out of the data sources, aggregate and tally Radon Reducers that \r\n    /// compose this WitOracleRequestTemplate. While no WitOracleRequest instance is \r\n    /// actually constructed, the returned value will be accepted as a valid\r\n    /// RAD hash on the witOracle() contract from now on. \r\n    /// Reverts if:\r\n    /// - the ranks of passed array don't match either the number of this \r\n    ///   template's data sources, or the number of required parameters by \r\n    ///   each one of those.\r\n    /// @dev This method requires less gas than buildWitOracleRequest(string[][]), and \r\n    /// @dev it's usually preferred when data requests built out of this template\r\n    /// @dev are intended to be used just once in lifetime.    \r\n    function verifyRadonRequest(string[][] calldata args) external returns (Witnet.RadonHash);\r\n\r\n    function witOracle() external view returns (address);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleTrustableAdmin.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\n/// @title Witnet Request Board ACLs administration interface.\r\n/// @author The Witnet Foundation.\r\ninterface IWitOracleTrustableAdmin {\r\n    \r\n    event ReportersSet(address[] reporters);\r\n    event ReportersUnset(address[] reporters);\r\n\r\n    /// Tells whether given address is included in the active reporters control list.\r\n    function isReporter(address) external view returns (bool);\r\n\r\n    /// Adds given addresses to the active reporters control list.\r\n    /// @dev Can only be called from the owner address.\r\n    /// @dev Emits the `ReportersSet` event. \r\n    function setReporters(address[] calldata reporters) external;\r\n\r\n    /// Removes given addresses from the active reporters control list.\r\n    /// @dev Can only be called from the owner address.\r\n    /// @dev Emits the `ReportersUnset` event. \r\n    function unsetReporters(address[] calldata reporters) external;\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitOracleTrustless.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleTrustless {\r\n\r\n    event Rollup(Witnet.Beacon head);\r\n\r\n    function determineBeaconIndexFromTimestamp(Witnet.Timestamp timestamp) external pure returns (uint64);\r\n    function determineEpochFromTimestamp(Witnet.Timestamp timestamp) external pure returns (Witnet.BlockNumber);\r\n\r\n    function getBeaconByIndex(uint32 index) external view returns (Witnet.Beacon memory);\r\n    function getGenesisBeacon() external pure returns (Witnet.Beacon memory);\r\n    function getLastKnownBeacon() external view returns (Witnet.Beacon memory);\r\n    function getLastKnownBeaconIndex() external view returns (uint32);\r\n\r\n    function rollupBeacons(Witnet.FastForward[] calldata ff) external returns (Witnet.Beacon memory);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitPriceFeeds.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {IWitPriceFeedsAdmin} from \"./IWitPriceFeedsAdmin.sol\";\r\nimport {IWitPriceFeedsConsumer} from \"./IWitPriceFeedsConsumer.sol\";\r\nimport {IWitPriceFeedsEvents} from \"./IWitPriceFeedsEvents.sol\";\r\nimport {IWitPriceFeedsTypes} from \"./IWitPriceFeedsTypes.sol\";\r\nimport {IWitPyth} from \"./legacy/IWitPyth.sol\";\r\n\r\ninterface IWitPriceFeeds\r\n    is\r\n        IWitPriceFeedsAdmin,\r\n        IWitPriceFeedsEvents, \r\n        IWitPriceFeedsTypes,\r\n        IWitPyth\r\n{\r\n    /// Address of the underlying logic contract.\r\n    function base() external view returns (address);\r\n\r\n    /// Creates a light-proxy clone to the `base()` contract address, to be owned by the specified `curator` address. \r\n    /// Curators of cloned contracts can optionally settle one single `IWitPriceFeedConsumer` consuming contract. \r\n    /// The consuming contract, if settled, will be immediately reported every time a new Witnet-certified price update\r\n    /// gets pushed into the cloned instance. Either way, price feeds data will be stored in the `WitPriceFeeds` storage. \r\n    /// @param curator Address that will have rights to manage price feeds on the new light-proxy clone.\r\n    function clone(address curator) external returns (address);\r\n\r\n    /// Returns the consumer address where all price updates will be reported to.\r\n    /// @dev If zero, new price updates will not be reported to any other external address.\r\n    /// @dev The consumer contract must implement the `IWitPriceFeedsConsumer` interface, \r\n    /// @dev and accept this instance as source of truth.\r\n    /// @dev It can only be settled by a curator on cloned instances.\r\n    function consumer() external view returns (IWitPriceFeedsConsumer);\r\n\r\n    /// Creates a Chainlink Aggregator proxy to the specified symbol.\r\n    /// @dev Reverts if symbol is not supported.\r\n    function createChainlinkAggregator(string calldata symbol) external returns (address);\r\n\r\n    /// Default update conditions that apply to brand new price feeds.\r\n    function defaultUpdateConditions() external view returns (UpdateConditions calldata);\r\n\r\n    /// Returns a unique hash determined by the combination of data sources being used by \r\n    /// supported non-routed price feeds, and dependencies of all supported routed \r\n    /// price feeds. The footprint changes if any price feed is modified, added, removed \r\n    /// or if the dependency tree of any routed price feed is altered.\r\n    function footprint() external view returns (bytes4);\r\n\r\n    /// Determines unique ID for the specified symbol.\r\n    function hash(string calldata symbol) external pure returns (ID);\r\n\r\n    /// @notice Returns last update price for the specified ID4 price feed.\r\n    /// Note: This function is sanity-checked version of `getPriceUnsafe` which is useful in applications and\r\n    /// smart contracts that require recentl updated price, and no hint of market deviation being currently excessive. \r\n    ///\r\n    /// @dev Reverts if:\r\n    /// - `StalePrice()`: the price feed has not been updated within the last `UpdateConditions.heartbeatSecs`,\r\n    /// - `DeviantPrice()`: a deviation greater than `UpdateConditions.maxDeviation1000` was detected upon last update attempt.\r\n    /// - `InvalidGovernanceTarget()`: no EMA is curretly settled to be computed for this price feed.\r\n    ///\r\n    /// @param id4 Unique ID4 identifier of a price feed supported by this contract.\r\n    function getPrice(ID4 id4) external view returns (Price memory);\r\n    \r\n    /// @notice Returns last updated price if no older than `_age` seconds of the current time.\r\n    /// Note: This function is a sanity-checked version of `getPriceUnsafe` which is useful in applications and\r\n    /// smart contracts that require last known non-deviant price, last updated within specified time range.\r\n    ///\r\n    /// @dev Reverts if:\r\n    /// - `StalePrice()`: the price feed has not been updated within the last `_age` seconds,\r\n    /// - `InvalidGovernanceTarget()`: no EMA is settled to be computed for specified price feed.\r\n    /// \r\n    /// @param id4 Unique ID4 identifier of a price feed supported by this contract.\r\n    /// @param age Maximum age of acceptable price value.\r\n    function getPriceNotOlderThan(ID4 id4, uint24 age) external view returns (Price memory);\r\n\r\n    /// @notice Returns last updated price without any sanity checks.\r\n    /// Note: This function is unsafe as the returned price update may be arbitrarily far in the past.\r\n    /// Users of this function should check the `timestamp` of each price feed to ensure that the returned values \r\n    /// are sufficiently recent for their application. If you need safe access to fresh data, please consider\r\n    /// using calling to either `getPrice` or `getPriceNoOlderThan` variants.\r\n    /// \r\n    /// @dev Reverts if:\r\n    /// - `InvalidGovernanceTarget()`: no EMA is settled to be computed for specified price feed.\r\n    /// \r\n    /// @param id4 Unique ID4 identifier of a price feed supported by this contract.\r\n    function getPriceUnsafe(ID4 id4) external view returns (Price memory);\r\n    \r\n    function lookupPriceFeed(ID4 id4) external view returns (Info memory);\r\n    function lookupPriceFeedCaption(ID4 id4) external view returns (string memory);\r\n    function lookupPriceFeedExponent(ID4 id4) external view returns (int8);\r\n    function lookupPriceFeedID(ID4 id4) external view returns (bytes32);\r\n\r\n    /// @notice Returns last known price updates and deviations for all supported price feeds without any sanity checks.    \r\n    function lookupPriceFeeds() external view returns (Info[] memory);\r\n    \r\n    /// Tells whether there is a price feed settled with the specified caption.\r\n    function supportsCaption(string calldata caption) external view returns (bool);\r\n\r\n    /// The Wit/Oracle core address accepted as source of truth.\r\n    function witOracle() external view returns (address);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitPriceFeedsAdmin.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {IWitPriceFeedsTypes} from \"./IWitPriceFeedsTypes.sol\";\r\nimport {Witnet} from \"../libs/Witnet.sol\";\r\n\r\ninterface IWitPriceFeedsAdmin {\r\n\r\n    function acceptOwnership() external;\r\n    function owner() external view returns (address);\r\n    function pendingOwner() external returns (address);\r\n    function removePriceFeed(string calldata, bool) external returns (bytes4);\r\n    \r\n    function settleConsumer(address) external;\r\n    function settleDefaultUpdateConditions(IWitPriceFeedsTypes.UpdateConditions calldata) external;\r\n    \r\n    function settlePriceFeedMapper(\r\n            string calldata caption, \r\n            int8 exponent, \r\n            IWitPriceFeedsTypes.Mappers mapper, \r\n            string[] calldata deps\r\n        ) external returns (bytes4);\r\n    \r\n    function settlePriceFeedOracle(\r\n            string calldata caption, \r\n            int8 exponent, \r\n            IWitPriceFeedsTypes.Oracles oracle, \r\n            address target, \r\n            bytes32 sources\r\n        ) external returns (bytes4);\r\n    \r\n    function settlePriceFeedRadonBytecode(\r\n            string calldata caption, \r\n            int8 exponent, \r\n            bytes calldata radonBytecode\r\n        ) external returns (bytes4);\r\n\r\n    function settlePriceFeedRadonHash(\r\n            string calldata caption, \r\n            int8 exponent, \r\n            Witnet.RadonHash radonHash\r\n        ) external returns (bytes4);\r\n\r\n    function settlePriceFeedUpdateConditions(\r\n            string calldata caption, \r\n            IWitPriceFeedsTypes.UpdateConditions calldata conditions\r\n        ) external;\r\n\r\n    function transferOwnership(address) external;\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitPriceFeedsConsumer.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport {IWitPriceFeeds} from \"./IWitPriceFeeds.sol\";\r\nimport {IWitPriceFeedsTypes} from \"./IWitPriceFeedsTypes.sol\";\r\nimport {Witnet} from \"../libs/Witnet.sol\";\r\n\r\ninterface IWitPriceFeedsConsumer {\r\n    /// Reports a Witnet-verified price feed update.\r\n    /// @dev It should revert if called from an address other than `witPriceFeeds()`.\r\n    function reportUpdate(\r\n            IWitPriceFeedsTypes.ID4 id4, \r\n            Witnet.Timestamp timestamp,\r\n            Witnet.TransactionHash trail,\r\n            uint64 price, \r\n            int56 deltaPrice,\r\n            uint64 deltaSecs,\r\n            int8 exponent\r\n        ) external;\r\n\r\n    /// Returns the address of the one and only `IWitPriceFeeds` \r\n    /// instance that can provide price feed updates.\r\n    function witPriceFeeds() external view returns (IWitPriceFeeds);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitPriceFeedsEvents.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.17 <0.9.0;\r\n\r\nimport {IWitPriceFeedsTypes, Witnet} from \"./IWitPriceFeedsTypes.sol\";\r\n\r\ninterface IWitPriceFeedsEvents {\r\n    /// Emitted when a new routed price feed gets settled.\r\n    event PriceFeedMapper(\r\n            address indexed from, \r\n            IWitPriceFeedsTypes.ID4 id4, \r\n            string caption, \r\n            int8 exponent, \r\n            IWitPriceFeedsTypes.Mappers mapper,\r\n            string[] dependencies\r\n        );\r\n\r\n    /// Emitted when a new oraclized price feed gets settled.\r\n    event PriceFeedOracle(\r\n            address indexed from, \r\n            IWitPriceFeedsTypes.ID4 id4, \r\n            string caption, \r\n            int8 exponent, \r\n            IWitPriceFeedsTypes.Oracles oracle,\r\n            address oracleAddress,\r\n            bytes32 oracleSources\r\n        );\r\n\r\n    /// Emitted when a price feeds gets removed from the list of supported price feeds.\r\n    event PriceFeedRemoved(\r\n        address indexed from, \r\n        IWitPriceFeedsTypes.ID4 id4, \r\n        string caption\r\n    );\r\n\r\n    event PriceFeedUpdate(\r\n        IWitPriceFeedsTypes.ID4 indexed ID4,\r\n        Witnet.Timestamp timestamp, \r\n        Witnet.TransactionHash trail,\r\n        uint64 price,\r\n        int56 deltaPrice,\r\n        int8 exponent\r\n    );\r\n\r\n    /// Emitted when the update conditions of some existing price feed get altered.\r\n    event PriceFeedUpdateConditions(\r\n        address indexed from, \r\n        IWitPriceFeedsTypes.ID4 id4, \r\n        string caption,\r\n        IWitPriceFeedsTypes.UpdateConditions conditions\r\n    );\r\n}"
      },
      "project/contracts/interfaces/IWitPriceFeedsTypes.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.17 <0.9.0;\r\n\r\nimport {Witnet} from \"../libs/Witnet.sol\";\r\nimport {IWitPyth} from \"./legacy/IWitPyth.sol\";\r\n\r\ninterface IWitPriceFeedsTypes {\r\n\r\n    enum Mappers {\r\n        None,\r\n        Fallback,\r\n        Hottest,\r\n        Product,\r\n        Inverse\r\n    }\r\n\r\n    enum Oracles {\r\n        Witnet,\r\n        ERC2362,\r\n        Chainlink,\r\n        Pyth\r\n    }\r\n\r\n    struct Price {\r\n        int8 exponent;\r\n        uint64 price;\r\n        int56  deltaPrice;\r\n        Witnet.Timestamp timestamp;\r\n        Witnet.TransactionHash trail;\r\n    }\r\n\r\n    struct Info {\r\n        IWitPyth.ID id;\r\n        int8 exponent;\r\n        string symbol;\r\n        Mapper mapper;\r\n        Oracle oracle;\r\n        UpdateConditions updateConditions;\r\n        Price lastUpdate;\r\n    }\r\n\r\n    struct Mapper {\r\n        Mappers class;\r\n        string[] deps;\r\n    }\r\n\r\n    struct Oracle {\r\n        Oracles class;\r\n        address target;\r\n        bytes32 sources;\r\n    }\r\n\r\n    struct UpdateConditions {\r\n        uint24 callbackGas;\r\n        bool   computeEma;\r\n        uint24 cooldownSecs;\r\n        uint24 heartbeatSecs;\r\n        uint16 maxDeviation1000;\r\n        uint16 minWitnesses;\r\n    }\r\n\r\n    type ID4 is bytes4;\r\n}"
      },
      "project/contracts/interfaces/IWitRandomness.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.17 <0.9.0;\r\n\r\nimport {IWitRandomnessAdmin} from \"./IWitRandomnessAdmin.sol\";\r\nimport {IWitRandomnessConsumer} from \"./IWitRandomnessConsumer.sol\";\r\nimport {IWitRandomnessEvents} from \"./IWitRandomnessEvents.sol\";\r\nimport {IWitRandomnessTypes, Witnet} from \"./IWitRandomnessTypes.sol\";\r\n\r\n/// @title The Wit/Randomness V3 appliance interface.\r\n/// @author Witnet Foundation.\r\ninterface IWitRandomness\r\n    is \r\n        IWitRandomnessAdmin,\r\n        IWitRandomnessEvents, \r\n        IWitRandomnessTypes        \r\n{\r\n    /// Address of the underlying logic contract.\r\n    function base() external view returns (address);\r\n\r\n    /// Creates a light-proxy clone to the `base()` logic address, to be owned by the specified `curator`address.\r\n    /// Curators of cloned instances can optionally settle one single `IWitRandomnessConsumer` consuming contract.\r\n    /// The consuming contract, if settled, will be immediately reported every time a new `randomize()` request\r\n    /// gets solved and bridged back from Witnet. Either way, randomness resolutions will be reamin stored in the \r\n    /// `WitRandomness` storage, as for future reference. \r\n    /// @param curator Address that will have authoritative access to `IWitRandomnessAdmin` methods.\r\n    function clone(address curator) external returns (IWitRandomness);\r\n\r\n    /// Returns the consumer address where all valid randomize results will be reported to.\r\n    /// @dev If zero, generated randomness will not be reported to any other external address. \r\n    /// @dev The consumer contract must implement the `IWitRandomnessConsumer` interface, \r\n    /// @dev and accept this instance as source of entropy.\r\n    /// @dev It can only be settled by a curator on cloned instances.\r\n    function consumer() external view returns (IWitRandomnessConsumer);\r\n\r\n    /// Returns amount of wei required to be paid as a fee when requesting randomization with a \r\n    /// transaction gas price as the one given.\r\n    function estimateRandomizeFee(uint256 evmGasPrice) external view returns (uint256);\r\n\r\n    /// Retrieves the result of keccak256-hashing the given block number with the randomness value \r\n    /// generated by the Witnet blockchain in response to the first non-failing randomize request solved \r\n    /// after such block number.\r\n    ///\r\n    /// @dev Reverts if:\r\n    ///    i.   no `randomize()` was queried on neither the given block, nor afterwards.\r\n    ///    ii.  the first non-failing `randomize()` request found on or after the given block is not solved yet.\r\n    ///    iii. all `randomize()` requests that took place on or after the given block were solved with errors.\r\n    ///\r\n    /// @param blockNumber Block number from which the search will start.\r\n    function fetchRandomnessAfter(uint256 blockNumber) external view returns (bytes32);\r\n\r\n    /// Retrieves the actual random value, unique hash and timestamp of the witnessing commit/reveal act \r\n    /// that took place in the Witnet blockchain in response to the first non-failing randomize query\r\n    /// solved after the given block number.\r\n    ///\r\n    /// @dev Reverts if:\r\n    ///    i.   no `randomize()` was queried on neither the given block, nor afterwards.\r\n    ///    ii.  the first non-failing `randomize()` request found on or after the given block is not solved yet.\r\n    ///    iii. all `randomize()` requests that took place on or after the given block were solved with errors.\r\n    ///\r\n    /// @param blockNumber Block number from which the search will start.\r\n    /// @return witnetQueryUUID Universal identifier of the query posted from this contract that ultimately solved randomness.\r\n    /// @return witnetTimestamp Timestamp at which the randomness value was generated by the Witnet blockchain.\r\n    /// @return witnetDrTxHash Hash of the witnessing commit/reveal act that took place on the Witnet blockchain.\r\n    //  @return evmFinalityBlock EVM block number at which the generated randomness can be considered to be final.\r\n    function fetchRandomnessAfterProof(uint256 blockNumber) external view returns (\r\n            bytes32 witnetQueryUUID,\r\n            Witnet.Timestamp witnetTimestamp,\r\n            Witnet.TransactionHash witnetDrTxHash,\r\n            uint256 evmFinalityBlock\r\n        );\r\n    \r\n    /// Returns last block number on which a randomize was queried.\r\n    function getLastRandomizeBlock() external view returns (uint256);\r\n\r\n    /// Retrieves metadata related to the randomize request that got queried to the `WitOracle` contract \r\n    /// on the specified block number, if any.\r\n    ///\r\n    /// @dev Returns zero values if no randomize request was actually queried on the specified block number.\r\n    ///\r\n    /// @param blockNumber Block number from which the search will start.\r\n    /// @return witOracleQueryId Identifier of the underlying Wit/Oracle query created on the specified block (0 if none).\r\n    /// @return prevRandomizeBlock Block number in which a randomize request got queried just before the specified block.\r\n    /// @return nextRandomizeBlock Block number in which a randomize request got queried just after the specified block.\r\n    function getRandomizeData(uint256 blockNumber) external view returns (\r\n            Witnet.QueryId witOracleQueryId,\r\n            uint256 prevRandomizeBlock,\r\n            uint256 nextRandomizeBlock\r\n        );\r\n    \r\n    /// Returns the number of the next block in which a randomize request was posted after the given one. \r\n    /// @param blockNumber Block number from which the search will start.\r\n    /// @return Number of the first block found after the given one, or `0` otherwise.\r\n    function getRandomizeNextBlock(uint256 blockNumber) external view returns (uint256); \r\n\r\n    /// Returns the number of the previous block in which a randomize request was posted before the given one.\r\n    /// @param blockNumber Block number from which the search will start.\r\n    /// @return First block found before the given one, or `0` otherwise.\r\n    function getRandomizePrevBlock(uint256 blockNumber) external view returns (uint256);\r\n\r\n    /// Returns the identifier of the Wit/Oracle query that has either solved randomness\r\n    /// for the specified block number, is currently attending randomness for the specified block number,\r\n    /// of the one that attempted to solve it. \r\n    /// @dev Returns zero if no randomize was request on or after the specified block number.\r\n    function getRandomizeQueryId(uint256 blockNumber) external view returns (Witnet.QueryId);\r\n\r\n    /// Explains why the last attempt of generating randomness for the specified block number failed.\r\n    function getRandomizeQueryErrorDescription(uint256 blockNumber) external view returns (string memory);\r\n\r\n    /// Returns security and liveness parameters required to the Witnet blockchain \r\n    /// when solving randomness requests, if no others are specified.\r\n    /// @return callbackGasLimit Max. expendable gas upon randomness delivery.\r\n    /// @return extraFeePercentage Overhead percentage applied when estimating the randomize request fee. \r\n    /// @return witCommitteeSize Number of Witnet witnessing nodes required to generate unbiased randomness.\r\n    /// @return witInclusionFees Minimum amount of fees in $nanoWIT to be paid on the Witnet blockchain.\r\n    function getRandomizeQueryParams()\r\n        external view returns (\r\n            uint24 callbackGasLimit,\r\n            uint16 extraFeePercentage,\r\n            uint16 witCommitteeSize,\r\n            uint64 witInclusionFees\r\n        );\r\n\r\n    /// Returns the immutable bytecode of the Radon Request that's being used \r\n    /// for solving randomness requests on the Witnet blockchain.\r\n    function getRandomizeRadonBytecode() external view returns (bytes memory);\r\n\r\n    /// Returns the unique identifier of the Radon Request that's being used \r\n    /// for solving request randomness requests on the Witnet blockchain.\r\n    function getRandomizeRadonHash() external view returns (Witnet.RadonHash);\r\n\r\n    /// @notice Returns status of the first non-errored randomize request queried on or after the given block number.\r\n    ///  - 0 -> Void: no randomize request was actually queried on or after the given block number.\r\n    ///  - 1 -> Awaiting: a randomize request was found but it's not yet solved by the Wit/Oracle.\r\n    ///  - 2 -> Ready: a successfull randomize value was reported and is ready to be read.\r\n    ///  - 3 -> Error: all attempted randomize requests at or after the given block were solved with errors.\r\n    ///  - 4 -> Finalizing: a randomize result was relayed already but cannot yet be considered to be final.\r\n    function getRandomizeStatus(uint256 blockNumber) external view returns (RandomizeStatus);    \r\n\r\n    /// Return the number of EVM blocks after a randomize requests that have to elapse before\r\n    /// considering such request to be delayed. Results to delayed requests can potentially be\r\n    /// provided by later requests, if solved earlier. A value of zero means that randomize \r\n    /// requests will never expire. \r\n    function getRandomizeWaitingBlocks() external view returns (uint16);\r\n\r\n    /// Returns `true` only if a successfull resolution from the Witnet blockchain is found for the \r\n    /// first non-failing randomize request posted on or after the given block number.\r\n    function isRandomized(uint256 blockNumber) external view returns (bool);\r\n\r\n    /// @notice Requests the Witnet blockchain to generate an unbiased 256-bit random seed.\r\n    /// @dev Only one randomize request per block will get ultimately relayed to the Witnet blockchain.\r\n    /// @return EVM funds actually paid as randomize fee.\r\n    function randomize() external payable returns (uint256);\r\n\r\n    /// Verifies that the specified randomness seed was actually generated on the Witnet blockchain\r\n    /// and used for producing the randomness value returned by `fetchRandomnessAfter(blockNumber)`.\r\n    function verifyRandomnessAfter(uint256 blockNumber, bytes32 witnetRandomness) external view returns (bool);\r\n\r\n    /// The Wit/Oracle core address accepted as source of entropy.\r\n    function witOracle() external view returns (address);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitRandomnessAdmin.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\ninterface IWitRandomnessAdmin {\r\n    function acceptOwnership() external;\r\n    function owner() external view returns (address);\r\n    function pendingOwner() external returns (address);\r\n    function settleConsumer(address consumer, uint24 maxCallbackGasLimit) external;\r\n    function settleQueryParams(\r\n            uint24 callbackGasLimit,\r\n            uint16 extraFeePercentage, \r\n            uint16 minWitnesses, \r\n            uint64 minInclusionFees\r\n        ) external;\r\n    function settleRandomizeWaitingBlocks(uint16) external;\r\n    function transferOwnership(address) external;\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitRandomnessConsumer.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport {IWitRandomness} from \"./IWitRandomness.sol\";\r\nimport {Witnet} from \"../libs/Witnet.sol\";\r\n\r\ninterface IWitRandomnessConsumer {\r\n    /// Reports some Witnet-certified randomness. \r\n    /// @dev It should revert if called from an address other than `witRandomness()`.\r\n    /// @dev Randomness metadata is stored in the `witRandomness()` address, indexed by `evmRandomizeBlock`.\r\n    function reportRandomness(\r\n            bytes32 randomness, \r\n            uint256 evmRandomizeBlock,\r\n            uint256 evmFinalityBlock,\r\n            Witnet.Timestamp witnetTimestamp,\r\n            Witnet.TransactionHash witnetDrTxHash\r\n        ) external;\r\n\r\n    /// Returns the address of the one and only `IWitRandomness` instance that can provide Witnet-certified randomness.\r\n    function witRandomness() external view returns (IWitRandomness);\r\n}\r\n"
      },
      "project/contracts/interfaces/IWitRandomnessEvents.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.17 <0.9.0;\r\n\r\nimport {Witnet} from \"../libs/Witnet.sol\";\r\n\r\ninterface IWitRandomnessEvents {\r\n    /// Emitted when a new randomize request gets posted to the Wit/Oracle framework.\r\n    event Randomizing(\r\n        address indexed evmRequester,\r\n        uint256 randomizeBlock, \r\n        Witnet.QueryId witOracleQueryId\r\n    );\r\n\r\n    /// Emitted when some requested randomness gets delivered from Witnet.\r\n    event Randomized(\r\n        uint256 randomizeBlock,\r\n        uint256 finalityBlock,\r\n        bytes32 randomness\r\n    );   \r\n}\r\n"
      },
      "project/contracts/interfaces/IWitRandomnessTypes.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.17 <0.9.0;\r\n\r\nimport {Witnet} from \"../libs/Witnet.sol\";\r\n\r\ninterface IWitRandomnessTypes {\r\n    /// Randomization status for some specified block number.\r\n    enum RandomizeStatus {\r\n        Void,\r\n        Awaiting,\r\n        Ready,\r\n        Error,\r\n        Finalizing\r\n    }\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IChainlinkAggregatorV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\ninterface IChainlinkAggregatorV3 {\r\n\r\n    function decimals() external view returns (uint8);\r\n    function description() external view returns (string memory);\r\n    \r\n    function getRoundData(uint80 _roundId)\r\n        external view returns (\r\n            uint80 roundId, \r\n            int256 answer, \r\n            uint256 startedAt, \r\n            uint256 updatedAt, \r\n            uint80 answeredInRound\r\n        );\r\n\r\n    function latestRoundData()\r\n        external view returns (\r\n            uint80 roundId, \r\n            int256 answer, \r\n            uint256 startedAt, \r\n            uint256 updatedAt, \r\n            uint80 answeredInRound\r\n        );\r\n\r\n    function version() external view returns (uint256);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IPythChainlinkAggregatorV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IChainlinkAggregatorV3.sol\";\r\nimport \"./IWitPyth.sol\";\r\n\r\ninterface IPythChainlinkAggregatorV3 is IChainlinkAggregatorV3 {\r\n    function priceId() external view returns (bytes32);\r\n    function pyth() external view returns (address);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitOracleConsumerLegacy.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"../../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleConsumerLegacy {\r\n\r\n    /// @notice Method to be called from the WitOracle contract as soon as the given Witnet `queryId`\r\n    /// @notice gets reported, if reported with no errors.\r\n    /// @dev It should revert if called from any other address different to the WitOracle being used\r\n    /// @dev by the data consumer contract. \r\n    /// @param queryId The unique identifier of the Witnet query being reported.\r\n    /// @param resultDrTxHash Hash of the commit/reveal witnessing act that took place in the Witnet blockahin.\r\n    /// @param resultTimestamp Timestamp at which the reported value was captured by the Witnet blockchain. \r\n    /// @param resultEvmFinalityBlock EVM block at which the provided data can be considered to be final.\r\n    /// @param witnetResultCborValue The CBOR-encoded resulting value of the Witnet query being reported.\r\n    function reportWitOracleResultValue(\r\n            uint256 queryId, \r\n            uint64  resultTimestamp,\r\n            bytes32 resultDrTxHash,\r\n            uint256 resultEvmFinalityBlock,\r\n            WitnetCBOR.CBOR calldata witnetResultCborValue\r\n        ) external;\r\n\r\n    /// @notice Method to be called from the WitOracle contract as soon as the given Witnet `queryId`\r\n    /// @notice gets reported, if reported WITH errors.\r\n    /// @dev It should revert if called from any other address different to the WitOracle being used\r\n    /// @dev by the data consumer contract. \r\n    /// @param queryId The unique identifier of the Witnet query being reported.\r\n    /// @param resultDrTxHash Hash of the commit/reveal witnessing act that took place in the Witnet blockahin.\r\n    /// @param resultTimestamp Timestamp at which the reported value was captured by the Witnet blockchain. \r\n    /// @param resultEvmFinalityBlock EVM block at which the provided data can be considered to be final.\r\n    /// @param errorCode The error code enum identifying the error produced during resolution on the Witnet blockchain.\r\n    /// @param errorArgs Error arguments, if any. An empty buffer is to be passed if no error arguments apply.\r\n    function reportWitOracleResultError(\r\n            uint256 queryId, \r\n            uint64  resultTimestamp,\r\n            bytes32 resultDrTxHash,\r\n            uint256 resultEvmFinalityBlock,\r\n            Witnet.ResultStatus errorCode, \r\n            WitnetCBOR.CBOR calldata errorArgs\r\n        ) external;\r\n\r\n    /// @notice Determines if Witnet queries can be reported from given address.\r\n    /// @dev In practice, must only be true on the WitOracle address that's being used by\r\n    /// @dev the data consumer contract to post queries. \r\n    function reportableFrom(address) external view returns (bool);\r\n}"
      },
      "project/contracts/interfaces/legacy/IWitOracleLegacy.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../IWitOracleRadonRegistry.sol\";\r\nimport \"./IWitOracleRequest.sol\";\r\nimport \"./IWitOracleRequestTemplate.sol\";\r\n\r\ninterface IWitOracleLegacy {\r\n\r\n    struct Query {\r\n        QueryRequest request;\r\n        QueryResponse response;\r\n    }\r\n\r\n    struct QueryRequest {\r\n        address requester;\r\n        uint24  callbackGas;\r\n        uint72  evmReward;\r\n        bytes   radonBytecode;\r\n        bytes32 radonHash;\r\n        RadonSLA radonParams;\r\n    }\r\n\r\n    struct QueryResponse {\r\n        address reporter;\r\n        uint64 finality;\r\n        uint32 timestamp;\r\n        bytes32 trail;\r\n        bytes cborBytes;\r\n    }\r\n\r\n    struct RadonSLA {\r\n        uint8 numWitnesses;\r\n        uint64 witnessReward;\r\n    }\r\n\r\n    event WitnetQuery(uint256 id, uint256 evmReward, RadonSLA witnetSLA);\r\n\r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @dev Underestimates if the size of returned data is greater than `resultMaxSize`. \r\n    /// @param gasPrice Expected gas price to pay upon posting the data request.\r\n    /// @param resultMaxSize Maximum expected size of returned data (in bytes).  \r\n    function estimateBaseFee(uint256 gasPrice, uint16 resultMaxSize) external view returns (uint256);\r\n    \r\n    /// @notice Estimate the minimum reward required for posting a data request.\r\n    /// @dev Fails if the RAD hash was not previously verified on the WitOracleRadonRegistry registry.\r\n    /// @param gasPrice Expected gas price to pay upon posting the data request.\r\n    /// @param radHash The RAD hash of the data request to be solved by Witnet.\r\n    function estimateBaseFee(uint256 gasPrice, bytes32 radHash) external view returns (uint256);\r\n\r\n    function getQuery(uint256) external view returns (Query memory);\r\n    function getQueryRequest(uint256) external view returns (QueryRequest memory);\r\n    function getQueryResponse(uint256) external view returns (QueryResponse memory);\r\n\r\n    /// @notice Returns query's result current status from a requester's point of view:\r\n    /// @notice   - 0 => Void: the query is either non-existent or deleted;\r\n    /// @notice   - 1 => Awaiting: the query has not yet been reported;\r\n    /// @notice   - 2 => Ready: the query response was finalized, and contains a result with no erros.\r\n    /// @notice   - 3 => Error: the query response was finalized, and contains a result with errors.\r\n    /// @notice   - 4 => Finalizing: some result to the query has been reported, but cannot yet be considered finalized.\r\n    /// @notice   - 5 => Delivered: at least one response, either successful or with errors, was delivered to the requesting contract.\r\n    function getQueryResponseStatus(uint256) external view returns (QueryResponseStatus);\r\n\r\n        /// QueryResponse status from a requester's point of view.\r\n        enum QueryResponseStatus {\r\n            Void,\r\n            Awaiting,\r\n            Ready,\r\n            Error,\r\n            Finalizing,\r\n            Delivered,\r\n            Expired\r\n        }\r\n\r\n    /// @notice Retrieves the CBOR-encoded buffer containing the Witnet-provided result to the given query.\r\n    function getQueryResultCborBytes(uint256) external view returns (bytes memory);\r\n\r\n    /// @notice Gets error code identifying some possible failure on the resolution of the given query.\r\n    function getQueryResultError(uint256) external view returns (ResultError memory);\r\n\r\n        /// Data struct describing an error when trying to fetch a Witnet-provided result to a Data Request.\r\n        struct ResultError {\r\n            uint8 code;\r\n            string reason;\r\n        }\r\n\r\n    function extractWitnetDataRequests(uint256[] calldata queryIds) external view returns (bytes[] memory);\r\n    function fetchQueryResponse(uint256 queryId) external returns (bytes memory);\r\n    function postRequest(bytes32, RadonSLA calldata) external payable returns (uint256);\r\n    function postRequestWithCallback(bytes32, RadonSLA calldata, uint24) external payable returns (uint256);\r\n    function reportResult(uint256, uint32, bytes32, bytes calldata) external returns (uint256);\r\n    function reportResult(uint256, bytes32, bytes calldata) external returns (uint256);\r\n\r\n    struct BatchResultLegacy {\r\n        uint256 queryId;\r\n        uint32 resultTimestamp;\r\n        bytes32 drTxHash;\r\n        bytes resultCborBytes;\r\n    }\r\n    function reportResultBatch(BatchResultLegacy[] calldata) external returns (uint256);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitOracleRadonRegistryLegacy.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleRadonRegistryLegacy {\r\n\r\n    function bytecodeOf(Witnet.RadonHash) external view returns (bytes memory);\r\n    function lookupRadonRequest(Witnet.RadonHash radonRequestHash) external view returns (Witnet.RadonRequest memory);\r\n    function lookupRadonRequestAggregator(Witnet.RadonHash radHash) external view returns (Witnet.RadonReducer memory);\r\n    function lookupRadonRequestResultMaxSize(bytes32 radHash) external view returns (uint16);\r\n    // function lookupRadonRequestRetrievalByIndex(Witnet.RadonHash radHash, uint256 index) external view returns (Witnet.RadonRetrieval memory);\r\n    function lookupRadonRequestSources(bytes32 radHash) external view returns (bytes32[] memory);\r\n    function lookupRadonRequestSourcesCount(bytes32 radHash) external view returns (uint);\r\n    function lookupRadonRequestTally(Witnet.RadonHash radHash) external view returns (Witnet.RadonReducer memory);\r\n    \r\n    function verifyRadonRequest(\r\n            bytes32[] calldata sources,\r\n            bytes32 aggregator,\r\n            bytes32 tally,\r\n            uint16 resultMaxSize,\r\n            string[][] calldata args\r\n        ) external returns (bytes32 radHash);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitOracleRequest.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../libs/Witnet.sol\";\r\n\r\ninterface IWitOracleRequest {\r\n\r\n    /// Returns the Witnet-compliant RAD bytecode for the data request (i.e. Radon Request) \r\n    /// contained within this WitOracleRequest.\r\n    function bytecode() external view returns (bytes memory);\r\n\r\n    /// Returns the Witnet-compliant RAD hash of the data request (i.e. Radon Request) \r\n    /// contained within this WitOracleRequest. \r\n    function radHash() external view returns (Witnet.RadonHash);\r\n\r\n    /// Returns the filters and reducing functions to be applied by witnessing nodes \r\n    /// on the Witnet blockchain both at the:\r\n    /// - Aggregate stage: when aggregating data extracted from the public \r\n    ///                    data sources (i.e. Radon Retrievals).\r\n    /// - Tally stage: when aggregating values revealed by witnesses.\r\n    function getRadonReducers() external view returns (\r\n            Witnet.RadonReducer memory aggregateStage,\r\n            Witnet.RadonReducer memory tallyStage\r\n        );\r\n\r\n    \r\n    /// Returns metadata concerning the data source specified by the given index.\r\n    function getRadonRetrievalByIndex(uint256) external view returns (Witnet.RadonRetrieval memory);\r\n\r\n    /// Returns the array of one or more data sources (i.e. Radon Retrievals) \r\n    /// that compose this WitOracleRequest.\r\n    function getRadonRetrievals() external view returns (Witnet.RadonRetrieval[] memory);\r\n\r\n    /// Returns the expected data type produced by successful resolutions of the \r\n    /// Witnet-compliant data request contained within this WitOracleRequest.\r\n    function getResultDataType() external view returns (Witnet.RadonDataTypes);\r\n\r\n    /// If built out of an upgradable factory, or template, returns the SemVer tag of \r\n    /// the actual implementation version at the time when this WitOracleRequest got built.\r\n    function version() external view returns (string memory);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitOracleRequestFactory.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IWitOracleRequestTemplate.sol\";\r\n\r\ninterface IWitOracleRequestFactory {\r\n    \r\n    /// @notice Builds a WitOracleRequest instance that will provide the bytecode\r\n    /// @notice and RAD hash of some Witnet-compliant data request, provably \r\n    /// @notice made out of some previously verified Witnet Radon Retrievals\r\n    /// @notice (i.e. data sources), aggregate and tally Witnet Radon Reducers.\r\n    /// @dev Reverts if:\r\n    /// @dev   - unverified retrievals are passed;\r\n    /// @dev   - any of the given retrievals is parameterized;\r\n    /// @dev   - retrievals return different data types;\r\n    /// @dev   - unsupported reducers are passed.\r\n    /// @param retrieveHashes Hashes of previously verified data sources.\r\n    /// @param aggregate The Radon Reducer to apply on values returned from data sources.\r\n    /// @param tally The Radon Reducer to apply on values revealed by witnessing nodes.\r\n    function buildWitOracleRequest(\r\n            bytes32[] calldata retrieveHashes,\r\n            Witnet.RadonReducer calldata aggregate,\r\n            Witnet.RadonReducer calldata tally\r\n        ) external returns (IWitOracleRequest);\r\n\r\n    /// @notice Builds a modal WitOracleRequest instance out of one single parameterized \r\n    /// @notice Witnet Radon Retrieval. Modal data requests apply the same data retrieval script\r\n    /// @notice to multiple data providers that are expected to produce exactly the same result. \r\n    /// @notice Moreover, modal data requests apply a Mode reducing function at both the \r\n    /// @notice Aggregate and Tally stages everytime they get eventually solved on the Wit/Oracle\r\n    /// @notice blockhain. You can optionally specify a list of filters to be applied at the Tally \r\n    /// @notice resolution stage (i.e. witnessing nodes on the Wit/Oracle blockchain reporting results\r\n    /// @notice that get ultimately filtered out on the Tally stage would get slashed by losing collateral).\r\n    /// @dev Reverts if:\r\n    /// @dev  - unverified base Radon Retrieval is passed;\r\n    /// @dev  - the specified base Radon Retrieval is not parameterized;\r\n    /// @dev  - 2nd dimension's rank of the `requestArgs` array doesn't match the number of required parameters \r\n    /// @dev    required by the given Radon Retrieval;\r\n    /// @dev  - unsupported Radon Filters are passed.\r\n    /// @param baseRetrieveHash Hash of the parameterized Radon Retrieval upon which the new data request will be built.\r\n    /// @param requestArgs Parameters to be applied to each repetition of the given retrieval.\r\n    /// @param tallySlashingFilters Optional array of slashing filters to will be applied at the Tally stage.\r\n    function buildWitOracleRequestModal(\r\n            bytes32 baseRetrieveHash,\r\n            string[][] calldata requestArgs,\r\n            Witnet.RadonFilter[] calldata tallySlashingFilters\r\n        ) external returns (IWitOracleRequest);\r\n\r\n    /// @notice Builds a WitOracleRequestTemplate instance made out of one or more\r\n    /// @notice parameterized Witnet Radon Retrievals (i.e. data sources), aggregate\r\n    /// @notice and tally Witnet Radon Reducers. \r\n    /// @dev Reverts if:\r\n    /// @dev   - unverified retrievals are passed;\r\n    /// @dev   - none of given retrievals is parameterized;\r\n    /// @dev   - retrievals return different data types;\r\n    /// @dev   - unsupported reducers are passed.\r\n    /// @param retrieveHashes Hashes of previously verified data sources.\r\n    /// @param aggregate The Radon Reducer to apply on values returned from data sources.\r\n    /// @param tally The Radon Reducer to apply on values revealed by witnessing nodes.\r\n    function buildWitOracleRequestTemplate(\r\n            bytes32[]  calldata retrieveHashes,\r\n            Witnet.RadonReducer calldata aggregate,\r\n            Witnet.RadonReducer calldata tally\r\n        ) external returns (IWitOracleRequestTemplate);\r\n\r\n    /// @notice Builds a modal WitOracleRequestTemplate instance out of one single parameterized \r\n    /// @notice Witnet Radon Retrieval. Modal request templates produce Witnet-compliant data requests\r\n    /// @notice that apply the same data retrieval script to multiple data providers that are expected to\r\n    /// @notice produce exactly the same result. Moreover, data requests built out of a modal request templates\r\n    /// @notice apply a Mode reducing function at both the Aggregate and Tally stages every time they get\r\n    /// @notice eventually solved on the Wit/Oracle blockchain. You can optionally specify a list of filters \r\n    /// @notice to be applied at the Tally resolution stage (i.e. witnessing nodes on the Wit/Oracle blockchain\r\n    /// @notice reporting results that get ultimately filtered out on the Tally stage would get slashed by losing collateral).\r\n    /// @dev Reverts if:\r\n    /// @dev  - unverified base Radon Retrieval is passed;\r\n    /// @dev  - the specified base Radon Retrieval is either not parameterized or requires just one single parameter;\r\n    /// @dev  - unsupported Radon Filters are passed.\r\n    /// @param baseRetrieveHash Hash of the parameterized Radon Retrieval upon which the new data request will be built.\r\n    /// @param lastArgValues Parameters to be applied to each repetition of the given retrieval.\r\n    /// @param tallySlashingFilters Optional array of slashing filters to will be applied at the Tally stage.\r\n    function buildWitOracleRequestTemplateModal(\r\n            bytes32 baseRetrieveHash,\r\n            string[] calldata lastArgValues,\r\n            Witnet.RadonFilter[] calldata tallySlashingFilters\r\n        ) external returns (IWitOracleRequestTemplate);\r\n\r\n    /// @notice Verifies and registers the specified Witnet Radon Retrieval \r\n    /// @notice (i.e. public data sources) into the WitOracleRadonRegistry of the\r\n    /// @notice WitOracle attached to this factory. Returns a hash that uniquely \r\n    /// @notice identifies validated data source within the WitOracleRadonRegistry.\r\n    /// @dev Note: all input parameters but the `requestMethod` are parameterizable\r\n    /// @dev       by using embedded wildcard `\\x\\` substrings (being `x='0'..'9').\r\n    /// @dev Reverts if:\r\n    /// @dev   - unsupported data request method is given;\r\n    /// @dev   - no URL is provided on Http/* data requests;\r\n    /// @dev   - non-empty strings given on RNG data requests..\r\n    function verifyRadonRetrieval(\r\n            Witnet.RadonRetrievalMethods requestMethod,\r\n            string calldata requestURL,\r\n            string calldata requestBody,\r\n            string[2][] calldata requestHeaders,\r\n            bytes calldata requestRadonScript\r\n        ) external returns (bytes32 retrievalHash);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitOracleRequestFactoryEvents.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\ninterface IWitOracleRequestFactoryEvents {\r\n\r\n    /// Emitted every time a new counter-factual WitOracleRequest gets verified and built. \r\n    event WitOracleRequestBuilt(address request);\r\n\r\n    /// Emitted every time a new counter-factual WitOracleRequestTemplate gets verified and built. \r\n    event WitOracleRequestTemplateBuilt(address template);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitOracleRequestTemplate.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IWitOracleRequest.sol\";\r\n\r\ninterface IWitOracleRequestTemplate {\r\n\r\n    /// Builds a WitOracleRequest instance that will provide the bytecode and RAD \r\n    /// hash of some Witnet-compliant Radon Request, provably made out of the \r\n    /// data sources, aggregate and tally Radon Reducers that compose this instance.\r\n    /// Reverts if the ranks of passed array don't match either the number of this template's \r\n    /// data sources, or the number of required parameters by each one of those.\r\n    /// @dev Produced addresses are counter-factual to the template address and the given values.\r\n    function buildWitOracleRequest (string[][] calldata args) external returns (IWitOracleRequest);\r\n\r\n    /// Builds a WitOracleRequest instance by specifying one single parameter value\r\n    /// that will be equally applied to all the template's data sources.\r\n    /// Reverts if any of the underlying data sources requires more than just one parameter.\r\n    /// @dev Produced addresses are counter-factual to the template address and the given value.\r\n    function buildWitOracleRequest (string calldata singleArgValue) external returns (IWitOracleRequest);\r\n\r\n    /// Returns an array of integers telling the number of parameters required \r\n    /// by every single data source (i.e. Radon Retrievals) that compose this \r\n    /// WitOracleRequestTemplate. The length of the returned array tells the number \r\n    /// of data sources that compose this instance.\r\n    function getArgsCount() external view returns (uint256[] memory);\r\n\r\n    /// Returns the filters and reducing functions to be applied by witnessing nodes \r\n    /// on the Witnet blockchain both at the:\r\n    /// - Aggregate stage: when aggregating data extracted from the public \r\n    ///                    data sources (i.e. Radon Retrievals).\r\n    /// - Tally stage: when aggregating values revealed by witnesses.\r\n    function getRadonReducers() external view returns (\r\n            Witnet.RadonReducer memory aggregateStage,\r\n            Witnet.RadonReducer memory tallyStage\r\n        );\r\n\r\n    /// Returns metadata concerning the data source specified by the given index. \r\n    function getRadonRetrievalByIndex(uint256) external view returns (Witnet.RadonRetrieval memory);\r\n\r\n    /// Returns the array of one or more parameterized data sources that compose \r\n    /// this WitOracleRequestTemplate.\r\n    function getRadonRetrievals() external view returns (Witnet.RadonRetrieval[] memory);\r\n\r\n    /// Returns the expected data type produced by successful resolutions of \r\n    /// any WitOracleRequest that gets built out of this WitOracleRequestTemplate.\r\n    function getResultDataType() external view returns (Witnet.RadonDataTypes); \r\n\r\n    /// Verifies into the bounded WitOracle's registry the actual bytecode \r\n    /// and RAD hash of the Witnet-compliant Radon Request that gets provably \r\n    /// made out of the data sources, aggregate and tally Radon Reducers that \r\n    /// compose this WitOracleRequestTemplate. While no WitOracleRequest instance is \r\n    /// actually constructed, the returned value will be accepted as a valid\r\n    /// RAD hash on the witOracle() contract from now on. \r\n    /// Reverts if:\r\n    /// - the ranks of passed array don't match either the number of this \r\n    ///   template's data sources, or the number of required parameters by \r\n    ///   each one of those.\r\n    /// @dev This method requires less gas than buildWitOracleRequest(string[][]), and \r\n    /// @dev it's usually preferred when data requests built out of this template\r\n    /// @dev are intended to be used just once in lifetime.    \r\n    function verifyRadonRequest(string[][] calldata args) external returns (Witnet.RadonHash);\r\n\r\n    /// Verifies into the bounded WitOracle's registry the actual bytecode\r\n    /// and RAD hash of the Witnet-compliant Radon Request that gets provably\r\n    /// made out as a result of applying the given parameter value to the underlying\r\n    /// data sources, aggregate and tally reducers that compose this template. \r\n    /// While no actual WitOracleRequest instance gets constructed, the returned value\r\n    /// will be accepted as a valid RAD hash on the bounded WitOracle contract from now on.\r\n    /// Reverts if any of the underlying data sources requires more than just one parameter.\r\n    /// @dev This method requires less gas than buildWitOracleRequest(string), and \r\n    /// @dev it's usually preferred when data requests built out of this template\r\n    /// @dev are intended to be used just once in lifetime.\r\n    function verifyRadonRequest(string calldata singleArgValue) external returns (Witnet.RadonHash);\r\n\r\n    /// If built out of an upgradable factory, returns the SemVer tag of the \r\n    /// factory implementation at the time when this WitOracleRequestTemplate got built.\r\n    function version() external view returns (string memory);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitPriceFeedsLegacy.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IWitOracleLegacy.sol\";\r\nimport \"./IWitPriceFeedsLegacySolver.sol\";\r\n\r\ninterface IWitPriceFeedsLegacy {   \r\n\r\n    /// A fresh update on the data feed identified as `erc2364Id4` has just been \r\n    /// requested and paid for by some `evmSender`, under command of the \r\n    /// `evmOrigin` externally owned account. \r\n    event PullingUpdate(\r\n        address evmOrigin,\r\n        address evmSender,\r\n        bytes4  erc2362Id4,\r\n        uint256 witOracleQueryId\r\n    );\r\n\r\n    struct RadonSLAv1 {\r\n        uint8 numWitnesses;\r\n        uint8 minConsensusPercentage;\r\n        uint64 witnessReward;\r\n        uint64 witnessCollateral;\r\n        uint64 minerCommitRevealFee;\r\n    }\r\n\r\n    struct RadonSLAv2 {\r\n        uint8  numWitnesses;\r\n        uint64 unitaryReward;\r\n    }\r\n\r\n    /// Primitive data type produced by successful data updates of all supported\r\n    /// feeds (e.g. Witnet.RadonDataTypes.Integer in WitPriceFeeds).\r\n    function dataType() external view returns (Witnet.RadonDataTypes);\r\n    \r\n    function defaultRadonSLA() external view returns (RadonSLAv1 memory);\r\n\r\n    function estimateUpdateBaseFee(uint256 evmGasPrice) external view returns (uint);\r\n\r\n    /// Returns a unique hash determined by the combination of data sources being used by \r\n    /// supported non-routed price feeds, and dependencies of all supported routed \r\n    /// price feeds. The footprint changes if any price feed is modified, added, removed \r\n    /// or if the dependency tree of any routed price feed is altered.\r\n    function footprint() external view returns (bytes4);\r\n\r\n    /// This pure function determines the ERC-2362 identifier of the given data feed \r\n    /// caption string, truncated to bytes4.\r\n    function hash(string calldata caption) external pure returns (bytes4);\r\n\r\n    /// Returns the query id (in the context of the WitOracle addressed by witOracle()) \r\n    /// that solved the most recently updated value for the given feed.\r\n    function lastValidQueryId(bytes4 feedId) external view returns (uint256);\r\n\r\n    /// Returns the actual response from the Witnet oracle blockchain to the last \r\n    /// successful update for the given data feed.\r\n    function lastValidQueryResponse(bytes4 feedId) external view returns (Witnet.QueryResponse memory);\r\n\r\n    function latestPrice(bytes4 feedId) external view returns (IWitPriceFeedsLegacySolver.Price memory);\r\n    function latestPrices(bytes4[] calldata feedIds)  external view returns (IWitPriceFeedsLegacySolver.Price[] memory);\r\n\r\n    /// Returns the Witnet query id of the latest update attempt for the given data feed.\r\n    function latestUpdateQueryId(bytes4 feedId) external view returns (uint256);\r\n\r\n    /// Returns the actual request queried to the the Witnet oracle blockchain on the latest \r\n    /// update attempt for the given data feed.\r\n    function latestUpdateQueryRequest(bytes4 feedId) external view returns (Witnet.QueryRequest memory);\r\n\r\n    function latestUpdateResponse(bytes4 feedId) external view returns (Witnet.QueryResponse memory);\r\n    function latestUpdateResponseStatus(bytes4 feedId) external view returns (IWitOracleLegacy.QueryResponseStatus);\r\n    function latestUpdateResultError(bytes4 feedId) external view returns (IWitOracleLegacy.ResultError memory);\r\n\r\n    /// Returns the ERC-2362 caption of the given feed identifier, if known. \r\n    function lookupCaption(bytes4) external view returns (string memory);\r\n\r\n    function lookupDecimals(bytes4 feedId) external view returns (uint8);    \r\n    function lookupPriceSolver(bytes4 feedId) external view returns (\r\n            address solverAddress, \r\n            string[] memory solverDeps\r\n        );\r\n    \r\n    function lookupWitnetBytecode(bytes4) external view returns (bytes memory);\r\n    function lookupWitnetRadHash(bytes4) external view returns (bytes32);\r\n    function lookupWitnetRetrievals(bytes4) external view returns (Witnet.RadonRetrieval[] memory);\r\n    \r\n    /// ERC-2362 caption prefix shared by all supported feeds (e.g. \"Price-\" in WitPriceFeeds).\r\n    function prefix() external view returns (string memory);\r\n    \r\n    /// Triggers a fresh update on the Witnet oracle blockchain for the given data feed, \r\n    /// using the defaultRadonSLA() security parameters.\r\n    function requestUpdate(bytes4 feedId) external payable returns (uint256 usedFunds);\r\n    function requestUpdate(bytes4, RadonSLAv2 calldata) external payable returns (uint256 usedFunds);\r\n\r\n    /// Returns the list of feed ERC-2362 ids, captions and RAD hashes of all currently supported \r\n    /// data feeds. The RAD hash of a data feed determines in a verifiable way the actual data sources \r\n    /// and off-chain computations solved by the Witnet oracle blockchain upon every data update. \r\n    /// The RAD hash value for a routed feed actually contains the address of the IWitnetPriceSolver \r\n    /// logic contract that solves it.\r\n    function supportedFeeds() external view returns (bytes4[] memory, string[] memory, bytes32[] memory);\r\n\r\n    /// Tells whether the given ERC-2362 feed caption is currently supported.\r\n    function supportsCaption(string calldata) external view returns (bool);\r\n\r\n    /// Total number of data feeds, routed or not, that are currently supported.\r\n    function totalFeeds() external view returns (uint256);\r\n\r\n    function witnet() external view returns (address);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitPriceFeedsLegacyAdmin.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../libs/Witnet.sol\";\r\n\r\nimport \"./IWitOracleRequest.sol\";\r\nimport \"./IWitOracleRequestTemplate.sol\";\r\nimport \"./IWitPriceFeedsLegacy.sol\";\r\n\r\ninterface IWitPriceFeedsLegacyAdmin {\r\n\r\n    event WitFeedDeleted(string caption, bytes4 feedId);\r\n    event WitFeedSettled(string caption, bytes4 feedId, bytes32 radHash);\r\n    event WitFeedSolverSettled(string caption, bytes4 feedId, address solver);\r\n\r\n    function acceptOwnership() external;\r\n    function baseFeeOverheadPercentage() external view returns (uint16);\r\n    function deleteFeed(string calldata caption) external;\r\n    function deleteFeeds() external;\r\n    function owner() external view returns (address);\r\n    function pendingOwner() external returns (address);\r\n    function settleBaseFeeOverheadPercentage(uint16) external;\r\n    function settleDefaultRadonSLA(IWitPriceFeedsLegacy.RadonSLAv2 calldata) external;\r\n    function settleFeedRequest(string calldata caption, bytes32 radHash) external;\r\n    function settleFeedRequest(string calldata caption, IWitOracleRequest request) external;\r\n    function settleFeedRequest(string calldata caption, IWitOracleRequestTemplate template, string[][] calldata) external;\r\n    function settleFeedSolver (string calldata caption, address solver, string[] calldata deps) external;\r\n    function transferOwnership(address) external;\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitPriceFeedsLegacySolver.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../libs/Witnet.sol\";\r\n\r\ninterface IWitPriceFeedsLegacySolver {\r\n    enum LatestUpdateStatus {\r\n        Void,\r\n        Awaiting,\r\n        Ready,\r\n        Error\r\n    }\r\n    struct Price {\r\n        uint64 value;\r\n        Witnet.Timestamp timestamp;\r\n        Witnet.TransactionHash drTxHash;\r\n        LatestUpdateStatus latestStatus;\r\n    }\r\n    function class() external pure returns (string memory);\r\n    function delegator() external view returns (address);\r\n    function solve(bytes4 feedId) external view returns (Price memory);\r\n    function specs() external pure returns (bytes4);\r\n    function validate(bytes4 feedId, string[] calldata initdata) external;\r\n}"
      },
      "project/contracts/interfaces/legacy/IWitPriceFeedsLegacySolverFactory.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\ninterface IWitPriceFeedsLegacySolverFactory {\r\n    event NewPriceFeedsSolver(address solver, bytes32 codehash, bytes constructorParams);\r\n    function deployPriceSolver(bytes calldata initcode, bytes calldata additionalParams) external returns (address);\r\n    function determinePriceSolverAddress(bytes calldata initcode, bytes calldata additionalParams) external view returns (address);\r\n}"
      },
      "project/contracts/interfaces/legacy/IWitPyth.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IWitPythErrors.sol\";\r\nimport \"./IWitPythEvents.sol\";\r\n\r\nimport \"../../libs/Witnet.sol\";\r\n\r\ninterface IWitPyth\r\n    is\r\n        IWitPythErrors,\r\n        IWitPythEvents\r\n{\r\n    type ID is bytes32;\r\n\r\n    struct PythPrice {\r\n        // Price\r\n        int64 price;\r\n        // Confidence interval around the price\r\n        uint64 conf;\r\n        // Price exponent\r\n        int32 expo;\r\n        // Unix timestamp describing when the price was published\r\n        uint publishTime;\r\n    }\r\n\r\n    /// @notice Returns the exponentially-weighted moving average price.\r\n    /// @dev Reverts if the EMA price is not available.\r\n    /// @param id The Price Feed ID of which to fetch the EMA price.\r\n    function getEmaPrice(ID id) external view returns (PythPrice memory);\r\n\r\n    /// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds\r\n    /// of the current time.\r\n    /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in\r\n    /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently\r\n    /// recently.\r\n    function getEmaPriceNotOlderThan(ID id, uint64 age) external view returns (PythPrice memory);\r\n\r\n    /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.\r\n    /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.\r\n    /// However, if the price is not recent this function returns the latest available price.\r\n    ///\r\n    /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that\r\n    /// the returned price is recent or useful for any particular application.\r\n    ///\r\n    /// Users of this function should check the `timestamp` in the price to ensure that the returned price is\r\n    /// sufficiently recent for their application. If you are considering using this function, it may be\r\n    /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.\r\n    function getEmaPriceUnsafe(ID id) external view returns (PythPrice memory);\r\n\r\n    // /// @notice Returns the latest known exponentially-weight average price for all required price feeds \r\n    // /// without any sanity checks. This function is unsafe as the returned price updates may be arbitrarily \r\n    // /// far in the past.\r\n    // /// \r\n    // /// Users of this function should check the `timestamp` of each price feed to ensure that the returned values \r\n    // /// are sufficiently recent for their application. If you need safe access to fresh data, please consider\r\n    // /// using calling to either `getEmaPrice` or `getEmaPriceNoOlderThan` for every individual price feed.\r\n    // function getEmaPricesUnsafe(ID[] calldata ids) external view returns (Price[] memory);\r\n\r\n    /// @notice Returns the price and confidence interval.\r\n    /// @dev Reverts if the price has not been updated within the last `heartbeatSecs`. \r\n    /// @param id The Price Feed ID of which to fetch the price.\r\n    function getPrice(ID id) external view returns (PythPrice memory);\r\n\r\n    /// @notice Returns the price that is no older than `age` seconds of the current time.\r\n    /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in\r\n    /// applications that require a sufficiently-recent price. \r\n    /// Reverts if the price wasn't updated sufficiently\r\n    /// recently.\r\n    function getPriceNotOlderThan(ID id, uint64 age) external view returns (PythPrice memory);\r\n\r\n    /// @notice Returns the price of a price feed without any sanity checks.\r\n    /// @dev This function returns the most recent price update in this contract without any recency checks.\r\n    /// This function is unsafe as the returned price update may be arbitrarily far in the past.\r\n    /// \r\n    /// Users of this function should check the `timestamp` in the price to ensure that the returned price is\r\n    /// sufficiently recent for their application. If you are considering using this function, it may be\r\n    /// safer / easier to use either `getPrice` or `getPriceNoOlderThan`.\r\n    function getPriceUnsafe(ID id) external view returns (PythPrice memory);\r\n    \r\n    /// @notice Legacy-compliant to get the required fee to update an array of price updates, which would be\r\n    /// always 0 if relying on the Wit/Oracle bridging framework. \r\n    function getUpdateFee(bytes calldata) external view returns (uint256);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitPythChainlinkAggregator.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IPythChainlinkAggregatorV3.sol\";\r\n\r\ninterface IWitPythChainlinkAggregator is IPythChainlinkAggregatorV3 {\r\n    function id4() external view returns (bytes4);\r\n    function symbol() external view returns (string memory);\r\n    function witOracle() external view returns (address);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitPythErrors.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\ninterface IWitPythErrors {\r\n\r\n    /// @notice Requested price deviated too much after previous update.\r\n    /// @dev Signature: 0x7b0d2bb5\r\n    error DeviantPrice();\r\n\r\n    /// @notice Attempting to update a price before cooldown period expires.\r\n    /// @dev Signature: 0x0fbbc581\r\n    error HotPrice();\r\n\r\n    /// @notice Function arguments are invalid (e.g., the arguments lengths mismatch)\r\n    /// @dev Signature: 0xa9cb9e0d\r\n    error InvalidArgument();\r\n    \r\n    /// @notice Either the number of witnesses that solved a price update is not within\r\n    /// the settled range in this contract, or an EMA is being asked for a price feed\r\n    /// that's not settled for the EMA to be computed. \r\n    // Signature: 0x63daeb77\r\n    error InvalidGovernanceTarget();\r\n    \r\n    /// @notice Update data is coming from an invalid Wit/Oracle Radon Hash.\r\n    /// @dev Signature: 0xe60dce71\r\n    error InvalidUpdateDataSource();\r\n\r\n    /// @notice Update data is invalid (e.g. badly serialized, or bad proof was provided).\r\n    /// @dev Signature: 0xe69ffece\r\n    error InvalidUpdateData();\r\n\r\n    /// @notice There is no fresh update, whereas expected fresh updates.\r\n    /// @dev Signature: 0xde2c57fa\r\n    error NoFreshUpdate();\r\n    \r\n    /// @notice Price feed not found or it is not pushed on-chain yet.\r\n    /// @dev Signature: 0x14aebe68\r\n    error PriceFeedNotFound();\r\n\r\n    /// @notice There is no price feed found within the given range or it does not exist.\r\n    /// @dev Signature: 0x45805f5d\r\n    error PriceFeedNotFoundWithinRange();\r\n\r\n    /// @notice Requested price is stale.\r\n    /// @dev Signature: 0x19abf40e\r\n    error StalePrice();\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitPythEvents.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\ninterface IWitPythEvents {\r\n    /// @dev Emitted when the price feed with `id` has received a fresh update.\r\n    /// @param id The Pyth Price Feed ID.\r\n    /// @param publishTime Publish time of the given price update.\r\n    /// @param price Price of the given price update.\r\n    event PriceFeedUpdate(bytes32 indexed id, uint64 publishTime, int64 price, uint64);\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitPythReporter.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IWitPyth.sol\";\r\n\r\ninterface IWitPythReporter {\r\n    \r\n    struct PriceFeed {\r\n        IWitPyth.ID id;\r\n        IWitPyth.PythPrice price;\r\n        IWitPyth.PythPrice emaPrice;\r\n    }\r\n\r\n    /// @notice Parse `updates` and return price feeds of the given `ids` if they reported\r\n    /// timestamps are within specified `minTimestamp` and `maxTimestamp`. Unlike `updatePriceFeeds`, \r\n    /// calling this function will NOT update the on-chain price. \r\n    ///\r\n    /// Use this function if you just want to use reported updates as long as they refer\r\n    /// a timestamp within the specified range, and not necessarily most recent updates in storage.  \r\n    /// Otherwise, consider using `updatePriceFeeds` followed by any of `get*Price*` methods.\r\n   \r\n    /// If you need to make sure to get the earliest update after `minTimestamp` (ie. the one on-chain \r\n    /// or the one being parsed), consider using `parsePriceFeedUpdatesUnique` instead.\r\n    /// \r\n    /// @dev Reverts if there is no update for any of the given `ids` within the given time range.\r\n    /// @param updates Array of price update reports.\r\n    /// @param ids Array of price ids.\r\n    /// @param minTimestamp minimum acceptable publishTime for the given `ids`.\r\n    /// @param maxTimestamp maximum acceptable publishTime for the given `ids`.\r\n    /// @return priceFeeds Array of parsed Prices corresponding to the given `ids` (with the same order).\r\n    function parsePriceFeedUpdates(\r\n            bytes[] calldata updates, \r\n            IWitPyth.ID[] calldata ids, \r\n            Witnet.Timestamp minTimestamp,\r\n            Witnet.Timestamp maxTimestamp\r\n        ) external view returns (PriceFeed[] memory);\r\n\r\n    /// @notice Similar to `parsePriceFeedUpdates` but ensures the returned prices correspond to\r\n    /// the earliest update after `minTimestamp`. That is to say, if `prevTs < minTs <= ts <= maxTs`, \r\n    /// where `prevTs` is the timestamp of latest on-chain timestamp for each referred price-feed.\r\n    /// This will guarantee no updates exist for the given `priceIds` earlier than the returned \r\n    /// updates and still in the given time range. \r\n    \r\n    /// Use this function is you just want to use reported updates for a fixed time window and \r\n    /// not necessarily the most recent update on-chain. Otherwise, consider using\r\n    /// `updatePriceFeeds` followed by any of the  `get*PriceNoOlderThan` variants.\r\n    /// \r\n    /// @dev Reverts if there is no update for any of the given `ids` within the given time range and \r\n    /// uniqueness condition.\r\n    /// @param updates Array of price update reports.\r\n    /// @param ids Array of price ids.\r\n    /// @param minTimestamp minimum acceptable publishTime for the given `ids`.\r\n    /// @param maxTimestamp maximum acceptable publishTime for the given `ids`.\r\n    /// @return priceFeeds Array of the Prices corresponding to the given `ids` (with the same order).\r\n    function parsePriceFeedUpdatesUnique(\r\n            bytes[] calldata updates, \r\n            IWitPyth.ID[] calldata ids, \r\n            Witnet.Timestamp minTimestamp,\r\n            Witnet.Timestamp maxTimestamp\r\n        ) external view returns (PriceFeed[] memory);\r\n\r\n    /// @notice Update price feeds with given update reports. Prices will be updated if \r\n    /// they are more recent than the current stored prices. \r\n    /// The call will succeed even if the update is not the most recent.\r\n    /// \r\n    /// @dev Reverts if any of the update reports is invalid.\r\n    /// @param updates Array of price update reports.\r\n    function updatePriceFeeds(bytes[] calldata updates) external;\r\n\r\n    /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. \r\n    /// A price update is necessary if the current on-chain publishTime is older than the given timestamp. \r\n    /// It relies solely on the given `timestamps` for the price feeds and does not read the actual price update \r\n    /// publish time within `updates`.\r\n    ///\r\n    /// `ids` and `timestamps` are two arrays with the same size that correspond to sender's known timestamps\r\n    /// of each Price Feed id when calling this method. If all of price feeds within `ids` have updated and have\r\n    /// a newer or equal timestamp than the given timestamp, it will reject the transaction to save gas.\r\n    /// Otherwise, it calls updatePriceFeeds method to update the prices.\r\n    ///\r\n    /// @dev Reverts also if any of the price update data is valid.\r\n    /// @param updates Array of price update data.\r\n    /// @param ids Array of price ids.\r\n    /// @param timestamps Array of timestamps: `timestamps[i]` corresponds to known `timestamp` of `ids[i]`\r\n    function updatePriceFeedsIfNecessary(\r\n            bytes[] calldata updates, \r\n            IWitPyth.ID[] calldata ids, \r\n            Witnet.Timestamp[] calldata timestamps\r\n        ) external;\r\n}\r\n"
      },
      "project/contracts/interfaces/legacy/IWitRandomnessAdminLegacy.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./IWitRandomnessLegacy.sol\";\r\n\r\ninterface IWitRandomnessAdminV2 {\r\n    struct WitParams {\r\n        uint16 minWitCommitteeSize;\r\n        uint64 minWitInclusionFees;\r\n    }\r\n    function acceptOwnership() external;\r\n    function baseFeeOverheadPercentage() external view returns (uint16);\r\n    function owner() external view returns (address);\r\n    function pendingOwner() external returns (address);\r\n    function transferOwnership(address) external;\r\n    function settleBaseFeeOverheadPercentage(uint16) external;\r\n    function settleWitnetQuerySLA(IWitRandomnessLegacy.RandomizeQueryParams calldata) external;\r\n}"
      },
      "project/contracts/interfaces/legacy/IWitRandomnessLegacy.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../WitOracle.sol\";\r\n\r\n/// @title The Wit/Randomness appliance interface.\r\n/// @author Witnet Foundation.\r\ninterface IWitRandomnessLegacy {\r\n\r\n    /// Randomization status for some specified block number.\r\n    enum RandomizeStatus {\r\n        Void,\r\n        Awaiting,\r\n        Ready,\r\n        Error,\r\n        Finalizing\r\n    }\r\n    \r\n    /// Emitted every time a new randomize is requested.\r\n    event Randomizing(\r\n        uint256 blockNumber, \r\n        uint256 evmTxGasPrice,\r\n        uint256 evmRandomizeFee,\r\n        uint256 witnetQueryId, \r\n        RandomizeQueryParams witnetQuerySLA\r\n    );\r\n\r\n    /// Randomize parameters\r\n    struct RandomizeQueryParams {\r\n        /// @notice Number of nodes in the Witnet blockchain that will take part in solving the data request. \r\n        uint8   committeeSize;\r\n        /// @notice Fee in $nanoWIT paid to every node in the Witnet blockchain involved in solving the data request.\r\n        uint64  witnessingFeeNanoWit;\r\n    }\r\n   \r\n    /// @notice Returns amount of wei required to be paid as a fee when requesting randomization with a \r\n    /// transaction gas price as the one given.\r\n    function estimateRandomizeFee(uint256 evmGasPrice) external view returns (uint256);\r\n\r\n    /// @notice Retrieves the result of keccak256-hashing the given block number with the randomness value \r\n    /// @notice generated by the Witnet Oracle blockchain in response to the first non-errored randomize request solved \r\n    /// @notice after such block number.\r\n    /// @dev Reverts if:\r\n    /// @dev   i.   no `randomize()` was requested on neither the given block, nor afterwards.\r\n    /// @dev   ii.  the first non-errored `randomize()` request found on or after the given block is not solved yet.\r\n    /// @dev   iii. all `randomize()` requests that took place on or after the given block were solved with errors.\r\n    /// @param blockNumber Block number from which the search will start.\r\n    function fetchRandomnessAfter(uint256 blockNumber) external view returns (bytes32);\r\n\r\n    /// @notice Retrieves the actual random value, unique hash and timestamp of the witnessing commit/reveal act that took\r\n    /// @notice place in the Witnet Oracle blockchain in response to the first non-errored randomize request\r\n    /// @notice solved after the given block number.\r\n    /// @dev Reverts if:\r\n    /// @dev   i.   no `randomize()` was requested on neither the given block, nor afterwards.\r\n    /// @dev   ii.  the first non-errored `randomize()` request found on or after the given block is not solved yet.\r\n    /// @dev   iii. all `randomize()` requests that took place on or after the given block were solved with errors.\r\n    /// @param blockNumber Block number from which the search will start.\r\n    /// @return witnetResultRandomness Random value provided by the Witnet blockchain and used for solving randomness after given block.\r\n    /// @return witnetResultTimestamp Timestamp at which the randomness value was generated by the Witnet blockchain.\r\n    /// @return witnetResultTallyHash Hash of the witnessing commit/reveal act that took place on the Witnet blockchain.\r\n    /// @return witnetResultFinalityBlock EVM block number from which the provided randomness can be considered to be final.\r\n    function fetchRandomnessAfterProof(uint256 blockNumber) external view returns (\r\n            bytes32 witnetResultRandomness,\r\n            uint64  witnetResultTimestamp, \r\n            bytes32 witnetResultTallyHash,\r\n            uint256 witnetResultFinalityBlock\r\n        ); \r\n\r\n    /// @notice Returns last block number on which a randomize was requested.\r\n    function getLastRandomizeBlock() external view returns (uint256);\r\n\r\n    /// @notice Retrieves metadata related to the randomize request that got posted to the \r\n    /// @notice Witnet Oracle contract on the given block number.\r\n    /// @dev Returns zero values if no randomize request was actually posted on the given block.\r\n    /// @return witnetQueryId Identifier of the underlying Witnet query created on the given block number. \r\n    /// @return prevRandomizeBlock Block number in which a randomize request got posted just before this one. 0 if none.\r\n    /// @return nextRandomizeBlock Block number in which a randomize request got posted just after this one, 0 if none.\r\n    function getRandomizeData(uint256 blockNumber) external view returns (\r\n            uint256 witnetQueryId,\r\n            uint256 prevRandomizeBlock, \r\n            uint256 nextRandomizeBlock\r\n        );\r\n    \r\n    /// @notice Returns the number of the next block in which a randomize request was posted after the given one. \r\n    /// @param blockNumber Block number from which the search will start.\r\n    /// @return Number of the first block found after the given one, or `0` otherwise.\r\n    function getRandomizeNextBlock(uint256 blockNumber) external view returns (uint256); \r\n\r\n    /// @notice Returns the number of the previous block in which a randomize request was posted before the given one.\r\n    /// @param blockNumber Block number from which the search will start.\r\n    /// @return First block found before the given one, or `0` otherwise.\r\n    function getRandomizePrevBlock(uint256 blockNumber) external view returns (uint256);\r\n\r\n    /// @notice Gets current status of the first non-errored randomize request posted on or after the given block number.\r\n    /// @dev Possible values:\r\n    /// @dev - 0 -> Void: no randomize request was actually posted on or after the given block number.\r\n    /// @dev - 1 -> Awaiting: a randomize request was found but it's not yet solved by the Witnet blockchain.\r\n    /// @dev - 2 -> Ready: a successfull randomize value was reported and ready to be read.\r\n    /// @dev - 3 -> Error: all randomize resolutions after the given block were solved with errors.\r\n    /// @dev - 4 -> Finalizing: a randomize resolution has been reported from the Witnet blockchain, but it's not yet final.  \r\n    function getRandomizeStatus(uint256 blockNumber) external view returns (RandomizeStatus);\r\n\r\n    /// @notice Returns `true` only if a successfull resolution from the Witnet blockchain is found for the first \r\n    /// @notice non-errored randomize request posted on or after the given block number.\r\n    function isRandomized(uint256 blockNumber) external view returns (bool);\r\n\r\n    /// @notice Generates a pseudo-random number uniformly distributed within the range [0 .. _range), by using \r\n    /// @notice the given `nonce` and the randomness returned by `getRandomnessAfter(blockNumber)`. \r\n    /// @dev Fails under same conditions as `getRandomnessAfter(uint256)` does.\r\n    /// @param range Range within which the uniformly-distributed random number will be generated.\r\n    /// @param nonce Nonce value enabling multiple random numbers from the same randomness value.\r\n    /// @param blockNumber Block number from which the search for the first randomize request solved aftewards will start.\r\n    function random(uint32 range, uint256 nonce, uint256 blockNumber) external view returns (uint32);\r\n\r\n    /// @notice Requests the Witnet oracle to generate an EVM-agnostic and trustless source of randomness. \r\n    /// @dev Only one randomness request per block will be actually posted to the Witnet Oracle. \r\n    /// @dev Unused funds will be transfered back to the `msg.sender`. \r\n    /// @return Funds actually paid as randomize fee. \r\n    function randomize() external payable returns (uint256);\r\n\r\n    /// @notice Returns address of the Witnet Oracle bridging contract being used for solving randomness requests.\r\n    function witnet() external view returns (address);\r\n\r\n    /// @notice Returns the SLA parameters required for the Witnet Oracle blockchain to fulfill \r\n    /// @notice when solving randomness requests:\r\n    /// @notice - number of witnessing nodes contributing to randomness generation\r\n    /// @notice - reward in $nanoWIT received per witnessing node in the Witnet blockchain\r\n    function witnetQuerySLA() external view returns (RandomizeQueryParams memory);\r\n\r\n    /// @notice Returns the unique identifier of the Witnet-compliant data request being used for solving randomness.\r\n    function witnetRadHash() external view returns (bytes32);\r\n}\r\n"
      },
      "project/contracts/libs/Bech32.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n// Stratonet Contracts (last updated v1.0.0) (utils/Bech32.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev Collection of functions related to the Bech32 address generation\r\n */\r\nlibrary Bech32 {\r\n    bytes constant ALPHABET = \"qpzry9x8gf2tvdw0s3jn54khce6mua7l\";\r\n    bytes constant ALPHABET_REV = hex\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0fff0a1115141a1e0705ffffffffffffff1dff180d19090817ff12161f1b13ff010003100b1c0c0e060402ffffffffffff1dff180d19090817ff12161f1b13ff010003100b1c0c0e060402ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\";\r\n    bytes constant ALPHABET_REV_LOWER_ONLY = hex\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0fff0a1115141a1e0705ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1dff180d19090817ff12161f1b13ff010003100b1c0c0e060402ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\";\r\n\r\n    // 0f <= 0: 48      | 30\r\n    // 0a <= 2: 50      | 32\r\n    // 11 <= 3: 51      | 33\r\n    // 15 <= 4: 52      | 34\r\n    // 14 <= 5: 53      | 35\r\n    // 1a <= 6: 54      | 36\r\n    // 1e <= 7: 55      | 37\r\n    // 07 <= 8: 56      | 38\r\n    // 05 <= 9: 57      | 39\r\n    \r\n    // 1d <= a: 97, 65  | 61, 41\r\n    // 18 <= c: 99, 67  | 63, 43\r\n    // 0d <= d: 100, 68 | 64, 44\r\n    // 19 <= e: 101, 69 | 65, 45\r\n    // 09 <= f: 102, 70 | 66, 46\r\n    // 08 <= g: 103, 71 | 67, 47\r\n    // 17 <= h: 104, 72 | 68, 48\r\n    // 12 <= j: 106, 74 | 6A, 4A\r\n    // 16 <= k: 107, 75 | 6B, 4B\r\n    // 1f <= l: 108, 76 | 6C, 4C\r\n    // 1b <= m: 109, 77 | 6D, 4D\r\n    // 13 <= n: 110, 78 | 6E, 4E\r\n    \r\n    // 01 <= p: 112, 80 | 70, 50\r\n    // 00 <= q: 113, 81 | 71, 51\r\n    // 03 <= r: 114, 82 | 72, 52\r\n    // 10 <= s: 115, 83 | 73, 53\r\n    // 0b <= t: 116, 84 | 74, 54\r\n    // 1c <= u: 117, 85 | 75, 55\r\n    // 0c <= v: 118, 86 | 76, 56\r\n    // 0e <= w: 119, 87 | 77, 57\r\n    // 06 <= x: 120, 88 | 78, 58\r\n    // 04 <= y: 121, 89 | 79, 59\r\n    // 02 <= z: 122, 90 | 7A, 5A\r\n    \r\n    uint32 constant ENC_BECH32 = 1;\r\n    uint32 constant ENC_BECH32M = 0x2bc830a3;\r\n\r\n\r\n    function toBech32(\r\n        address addr,\r\n        string memory prefix\r\n    ) internal pure returns (string memory) {\r\n        return toBech32(abi.encodePacked(addr), prefix);\r\n    }\r\n\r\n    function toBech32(\r\n        bytes memory data,\r\n        string memory prefix\r\n    ) internal pure returns (string memory) {\r\n        bytes memory hrp = abi.encodePacked(prefix);\r\n        bytes memory input = convertBits(data, 8, 5, true);\r\n        return encode(hrp, input, ENC_BECH32);\r\n    }\r\n\r\n    function toBech32(\r\n        address addr,\r\n        string memory prefix,\r\n        uint8 version\r\n    ) internal pure returns (string memory) {\r\n        return toBech32(abi.encodePacked(addr), prefix, version);\r\n    }\r\n\r\n    function toBech32(\r\n        bytes memory data,\r\n        string memory prefix,\r\n        uint8 version\r\n    ) internal pure returns (string memory) {\r\n        bytes memory hrp = abi.encodePacked(prefix);\r\n        bytes memory input = convertBits(data, 8, 5, true);\r\n        uint32 enc = ENC_BECH32;\r\n        if (version > 0) {\r\n            enc = ENC_BECH32M;\r\n        }\r\n        bytes memory inputWithV = abi.encodePacked(bytes1(version), input);\r\n        return encode(hrp, inputWithV, enc);\r\n    }\r\n\r\n    function fromBech32(\r\n        string memory bechAddr\r\n    ) internal pure returns (address) {\r\n        (, uint8[] memory data) = decode(\r\n            abi.encodePacked(bechAddr),\r\n            ENC_BECH32\r\n        );\r\n        bytes memory input = convertBits(data, 5, 8, false);\r\n        return getAddressFromBytes(input);\r\n    }\r\n\r\n    function fromBech32(\r\n        string memory bechAddr,\r\n        string memory prefix\r\n    ) internal pure returns (address) {\r\n        (bytes memory dHrp, uint8[] memory data) = decode(\r\n            abi.encodePacked(bechAddr),\r\n            ENC_BECH32\r\n        );\r\n        _requireHrpMatch(abi.encodePacked(prefix), dHrp);\r\n        bytes memory input = convertBits(data, 5, 8, false);\r\n        return getAddressFromBytes(input);\r\n    }\r\n\r\n    function fromBech32WithVersion(\r\n        string memory bechAddr,\r\n        string memory prefix,\r\n        uint32 enc\r\n    ) internal pure returns (uint8, bytes memory) {\r\n        (bytes memory dHrp, uint8[] memory data) = decode(\r\n            abi.encodePacked(bechAddr),\r\n            enc\r\n        );\r\n        _requireHrpMatch(abi.encodePacked(prefix), dHrp);\r\n        require(!(data.length < 1 || data[0] > 16), \"Bech32: wrong version\");\r\n        uint8[] memory dataNoV = new uint8[](data.length - 1);\r\n        for (uint8 i = 1; i < data.length; ++i) {\r\n            dataNoV[i - 1] = data[i];\r\n        }\r\n        bytes memory input = convertBits(dataNoV, 5, 8, false);\r\n        require(\r\n            input.length >= 2 && input.length <= 40,\r\n            \"Bech32: wrong bits length\"\r\n        );\r\n        require(\r\n            !(data[0] == 0 && input.length != 20 && input.length != 32),\r\n            \"Bech32: wrong bits length for version\"\r\n        );\r\n        return (uint8(data[0]), input);\r\n    }\r\n\r\n    function _requireHrpMatch(\r\n        bytes memory hrp1,\r\n        bytes memory hrp2\r\n    ) internal pure {\r\n        require(keccak256(hrp1) == keccak256(hrp2), \"Bech32: hrp mismatch\");\r\n    }\r\n\r\n    function getAddressFromBytes(\r\n        bytes memory data\r\n    ) internal pure returns (address) {\r\n        require(data.length == 20, \"Bech32: invalid data length\");\r\n\r\n        address addr;\r\n        assembly {\r\n            addr := mload(add(data, 20))\r\n        }\r\n        return addr;\r\n    }\r\n\r\n    function encode(\r\n        bytes memory hrp,\r\n        bytes memory input,\r\n        uint32 enc\r\n    ) internal pure returns (string memory) {\r\n        unchecked {\r\n            uint8[] memory checksum = createChecksum(hrp, input, enc);\r\n            bytes memory result = new bytes(hrp.length + input.length + checksum.length + 1);\r\n            for (uint i; i < hrp.length; ++ i) {\r\n                result[i] = hrp[i];\r\n            }\r\n            result[hrp.length] = bytes1(\"1\");\r\n            uint offset = hrp.length + 1;\r\n            for (uint i; i < input.length; ++ i) {\r\n                uint8 _data = uint8(input[i]);\r\n                if (_data < ALPHABET.length) {\r\n                    result[i + offset] = ALPHABET[_data];\r\n                }\r\n            }\r\n            offset += input.length;\r\n            for (uint i; i < checksum.length; ++ i) {\r\n                uint8 _data = uint8(checksum[i]);\r\n                if (_data < ALPHABET.length) {\r\n                    result[i + offset] = ALPHABET[_data];\r\n                }\r\n            }\r\n            return string(result);\r\n        }\r\n    }\r\n\r\n    function decode(bytes memory bechStr, uint32 enc) \r\n        internal pure \r\n        returns (bytes memory hrp, uint8[] memory data)\r\n    {\r\n        unchecked {\r\n            uint pos;\r\n            require(\r\n                bechStr.length <= 90, \r\n                \"Bech32: invalid string length\"\r\n            );\r\n            for (uint p = 0; p < bechStr.length; ++ p) {\r\n                uint8 charAt = uint8(bechStr[p]);\r\n                require(\r\n                    charAt >= 33 \r\n                        && charAt <= 126, \r\n                    \"Bech32: wrong char\"\r\n                );\r\n                if (charAt == uint8(bytes1(\"1\"))) {\r\n                    require(\r\n                        pos == 0 \r\n                            && p >= 1 \r\n                            && p + 7 <= bechStr.length, \r\n                        \"Bech32: wrong pos of 1\"\r\n                    );\r\n                    pos = p;\r\n                }\r\n            }\r\n            hrp = new bytes(pos);\r\n            for (uint i; i < pos; ++ i) {\r\n                hrp[i] = bechStr[i]; \r\n            }\r\n            data = new uint8[](bechStr.length - pos - 1);\r\n            for (uint i; i < data.length; ++ i) {\r\n                bytes1 charAt = ALPHABET_REV_LOWER_ONLY[uint8(bechStr[i + pos + 1])];\r\n                require(charAt != 0xff, \"Bech32: byte not in alphabet\");\r\n                data[i] = uint8(charAt);\r\n            }\r\n            require(\r\n                verifyChecksum(hrp, data, enc), \r\n                \"Bech32: wrong checksum\"\r\n            );\r\n            uint dataLength = data.length - 6;\r\n            assembly {\r\n                mstore(data, dataLength)\r\n            }\r\n        }\r\n    }\r\n\r\n    function hrpExpand(\r\n        bytes memory hrp\r\n    ) internal pure returns (uint8[] memory ret) {\r\n        unchecked {\r\n            ret = new uint8[](hrp.length + hrp.length + 1);\r\n            for (uint p; p < hrp.length; ++ p) {\r\n                ret[p] = uint8(hrp[p]) >> 5;\r\n                ret[p + hrp.length + 1] = uint8(hrp[p]) & 31;\r\n            }\r\n        }\r\n    }\r\n\r\n    function polymod(uint32[] memory values) internal pure returns (uint32) {\r\n        uint32 chk = 1;\r\n        uint32[5] memory GEN = [\r\n            0x3b6a57b2,\r\n            0x26508e6d,\r\n            0x1ea119fa,\r\n            0x3d4233dd,\r\n            0x2a1462b3\r\n        ];\r\n\r\n        unchecked {\r\n            for (uint32 i = 0; i < values.length; ++i) {\r\n                uint32 top = chk >> 25;\r\n                chk = (uint32(chk & 0x1ffffff) << 5) ^ uint32(values[i]);\r\n                for (uint32 j = 0; j < 5; ++j) {\r\n                    if (((top >> j) & 1) == 1) {\r\n                        chk ^= GEN[j];\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        return chk;\r\n    }\r\n\r\n    function createChecksum(\r\n        bytes memory hrp,\r\n        bytes memory data,\r\n        uint32 enc\r\n    ) internal pure returns (uint8[] memory res) {\r\n        unchecked {\r\n            uint8[] memory values = hrpExpand(hrp);\r\n            uint32[] memory comb = new uint32[](values.length + data.length + 6);\r\n\r\n            for (uint i; i < values.length + data.length; ++ i) {\r\n                if (i < values.length) {\r\n                    comb[i] = uint32(values[i]);\r\n                } else {\r\n                    comb[i] = uint32(uint8(data[i - values.length]));\r\n                }\r\n            }\r\n            \r\n            res = new uint8[](6);\r\n            uint32 mod = polymod(comb) ^ enc;\r\n            for (uint p = 0; p < 6; ++ p) {\r\n                res[p] = uint8((mod >> (5 * (5 - p))) & 31);\r\n            }\r\n        }\r\n    }\r\n\r\n    function verifyChecksum(\r\n        bytes memory hrp,\r\n        uint8[] memory data,\r\n        uint32 enc\r\n    ) internal pure returns (bool) {\r\n        unchecked {\r\n            uint8[] memory ehrp = hrpExpand(hrp);\r\n            uint32[] memory cData = new uint32[](ehrp.length + data.length);\r\n            for (uint i; i < ehrp.length; ++ i) {\r\n                cData[i] = uint32(ehrp[i]);\r\n            }\r\n            for (uint i; i < data.length; ++ i) {\r\n                cData[i + ehrp.length] = uint32(data[i]);\r\n            }\r\n            return polymod(cData) == enc;\r\n        }\r\n    }\r\n\r\n    function convertBits(\r\n        bytes memory data,\r\n        uint frombits,\r\n        uint tobits,\r\n        bool pad\r\n    ) internal pure returns (bytes memory) {\r\n        uint8[] memory dataBits = new uint8[](data.length);\r\n\r\n        for (uint32 p = 0; p < dataBits.length; ++p) {\r\n            dataBits[p] = uint8(data[p]);\r\n        }\r\n\r\n        return _convertBits(dataBits, frombits, tobits, pad);\r\n    }\r\n\r\n    function convertBits(\r\n        uint8[] memory data,\r\n        uint frombits,\r\n        uint tobits,\r\n        bool pad\r\n    ) internal pure returns (bytes memory) {\r\n        return _convertBits(data, frombits, tobits, pad);\r\n    }\r\n\r\n    function _convertBits(\r\n        uint8[] memory dataBits,\r\n        uint frombits,\r\n        uint tobits,\r\n        bool pad\r\n    ) internal pure returns (bytes memory ret) {\r\n        uint acc = 0;\r\n        uint bits = 0;\r\n\r\n        uint maxv = (1 << tobits) - 1;\r\n\r\n        unchecked {\r\n            for (uint p; p < dataBits.length; ++p) {\r\n                uint8 value = dataBits[p];\r\n                require(\r\n                    value >= 0 && (value >> frombits) == 0,\r\n                    \"Bech32: value must be non-negative and fit in frombits\"\r\n                );\r\n\r\n                acc = (acc << frombits) | value;\r\n                bits += frombits;\r\n\r\n                while (bits >= tobits) {\r\n                    bits -= tobits;\r\n                    ret = abi.encodePacked(\r\n                        ret,\r\n                        bytes1(uint8((acc >> bits) & maxv))\r\n                    );\r\n                }\r\n            }\r\n        }\r\n\r\n        if (pad) {\r\n            if (bits > 0) {\r\n                ret = abi.encodePacked(\r\n                    ret,\r\n                    bytes1(uint8((acc << (tobits - bits)) & maxv))\r\n                );\r\n            }\r\n        } else {\r\n            require(\r\n                bits < frombits || ((acc << (tobits - bits)) & maxv) == 0,\r\n                \"Bech32: invalid padding or value size\"\r\n            );\r\n        }\r\n    }\r\n}"
      },
      "project/contracts/libs/Create3.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/// @notice Deploy to deterministic addresses without an initcode factor.\r\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/CREATE3.sol)\r\n/// @author 0xSequence (https://github.com/0xSequence/create3/blob/master/contracts/Create3.sol)\r\n\r\nlibrary Create3 {\r\n\r\n    //--------------------------------------------------------------------------------//\r\n    // Opcode     | Opcode + Arguments    | Description      | Stack View             //\r\n    //--------------------------------------------------------------------------------//\r\n    // 0x36       |  0x36                 | CALLDATASIZE     | size                   //\r\n    // 0x3d       |  0x3d                 | RETURNDATASIZE   | 0 size                 //\r\n    // 0x3d       |  0x3d                 | RETURNDATASIZE   | 0 0 size               //\r\n    // 0x37       |  0x37                 | CALLDATACOPY     |                        //\r\n    // 0x36       |  0x36                 | CALLDATASIZE     | size                   //\r\n    // 0x3d       |  0x3d                 | RETURNDATASIZE   | 0 size                 //\r\n    // 0x34       |  0x34                 | CALLVALUE        | value 0 size           //\r\n    // 0xf0       |  0xf0                 | CREATE           | newContract            //\r\n    //--------------------------------------------------------------------------------//\r\n    // Opcode     | Opcode + Arguments    | Description      | Stack View             //\r\n    //--------------------------------------------------------------------------------//\r\n    // 0x67       |  0x67XXXXXXXXXXXXXXXX | PUSH8 bytecode   | bytecode               //\r\n    // 0x3d       |  0x3d                 | RETURNDATASIZE   | 0 bytecode             //\r\n    // 0x52       |  0x52                 | MSTORE           |                        //\r\n    // 0x60       |  0x6008               | PUSH1 08         | 8                      //\r\n    // 0x60       |  0x6018               | PUSH1 18         | 24 8                   //\r\n    // 0xf3       |  0xf3                 | RETURN           |                        //\r\n    //--------------------------------------------------------------------------------//\r\n    \r\n    bytes internal constant CREATE3_FACTORY_BYTECODE = hex\"67_36_3d_3d_37_36_3d_34_f0_3d_52_60_08_60_18_f3\";\r\n    bytes32 internal constant CREATE3_FACTORY_CODEHASH = keccak256(CREATE3_FACTORY_BYTECODE);\r\n\r\n    /// @notice Creates a new contract with given `_creationCode` and `_salt`\r\n    /// @param _salt Salt of the contract creation, resulting address will be derivated from this value only\r\n    /// @param _creationCode Creation code (constructor) of the contract to be deployed, this value doesn't affect the resulting address\r\n    /// @return addr of the deployed contract, reverts on error\r\n    function deploy(bytes32 _salt, bytes memory _creationCode)\r\n        internal \r\n        returns (address)\r\n    {\r\n        return deploy(_salt, _creationCode, 0);\r\n    }\r\n\r\n    /// @notice Creates a new contract with given `_creationCode`, `_salt` and `_value`. \r\n    /// @param _salt Salt of the contract creation, resulting address will be derivated from this value only\r\n    /// @param _creationCode Creation code (constructor) of the contract to be deployed, this value doesn't affect the resulting address\r\n    /// @param _value In WEI of ETH to be forwarded to child contract\r\n    /// @return _deployed The address of the deployed contract.\r\n    function deploy(bytes32 _salt, bytes memory _creationCode, uint256 _value)\r\n        internal\r\n        returns (address _deployed)\r\n    {\r\n        // Get target final address\r\n        _deployed = determineAddr(_salt);\r\n        if (_deployed.code.length != 0) revert(\"Create3: target already exists\");\r\n\r\n        // Create factory\r\n        address _factory;\r\n        bytes memory _factoryBytecode = CREATE3_FACTORY_BYTECODE;\r\n        /// @solidity memory-safe-assembly\r\n        assembly {\r\n            // Deploy a factory contract with our pre-made bytecode via CREATE2.\r\n            // We start 32 bytes into the code to avoid copying the byte length.\r\n            _factory := create2(0, add(_factoryBytecode, 32), mload(_factoryBytecode), _salt)\r\n        }\r\n        require(_factory != address(0), \"Create3: error creating factory\");       \r\n\r\n        // Use factory to deploy target\r\n        (bool _success, ) = _factory.call{value: _value}(_creationCode);\r\n        require(_success && _deployed.code.length != 0, \"Create3: error creating target\");\r\n    }\r\n\r\n    /// @notice Computes the resulting address of a contract deployed using address(this) and the given `_salt`\r\n    /// @param _salt Salt of the contract creation, resulting address will be derivated from this value only\r\n    /// @return addr of the deployed contract, reverts on error\r\n    /// @dev The address creation formula is: keccak256(rlp([keccak256(0xff ++ address(this) ++ _salt ++ keccak256(childBytecode))[12:], 0x01]))\r\n    function determineAddr(bytes32 _salt) internal view returns (address) {\r\n        address _factory = address(\r\n            uint160(\r\n                uint256(\r\n                    keccak256(\r\n                        abi.encodePacked(\r\n                            hex'ff',\r\n                            address(this),\r\n                            _salt,\r\n                            CREATE3_FACTORY_CODEHASH\r\n                        )\r\n                    )\r\n                )\r\n            )\r\n        );\r\n        return address(\r\n            uint160(\r\n                uint256(\r\n                    keccak256(\r\n                        abi.encodePacked(\r\n                            // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ _factory ++ 0x01)\r\n                            // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex)\r\n                            hex\"d6_94\",\r\n                            _factory,\r\n                            // _factory's nonce on which the target is created: 0x1\r\n                            hex\"01\"\r\n                        )\r\n                    )\r\n                )\r\n            )\r\n        );\r\n    }\r\n\r\n}"
      },
      "project/contracts/libs/Secp256k1.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >= 0.8.17;\r\n\r\n/**\r\n * @title Secp256k1 public key recovery Library\r\n * @dev Library providing arithmetic operations over signed `secpk256k1` signed message due to recover the signer public key EC point in `Solidity`.\r\n * @author cyphered.eth\r\n */\r\nlibrary Secp256k1 {\r\n    // Elliptic curve Constants\r\n    uint256 private constant U255_MAX_PLUS_1 =\r\n        57896044618658097711785492504343953926634992332820282019728792003956564819968;\r\n\r\n    // Curve Constants\r\n    uint256 private constant A = 0;\r\n    uint256 private constant B = 7;\r\n    uint256 private constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;\r\n    uint256 private constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;\r\n    uint256 private constant P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;\r\n    uint256 private constant N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;\r\n\r\n    /// @dev recovers signer public key point value.\r\n    /// @param digest hashed message\r\n    /// @param v recovery\r\n    /// @param r first 32 bytes of signature\r\n    /// @param v last 32 bytes of signature\r\n    /// @return (x, y) EC point\r\n    function recover(\r\n        uint256 digest,\r\n        uint8 v,\r\n        uint256 r,\r\n        uint256 s\r\n    ) internal pure returns (uint256, uint256) {\r\n        uint256 x = addmod(r, P * (v >> 1), P);\r\n        if (x > P || s > N || r > N || s == 0 || r == 0 || v > 1) {\r\n            return (0, 0);\r\n        }\r\n        uint256 rInv = invMod(r, N);\r\n\r\n        uint256 y2 = addmod(mulmod(x, mulmod(x, x, P), P), addmod(mulmod(x, A, P), B, P), P);\r\n        y2 = expMod(y2, (P + 1) / 4);\r\n        uint256 y = ((y2 + v + 2) & 1 == 0) ? y2 : P - y2;\r\n\r\n        (uint256 qx, uint256 qy, uint256 qz) = jacMul(mulmod(rInv, N - digest, N), GX, GY, 1);\r\n        (uint256 qx2, uint256 qy2, uint256 qz2) = jacMul(mulmod(rInv, s, N), x, y, 1);\r\n        (uint256 qx3, uint256 qy3) = ecAdd(qx, qy, qz, qx2, qy2, qz2);\r\n\r\n        return (qx3, qy3);\r\n    }\r\n\r\n    /// @dev Modular exponentiation, b^e % P.\r\n    /// Source: https://github.com/witnet/elliptic-curve-solidity/blob/master/contracts/EllipticCurve.sol\r\n    /// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol\r\n    /// @param _base base\r\n    /// @param _exp exponent\r\n    /// @return r such that r = b**e (mod P)\r\n    function expMod(uint256 _base, uint256 _exp) internal pure returns (uint256) {\r\n        if (_base == 0) return 0;\r\n        if (_exp == 0) return 1;\r\n\r\n        uint256 r = 1;\r\n        uint256 bit = U255_MAX_PLUS_1;\r\n        assembly {\r\n            for {\r\n\r\n            } gt(bit, 0) {\r\n\r\n            } {\r\n                r := mulmod(mulmod(r, r, P), exp(_base, iszero(iszero(and(_exp, bit)))), P)\r\n                r := mulmod(mulmod(r, r, P), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), P)\r\n                r := mulmod(mulmod(r, r, P), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), P)\r\n                r := mulmod(mulmod(r, r, P), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), P)\r\n                bit := div(bit, 16)\r\n            }\r\n        }\r\n\r\n        return r;\r\n    }\r\n\r\n    /// @dev Adds two points (x1, y1, z1) and (x2 y2, z2).\r\n    /// Source: https://github.com/witnet/elliptic-curve-solidity/blob/master/contracts/EllipticCurve.sol\r\n    /// @param _x1 coordinate x of P1\r\n    /// @param _y1 coordinate y of P1\r\n    /// @param _z1 coordinate z of P1\r\n    /// @param _x2 coordinate x of square\r\n    /// @param _y2 coordinate y of square\r\n    /// @param _z2 coordinate z of square\r\n    /// @return (qx, qy, qz) P1+square in Jacobian\r\n    function jacAdd(\r\n        uint256 _x1,\r\n        uint256 _y1,\r\n        uint256 _z1,\r\n        uint256 _x2,\r\n        uint256 _y2,\r\n        uint256 _z2\r\n    )\r\n        internal\r\n        pure\r\n        returns (\r\n            uint256,\r\n            uint256,\r\n            uint256\r\n        )\r\n    {\r\n        if (_x1 == 0 && _y1 == 0) return (_x2, _y2, _z2);\r\n        if (_x2 == 0 && _y2 == 0) return (_x1, _y1, _z1);\r\n\r\n        // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5\r\n        uint256[4] memory zs; // z1^2, z1^3, z2^2, z2^3\r\n        zs[0] = mulmod(_z1, _z1, P);\r\n        zs[1] = mulmod(_z1, zs[0], P);\r\n        zs[2] = mulmod(_z2, _z2, P);\r\n        zs[3] = mulmod(_z2, zs[2], P);\r\n\r\n        // u1, s1, u2, s2\r\n        zs = [mulmod(_x1, zs[2], P), mulmod(_y1, zs[3], P), mulmod(_x2, zs[0], P), mulmod(_y2, zs[1], P)];\r\n\r\n        // In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used\r\n        require(zs[0] != zs[2] || zs[1] != zs[3], 'Use jacDouble function instead');\r\n\r\n        uint256[4] memory hr;\r\n        //h\r\n        hr[0] = addmod(zs[2], P - zs[0], P);\r\n        //r\r\n        hr[1] = addmod(zs[3], P - zs[1], P);\r\n        //h^2\r\n        hr[2] = mulmod(hr[0], hr[0], P);\r\n        // h^3\r\n        hr[3] = mulmod(hr[2], hr[0], P);\r\n        // qx = -h^3  -2u1h^2+r^2\r\n        uint256 qx = addmod(mulmod(hr[1], hr[1], P), P - hr[3], P);\r\n        qx = addmod(qx, P - mulmod(2, mulmod(zs[0], hr[2], P), P), P);\r\n        // qy = -s1*z1*h^3+r(u1*h^2 -x^3)\r\n        uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], P), P - qx, P), P);\r\n        qy = addmod(qy, P - mulmod(zs[1], hr[3], P), P);\r\n        // qz = h*z1*z2\r\n        uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, P), P);\r\n        return (qx, qy, qz);\r\n    }\r\n\r\n    /// @dev Multiply point (x, y, z) times d.\r\n    /// Source: https://github.com/witnet/elliptic-curve-solidity/blob/master/contracts/EllipticCurve.sol\r\n    /// @param _d scalar to multiply\r\n    /// @param _x coordinate x of P1\r\n    /// @param _y coordinate y of P1\r\n    /// @param _z coordinate z of P1\r\n    /// @return (qx, qy, qz) d*P1 in Jacobian\r\n    function jacMul(\r\n        uint256 _d,\r\n        uint256 _x,\r\n        uint256 _y,\r\n        uint256 _z\r\n    )\r\n        internal\r\n        pure\r\n        returns (\r\n            uint256,\r\n            uint256,\r\n            uint256\r\n        )\r\n    {\r\n        // Early return in case that `_d == 0`\r\n        if (_d == 0) {\r\n            return (_x, _y, _z);\r\n        }\r\n\r\n        uint256 remaining = _d;\r\n        uint256 qx = 0;\r\n        uint256 qy = 0;\r\n        uint256 qz = 1;\r\n\r\n        // Double and add algorithm\r\n        while (remaining != 0) {\r\n            if ((remaining & 1) != 0) {\r\n                (qx, qy, qz) = jacAdd(qx, qy, qz, _x, _y, _z);\r\n            }\r\n            remaining = remaining / 2;\r\n            (_x, _y, _z) = jacDouble(_x, _y, _z);\r\n        }\r\n        return (qx, qy, qz);\r\n    }\r\n\r\n    /// @dev Doubles a points (x, y, z).\r\n    /// Source: https://github.com/witnet/elliptic-curve-solidity/blob/master/contracts/EllipticCurve.sol\r\n    /// @param _x coordinate x of P1\r\n    /// @param _y coordinate y of P1\r\n    /// @param _z coordinate z of P1\r\n    /// @return (qx, qy, qz) 2P in Jacobian\r\n    function jacDouble(\r\n        uint256 _x,\r\n        uint256 _y,\r\n        uint256 _z\r\n    )\r\n        internal\r\n        pure\r\n        returns (\r\n            uint256,\r\n            uint256,\r\n            uint256\r\n        )\r\n    {\r\n        if (_z == 0) return (_x, _y, _z);\r\n\r\n        // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5\r\n        // Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4)\r\n        // x, y, z at this point represent the squares of _x, _y, _z\r\n        uint256 x = mulmod(_x, _x, P); //x1^2\r\n        uint256 y = mulmod(_y, _y, P); //y1^2\r\n        uint256 z = mulmod(_z, _z, P); //z1^2\r\n\r\n        // s\r\n        uint256 s = mulmod(4, mulmod(_x, y, P), P);\r\n        // m\r\n        uint256 m = addmod(mulmod(3, x, P), mulmod(A, mulmod(z, z, P), P), P);\r\n\r\n        // x, y, z at this point will be reassigned and rather represent qx, qy, qz from the paper\r\n        // This allows to reduce the gas cost and stack footprint of the algorithm\r\n        // qx\r\n        x = addmod(mulmod(m, m, P), P - addmod(s, s, P), P);\r\n        // qy = -8*y1^4 + M(S-T)\r\n        y = addmod(mulmod(m, addmod(s, P - x, P), P), P - mulmod(8, mulmod(y, y, P), P), P);\r\n        // qz = 2*y1*z1\r\n        z = mulmod(2, mulmod(_y, _z, P), P);\r\n\r\n        return (x, y, z);\r\n    }\r\n\r\n    /// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates.\r\n    /// Source: https://github.com/witnet/elliptic-curve-solidity/blob/master/contracts/EllipticCurve.sol\r\n    /// @param _x1 coordinate x of P1\r\n    /// @param _y1 coordinate y of P1\r\n    /// @param _x2 coordinate x of P2\r\n    /// @param _y2 coordinate y of P2\r\n    /// @return (qx, qy) = P1+P2 in affine coordinates\r\n    function ecAdd(\r\n        uint256 _x1,\r\n        uint256 _y1,\r\n        uint256 _z1,\r\n        uint256 _x2,\r\n        uint256 _y2,\r\n        uint256 _z2\r\n    ) internal pure returns (uint256, uint256) {\r\n        uint256 x = 0;\r\n        uint256 y = 0;\r\n        uint256 z = 0;\r\n\r\n        // Double if x1==x2 else add\r\n        if (_x1 == _x2) {\r\n            // y1 = -y2 mod p\r\n            if (addmod(_y1, _y2, P) == 0) {\r\n                return (0, 0);\r\n            } else {\r\n                // P1 = P2\r\n                (x, y, z) = jacDouble(_x1, _y1, _z1);\r\n            }\r\n        } else {\r\n            (x, y, z) = jacAdd(_x1, _y1, _z1, _x2, _y2, _z2);\r\n        }\r\n        // Get back to affine\r\n        return toAffine(x, y, z);\r\n    }\r\n\r\n    /// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1).\r\n    /// Source: https://github.com/witnet/elliptic-curve-solidity/blob/master/contracts/EllipticCurve.sol\r\n    /// @param _x coordinate x\r\n    /// @param _y coordinate y\r\n    /// @param _z coordinate z\r\n    /// @return (x', y') affine coordinates\r\n    function toAffine(\r\n        uint256 _x,\r\n        uint256 _y,\r\n        uint256 _z\r\n    ) internal pure returns (uint256, uint256) {\r\n        uint256 zInv = invMod(_z, P);\r\n        uint256 zInv2 = mulmod(zInv, zInv, P);\r\n        uint256 x2 = mulmod(_x, zInv2, P);\r\n        uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, P), P);\r\n\r\n        return (x2, y2);\r\n    }\r\n\r\n    /// @dev Modular euclidean inverse of a number (mod p).\r\n    /// Source: https://github.com/witnet/elliptic-curve-solidity/blob/master/contracts/EllipticCurve.sol\r\n    /// @param _x The number\r\n    /// @param _pp The modulus\r\n    /// @return q such that x*q = 1 (mod _pp)\r\n    function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) {\r\n        require(_x != 0 && _x != _pp && _pp != 0, 'Invalid number');\r\n        uint256 q = 0;\r\n        uint256 newT = 1;\r\n        uint256 r = _pp;\r\n        uint256 t;\r\n        while (_x != 0) {\r\n            t = r / _x;\r\n            (q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp));\r\n            (r, _x) = (_x, r - t * _x);\r\n        }\r\n\r\n        return q;\r\n    }\r\n}"
      },
      "project/contracts/libs/Slices.sol": {
        "content": "// SPDX-License-Identifier: APACHE-2.0\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\n/*\r\n * @title String & Slice utility library for Solidity contracts.\r\n * @author Nick Johnson <arachnid@notdot.net>\r\n *\r\n * @dev Functionality in this library is largely implemented using an\r\n *      abstraction called a 'Slice'. A Slice represents a part of a string -\r\n *      anything from the entire string to a single character, or even no\r\n *      characters at all (a 0-length Slice). Since a Slice only has to specify\r\n *      an offset and a length, copying and manipulating slices is a lot less\r\n *      expensive than copying and manipulating the strings they reference.\r\n *\r\n *      To further reduce gas costs, most functions on Slice that need to return\r\n *      a Slice modify the original one instead of allocating a new one; for\r\n *      instance, `s.split(\".\")` will return the text up to the first '.',\r\n *      modifying s to only contain the remainder of the string after the '.'.\r\n *      In situations where you do not want to modify the original Slice, you\r\n *      can make a copy first with `.copy()`, for example:\r\n *      `s.copy().split(\".\")`. Try and avoid using this idiom in loops; since\r\n *      Solidity has no memory management, it will result in allocating many\r\n *      short-lived slices that are later discarded.\r\n *\r\n *      Functions that return two slices come in two versions: a non-allocating\r\n *      version that takes the second Slice as an argument, modifying it in\r\n *      place, and an allocating version that allocates and returns the second\r\n *      Slice; see `nextRune` for example.\r\n *\r\n *      Functions that have to copy string data will return strings rather than\r\n *      slices; these can be cast back to slices for further processing if\r\n *      required.\r\n *\r\n *      For convenience, some functions are provided with non-modifying\r\n *      variants that create a new Slice and return both; for instance,\r\n *      `s.splitNew('.')` leaves s unmodified, and returns two values\r\n *      corresponding to the left and right parts of the string.\r\n */\r\n\r\nlibrary Slices {\r\n    \r\n    struct Slice {\r\n        uint _len;\r\n        uint _ptr;\r\n    }\r\n\r\n    function _memcpy(uint _dest, uint _src, uint _len) private pure {\r\n        // Copy word-length chunks while possible\r\n        for(; _len >= 32; _len -= 32) {\r\n            assembly {\r\n                mstore(_dest, mload(_src))\r\n            }\r\n            _dest += 32;\r\n            _src += 32;\r\n        }\r\n\r\n        // Copy remaining bytes\r\n        uint _mask = type(uint).max;\r\n        if (_len > 0) {\r\n            _mask = 256 ** (32 - _len) - 1;\r\n        }\r\n        assembly {\r\n            let srcpart := and(mload(_src), not(_mask))\r\n            let destpart := and(mload(_dest), _mask)\r\n            mstore(_dest, or(destpart, srcpart))\r\n        }\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a Slice containing the entire string.\r\n     * @param self The string to make a Slice from.\r\n     * @return A newly allocated Slice containing the entire string.\r\n     */\r\n    function toSlice(string memory self) internal pure returns (Slice memory) {\r\n        uint ptr;\r\n        assembly {\r\n            ptr := add(self, 0x20)\r\n        }\r\n        return Slice(bytes(self).length, ptr);\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the length of a null-terminated bytes32 string.\r\n     * @param self The value to find the length of.\r\n     * @return The length of the string, from 0 to 32.\r\n     */\r\n    function len(bytes32 self) internal pure returns (uint) {\r\n        uint ret;\r\n        if (self == 0)\r\n            return 0;\r\n        if (uint(self) & type(uint128).max == 0) {\r\n            ret += 16;\r\n            self = bytes32(uint(self) / 0x100000000000000000000000000000000);\r\n        }\r\n        if (uint(self) & type(uint64).max == 0) {\r\n            ret += 8;\r\n            self = bytes32(uint(self) / 0x10000000000000000);\r\n        }\r\n        if (uint(self) & type(uint32).max == 0) {\r\n            ret += 4;\r\n            self = bytes32(uint(self) / 0x100000000);\r\n        }\r\n        if (uint(self) & type(uint16).max == 0) {\r\n            ret += 2;\r\n            self = bytes32(uint(self) / 0x10000);\r\n        }\r\n        if (uint(self) & type(uint8).max == 0) {\r\n            ret += 1;\r\n        }\r\n        return 32 - ret;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a Slice containing the entire bytes32, interpreted as a\r\n     *      null-terminated utf-8 string.\r\n     * @param self The bytes32 value to convert to a Slice.\r\n     * @return A new Slice containing the value of the input argument up to the\r\n     *         first null.\r\n     */\r\n    function toSliceB32(bytes32 self) internal pure returns (Slice memory ret) {\r\n        // Allocate space for `self` in memory, copy it there, and point ret at it\r\n        assembly {\r\n            let ptr := mload(0x40)\r\n            mstore(0x40, add(ptr, 0x20))\r\n            mstore(ptr, self)\r\n            mstore(add(ret, 0x20), ptr)\r\n        }\r\n        ret._len = len(self);\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a new Slice containing the same data as the current Slice.\r\n     * @param self The Slice to copy.\r\n     * @return A new Slice containing the same data as `self`.\r\n     */\r\n    function copy(Slice memory self) internal pure returns (Slice memory) {\r\n        return Slice(self._len, self._ptr);\r\n    }\r\n\r\n    /*\r\n     * @dev Copies a Slice to a new string.\r\n     * @param self The Slice to copy.\r\n     * @return A newly allocated string containing the Slice's text.\r\n     */\r\n    function toString(Slice memory self) internal pure returns (string memory) {\r\n        string memory ret = new string(self._len);\r\n        uint retptr;\r\n        assembly { retptr := add(ret, 32) }\r\n\r\n        _memcpy(retptr, self._ptr, self._len);\r\n        return ret;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the length in runes of the Slice. Note that this operation\r\n     *      takes time proportional to the length of the Slice; avoid using it\r\n     *      in loops, and call `Slice.empty()` if you only need to know whether\r\n     *      the Slice is empty or not.\r\n     * @param self The Slice to operate on.\r\n     * @return The length of the Slice in runes.\r\n     */\r\n    function len(Slice memory self) internal pure returns (uint _l) {\r\n        // Starting at ptr-31 means the LSB will be the byte we care about\r\n        uint ptr = self._ptr - 31;\r\n        uint end = ptr + self._len;\r\n        for (_l = 0; ptr < end; _l++) {\r\n            uint8 b;\r\n            assembly { b := and(mload(ptr), 0xFF) }\r\n            if (b < 0x80) {\r\n                ptr += 1;\r\n            } else if(b < 0xE0) {\r\n                ptr += 2;\r\n            } else if(b < 0xF0) {\r\n                ptr += 3;\r\n            } else if(b < 0xF8) {\r\n                ptr += 4;\r\n            } else if(b < 0xFC) {\r\n                ptr += 5;\r\n            } else {\r\n                ptr += 6;\r\n            }\r\n        }\r\n    }\r\n\r\n    /*\r\n     * @dev Returns true if the Slice is empty (has a length of 0).\r\n     * @param self The Slice to operate on.\r\n     * @return True if the Slice is empty, False otherwise.\r\n     */\r\n    function empty(Slice memory self) internal pure returns (bool) {\r\n        return self._len == 0;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a positive number if `other` comes lexicographically after\r\n     *      `self`, a negative number if it comes before, or zero if the\r\n     *      contents of the two slices are equal. Comparison is done per-rune,\r\n     *      on unicode codepoints.\r\n     * @param self The first Slice to compare.\r\n     * @param other The second Slice to compare.\r\n     * @return The result of the comparison.\r\n     */\r\n    function compare(Slice memory self, Slice memory other) internal pure returns (int) {\r\n        uint shortest = self._len;\r\n        if (other._len < self._len)\r\n            shortest = other._len;\r\n\r\n        uint selfptr = self._ptr;\r\n        uint otherptr = other._ptr;\r\n        for (uint idx = 0; idx < shortest; idx += 32) {\r\n            uint a;\r\n            uint b;\r\n            assembly {\r\n                a := mload(selfptr)\r\n                b := mload(otherptr)\r\n            }\r\n            if (a != b) {\r\n                // Mask out irrelevant bytes and check again\r\n                uint mask = type(uint).max; // 0xffff...\r\n                if(shortest < 32) {\r\n                  mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);\r\n                }\r\n                unchecked {\r\n                    uint diff = (a & mask) - (b & mask);\r\n                    if (diff != 0)\r\n                        return int(diff);\r\n                }\r\n            }\r\n            selfptr += 32;\r\n            otherptr += 32;\r\n        }\r\n        return int(self._len) - int(other._len);\r\n    }\r\n\r\n    /*\r\n     * @dev Returns true if the two slices contain the same text.\r\n     * @param self The first Slice to compare.\r\n     * @param self The second Slice to compare.\r\n     * @return True if the slices are equal, false otherwise.\r\n     */\r\n    function equals(Slice memory self, Slice memory other) internal pure returns (bool) {\r\n        return compare(self, other) == 0;\r\n    }\r\n\r\n    /*\r\n     * @dev Extracts the first rune in the Slice into `rune`, advancing the\r\n     *      Slice to point to the next rune and returning `self`.\r\n     * @param self The Slice to operate on.\r\n     * @param rune The Slice that will contain the first rune.\r\n     * @return `rune`.\r\n     */\r\n    function nextRune(Slice memory self, Slice memory rune) internal pure returns (Slice memory) {\r\n        rune._ptr = self._ptr;\r\n\r\n        if (self._len == 0) {\r\n            rune._len = 0;\r\n            return rune;\r\n        }\r\n\r\n        uint _l;\r\n        uint _b;\r\n        // Load the first byte of the rune into the LSBs of _b\r\n        assembly { _b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }\r\n        if (_b < 0x80) {\r\n            _l = 1;\r\n        } else if(_b < 0xE0) {\r\n            _l = 2;\r\n        } else if(_b < 0xF0) {\r\n            _l = 3;\r\n        } else {\r\n            _l = 4;\r\n        }\r\n\r\n        // Check for truncated codepoints\r\n        if (_l > self._len) {\r\n            rune._len = self._len;\r\n            self._ptr += self._len;\r\n            self._len = 0;\r\n            return rune;\r\n        }\r\n\r\n        self._ptr += _l;\r\n        self._len -= _l;\r\n        rune._len = _l;\r\n        return rune;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the first rune in the Slice, advancing the Slice to point\r\n     *      to the next rune.\r\n     * @param self The Slice to operate on.\r\n     * @return A Slice containing only the first rune from `self`.\r\n     */\r\n    function nextRune(Slice memory self) internal pure returns (Slice memory ret) {\r\n        nextRune(self, ret);\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the number of the first codepoint in the Slice.\r\n     * @param self The Slice to operate on.\r\n     * @return The number of the first codepoint in the Slice.\r\n     */\r\n    function ord(Slice memory self) internal pure returns (uint ret) {\r\n        if (self._len == 0) {\r\n            return 0;\r\n        }\r\n\r\n        uint word;\r\n        uint length;\r\n        uint divisor = 2 ** 248;\r\n\r\n        // Load the rune into the MSBs of b\r\n        assembly { word:= mload(mload(add(self, 32))) }\r\n        uint b = word / divisor;\r\n        if (b < 0x80) {\r\n            ret = b;\r\n            length = 1;\r\n        } else if(b < 0xE0) {\r\n            ret = b & 0x1F;\r\n            length = 2;\r\n        } else if(b < 0xF0) {\r\n            ret = b & 0x0F;\r\n            length = 3;\r\n        } else {\r\n            ret = b & 0x07;\r\n            length = 4;\r\n        }\r\n\r\n        // Check for truncated codepoints\r\n        if (length > self._len) {\r\n            return 0;\r\n        }\r\n\r\n        for (uint i = 1; i < length; i++) {\r\n            divisor = divisor / 256;\r\n            b = (word / divisor) & 0xFF;\r\n            if (b & 0xC0 != 0x80) {\r\n                // Invalid UTF-8 sequence\r\n                return 0;\r\n            }\r\n            ret = (ret * 64) | (b & 0x3F);\r\n        }\r\n\r\n        return ret;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the keccak-256 hash of the Slice.\r\n     * @param self The Slice to hash.\r\n     * @return The hash of the Slice.\r\n     */\r\n    function keccak(Slice memory self) internal pure returns (bytes32 ret) {\r\n        assembly {\r\n            ret := keccak256(mload(add(self, 32)), mload(self))\r\n        }\r\n    }\r\n\r\n    /*\r\n     * @dev Returns true if `self` starts with `needle`.\r\n     * @param self The Slice to operate on.\r\n     * @param needle The Slice to search for.\r\n     * @return True if the Slice starts with the provided text, false otherwise.\r\n     */\r\n    function startsWith(Slice memory self, Slice memory needle) internal pure returns (bool) {\r\n        if (self._len < needle._len) {\r\n            return false;\r\n        }\r\n\r\n        if (self._ptr == needle._ptr) {\r\n            return true;\r\n        }\r\n\r\n        bool equal;\r\n        assembly {\r\n            let length := mload(needle)\r\n            let selfptr := mload(add(self, 0x20))\r\n            let needleptr := mload(add(needle, 0x20))\r\n            equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n        }\r\n        return equal;\r\n    }\r\n\r\n    /*\r\n     * @dev If `self` starts with `needle`, `needle` is removed from the\r\n     *      beginning of `self`. Otherwise, `self` is unmodified.\r\n     * @param self The Slice to operate on.\r\n     * @param needle The Slice to search for.\r\n     * @return `self`\r\n     */\r\n    function beyond(Slice memory self, Slice memory needle) internal pure returns (Slice memory) {\r\n        if (self._len < needle._len) {\r\n            return self;\r\n        }\r\n\r\n        bool equal = true;\r\n        if (self._ptr != needle._ptr) {\r\n            assembly {\r\n                let length := mload(needle)\r\n                let selfptr := mload(add(self, 0x20))\r\n                let needleptr := mload(add(needle, 0x20))\r\n                equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n            }\r\n        }\r\n\r\n        if (equal) {\r\n            self._len -= needle._len;\r\n            self._ptr += needle._len;\r\n        }\r\n\r\n        return self;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns true if the Slice ends with `needle`.\r\n     * @param self The Slice to operate on.\r\n     * @param needle The Slice to search for.\r\n     * @return True if the Slice starts with the provided text, false otherwise.\r\n     */\r\n    function endsWith(Slice memory self, Slice memory needle) internal pure returns (bool) {\r\n        if (self._len < needle._len) {\r\n            return false;\r\n        }\r\n\r\n        uint selfptr = self._ptr + self._len - needle._len;\r\n\r\n        if (selfptr == needle._ptr) {\r\n            return true;\r\n        }\r\n\r\n        bool equal;\r\n        assembly {\r\n            let length := mload(needle)\r\n            let needleptr := mload(add(needle, 0x20))\r\n            equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n        }\r\n\r\n        return equal;\r\n    }\r\n\r\n    /*\r\n     * @dev If `self` ends with `needle`, `needle` is removed from the\r\n     *      end of `self`. Otherwise, `self` is unmodified.\r\n     * @param self The Slice to operate on.\r\n     * @param needle The Slice to search for.\r\n     * @return `self`\r\n     */\r\n    function until(Slice memory self, Slice memory needle) internal pure returns (Slice memory) {\r\n        if (self._len < needle._len) {\r\n            return self;\r\n        }\r\n\r\n        uint selfptr = self._ptr + self._len - needle._len;\r\n        bool equal = true;\r\n        if (selfptr != needle._ptr) {\r\n            assembly {\r\n                let length := mload(needle)\r\n                let needleptr := mload(add(needle, 0x20))\r\n                equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n            }\r\n        }\r\n\r\n        if (equal) {\r\n            self._len -= needle._len;\r\n        }\r\n\r\n        return self;\r\n    }\r\n\r\n    // Returns the memory address of the first byte of the first occurrence of\r\n    // `needle` in `self`, or the first byte after `self` if not found.\r\n    function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\r\n        uint ptr = selfptr;\r\n        uint idx;\r\n\r\n        if (needlelen <= selflen) {\r\n            if (needlelen <= 32) {\r\n                bytes32 mask;\r\n                if (needlelen > 0) {\r\n                    mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\r\n                }\r\n\r\n                bytes32 needledata;\r\n                assembly { needledata := and(mload(needleptr), mask) }\r\n\r\n                uint end = selfptr + selflen - needlelen;\r\n                bytes32 ptrdata;\r\n                assembly { ptrdata := and(mload(ptr), mask) }\r\n\r\n                while (ptrdata != needledata) {\r\n                    if (ptr >= end)\r\n                        return selfptr + selflen;\r\n                    ptr++;\r\n                    assembly { ptrdata := and(mload(ptr), mask) }\r\n                }\r\n                return ptr;\r\n            } else {\r\n                // For long needles, use hashing\r\n                bytes32 hash;\r\n                assembly { hash := keccak256(needleptr, needlelen) }\r\n\r\n                for (idx = 0; idx <= selflen - needlelen; idx++) {\r\n                    bytes32 testHash;\r\n                    assembly { testHash := keccak256(ptr, needlelen) }\r\n                    if (hash == testHash)\r\n                        return ptr;\r\n                    ptr += 1;\r\n                }\r\n            }\r\n        }\r\n        return selfptr + selflen;\r\n    }\r\n\r\n    // Returns the memory address of the first byte after the last occurrence of\r\n    // `needle` in `self`, or the address of `self` if not found.\r\n    function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\r\n        uint ptr;\r\n\r\n        if (needlelen <= selflen) {\r\n            if (needlelen <= 32) {\r\n                bytes32 mask;\r\n                if (needlelen > 0) {\r\n                    mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\r\n                }\r\n\r\n                bytes32 needledata;\r\n                assembly { needledata := and(mload(needleptr), mask) }\r\n\r\n                ptr = selfptr + selflen - needlelen;\r\n                bytes32 ptrdata;\r\n                assembly { ptrdata := and(mload(ptr), mask) }\r\n\r\n                while (ptrdata != needledata) {\r\n                    if (ptr <= selfptr)\r\n                        return selfptr;\r\n                    ptr--;\r\n                    assembly { ptrdata := and(mload(ptr), mask) }\r\n                }\r\n                return ptr + needlelen;\r\n            } else {\r\n                // For long needles, use hashing\r\n                bytes32 hash;\r\n                assembly { hash := keccak256(needleptr, needlelen) }\r\n                ptr = selfptr + (selflen - needlelen);\r\n                while (ptr >= selfptr) {\r\n                    bytes32 testHash;\r\n                    assembly { testHash := keccak256(ptr, needlelen) }\r\n                    if (hash == testHash)\r\n                        return ptr + needlelen;\r\n                    ptr -= 1;\r\n                }\r\n            }\r\n        }\r\n        return selfptr;\r\n    }\r\n\r\n    /*\r\n     * @dev Modifies `self` to contain everything from the first occurrence of\r\n     *      `needle` to the end of the Slice. `self` is set to the empty Slice\r\n     *      if `needle` is not found.\r\n     * @param self The Slice to search and modify.\r\n     * @param needle The text to search for.\r\n     * @return `self`.\r\n     */\r\n    function find(Slice memory self, Slice memory needle) internal pure returns (Slice memory) {\r\n        uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n        self._len -= ptr - self._ptr;\r\n        self._ptr = ptr;\r\n        return self;\r\n    }\r\n\r\n    /*\r\n     * @dev Modifies `self` to contain the part of the string from the start of\r\n     *      `self` to the end of the first occurrence of `needle`. If `needle`\r\n     *      is not found, `self` is set to the empty Slice.\r\n     * @param self The Slice to search and modify.\r\n     * @param needle The text to search for.\r\n     * @return `self`.\r\n     */\r\n    function rfind(Slice memory self, Slice memory needle) internal pure returns (Slice memory) {\r\n        uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n        self._len = ptr - self._ptr;\r\n        return self;\r\n    }\r\n\r\n    /*\r\n     * @dev Splits the Slice, setting `self` to everything after the first\r\n     *      occurrence of `needle`, and `token` to everything before it. If\r\n     *      `needle` does not occur in `self`, `self` is set to the empty Slice,\r\n     *      and `token` is set to the entirety of `self`.\r\n     * @param self The Slice to split.\r\n     * @param needle The text to search for in `self`.\r\n     * @param token An output parameter to which the first token is written.\r\n     * @return `token`.\r\n     */\r\n    function split(Slice memory self, Slice memory needle, Slice memory token) internal pure returns (Slice memory) {\r\n        uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n        token._ptr = self._ptr;\r\n        token._len = ptr - self._ptr;\r\n        if (ptr == self._ptr + self._len) {\r\n            // Not found\r\n            self._len = 0;\r\n        } else {\r\n            self._len -= token._len + needle._len;\r\n            self._ptr = ptr + needle._len;\r\n        }\r\n        return token;\r\n    }\r\n\r\n    /*\r\n     * @dev Splits the Slice, setting `self` to everything after the first\r\n     *      occurrence of `needle`, and returning everything before it. If\r\n     *      `needle` does not occur in `self`, `self` is set to the empty Slice,\r\n     *      and the entirety of `self` is returned.\r\n     * @param self The Slice to split.\r\n     * @param needle The text to search for in `self`.\r\n     * @return The part of `self` up to the first occurrence of `delim`.\r\n     */\r\n    function split(Slice memory self, Slice memory needle) internal pure returns (Slice memory token) {\r\n        split(self, needle, token);\r\n    }\r\n\r\n    /*\r\n     * @dev Splits the Slice, setting `self` to everything before the last\r\n     *      occurrence of `needle`, and `token` to everything after it. If\r\n     *      `needle` does not occur in `self`, `self` is set to the empty Slice,\r\n     *      and `token` is set to the entirety of `self`.\r\n     * @param self The Slice to split.\r\n     * @param needle The text to search for in `self`.\r\n     * @param token An output parameter to which the first token is written.\r\n     * @return `token`.\r\n     */\r\n    function rsplit(Slice memory self, Slice memory needle, Slice memory token) internal pure returns (Slice memory) {\r\n        uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n        token._ptr = ptr;\r\n        token._len = self._len - (ptr - self._ptr);\r\n        if (ptr == self._ptr) {\r\n            // Not found\r\n            self._len = 0;\r\n        } else {\r\n            self._len -= token._len + needle._len;\r\n        }\r\n        return token;\r\n    }\r\n\r\n    /*\r\n     * @dev Splits the Slice, setting `self` to everything before the last\r\n     *      occurrence of `needle`, and returning everything after it. If\r\n     *      `needle` does not occur in `self`, `self` is set to the empty Slice,\r\n     *      and the entirety of `self` is returned.\r\n     * @param self The Slice to split.\r\n     * @param needle The text to search for in `self`.\r\n     * @return The part of `self` after the last occurrence of `delim`.\r\n     */\r\n    function rsplit(Slice memory self, Slice memory needle) internal pure returns (Slice memory token) {\r\n        rsplit(self, needle, token);\r\n    }\r\n\r\n    /*\r\n     * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.\r\n     * @param self The Slice to search.\r\n     * @param needle The text to search for in `self`.\r\n     * @return The number of occurrences of `needle` found in `self`.\r\n     */\r\n    function count(Slice memory self, Slice memory needle) internal pure returns (uint cnt) {\r\n        uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;\r\n        while (ptr <= self._ptr + self._len) {\r\n            cnt++;\r\n            ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;\r\n        }\r\n    }\r\n\r\n    /*\r\n     * @dev Returns True if `self` contains `needle`.\r\n     * @param self The Slice to search.\r\n     * @param needle The text to search for in `self`.\r\n     * @return True if `needle` is found in `self`, false otherwise.\r\n     */\r\n    function contains(Slice memory self, Slice memory needle) internal pure returns (bool) {\r\n        return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a newly allocated string containing the concatenation of\r\n     *      `self` and `other`.\r\n     * @param self The first Slice to concatenate.\r\n     * @param other The second Slice to concatenate.\r\n     * @return The concatenation of the two strings.\r\n     */\r\n    function concat(Slice memory self, Slice memory other) internal pure returns (string memory) {\r\n        string memory ret = new string(self._len + other._len);\r\n        uint retptr;\r\n        assembly { retptr := add(ret, 32) }\r\n        _memcpy(retptr, self._ptr, self._len);\r\n        _memcpy(retptr + self._len, other._ptr, other._len);\r\n        return ret;\r\n    }\r\n\r\n    /*\r\n     * @dev Joins an array of slices, using `self` as a delimiter, returning a\r\n     *      newly allocated string.\r\n     * @param self The delimiter to use.\r\n     * @param parts A list of slices to join.\r\n     * @return A newly allocated string containing all the slices in `parts`,\r\n     *         joined with `self`.\r\n     */\r\n    function join(Slice memory self, Slice[] memory parts) internal pure returns (string memory) {\r\n        if (parts.length == 0)\r\n            return \"\";\r\n\r\n        uint length = self._len * (parts.length - 1);\r\n        for(uint i = 0; i < parts.length; i++)\r\n            length += parts[i]._len;\r\n\r\n        string memory ret = new string(length);\r\n        uint retptr;\r\n        assembly { retptr := add(ret, 32) }\r\n\r\n        for(uint i = 0; i < parts.length; i++) {\r\n            _memcpy(retptr, parts[i]._ptr, parts[i]._len);\r\n            retptr += parts[i]._len;\r\n            if (i < parts.length - 1) {\r\n                _memcpy(retptr, self._ptr, self._len);\r\n                retptr += self._len;\r\n            }\r\n        }\r\n\r\n        return ret;\r\n    }\r\n}"
      },
      "project/contracts/libs/Witnet.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./Bech32.sol\";\r\nimport \"./Secp256k1.sol\";\r\nimport \"./WitnetCBOR.sol\";\r\n\r\nlibrary Witnet {\r\n\r\n    using Bech32 for Witnet.Address;\r\n    using WitnetBuffer for WitnetBuffer.Buffer;\r\n    using WitnetCBOR for WitnetCBOR.CBOR;\r\n    using WitnetCBOR for WitnetCBOR.CBOR[];\r\n\r\n    type Address is bytes20;\r\n\r\n    type BlockNumber is uint64;\r\n    \r\n    type QueryEvmReward is uint72;\r\n    type QueryUUID is bytes15;\r\n    type QueryId is uint64;\r\n\r\n    type RadonHash is bytes32;\r\n    type ServiceProvider is bytes20;\r\n    \r\n    type Timestamp is uint64;\r\n    type TransactionHash is bytes32;\r\n\r\n    uint32  constant internal WIT_1_GENESIS_TIMESTAMP = 0; // TBD    \r\n    uint32  constant internal WIT_1_SECS_PER_EPOCH = 45;\r\n\r\n    uint32  constant internal WIT_2_GENESIS_BEACON_INDEX = 0;       // TBD\r\n    uint32  constant internal WIT_2_GENESIS_BEACON_PREV_INDEX = 0;  // TBD\r\n    bytes24 constant internal WIT_2_GENESIS_BEACON_PREV_ROOT = 0;   // TBD\r\n    bytes16 constant internal WIT_2_GENESIS_BEACON_DDR_TALLIES_MERKLE_ROOT = 0;  // TBD\r\n    bytes16 constant internal WIT_2_GENESIS_BEACON_DRO_TALLIES_MERKLE_ROOT = 0;  // TBD\r\n    uint256 constant internal WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_0 = 0; // TBD\r\n    uint256 constant internal WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_1 = 0; // TBD\r\n    uint256 constant internal WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_2 = 0; // TBD\r\n    uint256 constant internal WIT_2_GENESIS_BEACON_NEXT_COMMITTEE_AGG_PUBKEY_3 = 0; // TBD\r\n    uint32  constant internal WIT_2_GENESIS_EPOCH = 0;      // TBD\r\n    uint32  constant internal WIT_2_GENESIS_TIMESTAMP = 0;  // TBD\r\n    uint32  constant internal WIT_2_SECS_PER_EPOCH = 20;    // TBD\r\n    uint32  constant internal WIT_2_FAST_FORWARD_COMMITTEE_SIZE = 64; // TBD\r\n\r\n\r\n    function channel(address wrb) internal view returns (bytes4) {\r\n        return bytes4(keccak256(abi.encode(address(wrb), block.chainid)));\r\n    }\r\n\r\n    struct Beacon {\r\n        uint32  index;\r\n        uint32  prevIndex;\r\n        bytes24 prevRoot;\r\n        bytes16 ddrTalliesMerkleRoot;\r\n        bytes16 droTalliesMerkleRoot;\r\n        uint256[4] nextCommitteeAggPubkey;\r\n    }\r\n\r\n    struct DataPullReport {\r\n        QueryId queryId;\r\n        QueryUUID queryHash;           // KECCAK256(channel | blockhash(block.number - 1) | ...)\r\n        bytes witDrRelayerSignature;   // ECDSA.signature(queryHash)\r\n        BlockNumber witDrResultEpoch;\r\n        bytes witDrResultCborBytes;\r\n        TransactionHash witDrTxHash;\r\n    }\r\n\r\n    struct DataPushReport {\r\n        TransactionHash witDrTxHash;\r\n        RadonHash queryRadHash;\r\n        QuerySLA  queryParams;\r\n        Timestamp resultTimestamp;\r\n        bytes resultCborBytes;\r\n    }\r\n\r\n    /// Data struct containing the Witnet-provided result to a Data Request.\r\n    struct DataResult {\r\n        ResultStatus status;\r\n        RadonDataTypes dataType;\r\n        TransactionHash drTxHash;\r\n        uint256 finality;\r\n        Timestamp timestamp;\r\n        WitnetCBOR.CBOR value;\r\n    }\r\n\r\n    struct FastForward {\r\n        Beacon beacon;\r\n        uint256[2] committeeAggSignature;\r\n        uint256[4][] committeeMissingPubkeys;\r\n    }\r\n\r\n    /// Struct containing both request and response data related to every query posted to the Witnet Request Board\r\n    struct Query {\r\n        QueryRequest request;\r\n        QueryResponse response;\r\n        QuerySLA slaParams;      // Minimum Service-Level parameters to be committed by the Witnet blockchain.\r\n        QueryUUID uuid;          // Universal unique identifier determined by the payload, WRB instance, chain id and EVM's previous block hash.\r\n        QueryEvmReward reward;   // EVM amount in wei eventually to be paid to the legit reporter.\r\n        BlockNumber checkpoint;\r\n    }\r\n\r\n    /// Possible status of a Witnet query.\r\n    enum QueryStatus {\r\n        Unknown,\r\n        Posted,\r\n        Reported,\r\n        Finalized,\r\n        Delayed,\r\n        Expired,\r\n        Disputed\r\n    }\r\n\r\n    struct QueryCallback {\r\n        address consumer;               // consumer contract address to which the query result will be reported\r\n        uint24  gasLimit;               // expected max amount of gas required by the callback method in the consumer contract\r\n    }\r\n\r\n    /// Data kept in EVM-storage for every Request posted to the Witnet Request Board.\r\n    struct QueryRequest {\r\n        address   requester;     // EVM address from which the request was posted.\r\n        uint24    callbackGas;   // Max callback gas limit upon response, if a callback is required.\r\n        bytes     radonBytecode; // Optional: Witnet Data Request bytecode to be solved by the Witnet blockchain.\r\n        RadonHash radonHash;     // Optional: Previously verified hash of the Witnet Data Request to be solved.\r\n    }\r\n\r\n    /// QueryResponse metadata and result as resolved by the Witnet blockchain.\r\n    struct QueryResponse {\r\n        address reporter;               // EVM address from which the Data Request result was reported.\r\n        Timestamp resultTimestamp;      // Unix timestamp (seconds) at which the data request was resolved in the Witnet blockchain.\r\n        TransactionHash resultDrTxHash; // Unique hash of the commit/reveal act in the Witnet blockchain that resolved the data request.\r\n        bytes resultCborBytes;          // CBOR-encode result to the request, as resolved in the Witnet blockchain.\r\n        address disputer;\r\n    }\r\n\r\n    /// Structure containing all possible SLA security parameters for Wit/2.1 Data Requests\r\n    struct QuerySLA {\r\n        uint16  witResultMaxSize; // max size permitted to whatever query result may come from the Wit/Oracle blockchain.\r\n        uint16  witCommitteeSize; // max number of eligibile witnesses in the Wit/Oracle blockchain for solving some query.\r\n        uint64  witUnitaryReward; // min fees in nanowits to be paid for getting the query solved and reported from the Wit/Oracle.\r\n    }\r\n\r\n    enum ResultStatus {\r\n        /// 0x00: No errors.\r\n        NoErrors,\r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Source-specific format error sub-codes ============================================================================\r\n        \r\n        /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value.\r\n        SourceScriptNotCBOR, \r\n        \r\n        /// 0x02: The CBOR value decoded from a source script is not an Array.\r\n        SourceScriptNotArray,\r\n        \r\n        /// 0x03: The Array value decoded form a source script is not a valid Data Request.\r\n        SourceScriptNotRADON,\r\n        \r\n        /// 0x04: The request body of at least one data source was not properly formated.\r\n        SourceRequestBody,\r\n        \r\n        /// 0x05: The request headers of at least one data source was not properly formated.\r\n        SourceRequestHeaders,\r\n        \r\n        /// 0x06: The request URL of at least one data source was not properly formated.\r\n        SourceRequestURL,\r\n        \r\n        /// Unallocated\r\n        SourceFormat0x07, SourceFormat0x08, SourceFormat0x09, SourceFormat0x0A, SourceFormat0x0B, SourceFormat0x0C,\r\n        SourceFormat0x0D, SourceFormat0x0E, SourceFormat0x0F, \r\n        \r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Complexity error sub-codes ========================================================================================\r\n        \r\n        /// 0x10: The request contains too many sources.\r\n        RequestTooManySources,\r\n        \r\n        /// 0x11: The script contains too many calls.\r\n        ScriptTooManyCalls,\r\n        \r\n        /// Unallocated\r\n        Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18,\r\n        Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F,\r\n\r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Lack of support error sub-codes ===================================================================================\r\n        \r\n        /// 0x20: Some Radon operator code was found that is not supported (1+ args).\r\n        UnsupportedOperator,\r\n        \r\n        /// 0x21: Some Radon filter opcode is not currently supported (1+ args).\r\n        UnsupportedFilter,\r\n        \r\n        /// 0x22: Some Radon request type is not currently supported (1+ args).\r\n        UnsupportedHashFunction,\r\n        \r\n        /// 0x23: Some Radon reducer opcode is not currently supported (1+ args)\r\n        UnsupportedReducer,\r\n        \r\n        /// 0x24: Some Radon hash function is not currently supported (1+ args).\r\n        UnsupportedRequestType, \r\n        \r\n        /// 0x25: Some Radon encoding function is not currently supported (1+ args).\r\n        UnsupportedEncodingFunction,\r\n        \r\n        /// Unallocated\r\n        Operator0x26, Operator0x27, \r\n        \r\n        /// 0x28: Wrong number (or type) of arguments were passed to some Radon operator.\r\n        WrongArguments,\r\n        \r\n        /// Unallocated\r\n        Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F,\r\n        \r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Retrieve-specific circumstantial error sub-codes ================================================================================\r\n        /// 0x30: A majority of data sources returned an HTTP status code other than 200 (1+ args):\r\n        HttpErrors,\r\n        \r\n        /// 0x31: A majority of data sources timed out:\r\n        RetrievalsTimeout,\r\n        \r\n        /// Unallocated\r\n        RetrieveCircumstance0x32, RetrieveCircumstance0x33, RetrieveCircumstance0x34, RetrieveCircumstance0x35,\r\n        RetrieveCircumstance0x36, RetrieveCircumstance0x37, RetrieveCircumstance0x38, RetrieveCircumstance0x39,\r\n        RetrieveCircumstance0x3A, RetrieveCircumstance0x3B, RetrieveCircumstance0x3C, RetrieveCircumstance0x3D,\r\n        RetrieveCircumstance0x3E, RetrieveCircumstance0x3F,\r\n        \r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Scripting-specific runtime error sub-code =========================================================================\r\n        /// 0x40: Math operator caused an underflow.\r\n        MathUnderflow,\r\n        \r\n        /// 0x41: Math operator caused an overflow.\r\n        MathOverflow,\r\n        \r\n        /// 0x42: Math operator tried to divide by zero.\r\n        MathDivisionByZero,            \r\n        \r\n        /// 0x43: Wrong input to subscript call.\r\n        WrongSubscriptInput,\r\n        \r\n        /// 0x44: Value cannot be extracted from input binary buffer.\r\n        BufferIsNotValue,\r\n        \r\n        /// 0x45: Value cannot be decoded from expected type.\r\n        Decode,\r\n        \r\n        /// 0x46: Unexpected empty array.\r\n        EmptyArray,\r\n        \r\n        /// 0x47: Value cannot be encoded to expected type.\r\n        Encode,\r\n        \r\n        /// 0x48: Failed to filter input values (1+ args).\r\n        Filter,\r\n        \r\n        /// 0x49: Failed to hash input value.\r\n        Hash,\r\n        \r\n        /// 0x4A: Mismatching array ranks.\r\n        MismatchingArrays,\r\n        \r\n        /// 0x4B: Failed to process non-homogenous array.\r\n        NonHomegeneousArray,\r\n        \r\n        /// 0x4C: Failed to parse syntax of some input value, or argument.\r\n        Parse,\r\n        \r\n        /// 0x4D: Parsing logic limits were exceeded.\r\n        ParseOverflow,\r\n        \r\n        /// Unallocated\r\n        ScriptError0x4E, ScriptError0x4F,\r\n    \r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Actual first-order result error codes =============================================================================\r\n        \r\n        /// 0x50: Not enough reveals were received in due time:\r\n        InsufficientReveals,\r\n        \r\n        /// 0x51: No actual reveal majority was reached on tally stage:\r\n        InsufficientMajority,\r\n        \r\n        /// 0x52: Not enough commits were received before tally stage:\r\n        InsufficientCommits,\r\n        \r\n        /// 0x53: Generic error during tally execution (to be deprecated after WIP #0028)\r\n        TallyExecution,\r\n        \r\n        /// 0x54: A majority of data sources could either be temporarily unresponsive or failing to report the requested data:\r\n        CircumstantialFailure,\r\n        \r\n        /// 0x55: At least one data source is inconsistent when queried through multiple transports at once:\r\n        InconsistentSources,\r\n        \r\n        /// 0x56: Any one of the (multiple) Retrieve, Aggregate or Tally scripts were badly formated:\r\n        MalformedDataRequest,\r\n        \r\n        /// 0x57: Values returned from a majority of data sources don't match the expected schema:\r\n        MalformedQueryResponses,\r\n        \r\n        /// Unallocated:    \r\n        OtherError0x58, OtherError0x59, OtherError0x5A, OtherError0x5B, OtherError0x5C, OtherError0x5D, OtherError0x5E, \r\n        \r\n        /// 0x5F: Size of serialized tally result exceeds allowance:\r\n        OversizedTallyResult,\r\n\r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Inter-stage runtime error sub-codes ===============================================================================\r\n        \r\n        /// 0x60: Data aggregation reveals could not get decoded on the tally stage:\r\n        MalformedReveals,\r\n        \r\n        /// 0x61: The result to data aggregation could not get encoded:\r\n        EncodeReveals,  \r\n        \r\n        /// 0x62: A mode tie ocurred when calculating some mode value on the aggregation or the tally stage:\r\n        ModeTie, \r\n        \r\n        /// Unallocated:\r\n        OtherError0x63, OtherError0x64, OtherError0x65, OtherError0x66, OtherError0x67, OtherError0x68, OtherError0x69, \r\n        OtherError0x6A, OtherError0x6B, OtherError0x6C, OtherError0x6D, OtherError0x6E, OtherError0x6F,\r\n        \r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Runtime access error sub-codes ====================================================================================\r\n        \r\n        /// 0x70: Tried to access a value from an array using an index that is out of bounds (1+ args):\r\n        ArrayIndexOutOfBounds,\r\n        \r\n        /// 0x71: Tried to access a value from a map using a key that does not exist (1+ args):\r\n        MapKeyNotFound,\r\n        \r\n        /// 0X72: Tried to extract value from a map using a JSON Path that returns no values (+1 args):\r\n        JsonPathNotFound,\r\n        \r\n        /// Unallocated:\r\n        OtherError0x73, OtherError0x74, OtherError0x75, OtherError0x76, OtherError0x77, OtherError0x78, \r\n        OtherError0x79, OtherError0x7A, OtherError0x7B, OtherError0x7C, OtherError0x7D, OtherError0x7E, OtherError0x7F, \r\n        OtherError0x80, OtherError0x81, OtherError0x82, OtherError0x83, OtherError0x84, OtherError0x85, OtherError0x86, \r\n        OtherError0x87, OtherError0x88, OtherError0x89, OtherError0x8A, OtherError0x8B, OtherError0x8C, OtherError0x8D, \r\n        OtherError0x8E, OtherError0x8F, OtherError0x90, OtherError0x91, OtherError0x92, OtherError0x93, OtherError0x94, \r\n        OtherError0x95, OtherError0x96, OtherError0x97, OtherError0x98, OtherError0x99, OtherError0x9A, OtherError0x9B,\r\n        OtherError0x9C, OtherError0x9D, OtherError0x9E, OtherError0x9F, OtherError0xA0, OtherError0xA1, OtherError0xA2, \r\n        OtherError0xA3, OtherError0xA4, OtherError0xA5, OtherError0xA6, OtherError0xA7, OtherError0xA8, OtherError0xA9, \r\n        OtherError0xAA, OtherError0xAB, OtherError0xAC, OtherError0xAD, OtherError0xAE, OtherError0xAF, OtherError0xB0,\r\n        OtherError0xB1, OtherError0xB2, OtherError0xB3, OtherError0xB4, OtherError0xB5, OtherError0xB6, OtherError0xB7,\r\n        OtherError0xB8, OtherError0xB9, OtherError0xBA, OtherError0xBB, OtherError0xBC, OtherError0xBD, OtherError0xBE,\r\n        OtherError0xBF, OtherError0xC0, OtherError0xC1, OtherError0xC2, OtherError0xC3, OtherError0xC4, OtherError0xC5,\r\n        OtherError0xC6, OtherError0xC7, OtherError0xC8, OtherError0xC9, OtherError0xCA, OtherError0xCB, OtherError0xCC,\r\n        OtherError0xCD, OtherError0xCE, OtherError0xCF, OtherError0xD0, OtherError0xD1, OtherError0xD2, OtherError0xD3,\r\n        OtherError0xD4, OtherError0xD5, OtherError0xD6, OtherError0xD7, OtherError0xD8, OtherError0xD9, OtherError0xDA,\r\n        OtherError0xDB, OtherError0xDC, OtherError0xDD, OtherError0xDE, OtherError0xDF,\r\n        \r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Inter-client generic error codes ==================================================================================\r\n        /// Data requests that cannot be relayed into the Witnet blockchain should be reported\r\n        /// with one of these errors. \r\n        \r\n        /// 0xE0: Requests that cannot be parsed must always get this error as their result.\r\n        BridgeMalformedDataRequest,\r\n        \r\n        /// 0xE1: Witnesses exceeds 100\r\n        BridgePoorIncentives,\r\n        \r\n        /// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an\r\n        /// amount of value that is unjustifiably high when compared with the reward they will be getting\r\n        BridgeOversizedTallyResult,\r\n        \r\n        /// Unallocated:\r\n        OtherError0xE3, OtherError0xE4, OtherError0xE5, OtherError0xE6, OtherError0xE7, OtherError0xE8, OtherError0xE9,\r\n        OtherError0xEA, OtherError0xEB, OtherError0xEC, OtherError0xED, OtherError0xEE, OtherError0xEF, \r\n        \r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Transient errors as determined by the Request Board contract ======================================================\r\n        \r\n        /// 0xF0: \r\n        BoardAwaitingResult,\r\n\r\n        /// 0xF1:\r\n        BoardFinalizingResult,\r\n\r\n        /// 0xF2:\r\n        BoardBeingDisputed,\r\n\r\n        /// Unallocated\r\n        OtherError0xF3, OtherError0xF4, OtherError0xF5, OtherError0xF6, OtherError0xF7,\r\n\r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// Final errors as determined by the Request Board contract ==========================================================\r\n\r\n        /// 0xF8:\r\n        BoardAlreadyDelivered,\r\n\r\n        /// 0xF9:\r\n        BoardResolutionTimeout,\r\n\r\n        /// Unallocated:\r\n        OtherError0xFA, OtherError0xFB, OtherError0xFC, OtherError0xFD, OtherError0xFE,\r\n        \r\n        \r\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n        /// 0xFF: Some tally error is not intercepted but it should (0+ args)\r\n        UnhandledIntercept\r\n    }\r\n\r\n    /// Possible types either processed by Witnet Radon Scripts or included within results to Witnet Data Requests.\r\n    enum RadonDataTypes {\r\n        /* 0x00 */ Any, \r\n        /* 0x01 */ Array,\r\n        /* 0x02 */ Bool,\r\n        /* 0x03 */ Bytes,\r\n        /* 0x04 */ Integer,\r\n        /* 0x05 */ Float,\r\n        /* 0x06 */ Map,\r\n        /* 0x07 */ String,\r\n        Unused0x08, Unused0x09, Unused0x0A, Unused0x0B,\r\n        Unused0x0C, Unused0x0D, Unused0x0E, Unused0x0F,\r\n        /* 0x10 */ Same,\r\n        /* 0x11 */ Inner,\r\n        /* 0x12 */ Match,\r\n        /* 0x13 */ Subscript\r\n    }\r\n\r\n    /// Structure defining some data filtering that can be applied at the Aggregation or the Tally stages\r\n    /// within a Witnet Data Request resolution workflow.\r\n    struct RadonFilter {\r\n        RadonFilterOpcodes opcode;\r\n        bytes cborArgs;\r\n    }\r\n\r\n    /// Filtering methods currently supported on the Witnet blockchain. \r\n    enum RadonFilterOpcodes {\r\n        /* 0x00 */ Reserved0x00, //GreaterThan,\r\n        /* 0x01 */ Reserved0x01, //LessThan,\r\n        /* 0x02 */ Reserved0x02, //Equals,\r\n        /* 0x03 */ Reserved0x03, //AbsoluteDeviation,\r\n        /* 0x04 */ Reserved0x04, //RelativeDeviation\r\n        /* 0x05 */ StandardDeviation,\r\n        /* 0x06 */ Reserved0x06, //Top,\r\n        /* 0x07 */ Reserved0x07, //Bottom,\r\n        /* 0x08 */ Mode,\r\n        /* 0x09 */ Reserved0x09  //LessOrEqualThan\r\n    }\r\n\r\n    /// Structure defining the array of filters and reducting function to be applied at either the Aggregation\r\n    /// or the Tally stages within a Witnet Data Request resolution workflow.\r\n    struct RadonReducer {\r\n        RadonReduceOpcodes opcode;\r\n        RadonFilter[] filters;\r\n    }\r\n\r\n    /// Reducting functions currently supported on the Witnet blockchain.\r\n    enum RadonReduceOpcodes {\r\n        /* 0x00 */ Reserved0x00, //Minimum,\r\n        /* 0x01 */ Reserved0x01, //Maximum,\r\n        /* 0x02 */ Mode,\r\n        /* 0x03 */ AverageMean,\r\n        /* 0x04 */ Reserved0x04, //AverageMeanWeighted,\r\n        /* 0x05 */ AverageMedian,\r\n        /* 0x06 */ Reserved0x06, //AverageMedianWeighted,\r\n        /* 0x07 */ StandardDeviation,\r\n        /* 0x08 */ Reserved0x08, //AverageDeviation,\r\n        /* 0x09 */ Reserved0x09, //MedianDeviation,\r\n        /* 0x0A */ Reserved0x10, //MaximumDeviation,\r\n        /* 0x0B */ ConcatenateAndHash\r\n    }\r\n    \r\n    /// Structure containing the Retrieve-Attestation-Delivery parts of a Witnet-compliant Data Request.\r\n    struct RadonRequest {\r\n        RadonRetrieval[] retrieve;\r\n        RadonReducer aggregate;\r\n        RadonReducer tally;\r\n    }\r\n\r\n    /// Structure containing all the parameters that fully describe a Witnet Radon Retrieval within a Witnet Data Request.\r\n    struct RadonRetrieval {\r\n        uint8 argsCount;\r\n        RadonRetrievalMethods method;\r\n        RadonDataTypes dataType;\r\n        string url;\r\n        string body;\r\n        string[2][] headers;\r\n        bytes radonScript;\r\n    }\r\n\r\n    /// Possible Radon retrieval methods that can be used within a Radon Retrieval. \r\n    enum RadonRetrievalMethods {\r\n        /* 0 */ Unknown,\r\n        /* 1 */ HttpGet,\r\n        /* 2 */ RNG,\r\n        /* 3 */ HttpPost,\r\n        /* 4 */ HttpHead\r\n    }\r\n\r\n    /// Structure containing all possible SLA security parameters of a Witnet-compliant Data Request.\r\n\r\n    struct RadonSLAv1 {\r\n        uint8 numWitnesses;\r\n        uint8 minConsensusPercentage;\r\n        uint64 witnessReward;\r\n        uint64 witnessCollateral;\r\n        uint64 minerCommitRevealFee;\r\n    }\r\n\r\n\r\n    /// =======================================================================\r\n    /// --- Witnet.Address helper functions -----------------------------------\r\n\r\n    function eq(Address a, Address b) internal pure returns (bool) {\r\n        return Address.unwrap(a) == Address.unwrap(b);\r\n    }\r\n\r\n    function fromBech32(string memory pkh, bool mainnet) internal pure returns (Address) {\r\n        require(bytes(pkh).length == (mainnet ? 42 : 43), \"Bech32: invalid length\");\r\n        return Address.wrap(bytes20(Bech32.fromBech32(pkh, mainnet ? \"wit\" : \"twit\")));\r\n    }\r\n\r\n    function toBech32(Address witAddress, bool mainnet) internal pure returns (string memory) {\r\n        return Bech32.toBech32(address(Address.unwrap(witAddress)), mainnet ? \"wit\" : \"twit\");\r\n    }\r\n\r\n    function isZero(Address a) internal pure returns (bool) {\r\n        return Address.unwrap(a) == bytes20(0);\r\n    }\r\n\r\n    \r\n    /// =======================================================================\r\n    /// --- Witnet.Beacon helper functions ------------------------------------\r\n\r\n    function equals(Beacon storage self, Beacon calldata other)\r\n        internal view returns (bool)\r\n    {\r\n        return (\r\n            root(self) == root(other)\r\n        );\r\n    }\r\n\r\n    function root(Beacon calldata self) internal pure returns (bytes24) {\r\n        return bytes24(keccak256(abi.encode(\r\n            self.index,\r\n            self.prevIndex,\r\n            self.prevRoot,\r\n            self.ddrTalliesMerkleRoot,\r\n            self.droTalliesMerkleRoot,\r\n            self.nextCommitteeAggPubkey\r\n        )));\r\n    }\r\n    \r\n    function root(Beacon storage self) internal view returns (bytes24) {\r\n        return bytes24(keccak256(abi.encode(\r\n            self.index,\r\n            self.prevIndex,\r\n            self.prevRoot,\r\n            self.ddrTalliesMerkleRoot,\r\n            self.droTalliesMerkleRoot,\r\n            self.nextCommitteeAggPubkey\r\n        )));\r\n    }\r\n\r\n    \r\n    /// =======================================================================\r\n    /// --- BlockNumber helper functions --------------------------------------\r\n\r\n    function egt(BlockNumber a, BlockNumber b) internal pure returns (bool) {\r\n        return BlockNumber.unwrap(a) >= BlockNumber.unwrap(b);\r\n    }\r\n\r\n    function elt(BlockNumber a, BlockNumber b) internal pure returns (bool) {\r\n        return BlockNumber.unwrap(a) <= BlockNumber.unwrap(b);\r\n    }\r\n\r\n    function gt(BlockNumber a, BlockNumber b) internal pure returns (bool) {\r\n        return BlockNumber.unwrap(a) > BlockNumber.unwrap(b);\r\n    }\r\n\r\n    function lt(BlockNumber a, BlockNumber b) internal pure returns (bool) {\r\n        return BlockNumber.unwrap(a) < BlockNumber.unwrap(b);\r\n    }\r\n\r\n    function isZero(BlockNumber b) internal pure returns (bool) {\r\n        return (BlockNumber.unwrap(b) == 0);\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- Data*Report helper methods --------------------------------------------------------------------------------\r\n\r\n    function queryRelayer(DataPullReport calldata self) internal pure returns (address) {\r\n        return recoverEvmAddr(\r\n            self.witDrRelayerSignature, \r\n            hashify(self.queryHash)\r\n        );\r\n    }\r\n\r\n    function tallyHash(DataPullReport calldata self) internal pure returns (bytes32) {\r\n        return keccak256(abi.encode(\r\n            self.queryHash,\r\n            self.witDrRelayerSignature,\r\n            self.witDrTxHash,\r\n            self.witDrResultEpoch,\r\n            self.witDrResultCborBytes\r\n        ));\r\n    }\r\n\r\n    function digest(DataPushReport calldata self) internal pure returns (bytes32) {\r\n        return keccak256(abi.encode(\r\n            self.witDrTxHash,\r\n            self.queryRadHash,\r\n            self.queryParams.witResultMaxSize,\r\n            self.queryParams.witCommitteeSize,\r\n            self.queryParams.witUnitaryReward,\r\n            self.resultTimestamp,\r\n            self.resultCborBytes\r\n        ));\r\n    }\r\n    \r\n    /// ========================================================================================================\r\n    /// --- 'DataResult' helper methods ------------------------------------------------------------------------\r\n\r\n    function noErrors(DataResult memory self) internal pure returns (bool) {\r\n        return self.status == ResultStatus.NoErrors;\r\n    }\r\n\r\n    function keepWaiting(DataResult memory self) internal pure returns (bool) {\r\n        return keepWaiting(self.status);\r\n    }\r\n\r\n    function hasErrors(DataResult memory self) internal pure returns (bool) {\r\n        return hasErrors(self.status);\r\n    }\r\n\r\n    modifier _checkDataType(DataResult memory self, RadonDataTypes expectedDataType) {\r\n        require(\r\n            !keepWaiting(self)\r\n                && self.dataType == expectedDataType\r\n            , \"cbor: cannot fetch data\"\r\n        ); _; \r\n        self.dataType = peekRadonDataType(self.value);\r\n    }\r\n\r\n    function fetchAddress(DataResult memory self) \r\n        internal pure \r\n        _checkDataType(self, RadonDataTypes.Bytes) \r\n        returns (address _res)\r\n    {\r\n        return toAddress(self.value.readBytes());\r\n    }\r\n\r\n    function fetchBool(DataResult memory self) \r\n        internal pure \r\n        _checkDataType(self, RadonDataTypes.Bool) \r\n        returns (bool)\r\n    {\r\n        return self.value.readBool();\r\n    }\r\n\r\n    function fetchBytes(DataResult memory self)\r\n        internal pure \r\n        _checkDataType(self, RadonDataTypes.Bytes) \r\n        returns (bytes memory)\r\n    {\r\n        return self.value.readBytes();\r\n    }\r\n\r\n    function fetchBytes4(DataResult memory self)\r\n        internal pure \r\n        _checkDataType(self, RadonDataTypes.Bytes) \r\n        returns (bytes4)\r\n    {\r\n        return toBytes4(self.value.readBytes());\r\n    }\r\n\r\n    function fetchBytes32(DataResult memory self)\r\n        internal pure \r\n        _checkDataType(self, RadonDataTypes.Bytes) \r\n        returns (bytes32)\r\n    {\r\n        return toBytes32(self.value.readBytes());\r\n    }\r\n\r\n    function fetchCborArray(DataResult memory self)\r\n        internal pure \r\n        _checkDataType(self, RadonDataTypes.Array) \r\n        returns (WitnetCBOR.CBOR[] memory)\r\n    {\r\n        return self.value.readArray();\r\n    }\r\n\r\n    /// @dev Decode a fixed16 (half-precision) numeric value from the Result's CBOR value.\r\n    /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values.\r\n    /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`.\r\n    /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.\r\n    function fetchFloatFixed16(DataResult memory self)\r\n        internal pure \r\n        _checkDataType(self, RadonDataTypes.Float) \r\n        returns (int32)\r\n    {\r\n        return self.value.readFloat16();\r\n    }\r\n\r\n    /// @dev Decode an array of fixed16 values from the Result's CBOR value.\r\n    function fetchFloatFixed16Array(DataResult memory self)\r\n        internal pure\r\n        _checkDataType(self, RadonDataTypes.Array)\r\n        returns (int32[] memory)\r\n    {\r\n        return self.value.readFloat16Array();\r\n    }\r\n\r\n    /// @dev Decode a `int64` value from the DataResult's CBOR value.\r\n    function fetchInt(DataResult memory self)\r\n        internal pure\r\n        _checkDataType(self, RadonDataTypes.Integer)\r\n        returns (int64)\r\n    {\r\n        return self.value.readInt();\r\n    }\r\n\r\n    function fetchInt64Array(DataResult memory self)\r\n        internal pure\r\n        _checkDataType(self, RadonDataTypes.Array)\r\n        returns (int64[] memory)\r\n    {\r\n        return self.value.readIntArray();\r\n    }\r\n\r\n    function fetchString(DataResult memory self)\r\n        internal pure\r\n        _checkDataType(self, RadonDataTypes.String)\r\n        returns (string memory)\r\n    {\r\n        return self.value.readString();\r\n    }\r\n\r\n    function fetchStringArray(DataResult memory self)\r\n        internal pure\r\n        _checkDataType(self, RadonDataTypes.Array)\r\n        returns (string[] memory)\r\n    {\r\n        return self.value.readStringArray();\r\n    }\r\n\r\n    /// @dev Decode a `uint64` value from the DataResult's CBOR value.\r\n    function fetchUint(DataResult memory self)\r\n        internal pure\r\n        _checkDataType(self, RadonDataTypes.Integer)\r\n        returns (uint64)\r\n    {\r\n        return self.value.readUint();\r\n    }\r\n\r\n    function fetchUint64Array(DataResult memory self)\r\n        internal pure\r\n        _checkDataType(self, RadonDataTypes.Array)\r\n        returns (uint64[] memory)\r\n    {\r\n        return self.value.readUintArray();\r\n    }\r\n\r\n    bytes7 private constant _CBOR_MAJOR_TYPE_TO_RADON_DATA_TYPES_MAP = 0x04040307010600;\r\n    function peekRadonDataType(WitnetCBOR.CBOR memory cbor) internal pure returns (RadonDataTypes _type) {\r\n        _type = RadonDataTypes.Any;\r\n        if (!cbor.eof()) {\r\n            if (cbor.majorType <= 6) {\r\n                return RadonDataTypes(uint8(bytes1(_CBOR_MAJOR_TYPE_TO_RADON_DATA_TYPES_MAP[cbor.majorType])));\r\n            \r\n            } else if (cbor.majorType == 7) {\r\n                if (cbor.additionalInformation == 20 || cbor.additionalInformation == 21) {\r\n                    return RadonDataTypes.Bool;\r\n                \r\n                } else if (cbor.additionalInformation >= 25 && cbor.additionalInformation <= 27) {\r\n                    return RadonDataTypes.Float;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n    /// =======================================================================\r\n    /// --- FastForward helper functions --------------------------------------\r\n\r\n    function head(FastForward[] calldata rollup)\r\n        internal pure returns (Beacon calldata)\r\n    {\r\n        return rollup[rollup.length - 1].beacon;\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- Query* helper methods -------------------------------------------------------------------------------------\r\n\r\n    function equalOrGreaterThan(QuerySLA calldata self, QuerySLA storage stored) internal view returns (bool) {\r\n        return (\r\n                self.witCommitteeSize >= stored.witCommitteeSize\r\n                && self.witUnitaryReward >= stored.witUnitaryReward \r\n                && self.witResultMaxSize <= stored.witResultMaxSize\r\n        );\r\n    }\r\n\r\n    function hashify(QueryUUID hash) internal pure returns (bytes32) {\r\n        return keccak256(abi.encode(QueryUUID.unwrap(hash)));\r\n    }\r\n\r\n    function hashify(QueryId _queryId, Witnet.RadonHash _radHash, bytes32 _slaHash) internal view returns (Witnet.QueryUUID) {\r\n        return Witnet.QueryUUID.wrap(bytes15(\r\n            keccak256(abi.encode(\r\n                channel(address(this)), \r\n                blockhash(block.number - 1),\r\n                _queryId, Witnet.RadonHash.unwrap(_radHash), _slaHash\r\n            ))\r\n        ));\r\n    }\r\n\r\n    function hashify(QuerySLA memory querySLA) internal pure returns (bytes32) {\r\n        return keccak256(abi.encodePacked(\r\n            querySLA.witResultMaxSize,\r\n            querySLA.witCommitteeSize,\r\n            querySLA.witUnitaryReward\r\n        ));\r\n    }\r\n\r\n    function isValid(QuerySLA memory self) internal pure returns (bool) {\r\n        return (\r\n            self.witResultMaxSize >= 0\r\n                && self.witCommitteeSize > 0\r\n                && self.witCommitteeSize <= 127\r\n                && self.witUnitaryReward > 0\r\n        );\r\n    }\r\n\r\n    function isZero(QueryId a) internal pure returns (bool) {\r\n        return (QueryId.unwrap(a) == 0);\r\n    }\r\n\r\n    function toV1(QuerySLA calldata self) internal pure returns (RadonSLAv1 memory) {\r\n        return RadonSLAv1({\r\n            numWitnesses: uint8(self.witCommitteeSize),\r\n            minConsensusPercentage: 51,\r\n            witnessReward: self.witUnitaryReward,\r\n            witnessCollateral: self.witUnitaryReward * self.witCommitteeSize,\r\n            minerCommitRevealFee: self.witUnitaryReward / self.witCommitteeSize\r\n        });\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- RadonHash helper methods ----------------------------------------------------------------------------------\r\n\r\n    function eq(RadonHash a, RadonHash b) internal pure returns (bool) {\r\n        return RadonHash.unwrap(a) == RadonHash.unwrap(b);\r\n    }\r\n    \r\n    function isZero(RadonHash h) internal pure returns (bool) {\r\n        return RadonHash.unwrap(h) == bytes32(0);\r\n    }\r\n\r\n    \r\n    /// ===============================================================================================================\r\n    /// --- ResultStatus helper methods -------------------------------------------------------------------------------\r\n\r\n    function hasErrors(ResultStatus self) internal pure returns (bool) {\r\n        return (\r\n            self != ResultStatus.NoErrors\r\n                && !keepWaiting(self)\r\n        );\r\n    }\r\n\r\n    function isCircumstantial(ResultStatus self) internal pure returns (bool) {\r\n        return (self == ResultStatus.CircumstantialFailure);\r\n    }\r\n\r\n    function isRetriable(ResultStatus self) internal pure returns (bool) {\r\n        return (\r\n            lackOfConsensus(self)\r\n                || isCircumstantial(self)\r\n                || poorIncentives(self)\r\n        );\r\n    }\r\n\r\n    function keepWaiting(ResultStatus self) internal pure returns (bool) {\r\n        return (\r\n            self == ResultStatus.BoardAwaitingResult\r\n                || self == ResultStatus.BoardFinalizingResult\r\n        );\r\n    }\r\n\r\n    function lackOfConsensus(ResultStatus self) internal pure returns (bool) {\r\n        return (\r\n            self == ResultStatus.InsufficientCommits\r\n                || self == ResultStatus.InsufficientMajority\r\n                || self == ResultStatus.InsufficientReveals\r\n        );\r\n    }\r\n\r\n    function poorIncentives(ResultStatus self) internal pure returns (bool) {\r\n        return (\r\n            self == ResultStatus.OversizedTallyResult\r\n                || self == ResultStatus.InsufficientCommits\r\n                || self == ResultStatus.BridgePoorIncentives\r\n                || self == ResultStatus.BridgeOversizedTallyResult\r\n        );\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- Timestamp helper methods ----------------------------------------------------------------------------------\r\n\r\n    function gt(Timestamp a, Timestamp b) internal pure returns (bool) {\r\n        return Timestamp.unwrap(a) > Timestamp.unwrap(b);\r\n    }\r\n\r\n    function egt(Timestamp a, Timestamp b) internal pure returns (bool) {\r\n        return Timestamp.unwrap(a) >= Timestamp.unwrap(b);\r\n    }\r\n\r\n    function elt(Timestamp a, Timestamp b) internal pure returns (bool) {\r\n        return Timestamp.unwrap(a) <= Timestamp.unwrap(b);\r\n    }\r\n\r\n    function isZero(Timestamp t) internal pure returns (bool) {\r\n        return Timestamp.unwrap(t) == 0;\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- 'bytes*' helper methods -----------------------------------------------------------------------------------\r\n\r\n    function intoMemArray(bytes32[1] memory _values) internal pure returns (bytes32[] memory) {\r\n        return abi.decode(abi.encode(uint256(32), 1, _values), (bytes32[]));\r\n    }\r\n\r\n    function intoMemArray(bytes32[2] memory _values) internal pure returns (bytes32[] memory) {\r\n        return abi.decode(abi.encode(uint256(32), 2, _values), (bytes32[]));\r\n    }\r\n\r\n    function intoMemArray(bytes32[3] memory _values) internal pure returns (bytes32[] memory) {\r\n        return abi.decode(abi.encode(uint256(32), 3, _values), (bytes32[]));\r\n    }\r\n\r\n    function intoMemArray(bytes32[4] memory _values) internal pure returns (bytes32[] memory) {\r\n        return abi.decode(abi.encode(uint256(32), 4, _values), (bytes32[]));\r\n    }\r\n\r\n    function intoMemArray(bytes32[5] memory _values) internal pure returns (bytes32[] memory) {\r\n        return abi.decode(abi.encode(uint256(32), 5, _values), (bytes32[]));\r\n    }\r\n\r\n    function intoMemArray(bytes32[6] memory _values) internal pure returns (bytes32[] memory) {\r\n        return abi.decode(abi.encode(uint256(32), 6, _values), (bytes32[]));\r\n    }\r\n\r\n    function intoMemArray(bytes32[7] memory _values) internal pure returns (bytes32[] memory) {\r\n        return abi.decode(abi.encode(uint256(32), 7, _values), (bytes32[]));\r\n    }\r\n\r\n    function intoMemArray(bytes32[8] memory _values) internal pure returns (bytes32[] memory) {\r\n        return abi.decode(abi.encode(uint256(32), 8, _values), (bytes32[]));\r\n    }\r\n    \r\n    function merkleHash(bytes32 a, bytes32 b) internal pure returns (bytes32) {\r\n        return (a < b\r\n            ? _merkleHash(a, b)\r\n            : _merkleHash(b, a)\r\n        );\r\n    }\r\n\r\n    function merkleRoot(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32 _root) {\r\n        _root = leaf;\r\n        for (uint _ix = 0; _ix < proof.length; _ix ++) {\r\n            _root = merkleHash(_root, proof[_ix]);\r\n        }\r\n    }\r\n\r\n    function radHash(bytes calldata bytecode) internal pure returns (Witnet.RadonHash) {\r\n        return Witnet.RadonHash.wrap(keccak256(bytecode));\r\n    }\r\n\r\n    function recoverEvmAddr(bytes memory signature, bytes32 hash_)\r\n        internal pure \r\n        returns (address)\r\n    {\r\n        if (signature.length != 65) {\r\n            return (address(0));\r\n        }\r\n        bytes32 r;\r\n        bytes32 s;\r\n        uint8 v;\r\n        assembly {\r\n            r := mload(add(signature, 0x20))\r\n            s := mload(add(signature, 0x40))\r\n            v := byte(0, mload(add(signature, 0x60)))\r\n        }\r\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\r\n            return address(0);\r\n        }\r\n        if (v != 27 && v != 28) {\r\n            return address(0);\r\n        }\r\n        return ecrecover(hash_, v, r, s);\r\n    }\r\n\r\n    function verifyWitAddressAuthorization(\r\n            address evmAuthorized, \r\n            Address witSigner,\r\n            bytes memory witSignature\r\n        )\r\n        internal pure\r\n        returns (bool)\r\n    {\r\n        bytes32 _publicKeyX = recoverWitPublicKey(keccak256(abi.encodePacked(evmAuthorized)), witSignature);\r\n        bytes20 _witSigner = Address.unwrap(witSigner);\r\n        return (\r\n            _witSigner == bytes20(sha256(abi.encodePacked(bytes1(0x00), _publicKeyX)))\r\n                || _witSigner == bytes20(sha256(abi.encodePacked(bytes1(0x01), _publicKeyX)))\r\n                || _witSigner == bytes20(sha256(abi.encodePacked(bytes1(0x02), _publicKeyX)))\r\n                || _witSigner == bytes20(sha256(abi.encodePacked(bytes1(0x03), _publicKeyX)))\r\n        );\r\n    }\r\n\r\n    function recoverWitPublicKey(bytes32 evmDigest, bytes memory witSignature)\r\n        internal pure\r\n        returns (bytes32 _witPublicKey)\r\n    {\r\n        if (witSignature.length == 65) {\r\n            bytes32 r;\r\n            bytes32 s;\r\n            uint8 v;\r\n            assembly {\r\n                r := mload(add(witSignature, 0x20))\r\n                s := mload(add(witSignature, 0x40))\r\n                v := byte(0, mload(add(witSignature, 0x60)))\r\n            }\r\n            if (\r\n                uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0\r\n                    && (v == 27 || v == 28)\r\n            ) {\r\n                (uint256 x,) = Secp256k1.recover(uint256(evmDigest), v - 27, uint256(r), uint256(s));\r\n                _witPublicKey = bytes32(x);\r\n            }\r\n        }\r\n    }\r\n\r\n    function toAddress(bytes memory _value) internal pure returns (address) {\r\n        return address(toBytes20(_value));\r\n    }\r\n\r\n    function toBytes4(bytes memory _value) internal pure returns (bytes4) {\r\n        return bytes4(toFixedBytes(_value, 4));\r\n    }\r\n    \r\n    function toBytes20(bytes memory _value) internal pure returns (bytes20) {\r\n        return bytes20(toFixedBytes(_value, 20));\r\n    }\r\n    \r\n    function toBytes32(bytes memory _value) internal pure returns (bytes32) {\r\n        return toFixedBytes(_value, 32);\r\n    }\r\n\r\n    function toFixedBytes(bytes memory _value, uint8 _numBytes)\r\n        internal pure\r\n        returns (bytes32 _bytes32)\r\n    {\r\n        assert(_numBytes <= 32);\r\n        unchecked {\r\n            uint _len = _value.length > _numBytes ? _numBytes : _value.length;\r\n            for (uint _i = 0; _i < _len; _i ++) {\r\n                _bytes32 |= bytes32(_value[_i] & 0xff) >> (_i * 8);\r\n            }\r\n        }\r\n    }\r\n    \r\n    /// @notice Converts bytes32 into string.\r\n    function asAscii(bytes32 _bytes32)\r\n        internal pure\r\n        returns (string memory)\r\n    {\r\n        bytes memory _bytes = new bytes(_toStringLength(_bytes32));\r\n        for (uint _i = 0; _i < _bytes.length;) {\r\n            _bytes[_i] = _bytes32[_i];\r\n            unchecked {\r\n                _i ++;\r\n            }\r\n        }\r\n        return string(_bytes);\r\n    }\r\n\r\n    function toHexString(bytes32 _bytes32) \r\n        internal pure\r\n        returns (string memory)\r\n    {\r\n        bytes memory _bytes = new bytes(64);\r\n        for (uint8 _i; _i < _bytes.length;) {\r\n            _bytes[_i ++] = _toHexChar(uint8(_bytes32[_i / 2] >> 4));\r\n            _bytes[_i ++] = _toHexChar(uint8(_bytes32[_i / 2] & 0x0f));\r\n        }\r\n        return string(_bytes);\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- 'string' helper methods -----------------------------------------------------------------------------------\r\n\r\n    function toLowerCase(string memory str)\r\n        internal pure\r\n        returns (string memory)\r\n    {\r\n        bytes memory lowered = new bytes(bytes(str).length);\r\n        unchecked {\r\n            for (uint i = 0; i < lowered.length; i ++) {\r\n                uint8 char = uint8(bytes(str)[i]);\r\n                if (char >= 65 && char <= 90) {\r\n                    lowered[i] = bytes1(char + 32);\r\n                } else {\r\n                    lowered[i] = bytes1(char);\r\n                }\r\n            }\r\n        }\r\n        return string(lowered);\r\n    }\r\n\r\n    // Function to parse a hex string into a byte array\r\n    function parseHexString(string memory hexString) internal pure returns (bytes memory result) {\r\n        unchecked {\r\n            result = new bytes(bytes(hexString).length / 2);\r\n            for (uint256 i; i < result.length; i ++) {\r\n                uint8 byte1 = _hexCharToByte(uint8(bytes(hexString)[2 * i]));\r\n                uint8 byte2 = _hexCharToByte(uint8(bytes(hexString)[2 * i + 1]));\r\n                result[i] = bytes1(byte1 * 16 + byte2); // Combining the two hex digits into one byte\r\n            }\r\n        }\r\n    }\r\n\r\n    function tryUint(string memory str)\r\n        internal pure\r\n        returns (uint res, bool)\r\n    {\r\n        unchecked {\r\n            for (uint256 i = 0; i < bytes(str).length; i++) {\r\n                if (\r\n                    (uint8(bytes(str)[i]) - 48) < 0\r\n                        || (uint8(bytes(str)[i]) - 48) > 9\r\n                ) {\r\n                    return (0, false);\r\n                }\r\n                res += (uint8(bytes(str)[i]) - 48) * 10 ** (bytes(str).length - i - 1);\r\n            }\r\n            return (res, true);\r\n        }\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- 'uint*' helper methods ------------------------------------------------------------------------------------\r\n\r\n    function determineBeaconIndexFromEpoch(BlockNumber epoch) internal pure returns (uint64) {\r\n        return BlockNumber.unwrap(epoch) / 10;\r\n    }\r\n    \r\n    function determineBeaconIndexFromTimestamp(Timestamp timestamp) internal pure returns (uint64) {\r\n        return determineBeaconIndexFromEpoch(\r\n            determineEpochFromTimestamp(\r\n                timestamp\r\n            )\r\n        );\r\n    }\r\n\r\n    function determineEpochFromTimestamp(Timestamp timestamp) internal pure returns (BlockNumber) {\r\n        if (Timestamp.unwrap(timestamp) > WIT_2_GENESIS_TIMESTAMP) {\r\n            return BlockNumber.wrap(\r\n                WIT_2_GENESIS_EPOCH\r\n                    + (Timestamp.unwrap(timestamp) - WIT_2_GENESIS_TIMESTAMP)\r\n                        / WIT_2_SECS_PER_EPOCH\r\n            );\r\n        } else if (Timestamp.unwrap(timestamp) > WIT_1_GENESIS_TIMESTAMP) {\r\n            return BlockNumber.wrap(\r\n                (Timestamp.unwrap(timestamp) - WIT_1_GENESIS_TIMESTAMP)\r\n                    / WIT_1_SECS_PER_EPOCH\r\n            );\r\n        } else {\r\n            return BlockNumber.wrap(0);\r\n        }\r\n    }\r\n\r\n    function determineTimestampFromEpoch(BlockNumber epoch) internal pure returns (Timestamp) {\r\n        if (BlockNumber.unwrap(epoch) >= WIT_2_GENESIS_EPOCH) {\r\n            return Timestamp.wrap(\r\n                WIT_2_GENESIS_TIMESTAMP\r\n                    + (WIT_2_SECS_PER_EPOCH * (\r\n                        BlockNumber.unwrap(epoch)\r\n                            - WIT_2_GENESIS_EPOCH)\r\n                    )\r\n            );\r\n        } else return Timestamp.wrap(\r\n            WIT_1_GENESIS_TIMESTAMP\r\n                + (WIT_1_SECS_PER_EPOCH * BlockNumber.unwrap(epoch))\r\n        );\r\n    }\r\n\r\n    /// Generates a pseudo-random uint32 number uniformly distributed within the range `[0 .. range)`, based on\r\n    /// the given `nonce` and `seed` values. \r\n    function randomUniformUint64(uint64 range, uint256 nonce, bytes32 seed)\r\n        internal pure \r\n        returns (uint64) \r\n    {\r\n        uint256 _number = uint256(\r\n            keccak256(\r\n                abi.encode(seed, nonce)\r\n            )\r\n        ) & uint256(2 ** 192 - 1);\r\n        return uint64((_number * range) >> 192);\r\n    }\r\n\r\n    /// @notice Convert a `uint8` into a 2 characters long `string` representing its two less significant hexadecimal values.\r\n    function toHexString(uint8 _u)\r\n        internal pure\r\n        returns (string memory)\r\n    {\r\n        bytes memory b2 = new bytes(2);\r\n        uint8 d0 = uint8(_u / 16) + 48;\r\n        uint8 d1 = uint8(_u % 16) + 48;\r\n        if (d0 > 57)\r\n            d0 += 7;\r\n        if (d1 > 57)\r\n            d1 += 7;\r\n        b2[0] = bytes1(d0);\r\n        b2[1] = bytes1(d1);\r\n        return string(b2);\r\n    }\r\n\r\n    /// @notice Convert a `uint8` into a 1, 2 or 3 characters long `string` representing its.\r\n    /// three less significant decimal values.\r\n    function toString(uint8 _u)\r\n        internal pure\r\n        returns (string memory)\r\n    {\r\n        if (_u < 10) {\r\n            bytes memory b1 = new bytes(1);\r\n            b1[0] = bytes1(uint8(_u) + 48);\r\n            return string(b1);\r\n        } else if (_u < 100) {\r\n            bytes memory b2 = new bytes(2);\r\n            b2[0] = bytes1(uint8(_u / 10) + 48);\r\n            b2[1] = bytes1(uint8(_u % 10) + 48);\r\n            return string(b2);\r\n        } else {\r\n            bytes memory b3 = new bytes(3);\r\n            b3[0] = bytes1(uint8(_u / 100) + 48);\r\n            b3[1] = bytes1(uint8(_u % 100 / 10) + 48);\r\n            b3[2] = bytes1(uint8(_u % 10) + 48);\r\n            return string(b3);\r\n        }\r\n    }\r\n\r\n    /// @notice Convert a `uint` into a string` representing its value.\r\n    function toString(uint v)\r\n        internal pure \r\n        returns (string memory)\r\n    {\r\n        uint maxlength = 100;\r\n        bytes memory reversed = new bytes(maxlength);\r\n        uint i = 0;\r\n        do {\r\n            uint8 remainder = uint8(v % 10);\r\n            v = v / 10;\r\n            reversed[i ++] = bytes1(48 + remainder);\r\n        } while (v != 0);\r\n        bytes memory buf = new bytes(i);\r\n        for (uint j = 1; j <= i; j ++) {\r\n            buf[j - 1] = reversed[i - j];\r\n        }\r\n        return string(buf);\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- Witnet library private methods ----------------------------------------------------------------------------\r\n\r\n    function _hexCharToByte(uint8 hexChar) private pure returns (uint8) {\r\n        if (hexChar >= 0x30 && hexChar <= 0x39) {\r\n            return hexChar - 0x30; // '0'-'9' to 0-9\r\n        } else if (hexChar >= 0x41 && hexChar <= 0x46) {\r\n            return hexChar - 0x41 + 10; // 'A'-'F' to 10-15\r\n        } else if (hexChar >= 0x61 && hexChar <= 0x66) {\r\n            return hexChar - 0x61 + 10; // 'a'-'f' to 10-15\r\n        } else {\r\n            revert(\"Invalid hex character\");\r\n        }\r\n    }\r\n\r\n    function _merkleHash(bytes32 _a, bytes32 _b) private pure returns (bytes32 _hash) {\r\n        assembly {\r\n            mstore(0x0, _a)\r\n            mstore(0x20, _b)\r\n            _hash := keccak256(0x0, 0x40)\r\n        }\r\n    }\r\n\r\n    function _toHexChar(uint8 _uint8) private pure returns (bytes1) {\r\n        return _uint8 < 10 ? bytes1(_uint8 + 48) : bytes1(_uint8 + 87);\r\n    }\r\n\r\n    /// @dev Calculate length of string-equivalent to given bytes32.\r\n    function _toStringLength(bytes32 _bytes32)\r\n        private pure\r\n        returns (uint _length)\r\n    {\r\n        for (; _length < 32; ) {\r\n            if (_bytes32[_length] == 0) {\r\n                break;\r\n            }\r\n            unchecked {\r\n                _length ++;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/libs/WitnetBuffer.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\n/// @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface\r\n/// @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will\r\n/// start with the byte that goes right after the last one in the previous read.\r\n/// @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some\r\n/// theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded.\r\n/// @author The Witnet Foundation.\r\nlibrary WitnetBuffer {\r\n\r\n  error EmptyBuffer();\r\n  error IndexOutOfBounds(uint index, uint range);\r\n  error MissingArgs(uint expected, uint given);\r\n\r\n  /// Iterable bytes buffer.\r\n  struct Buffer {\r\n      bytes data;\r\n      uint cursor;\r\n  }\r\n\r\n  // Ensures we access an existing index in an array\r\n  modifier withinRange(uint index, uint _range) {\r\n    if (index > _range) {\r\n      revert IndexOutOfBounds(index, _range);\r\n    }\r\n    _;\r\n  }\r\n\r\n  /// @notice Concatenate undefinite number of bytes chunks.\r\n  /// @dev Faster than looping on `abi.encodePacked(output, _buffs[ix])`.\r\n  function concat(bytes[] memory _buffs)\r\n    internal pure\r\n    returns (bytes memory output)\r\n  {\r\n    unchecked {\r\n      uint destinationPointer;\r\n      uint destinationLength;\r\n      assembly {\r\n        // get safe scratch location\r\n        output := mload(0x40)\r\n        // set starting destination pointer\r\n        destinationPointer := add(output, 32)\r\n      }      \r\n      for (uint ix = 1; ix <= _buffs.length; ix ++) {  \r\n        uint source;\r\n        uint sourceLength;\r\n        uint sourcePointer;        \r\n        assembly {\r\n          // load source length pointer\r\n          source := mload(add(_buffs, mul(ix, 32)))\r\n          // load source length\r\n          sourceLength := mload(source)\r\n          // sets source memory pointer\r\n          sourcePointer := add(source, 32)\r\n        }\r\n        memcpy(\r\n          destinationPointer,\r\n          sourcePointer,\r\n          sourceLength\r\n        );\r\n        assembly {          \r\n          // increase total destination length\r\n          destinationLength := add(destinationLength, sourceLength)\r\n          // sets destination memory pointer\r\n          destinationPointer := add(destinationPointer, sourceLength)\r\n        }\r\n      }\r\n      assembly {\r\n        // protect output bytes\r\n        mstore(output, destinationLength)\r\n        // set final output length\r\n        mstore(0x40, add(mload(0x40), add(destinationLength, 32)))\r\n      }\r\n    }\r\n  }\r\n\r\n  function fork(WitnetBuffer.Buffer memory buffer)\r\n    internal pure\r\n    returns (WitnetBuffer.Buffer memory)\r\n  {\r\n    return Buffer(\r\n      buffer.data,\r\n      buffer.cursor\r\n    );\r\n  }\r\n\r\n  function mutate(\r\n      WitnetBuffer.Buffer memory buffer,\r\n      uint length,\r\n      bytes memory pokes\r\n    )\r\n    internal pure\r\n    withinRange(length, buffer.data.length - buffer.cursor + 1)\r\n  {\r\n    bytes[] memory parts = new bytes[](3);\r\n    parts[0] = peek(\r\n      buffer,\r\n      0,\r\n      buffer.cursor\r\n    );\r\n    parts[1] = pokes;\r\n    parts[2] = peek(\r\n      buffer,\r\n      buffer.cursor + length,\r\n      buffer.data.length - buffer.cursor - length\r\n    );\r\n    buffer.data = concat(parts);\r\n  }\r\n\r\n  /// @notice Read and consume the next byte from the buffer.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return The next byte in the buffer counting from the cursor position.\r\n  function next(Buffer memory buffer)\r\n    internal pure\r\n    withinRange(buffer.cursor, buffer.data.length)\r\n    returns (bytes1)\r\n  {\r\n    // Return the byte at the position marked by the cursor and advance the cursor all at once\r\n    return buffer.data[buffer.cursor ++];\r\n  }\r\n\r\n  function peek(\r\n      WitnetBuffer.Buffer memory buffer,\r\n      uint offset,\r\n      uint length\r\n    )\r\n    internal pure\r\n    withinRange(offset + length, buffer.data.length)\r\n    returns (bytes memory)\r\n  {\r\n    bytes memory data = buffer.data;\r\n    bytes memory peeks = new bytes(length);\r\n    uint destinationPointer;\r\n    uint sourcePointer;\r\n    assembly {\r\n      destinationPointer := add(peeks, 32)\r\n      sourcePointer := add(add(data, 32), offset)\r\n    }\r\n    memcpy(\r\n      destinationPointer,\r\n      sourcePointer,\r\n      length\r\n    );\r\n    return peeks;\r\n  }\r\n\r\n  // @notice Extract bytes array from buffer starting from current cursor.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @param length How many bytes to peek from the Buffer.\r\n  // solium-disable-next-line security/no-assign-params\r\n  function peek(\r\n      WitnetBuffer.Buffer memory buffer,\r\n      uint length\r\n    )\r\n    internal pure\r\n    withinRange(length, buffer.data.length - buffer.cursor)\r\n    returns (bytes memory)\r\n  {\r\n    return peek(\r\n      buffer,\r\n      buffer.cursor,\r\n      length\r\n    );\r\n  }\r\n\r\n  /// @notice Read and consume a certain amount of bytes from the buffer.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @param length How many bytes to read and consume from the buffer.\r\n  /// @return output A `bytes memory` containing the first `length` bytes from the buffer, counting from the cursor position.\r\n  function read(Buffer memory buffer, uint length)\r\n    internal pure\r\n    withinRange(buffer.cursor + length, buffer.data.length)\r\n    returns (bytes memory output)\r\n  {\r\n    // Create a new `bytes memory destination` value\r\n    output = new bytes(length);\r\n    // Early return in case that bytes length is 0\r\n    if (length > 0) {\r\n      bytes memory input = buffer.data;\r\n      uint offset = buffer.cursor;\r\n      // Get raw pointers for source and destination\r\n      uint sourcePointer;\r\n      uint destinationPointer;\r\n      assembly {\r\n        sourcePointer := add(add(input, 32), offset)\r\n        destinationPointer := add(output, 32)\r\n      }\r\n      // Copy `length` bytes from source to destination\r\n      memcpy(\r\n        destinationPointer,\r\n        sourcePointer,\r\n        length\r\n      );\r\n      // Move the cursor forward by `length` bytes\r\n      seek(\r\n        buffer,\r\n        length,\r\n        true\r\n      );\r\n    }\r\n  }\r\n  \r\n  /// @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an\r\n  /// `int32`.\r\n  /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values\r\n  /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16`\r\n  /// use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are\r\n  /// expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return result The `int32` value of the next 4 bytes in the buffer counting from the cursor position.\r\n  function readFloat16(Buffer memory buffer)\r\n    internal pure\r\n    returns (int32 result)\r\n  {\r\n    uint32 value = readUint16(buffer);\r\n    // Get bit at position 0\r\n    uint32 sign = value & 0x8000;\r\n    // Get bits 1 to 5, then normalize to the [-15, 16] range so as to counterweight the IEEE 754 exponent bias\r\n    int32 exponent = (int32(value & 0x7c00) >> 10) - 15;\r\n    // Get bits 6 to 15\r\n    int32 fraction = int32(value & 0x03ff);\r\n    // Add 2^10 to the fraction if exponent is not -15\r\n    if (exponent != -15) {\r\n      fraction |= 0x400;\r\n    } else if (exponent == 16) {\r\n      revert(\r\n        string(abi.encodePacked(\r\n          \"WitnetBuffer.readFloat16: \",\r\n          sign != 0 ? \"negative\" : hex\"\",\r\n          \" infinity\"\r\n        ))\r\n      );\r\n    }\r\n    // Compute `2 ^ exponent · (1 + fraction / 1024)`\r\n    if (exponent >= 0) {\r\n      result = int32(int(\r\n        int(1 << uint256(int256(exponent)))\r\n          * 10000\r\n          * fraction\r\n      ) >> 10);\r\n    } else {\r\n      result = int32(int(\r\n        int(fraction)\r\n          * 10000\r\n          / int(1 << uint(int(- exponent)))\r\n      ) >> 10);\r\n    }\r\n    // Make the result negative if the sign bit is not 0\r\n    if (sign != 0) {\r\n      result *= -1;\r\n    }\r\n  }\r\n\r\n  /// @notice Consume the next 4 bytes from the buffer as an IEEE 754-2008 floating point number enclosed into an `int`.\r\n  /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values\r\n  /// by 9 decimal orders so as to get a fixed precision of 9 decimal positions, which should be OK for most `float32`\r\n  /// use cases. In other words, the integer output of this method is 10^9 times the actual value. The input bytes are\r\n  /// expected to follow the 64-bit base-2 format (a.k.a. `binary32`) in the IEEE 754-2008 standard.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return result The `int` value of the next 8 bytes in the buffer counting from the cursor position.\r\n  function readFloat32(Buffer memory buffer)\r\n    internal pure\r\n    returns (int result)\r\n  {\r\n    uint value = readUint32(buffer);\r\n    // Get bit at position 0\r\n    uint sign = value & 0x80000000;\r\n    // Get bits 1 to 8, then normalize to the [-127, 128] range so as to counterweight the IEEE 754 exponent bias\r\n    int exponent = (int(value & 0x7f800000) >> 23) - 127;\r\n    // Get bits 9 to 31\r\n    int fraction = int(value & 0x007fffff);\r\n    // Add 2^23 to the fraction if exponent is not -127\r\n    if (exponent != -127) {\r\n      fraction |= 0x800000;\r\n    } else if (exponent == 128) {\r\n      revert(\r\n        string(abi.encodePacked(\r\n          \"WitnetBuffer.readFloat32: \",\r\n          sign != 0 ? \"negative\" : hex\"\",\r\n          \" infinity\"\r\n        ))\r\n      );\r\n    }\r\n    // Compute `2 ^ exponent · (1 + fraction / 2^23)`\r\n    if (exponent >= 0) {\r\n      result = (\r\n        int(1 << uint(exponent))\r\n          * (10 ** 9)\r\n          * fraction\r\n      ) >> 23;\r\n    } else {\r\n      result = (\r\n        fraction \r\n          * (10 ** 9)\r\n          / int(1 << uint(-exponent)) \r\n      ) >> 23;\r\n    }\r\n    // Make the result negative if the sign bit is not 0\r\n    if (sign != 0) {\r\n      result *= -1;\r\n    }\r\n  }\r\n\r\n  /// @notice Consume the next 8 bytes from the buffer as an IEEE 754-2008 floating point number enclosed into an `int`.\r\n  /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values\r\n  /// by 15 decimal orders so as to get a fixed precision of 15 decimal positions, which should be OK for most `float64`\r\n  /// use cases. In other words, the integer output of this method is 10^15 times the actual value. The input bytes are\r\n  /// expected to follow the 64-bit base-2 format (a.k.a. `binary64`) in the IEEE 754-2008 standard.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return result The `int` value of the next 8 bytes in the buffer counting from the cursor position.\r\n  function readFloat64(Buffer memory buffer)\r\n    internal pure\r\n    returns (int result)\r\n  {\r\n    uint value = readUint64(buffer);\r\n    // Get bit at position 0\r\n    uint sign = value & 0x8000000000000000;\r\n    // Get bits 1 to 12, then normalize to the [-1023, 1024] range so as to counterweight the IEEE 754 exponent bias\r\n    int exponent = (int(value & 0x7ff0000000000000) >> 52) - 1023;\r\n    // Get bits 6 to 15\r\n    int fraction = int(value & 0x000fffffffffffff);\r\n    // Add 2^52 to the fraction if exponent is not -1023\r\n    if (exponent != -1023) {\r\n      fraction |= 0x10000000000000;\r\n    } else if (exponent == 1024) {\r\n      revert(\r\n        string(abi.encodePacked(\r\n          \"WitnetBuffer.readFloat64: \",\r\n          sign != 0 ? \"negative\" : hex\"\",\r\n          \" infinity\"\r\n        ))\r\n      );\r\n    }\r\n    // Compute `2 ^ exponent · (1 + fraction / 1024)`\r\n    if (exponent >= 0) {\r\n      result = (\r\n        int(1 << uint(exponent))\r\n          * (10 ** 15)\r\n          * fraction\r\n      ) >> 52;\r\n    } else {\r\n      result = (\r\n        fraction \r\n          * (10 ** 15)\r\n          / int(1 << uint(-exponent)) \r\n      ) >> 52;\r\n    }\r\n    // Make the result negative if the sign bit is not 0\r\n    if (sign != 0) {\r\n      result *= -1;\r\n    }\r\n  }\r\n\r\n  // Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness,\r\n  /// but it can be easily casted into a string with `string(result)`.\r\n  // solium-disable-next-line security/no-assign-params\r\n  function readText(\r\n      WitnetBuffer.Buffer memory buffer,\r\n      uint64 length\r\n    )\r\n    internal pure\r\n    returns (bytes memory text)\r\n  {\r\n    text = new bytes(length);\r\n    unchecked {\r\n      for (uint64 index = 0; index < length; index ++) {\r\n        uint8 char = readUint8(buffer);\r\n        if (char & 0x80 != 0) {\r\n          if (char < 0xe0) {\r\n            char = (char & 0x1f) << 6\r\n              | (readUint8(buffer) & 0x3f);\r\n            length -= 1;\r\n          } else if (char < 0xf0) {\r\n            char  = (char & 0x0f) << 12\r\n              | (readUint8(buffer) & 0x3f) << 6\r\n              | (readUint8(buffer) & 0x3f);\r\n            length -= 2;\r\n          } else {\r\n            char = (char & 0x0f) << 18\r\n              | (readUint8(buffer) & 0x3f) << 12\r\n              | (readUint8(buffer) & 0x3f) << 6  \r\n              | (readUint8(buffer) & 0x3f);\r\n            length -= 3;\r\n          }\r\n        }\r\n        text[index] = bytes1(char);\r\n      }\r\n      // Adjust text to actual length:\r\n      assembly {\r\n        mstore(text, length)\r\n      }\r\n    }\r\n  }\r\n\r\n  /// @notice Read and consume the next byte from the buffer as an `uint8`.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return value The `uint8` value of the next byte in the buffer counting from the cursor position.\r\n  function readUint8(Buffer memory buffer)\r\n    internal pure\r\n    withinRange(buffer.cursor, buffer.data.length)\r\n    returns (uint8 value)\r\n  {\r\n    bytes memory data = buffer.data;\r\n    uint offset = buffer.cursor;\r\n    assembly {\r\n      value := mload(add(add(data, 1), offset))\r\n    }\r\n    buffer.cursor ++;\r\n  }\r\n\r\n  /// @notice Read and consume the next 2 bytes from the buffer as an `uint16`.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return value The `uint16` value of the next 2 bytes in the buffer counting from the cursor position.\r\n  function readUint16(Buffer memory buffer)\r\n    internal pure\r\n    withinRange(buffer.cursor + 2, buffer.data.length)\r\n    returns (uint16 value)\r\n  {\r\n    bytes memory data = buffer.data;\r\n    uint offset = buffer.cursor;\r\n    assembly {\r\n      value := mload(add(add(data, 2), offset))\r\n    }\r\n    buffer.cursor += 2;\r\n  }\r\n\r\n  /// @notice Read and consume the next 4 bytes from the buffer as an `uint32`.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return value The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.\r\n  function readUint32(Buffer memory buffer)\r\n    internal pure\r\n    withinRange(buffer.cursor + 4, buffer.data.length)\r\n    returns (uint32 value)\r\n  {\r\n    bytes memory data = buffer.data;\r\n    uint offset = buffer.cursor;\r\n    assembly {\r\n      value := mload(add(add(data, 4), offset))\r\n    }\r\n    buffer.cursor += 4;\r\n  }\r\n\r\n  /// @notice Read and consume the next 8 bytes from the buffer as an `uint64`.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return value The `uint64` value of the next 8 bytes in the buffer counting from the cursor position.\r\n  function readUint64(Buffer memory buffer)\r\n    internal pure\r\n    withinRange(buffer.cursor + 8, buffer.data.length)\r\n    returns (uint64 value)\r\n  {\r\n    bytes memory data = buffer.data;\r\n    uint offset = buffer.cursor;\r\n    assembly {\r\n      value := mload(add(add(data, 8), offset))\r\n    }\r\n    buffer.cursor += 8;\r\n  }\r\n\r\n  /// @notice Read and consume the next 16 bytes from the buffer as an `uint128`.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return value The `uint128` value of the next 16 bytes in the buffer counting from the cursor position.\r\n  function readUint128(Buffer memory buffer)\r\n    internal pure\r\n    withinRange(buffer.cursor + 16, buffer.data.length)\r\n    returns (uint128 value)\r\n  {\r\n    bytes memory data = buffer.data;\r\n    uint offset = buffer.cursor;\r\n    assembly {\r\n      value := mload(add(add(data, 16), offset))\r\n    }\r\n    buffer.cursor += 16;\r\n  }\r\n\r\n  /// @notice Read and consume the next 32 bytes from the buffer as an `uint256`.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @return value The `uint256` value of the next 32 bytes in the buffer counting from the cursor position.\r\n  function readUint256(Buffer memory buffer)\r\n    internal pure\r\n    withinRange(buffer.cursor + 32, buffer.data.length)\r\n    returns (uint256 value)\r\n  {\r\n    bytes memory data = buffer.data;\r\n    uint offset = buffer.cursor;\r\n    assembly {\r\n      value := mload(add(add(data, 32), offset))\r\n    }\r\n    buffer.cursor += 32;\r\n  }\r\n\r\n  /// @notice Count number of required parameters for given bytes arrays\r\n  /// @dev Wildcard format: \"\\#\\\", with # in [\"0\"..\"9\"].\r\n  /// @param input Bytes array containing strings.\r\n  /// @param count Highest wildcard index found, plus 1.\r\n  function argsCountOf(bytes memory input)\r\n    internal pure\r\n    returns (uint8 count)\r\n  {\r\n    if (input.length < 3) {\r\n      return 0;\r\n    }\r\n    unchecked {\r\n      uint ix = 0; \r\n      uint length = input.length - 2;\r\n      for (; ix < length; ) {\r\n        if (\r\n          input[ix] == bytes1(\"\\\\\")\r\n            && input[ix + 2] == bytes1(\"\\\\\")\r\n            && input[ix + 1] >= bytes1(\"0\")\r\n            && input[ix + 1] <= bytes1(\"9\")\r\n        ) {\r\n          uint8 ax = uint8(uint8(input[ix + 1]) - uint8(bytes1(\"0\")) + 1);\r\n          if (ax > count) {\r\n            count = ax;\r\n          }\r\n          ix += 3;\r\n        } else {\r\n          ix ++;\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  /// @notice Replace indexed bytes-wildcards by correspondent substrings.\r\n  /// @dev Wildcard format: \"\\#\\\", with # in [\"0\"..\"9\"].\r\n  /// @param input Bytes array containing strings.\r\n  /// @param args Array of substring values for replacing indexed wildcards.\r\n  /// @return output Resulting bytes array after replacing all wildcards.\r\n  /// @return hits Total number of replaced wildcards.\r\n  function replace(bytes memory input, string[] memory args)\r\n    internal pure\r\n    returns (bytes memory output, uint hits)\r\n  {\r\n    uint ix = 0; uint lix = 0;\r\n    uint inputLength;\r\n    uint inputPointer;\r\n    uint outputLength;\r\n    uint outputPointer;    \r\n    uint source;\r\n    uint sourceLength;\r\n    uint sourcePointer;\r\n\r\n    if (input.length < 3) {\r\n      return (input, 0);\r\n    }\r\n    \r\n    assembly {\r\n      // set starting input pointer\r\n      inputPointer := add(input, 32)\r\n      // get safe output location\r\n      output := mload(0x40)\r\n      // set starting output pointer\r\n      outputPointer := add(output, 32)\r\n    }         \r\n\r\n    unchecked {\r\n      uint length = input.length - 2;\r\n      for (; ix < length; ) {\r\n        if (\r\n          input[ix] == bytes1(\"\\\\\")\r\n            && input[ix + 2] == bytes1(\"\\\\\")\r\n            && input[ix + 1] >= bytes1(\"0\")\r\n            && input[ix + 1] <= bytes1(\"9\")\r\n        ) {\r\n          inputLength = (ix - lix);\r\n          if (ix > lix) {\r\n            memcpy(\r\n              outputPointer,\r\n              inputPointer,\r\n              inputLength\r\n            );\r\n            inputPointer += inputLength + 3;\r\n            outputPointer += inputLength;\r\n          } else {\r\n            inputPointer += 3;\r\n          }\r\n          uint ax = uint(uint8(input[ix + 1]) - uint8(bytes1(\"0\")));\r\n          if (ax >= args.length) {\r\n            revert MissingArgs(ax + 1, args.length);\r\n          }\r\n          assembly {\r\n            source := mload(add(args, mul(32, add(ax, 1))))\r\n            sourceLength := mload(source)\r\n            sourcePointer := add(source, 32)      \r\n          }        \r\n          memcpy(\r\n            outputPointer,\r\n            sourcePointer,\r\n            sourceLength\r\n          );\r\n          outputLength += inputLength + sourceLength;\r\n          outputPointer += sourceLength;\r\n          ix += 3;\r\n          lix = ix;\r\n          hits ++;\r\n        } else {\r\n          ix ++;\r\n        }\r\n      }\r\n      ix = input.length;    \r\n    }\r\n    if (outputLength > 0) {\r\n      if (ix > lix ) {\r\n        memcpy(\r\n          outputPointer,\r\n          inputPointer,\r\n          ix - lix\r\n        );\r\n        outputLength += (ix - lix);\r\n      }\r\n      assembly {\r\n        // set final output length\r\n        mstore(output, outputLength)\r\n        // protect output bytes\r\n        mstore(0x40, add(mload(0x40), add(outputLength, 32)))\r\n      }\r\n    }\r\n    else {\r\n      return (input, 0);\r\n    }\r\n  }\r\n\r\n  /// @notice Replace indexed bytes-wildcard by given substring.\r\n  /// @dev Wildcard format: \"\\#\\\", with # in [\"0\"..\"9\"].\r\n  /// @param input Bytes array containing strings.\r\n  /// @param argIndex Index of the wildcard to be replaced.\r\n  /// @param argValue Replacing substring to be used.\r\n  /// @return output Resulting bytes array after replacing all wildcards.\r\n  /// @return hits Total number of replaced wildcards.\r\n  function replace(bytes memory input, uint8 argIndex, string memory argValue)\r\n    internal pure\r\n    returns (bytes memory output, uint hits)\r\n  {\r\n    uint ix = 0; uint lix = 0;\r\n    uint inputLength;\r\n    uint inputPointer;\r\n    uint outputLength;\r\n    uint outputPointer; \r\n    uint argValueLength;\r\n    uint argValuePointer;\r\n\r\n    if (input.length < 3) {\r\n      return (input, 0);\r\n    }\r\n    \r\n    assembly {\r\n      // set starting input pointer\r\n      inputPointer := add(input, 32)\r\n      // get safe output location\r\n      output := mload(0x40)\r\n      // set starting output pointer\r\n      outputPointer := add(output, 32)\r\n      // set pointer to arg value substring\r\n      argValuePointer := add(argValue, 32)\r\n      // set arg value substring length\r\n      argValueLength := mload(argValue)\r\n    }         \r\n\r\n    unchecked {\r\n      uint length = input.length - 2;\r\n      for (; ix < length; ) {\r\n        if (\r\n          input[ix] == bytes1(\"\\\\\")\r\n            && input[ix + 2] == bytes1(\"\\\\\")\r\n            && input[ix + 1] >= bytes1(\"0\")\r\n            && input[ix + 1] <= bytes1(\"9\")\r\n            && uint8(input[ix + 1]) - uint8(bytes1(\"0\")) == argIndex\r\n        ) {\r\n          inputLength = (ix - lix);\r\n          if (ix > lix) {\r\n            memcpy(\r\n              outputPointer,\r\n              inputPointer,\r\n              inputLength\r\n            );\r\n            inputPointer += inputLength + 3;\r\n            outputPointer += inputLength;\r\n          } else {\r\n            inputPointer += 3;\r\n          }\r\n          memcpy(\r\n            outputPointer,\r\n            argValuePointer,\r\n            argValueLength\r\n          );\r\n          outputLength += inputLength + argValueLength;\r\n          outputPointer += argValueLength;\r\n          ix += 3;\r\n          lix = ix;\r\n          hits ++;\r\n        } else {\r\n          ix ++;\r\n        }\r\n      }\r\n      ix = input.length;    \r\n    }\r\n    if (outputLength > 0) {\r\n      if (ix > lix ) {\r\n        memcpy(\r\n          outputPointer,\r\n          inputPointer,\r\n          ix - lix\r\n        );\r\n        outputLength += (ix - lix);\r\n      }\r\n      assembly {\r\n        // set final output length\r\n        mstore(output, outputLength)\r\n        // protect output bytes\r\n        mstore(0x40, add(mload(0x40), add(outputLength, 32)))\r\n      }\r\n    }\r\n    else {\r\n      return (input, 0);\r\n    }\r\n  }\r\n\r\n  /// @notice Replace indexed string wildcards by correspondent substrings.\r\n  /// @dev Wildcard format: \"\\#\\\", with # in [\"0\"..\"9\"].\r\n  /// @param input String potentially containing wildcards.\r\n  /// @param args Array of substring values for replacing indexed wildcards.\r\n  /// @return output Resulting string after replacing all wildcards.\r\n  function replace(string memory input, string[] memory args)\r\n    internal pure\r\n    returns (string memory)\r\n  {\r\n    (bytes memory _outputBytes, ) = replace(bytes(input), args);\r\n    return string(_outputBytes);\r\n  }\r\n\r\n  /// @notice Replace last indexed wildcard by given substring.\r\n  /// @dev Wildcard format: \"\\#\\\", with # in [\"0\"..\"9\"].\r\n  /// @param input String potentially containing wildcards.\r\n  /// @param argIndex Index of the wildcard to be replaced.\r\n  /// @param argValue Replacing string to be used.\r\n  /// @return output Resulting string after replacing all wildcards.\r\n  function replace(string memory input, uint8 argIndex, string memory argValue)\r\n    internal pure\r\n    returns (string memory)\r\n  {\r\n    (bytes memory _outputBytes, ) = replace(bytes(input), argIndex, argValue);\r\n    return string(_outputBytes);\r\n  }\r\n\r\n  /// @notice Move the inner cursor of the buffer to a relative or absolute position.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @param offset How many bytes to move the cursor forward.\r\n  /// @param relative Whether to count `offset` from the last position of the cursor (`true`) or the beginning of the\r\n  /// buffer (`true`).\r\n  /// @return The final position of the cursor (will equal `offset` if `relative` is `false`).\r\n  // solium-disable-next-line security/no-assign-params\r\n  function seek(\r\n      Buffer memory buffer,\r\n      uint offset,\r\n      bool relative\r\n    )\r\n    internal pure\r\n    withinRange(offset, buffer.data.length)\r\n    returns (uint)\r\n  {\r\n    // Deal with relative offsets\r\n    if (relative) {\r\n      offset += buffer.cursor;\r\n    }\r\n    buffer.cursor = offset;\r\n    return offset;\r\n  }\r\n\r\n  /// @notice Move the inner cursor a number of bytes forward.\r\n  /// @dev This is a simple wrapper around the relative offset case of `seek()`.\r\n  /// @param buffer An instance of `Buffer`.\r\n  /// @param relativeOffset How many bytes to move the cursor forward.\r\n  /// @return The final position of the cursor.\r\n  function seek(\r\n      Buffer memory buffer,\r\n      uint relativeOffset\r\n    )\r\n    internal pure\r\n    returns (uint)\r\n  {\r\n    return seek(\r\n      buffer,\r\n      relativeOffset,\r\n      true\r\n    );\r\n  }\r\n\r\n  /// @notice Copy bytes from one memory address into another.\r\n  /// @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms\r\n  /// of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE).\r\n  /// @param dest Address of the destination memory.\r\n  /// @param src Address to the source memory.\r\n  /// @param len How many bytes to copy.\r\n  // solium-disable-next-line security/no-assign-params\r\n  function memcpy(\r\n      uint dest,\r\n      uint src,\r\n      uint len\r\n    )\r\n    private pure\r\n  {\r\n    unchecked {\r\n      // Copy word-length chunks while possible\r\n      for (; len >= 32; len -= 32) {\r\n        assembly {\r\n          mstore(dest, mload(src))\r\n        }\r\n        dest += 32;\r\n        src += 32;\r\n      }\r\n      if (len > 0) {\r\n        // Copy remaining bytes\r\n        uint _mask = 256 ** (32 - len) - 1;\r\n        assembly {\r\n          let srcpart := and(mload(src), not(_mask))\r\n          let destpart := and(mload(dest), _mask)\r\n          mstore(dest, or(destpart, srcpart))\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n}"
      },
      "project/contracts/libs/WitnetCBOR.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./WitnetBuffer.sol\";\r\n\r\n/// @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation”\r\n/// @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize\r\n/// the gas cost of decoding them into a useful native type.\r\n/// @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js\r\n/// @author The Witnet Foundation.\r\n\r\nlibrary WitnetCBOR {\r\n\r\n  using WitnetBuffer for WitnetBuffer.Buffer;\r\n  using WitnetCBOR for WitnetCBOR.CBOR;\r\n\r\n  /// Data struct following the RFC-7049 standard: Concise Binary Object Representation.\r\n  struct CBOR {\r\n      WitnetBuffer.Buffer buffer;\r\n      uint8 initialByte;\r\n      uint8 majorType;\r\n      uint8 additionalInformation;\r\n      uint64 len;\r\n      uint64 tag;\r\n  }\r\n\r\n  uint8 internal constant MAJOR_TYPE_INT = 0;\r\n  uint8 internal constant MAJOR_TYPE_NEGATIVE_INT = 1;\r\n  uint8 internal constant MAJOR_TYPE_BYTES = 2;\r\n  uint8 internal constant MAJOR_TYPE_STRING = 3;\r\n  uint8 internal constant MAJOR_TYPE_ARRAY = 4;\r\n  uint8 internal constant MAJOR_TYPE_MAP = 5;\r\n  uint8 internal constant MAJOR_TYPE_TAG = 6;\r\n  uint8 internal constant MAJOR_TYPE_CONTENT_FREE = 7;\r\n\r\n  uint32 internal constant UINT32_MAX = type(uint32).max;\r\n  uint64 internal constant UINT64_MAX = type(uint64).max;\r\n  \r\n  error EmptyArray();\r\n  error InvalidLengthEncoding(uint length);\r\n  error UnexpectedMajorType(uint read, uint expected);\r\n  error UnsupportedPrimitive(uint primitive);\r\n  error UnsupportedMajorType(uint unexpected);  \r\n\r\n  modifier isMajorType(\r\n      WitnetCBOR.CBOR memory cbor,\r\n      uint8 expected\r\n  ) {\r\n    if (cbor.majorType != expected) {\r\n      revert UnexpectedMajorType(cbor.majorType, expected);\r\n    }\r\n    _;\r\n  }\r\n\r\n  modifier notEmpty(WitnetBuffer.Buffer memory buffer) {\r\n    if (buffer.data.length == 0) {\r\n      revert WitnetBuffer.EmptyBuffer();\r\n    }\r\n    _;\r\n  }\r\n\r\n  function eof(CBOR memory cbor)\r\n    internal pure\r\n    returns (bool)\r\n  {\r\n    return cbor.buffer.cursor >= cbor.buffer.data.length;\r\n  }\r\n\r\n  /// @notice Decode a CBOR structure from raw bytes.\r\n  /// @dev This is the main factory for CBOR instances, which can be later decoded into native EVM types.\r\n  /// @param bytecode Raw bytes representing a CBOR-encoded value.\r\n  /// @return A `CBOR` instance containing a partially decoded value.\r\n  function fromBytes(bytes memory bytecode)\r\n    internal pure\r\n    returns (CBOR memory)\r\n  {\r\n    WitnetBuffer.Buffer memory buffer = WitnetBuffer.Buffer(bytecode, 0);\r\n    return fromBuffer(buffer);\r\n  }\r\n\r\n  /// @notice Decode a CBOR structure from raw bytes.\r\n  /// @dev This is an alternate factory for CBOR instances, which can be later decoded into native EVM types.\r\n  /// @param buffer A Buffer structure representing a CBOR-encoded value.\r\n  /// @return A `CBOR` instance containing a partially decoded value.\r\n  function fromBuffer(WitnetBuffer.Buffer memory buffer)\r\n    internal pure\r\n    notEmpty(buffer)\r\n    returns (CBOR memory)\r\n  {\r\n    uint8 initialByte;\r\n    uint8 majorType = 255;\r\n    uint8 additionalInformation;\r\n    uint64 tag = UINT64_MAX;\r\n    uint256 len;\r\n    bool isTagged = true;\r\n    while (isTagged) {\r\n      // Extract basic CBOR properties from input bytes\r\n      initialByte = buffer.readUint8();\r\n      len ++;\r\n      majorType = initialByte >> 5;\r\n      additionalInformation = initialByte & 0x1f;\r\n      // Early CBOR tag parsing.\r\n      if (majorType == MAJOR_TYPE_TAG) {\r\n        uint _cursor = buffer.cursor;\r\n        tag = readLength(buffer, additionalInformation);\r\n        len += buffer.cursor - _cursor;\r\n      } else {\r\n        isTagged = false;\r\n      }\r\n    }\r\n    if (majorType > MAJOR_TYPE_CONTENT_FREE) {\r\n      revert UnsupportedMajorType(majorType);\r\n    }\r\n    return CBOR(\r\n      buffer,\r\n      initialByte,\r\n      majorType,\r\n      additionalInformation,\r\n      uint64(len),\r\n      tag\r\n    );\r\n  }\r\n\r\n  function fork(WitnetCBOR.CBOR memory self)\r\n    internal pure\r\n    returns (WitnetCBOR.CBOR memory)\r\n  {\r\n    return CBOR({\r\n      buffer: self.buffer.fork(),\r\n      initialByte: self.initialByte,\r\n      majorType: self.majorType,\r\n      additionalInformation: self.additionalInformation,\r\n      len: self.len,\r\n      tag: self.tag\r\n    });\r\n  }\r\n\r\n  function settle(CBOR memory self)\r\n      internal pure\r\n      returns (WitnetCBOR.CBOR memory)\r\n  {\r\n    if (!self.eof()) {\r\n      return fromBuffer(self.buffer);\r\n    } else {\r\n      return self;\r\n    }\r\n  }\r\n\r\n  function skip(CBOR memory self)\r\n      internal pure\r\n      returns (WitnetCBOR.CBOR memory)\r\n  {\r\n    if (\r\n      self.majorType == MAJOR_TYPE_INT\r\n        || self.majorType == MAJOR_TYPE_NEGATIVE_INT\r\n        || (\r\n          self.majorType == MAJOR_TYPE_CONTENT_FREE \r\n            && self.additionalInformation >= 25\r\n            && self.additionalInformation <= 27\r\n        )\r\n    ) {\r\n      self.buffer.cursor += self.peekLength();\r\n    } else if (\r\n        self.majorType == MAJOR_TYPE_STRING\r\n          || self.majorType == MAJOR_TYPE_BYTES\r\n    ) {\r\n      uint64 len = readLength(self.buffer, self.additionalInformation);\r\n      self.buffer.cursor += len;\r\n    } else if (\r\n      self.majorType == MAJOR_TYPE_ARRAY\r\n        || self.majorType == MAJOR_TYPE_MAP\r\n    ) { \r\n      self.len = readLength(self.buffer, self.additionalInformation);      \r\n    } else if (\r\n       self.majorType != MAJOR_TYPE_CONTENT_FREE\r\n        || (\r\n          self.additionalInformation != 20\r\n            && self.additionalInformation != 21\r\n        )\r\n    ) {\r\n      revert(\"WitnetCBOR.skip: unsupported major type\");\r\n    }\r\n    return self;\r\n  }\r\n\r\n  function peekLength(CBOR memory self)\r\n    internal pure\r\n    returns (uint64)\r\n  {\r\n    if (self.additionalInformation < 24) {\r\n      return 0;\r\n    } else if (self.additionalInformation < 28) {\r\n      return uint64(1 << (self.additionalInformation - 24));\r\n    } else {\r\n      revert InvalidLengthEncoding(self.additionalInformation);\r\n    }\r\n  }\r\n\r\n  function readArray(CBOR memory self)\r\n    internal pure\r\n    isMajorType(self, MAJOR_TYPE_ARRAY)\r\n    returns (CBOR[] memory items)\r\n  {\r\n    // read array's length and move self cursor forward to the first array element:\r\n    uint64 len = readLength(self.buffer, self.additionalInformation);\r\n    items = new CBOR[](len + 1);\r\n    for (uint ix = 0; ix < len; ix ++) {\r\n      // settle next element in the array:\r\n      self = self.settle();\r\n      // fork it and added to the list of items to be returned:\r\n      items[ix] = self.fork();\r\n      if (self.majorType == MAJOR_TYPE_ARRAY) {\r\n        CBOR[] memory _subitems = self.readArray();\r\n        // move forward to the first element after inner array:\r\n        self = _subitems[_subitems.length - 1];\r\n      } else if (self.majorType == MAJOR_TYPE_MAP) {\r\n        CBOR[] memory _subitems = self.readMap();\r\n        // move forward to the first element after inner map:\r\n        self = _subitems[_subitems.length - 1];\r\n      } else {\r\n        // move forward to the next element:\r\n        self.skip();\r\n      }\r\n    }\r\n    // return self cursor as extra item at the end of the list,\r\n    // as to optimize recursion when jumping over nested arrays:\r\n    items[len] = self;\r\n  }\r\n\r\n  function readMap(CBOR memory self)\r\n    internal pure\r\n    isMajorType(self, MAJOR_TYPE_MAP)\r\n    returns (CBOR[] memory items)\r\n  {\r\n    // read number of items within the map and move self cursor forward to the first inner element:\r\n    uint64 len = readLength(self.buffer, self.additionalInformation) * 2;\r\n    items = new CBOR[](len + 1);\r\n    for (uint ix = 0; ix < len; ix ++) {\r\n      // settle next element in the array:\r\n      self = self.settle();\r\n      // fork it and added to the list of items to be returned:\r\n      items[ix] = self.fork();\r\n      if (ix % 2 == 0 && self.majorType != MAJOR_TYPE_STRING) {\r\n        revert UnexpectedMajorType(self.majorType, MAJOR_TYPE_STRING);\r\n      } else if (self.majorType == MAJOR_TYPE_ARRAY || self.majorType == MAJOR_TYPE_MAP) {\r\n        CBOR[] memory _subitems = (self.majorType == MAJOR_TYPE_ARRAY\r\n            ? self.readArray()\r\n            : self.readMap()\r\n        );\r\n        // move forward to the first element after inner array or map:\r\n        self = _subitems[_subitems.length - 1];\r\n      } else {\r\n        // move forward to the next element:\r\n        self.skip();\r\n      }\r\n    }\r\n    // return self cursor as extra item at the end of the list,\r\n    // as to optimize recursion when jumping over nested arrays:\r\n    items[len] = self;\r\n  }\r\n\r\n  /// Reads the length of the settle CBOR item from a buffer, consuming a different number of bytes depending on the\r\n  /// value of the `additionalInformation` argument.\r\n  function readLength(\r\n      WitnetBuffer.Buffer memory buffer,\r\n      uint8 additionalInformation\r\n    ) \r\n    internal pure\r\n    returns (uint64)\r\n  {\r\n    if (additionalInformation < 24) {\r\n      return additionalInformation;\r\n    }\r\n    if (additionalInformation == 24) {\r\n      return buffer.readUint8();\r\n    }\r\n    if (additionalInformation == 25) {\r\n      return buffer.readUint16();\r\n    }\r\n    if (additionalInformation == 26) {\r\n      return buffer.readUint32();\r\n    }\r\n    if (additionalInformation == 27) {\r\n      return buffer.readUint64();\r\n    }\r\n    if (additionalInformation == 31) {\r\n      return UINT64_MAX;\r\n    }\r\n    revert InvalidLengthEncoding(additionalInformation);\r\n  }\r\n\r\n  /// @notice Read a `CBOR` structure into a native `bool` value.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return The value represented by the input, as a `bool` value.\r\n  function readBool(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_CONTENT_FREE)\r\n    returns (bool)\r\n  {\r\n    if (cbor.additionalInformation == 20) {\r\n      return false;\r\n    } else if (cbor.additionalInformation == 21) {\r\n      return true;\r\n    } else {\r\n      revert UnsupportedPrimitive(cbor.additionalInformation);\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a native `bytes` value.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return output The value represented by the input, as a `bytes` value.   \r\n  function readBytes(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_BYTES)\r\n    returns (bytes memory output)\r\n  {\r\n    cbor.len = readLength(\r\n      cbor.buffer,\r\n      cbor.additionalInformation\r\n    );\r\n    if (cbor.len == UINT32_MAX) {\r\n      // These checks look repetitive but the equivalent loop would be more expensive.\r\n      uint32 length = uint32(_readIndefiniteStringLength(\r\n        cbor.buffer,\r\n        cbor.majorType\r\n      ));\r\n      if (length < UINT32_MAX) {\r\n        output = abi.encodePacked(cbor.buffer.read(length));\r\n        length = uint32(_readIndefiniteStringLength(\r\n          cbor.buffer,\r\n          cbor.majorType\r\n        ));\r\n        if (length < UINT32_MAX) {\r\n          output = abi.encodePacked(\r\n            output,\r\n            cbor.buffer.read(length)\r\n          );\r\n        }\r\n      }\r\n    } else {\r\n      return cbor.buffer.read(uint32(cbor.len));\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a `fixed16` value.\r\n  /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values\r\n  /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`\r\n  /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return The value represented by the input, as an `int128` value.\r\n  function readFloat16(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_CONTENT_FREE)\r\n    returns (int32)\r\n  {\r\n    if (cbor.additionalInformation == 25) {\r\n      return cbor.buffer.readFloat16();\r\n    } else {\r\n      revert UnsupportedPrimitive(cbor.additionalInformation);\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a `fixed32` value.\r\n  /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values\r\n  /// by 9 decimal orders so as to get a fixed precision of 9 decimal positions, which should be OK for most `fixed64`\r\n  /// use cases. In other words, the output of this method is 10^9 times the actual value, encoded into an `int`.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return The value represented by the input, as an `int` value.\r\n  function readFloat32(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_CONTENT_FREE)\r\n    returns (int)\r\n  {\r\n    if (cbor.additionalInformation == 26) {\r\n      return cbor.buffer.readFloat32();\r\n    } else {\r\n      revert UnsupportedPrimitive(cbor.additionalInformation);\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a `fixed64` value.\r\n  /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values\r\n  /// by 15 decimal orders so as to get a fixed precision of 15 decimal positions, which should be OK for most `fixed64`\r\n  /// use cases. In other words, the output of this method is 10^15 times the actual value, encoded into an `int`.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return The value represented by the input, as an `int` value.\r\n  function readFloat64(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_CONTENT_FREE)\r\n    returns (int)\r\n  {\r\n    if (cbor.additionalInformation == 27) {\r\n      return cbor.buffer.readFloat64();\r\n    } else {\r\n      revert UnsupportedPrimitive(cbor.additionalInformation);\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a native `int128[]` value whose inner values follow the same convention \r\n  /// @notice as explained in `decodeFixed16`.\r\n  /// @param cbor An instance of `CBOR`.\r\n  function readFloat16Array(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_ARRAY)\r\n    returns (int32[] memory values)\r\n  {\r\n    uint64 length = readLength(cbor.buffer, cbor.additionalInformation);\r\n    if (length < UINT64_MAX) {\r\n      values = new int32[](length);\r\n      for (uint64 i = 0; i < length; ) {\r\n        CBOR memory item = fromBuffer(cbor.buffer);\r\n        values[i] = readFloat16(item);\r\n        unchecked {\r\n          i ++;\r\n        }\r\n      }\r\n    } else {\r\n      revert InvalidLengthEncoding(length);\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a native `int128` value.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return The value represented by the input, as an `int128` value.\r\n  function readInt(CBOR memory cbor)\r\n    internal pure\r\n    returns (int64)\r\n  {\r\n    if (cbor.majorType == 1) {\r\n      uint64 _value = readLength(\r\n        cbor.buffer,\r\n        cbor.additionalInformation\r\n      );\r\n      return int64(-1) - int64(uint64(_value));\r\n    } else if (cbor.majorType == 0) {\r\n      // Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer\r\n      // a uniform API for positive and negative numbers\r\n      return int64(readUint(cbor));\r\n    }\r\n    else {\r\n      revert UnexpectedMajorType(cbor.majorType, 1);\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a native `int[]` value.\r\n  /// @param cbor instance of `CBOR`.\r\n  /// @return array The value represented by the input, as an `int[]` value.\r\n  function readIntArray(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_ARRAY)\r\n    returns (int64[] memory array)\r\n  {\r\n    uint64 length = readLength(cbor.buffer, cbor.additionalInformation);\r\n    if (length < UINT64_MAX) {\r\n      array = new int64[](length);\r\n      for (uint i = 0; i < length; ) {\r\n        CBOR memory item = fromBuffer(cbor.buffer);\r\n        array[i] = readInt(item);\r\n        unchecked {\r\n          i ++;\r\n        }\r\n      }\r\n    } else {\r\n      revert InvalidLengthEncoding(length);\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a native `string` value.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return text The value represented by the input, as a `string` value.\r\n  function readString(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_STRING)\r\n    returns (string memory text)\r\n  {\r\n    cbor.len = readLength(cbor.buffer, cbor.additionalInformation);\r\n    if (cbor.len == UINT64_MAX) {\r\n      bool _done;\r\n      while (!_done) {\r\n        uint64 length = _readIndefiniteStringLength(\r\n          cbor.buffer,\r\n          cbor.majorType\r\n        );\r\n        if (length < UINT64_MAX) {\r\n          text = string(abi.encodePacked(\r\n            text,\r\n            cbor.buffer.readText(length / 4)\r\n          ));\r\n        } else {\r\n          _done = true;\r\n        }\r\n      }\r\n    } else {\r\n      return string(cbor.buffer.readText(cbor.len));\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a native `string[]` value.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return strings The value represented by the input, as an `string[]` value.\r\n  function readStringArray(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_ARRAY)\r\n    returns (string[] memory strings)\r\n  {\r\n    uint length = readLength(cbor.buffer, cbor.additionalInformation);\r\n    if (length < UINT64_MAX) {\r\n      strings = new string[](length);\r\n      for (uint i = 0; i < length; ) {\r\n        CBOR memory item = fromBuffer(cbor.buffer);\r\n        strings[i] = readString(item);\r\n        unchecked {\r\n          i ++;\r\n        }\r\n      }\r\n    } else {\r\n      revert InvalidLengthEncoding(length);\r\n    }\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a native `uint64` value.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return The value represented by the input, as an `uint64` value.\r\n  function readUint(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_INT)\r\n    returns (uint64)\r\n  {\r\n    return readLength(\r\n      cbor.buffer,\r\n      cbor.additionalInformation\r\n    );\r\n  }\r\n\r\n  /// @notice Decode a `CBOR` structure into a native `uint64[]` value.\r\n  /// @param cbor An instance of `CBOR`.\r\n  /// @return values The value represented by the input, as an `uint64[]` value.\r\n  function readUintArray(CBOR memory cbor)\r\n    internal pure\r\n    isMajorType(cbor, MAJOR_TYPE_ARRAY)\r\n    returns (uint64[] memory values)\r\n  {\r\n    uint64 length = readLength(cbor.buffer, cbor.additionalInformation);\r\n    if (length < UINT64_MAX) {\r\n      values = new uint64[](length);\r\n      for (uint ix = 0; ix < length; ) {\r\n        CBOR memory item = fromBuffer(cbor.buffer);\r\n        values[ix] = readUint(item);\r\n        unchecked {\r\n          ix ++;\r\n        }\r\n      }\r\n    } else {\r\n      revert InvalidLengthEncoding(length);\r\n    }\r\n  }  \r\n\r\n  /// Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming\r\n  /// as many bytes as specified by the first byte.\r\n  function _readIndefiniteStringLength(\r\n      WitnetBuffer.Buffer memory buffer,\r\n      uint8 majorType\r\n    )\r\n    private pure\r\n    returns (uint64 len)\r\n  {\r\n    uint8 initialByte = buffer.readUint8();\r\n    if (initialByte == 0xff) {\r\n      return UINT64_MAX;\r\n    }\r\n    len = readLength(\r\n      buffer,\r\n      initialByte & 0x1f\r\n    );\r\n    if (len >= UINT64_MAX) {\r\n      revert InvalidLengthEncoding(len);\r\n    } else if (majorType != (initialByte >> 5)) {\r\n      revert UnexpectedMajorType((initialByte >> 5), majorType);\r\n    }\r\n  }\r\n \r\n}"
      },
      "project/contracts/libs/WitOracleRadonEncodingLib.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./Witnet.sol\";\r\n\r\n/// @title A library for encoding Witnet Data Requests.\r\n/// @author The Witnet Foundation.\r\nlibrary WitOracleRadonEncodingLib {\r\n\r\n    using WitnetBuffer for WitnetBuffer.Buffer;\r\n    using WitnetCBOR for WitnetCBOR.CBOR;\r\n    using WitnetCBOR for WitnetCBOR.CBOR[];\r\n\r\n    bytes internal constant WITNET_RADON_OPCODES_RESULT_TYPES =\r\n        hex\"10ffffffffffffffffffffffffffffff040100010203050406071311ff0101ff07ff02ffffffffffffffffffffffffff070304ff04ffffffffffffff03ffffff0405070202ff0404040403ffffffffff05070402040205050505ff04ff04ffff07010203050406070101ff06ffff06ff0203050404000106060707070701ffff\";\r\n            // 10ffffffffffffffffffffffffffffff\r\n            // 040100001203050406070100ff0101ff\r\n            // 07ff02ffffffffffffffffffffffffff\r\n            // 070304ff04ffffffffffffff03ffffff\r\n            // 0405070202ff0404040403ffffffffff\r\n            // 05070402040205050505ff04ff04ffff\r\n            // 07010203050406070101ff06ffff06ff\r\n            // 0203050404000106060707070701ffff\r\n\r\n    error UnsupportedDataRequestMethod(uint8 method, string schema, string body, string[2][] headers);\r\n    error UnsupportedRadonDataType(uint8 datatype, uint256 maxlength);\r\n    error UnsupportedRadonFilterOpcode(uint8 opcode);\r\n    error UnsupportedRadonFilterArgs(uint8 opcode, bytes args);\r\n    error UnsupportedRadonReducerOpcode(uint8 opcode);\r\n    error UnsupportedRadonReducerScript(uint8 opcode, bytes script, uint256 offset);\r\n    error UnsupportedRadonScript(bytes script, uint256 offset);\r\n    error UnsupportedRadonScriptOpcode(bytes script, uint256 cursor, uint8 opcode);\r\n    error UnsupportedRadonTallyScript(bytes32 hash);\r\n\r\n    /// ===============================================================================================================\r\n    /// --- WitOracleRadonEncodingLib internal methods --------------------------------------------------------------------------------\r\n\r\n    function size(Witnet.RadonDataTypes _type) internal pure returns (uint16) {\r\n        if (_type == Witnet.RadonDataTypes.Integer\r\n            || _type == Witnet.RadonDataTypes.Float\r\n        ) {\r\n            return 9;\r\n        } else if (_type == Witnet.RadonDataTypes.Bool) {\r\n            return 1;\r\n        } else {\r\n            // undetermined\r\n            return 0; \r\n        }\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- WitOracleRadonEncodingLib public methods (if used library will have to linked to calling contracts) -----------------------\r\n\r\n    /// @notice Encode bytes array into given major type (UTF-8 not yet supported)\r\n    /// @param buf Bytes array\r\n    /// @return Marshaled bytes\r\n    function encode(bytes memory buf, uint majorType)\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        uint len = buf.length;\r\n        if (len < 23) {\r\n            return abi.encodePacked(\r\n                uint8((majorType << 5) | uint8(len)),\r\n                buf\r\n            );\r\n        } else {\r\n            uint8 buf0 = uint8((majorType << 5));\r\n            bytes memory buf1;\r\n            if (len <= 0xff) {\r\n                buf0 |= 24;\r\n                buf1 = abi.encodePacked(uint8(len));                \r\n            } else if (len <= 0xffff) {\r\n                buf0 |= 25;\r\n                buf1 = abi.encodePacked(uint16(len));\r\n            } else if (len <= 0xffffffff) {\r\n                buf0 |= 26;\r\n                buf1 = abi.encodePacked(uint32(len));\r\n            } else {\r\n                buf0 |= 27;\r\n                buf1 = abi.encodePacked(uint64(len));\r\n            }\r\n            return abi.encodePacked(\r\n                buf0,\r\n                buf1,\r\n                buf\r\n            );\r\n        }\r\n    }\r\n\r\n    /// @notice Encode bytes array.\r\n    /// @param buf Bytes array\r\n    /// @return Mashaled bytes\r\n    function encode(bytes memory buf)\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        return encode(buf, WitnetCBOR.MAJOR_TYPE_BYTES);\r\n    } \r\n\r\n    /// @notice Encode string array (UTF-8 not yet supported).\r\n    /// @param str String bytes.\r\n    /// @return Mashaled bytes\r\n    function encode(string memory str)\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        return encode(bytes(str), WitnetCBOR.MAJOR_TYPE_STRING);\r\n    }\r\n\r\n    /// @dev Encode uint64 into tagged varint.\r\n    /// @dev See https://developers.google.com/protocol-buffers/docs/encoding#varints.\r\n    /// @param n Number\r\n    /// @param t Tag\r\n    /// @return buf Marshaled bytes\r\n    function encode(uint64 n, bytes1 t)\r\n        public pure\r\n        returns (bytes memory buf)\r\n    {\r\n        unchecked {\r\n            // Count the number of groups of 7 bits\r\n            // We need this pre-processing step since Solidity doesn't allow dynamic memory resizing\r\n            uint64 tmp = n;\r\n            uint64 numBytes = 2;\r\n            while (tmp > 0x7F) {\r\n                tmp = tmp >> 7;\r\n                numBytes += 1;\r\n            }\r\n            buf = new bytes(numBytes);\r\n            tmp = n;\r\n            buf[0] = t;\r\n            for (uint64 i = 1; i < numBytes; i++) {\r\n                // Set the first bit in the byte for each group of 7 bits\r\n                buf[i] = bytes1(0x80 | uint8(tmp & 0x7F));\r\n                tmp = tmp >> 7;\r\n            }\r\n            // Unset the first bit of the last byte\r\n            buf[numBytes - 1] &= 0x7F;\r\n        }\r\n    }   \r\n\r\n    function encode(Witnet.RadonRetrieval memory source)\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        bytes memory _encodedMethod = encode(uint64(source.method), bytes1(0x08));\r\n        bytes memory _encodedUrl;\r\n        if (bytes(source.url).length > 0) {\r\n            _encodedUrl = abi.encodePacked(\r\n                encode(uint64(bytes(source.url).length), bytes1(0x12)),\r\n                bytes(source.url)\r\n            );\r\n        }\r\n        bytes memory _encodedScript;\r\n        if (source.radonScript.length > 0) {\r\n            _encodedScript = abi.encodePacked(\r\n                encode(uint64(source.radonScript.length), bytes1(0x1a)),\r\n                source.radonScript\r\n            );\r\n        }\r\n        bytes memory _encodedBody;\r\n        if (bytes(source.body).length > 0) {\r\n            _encodedBody = abi.encodePacked(\r\n                encode(uint64(bytes(source.body).length), bytes1(0x22)),\r\n                bytes(source.body)\r\n            );\r\n        }\r\n        bytes memory _encodedHeaders;\r\n        if (source.headers.length > 0) {\r\n            for (uint _ix = 0; _ix < source.headers.length; _ix ++) {\r\n                bytes memory _headers = abi.encodePacked(\r\n                    encode(uint64(bytes(source.headers[_ix][0]).length), bytes1(0x0a)),\r\n                    bytes(source.headers[_ix][0]),\r\n                    encode(uint64(bytes(source.headers[_ix][1]).length), bytes1(0x12)),\r\n                    bytes(source.headers[_ix][1])\r\n                );\r\n                _encodedHeaders = abi.encodePacked(\r\n                    _encodedHeaders,\r\n                    encode(uint64(_headers.length), bytes1(0x2a)),\r\n                    _headers\r\n                );\r\n            }\r\n        }\r\n        uint _innerSize = (\r\n            _encodedMethod.length\r\n                + _encodedUrl.length\r\n                + _encodedScript.length\r\n                + _encodedBody.length\r\n                + _encodedHeaders.length\r\n        );\r\n        return abi.encodePacked(\r\n            encode(uint64(_innerSize), bytes1(0x12)),\r\n            _encodedMethod,\r\n            _encodedUrl,\r\n            _encodedScript,\r\n            _encodedBody,\r\n            _encodedHeaders\r\n        );\r\n    }\r\n\r\n    function encode(\r\n            Witnet.RadonRetrieval[] memory retrievals,\r\n            string[] calldata args,\r\n            bytes memory aggregatorInnerBytecode,\r\n            bytes memory tallyInnerBytecode\r\n        )\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        bytes[] memory encodedSources = new bytes[](retrievals.length);\r\n        for (uint ix; ix < retrievals.length; ++ ix) {\r\n            replaceWildcards(retrievals[ix], args);\r\n            encodedSources[ix] = encode(retrievals[ix]);\r\n        }\r\n        return abi.encodePacked(\r\n            WitnetBuffer.concat(encodedSources),\r\n            encode(uint64(aggregatorInnerBytecode.length), bytes1(0x1a)),\r\n            aggregatorInnerBytecode,\r\n            encode(uint64(tallyInnerBytecode.length), bytes1(0x22)),\r\n            tallyInnerBytecode\r\n        );\r\n    }\r\n    \r\n    function encode(\r\n            Witnet.RadonRetrieval[] memory sources,\r\n            string[][] memory args,\r\n            bytes memory aggregatorInnerBytecode,\r\n            bytes memory tallyInnerBytecode,\r\n            uint16\r\n        )\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        bytes[] memory encodedSources = new bytes[](sources.length);\r\n        for (uint ix = 0; ix < sources.length; ix ++) {\r\n            replaceWildcards(sources[ix], args[ix]);\r\n            encodedSources[ix] = encode(sources[ix]);\r\n        }\r\n        return abi.encodePacked(\r\n            WitnetBuffer.concat(encodedSources),\r\n            encode(uint64(aggregatorInnerBytecode.length), bytes1(0x1a)),\r\n            aggregatorInnerBytecode,\r\n            encode(uint64(tallyInnerBytecode.length), bytes1(0x22)),\r\n            tallyInnerBytecode\r\n        );\r\n    }\r\n\r\n    function encode(Witnet.RadonReducer memory reducer)\r\n        public pure\r\n        returns (bytes memory bytecode)\r\n    {\r\n        // if (reducer.script.length == 0) {\r\n            for (uint ix = 0; ix < reducer.filters.length; ix ++) {\r\n                bytecode = abi.encodePacked(\r\n                    bytecode,\r\n                    encode(reducer.filters[ix])\r\n                );\r\n            }\r\n            bytecode = abi.encodePacked(\r\n                bytecode,\r\n                encode(reducer.opcode)\r\n            );\r\n        // } else {\r\n        //     return abi.encodePacked(\r\n        //         encode(uint64(reducer.script.length), bytes1(0x18)),\r\n        //         reducer.script\r\n        //     );\r\n        // }\r\n    }\r\n\r\n    function encode(Witnet.RadonFilter memory filter)\r\n        public pure\r\n        returns (bytes memory bytecode)\r\n    {        \r\n        bytecode = abi.encodePacked(\r\n            encode(uint64(filter.opcode), bytes1(0x08)),\r\n            filter.cborArgs.length > 0\r\n                ? abi.encodePacked(\r\n                    encode(uint64(filter.cborArgs.length), bytes1(0x12)),\r\n                    filter.cborArgs\r\n                ) : bytes(\"\")\r\n        );\r\n        return abi.encodePacked(\r\n            encode(uint64(bytecode.length), bytes1(0x0a)),\r\n            bytecode\r\n        );\r\n    }\r\n\r\n    function encode(Witnet.RadonReduceOpcodes opcode)\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        \r\n        return encode(uint64(opcode), bytes1(0x10));\r\n    }\r\n\r\n    function encode(Witnet.RadonSLAv1 memory sla)\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        return abi.encodePacked(\r\n            encode(uint64(sla.witnessReward), bytes1(0x10)),\r\n            encode(uint64(sla.numWitnesses), bytes1(0x18)),\r\n            encode(uint64(sla.minerCommitRevealFee), bytes1(0x20)),\r\n            encode(uint64(sla.minConsensusPercentage), bytes1(0x28)),\r\n            encode(uint64(sla.witnessCollateral), bytes1(0x30))\r\n        );\r\n    }\r\n\r\n    function replaceCborStringsFromBytes(\r\n            bytes memory data,\r\n            uint8 argIndex,\r\n            string memory argValue\r\n        )\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        WitnetCBOR.CBOR memory cbor = WitnetCBOR.fromBytes(data);\r\n        while (!cbor.eof()) {\r\n            if (cbor.majorType == WitnetCBOR.MAJOR_TYPE_STRING) {\r\n                _replaceCborWildcard(cbor, argIndex, argValue);\r\n                cbor = cbor.settle();\r\n            } else {\r\n                cbor = cbor.skip().settle();\r\n            }\r\n        }\r\n        return cbor.buffer.data;\r\n    }\r\n\r\n    function replaceCborStringsFromBytes(\r\n            bytes memory data,\r\n            string[] memory args\r\n        )\r\n        public pure\r\n        returns (bytes memory)\r\n    {\r\n        WitnetCBOR.CBOR memory cbor = WitnetCBOR.fromBytes(data);\r\n        while (!cbor.eof()) {\r\n            if (cbor.majorType == WitnetCBOR.MAJOR_TYPE_STRING) {\r\n                _replaceCborWildcards(cbor, args);\r\n                cbor = cbor.settle();\r\n            } else {\r\n                cbor = cbor.skip().settle();\r\n            }\r\n        }\r\n        return cbor.buffer.data;\r\n    }\r\n\r\n    function replaceWildcards(Witnet.RadonRetrieval memory self, uint8 argIndex, string memory argValue)\r\n        public pure\r\n        returns (Witnet.RadonRetrieval memory)\r\n    {\r\n        self.url = WitnetBuffer.replace(self.url, argIndex, argValue);\r\n        self.body = WitnetBuffer.replace(self.body, argIndex, argValue);\r\n        self.radonScript = replaceCborStringsFromBytes(self.radonScript, argIndex, argValue);\r\n        for (uint _ix = 0 ; _ix < self.headers.length; _ix ++) {\r\n            self.headers[_ix][0] = WitnetBuffer.replace(self.headers[_ix][0], argIndex, argValue);\r\n            self.headers[_ix][1] = WitnetBuffer.replace(self.headers[_ix][1], argIndex, argValue);\r\n        }\r\n        return self;\r\n    }\r\n\r\n    function replaceWildcards(Witnet.RadonRetrieval memory self, string[] memory args)\r\n        public pure\r\n        returns (Witnet.RadonRetrieval memory)\r\n    {\r\n        self.url = WitnetBuffer.replace(self.url, args);\r\n        self.body = WitnetBuffer.replace(self.body, args);\r\n        self.radonScript = replaceCborStringsFromBytes(self.radonScript, args);\r\n        for (uint _ix = 0 ; _ix < self.headers.length; _ix ++) {\r\n            self.headers[_ix][0] = WitnetBuffer.replace(self.headers[_ix][0], args);\r\n            self.headers[_ix][1] = WitnetBuffer.replace(self.headers[_ix][1], args);\r\n        }\r\n        return self;\r\n    }\r\n\r\n    function validate(\r\n            Witnet.RadonRetrievalMethods method,\r\n            string memory url,\r\n            string memory body,\r\n            string[2][] memory headers,\r\n            bytes memory script\r\n        )\r\n        public pure\r\n        returns (bytes32)\r\n    {\r\n        if (!(\r\n            method == Witnet.RadonRetrievalMethods.HttpPost\r\n            || (method == Witnet.RadonRetrievalMethods.HttpGet && bytes(body).length == 0)\r\n            || (method == Witnet.RadonRetrievalMethods.HttpHead && bytes(body).length == 0)\r\n            || (method == Witnet.RadonRetrievalMethods.RNG\r\n                && bytes(url).length == 0\r\n                && bytes(body).length == 0\r\n                && headers.length == 0\r\n                && script.length >= 1\r\n            )\r\n        )) {\r\n            revert UnsupportedDataRequestMethod(\r\n                uint8(method),\r\n                url,\r\n                body,\r\n                headers\r\n            );\r\n        }\r\n        return keccak256(abi.encode(method, url, body, headers, script));\r\n    }\r\n    \r\n    function validate(\r\n            Witnet.RadonDataTypes dataType,\r\n            uint16 maxDataSize\r\n        )\r\n        public pure\r\n        returns (uint16)\r\n    {\r\n        if (\r\n            dataType == Witnet.RadonDataTypes.Any\r\n                || dataType == Witnet.RadonDataTypes.String\r\n                || dataType == Witnet.RadonDataTypes.Bytes\r\n                || dataType == Witnet.RadonDataTypes.Array\r\n                || dataType == Witnet.RadonDataTypes.Map\r\n        ) {\r\n            if (maxDataSize == 0) {\r\n                revert UnsupportedRadonDataType(\r\n                    uint8(dataType),\r\n                    maxDataSize\r\n                );\r\n            }\r\n            return maxDataSize + 3; // todo?: determine CBOR-encoding length overhead??\r\n        \r\n        } else if (\r\n            dataType == Witnet.RadonDataTypes.Integer\r\n                || dataType == Witnet.RadonDataTypes.Float\r\n                || dataType == Witnet.RadonDataTypes.Bool\r\n        ) {\r\n            return 9; \r\n        \r\n        } else {\r\n            revert UnsupportedRadonDataType(\r\n                uint8(dataType),\r\n                size(dataType)\r\n            );\r\n        }\r\n    }\r\n\r\n    function validate(Witnet.RadonFilter memory filter)\r\n        public pure\r\n    {\r\n        if (\r\n            filter.opcode == Witnet.RadonFilterOpcodes.StandardDeviation\r\n        ) {\r\n            // check filters that require arguments\r\n            if (filter.cborArgs.length == 0) {\r\n                revert UnsupportedRadonFilterArgs(uint8(filter.opcode), filter.cborArgs);\r\n            }\r\n        } else if (\r\n            filter.opcode == Witnet.RadonFilterOpcodes.Mode\r\n        ) {\r\n            // check filters that don't require any arguments\r\n            if (filter.cborArgs.length > 0) {\r\n                revert UnsupportedRadonFilterArgs(uint8(filter.opcode), filter.cborArgs);\r\n            }\r\n        } else {\r\n            // reject unsupported opcodes\r\n            revert UnsupportedRadonFilterOpcode(uint8(filter.opcode));\r\n        }\r\n    }\r\n\r\n    function validate(Witnet.RadonReducer memory reducer)\r\n        public pure\r\n    {\r\n        // if (reducer.script.length == 0) {\r\n            if (!(\r\n                reducer.opcode == Witnet.RadonReduceOpcodes.AverageMean \r\n                    || reducer.opcode == Witnet.RadonReduceOpcodes.StandardDeviation\r\n                    || reducer.opcode == Witnet.RadonReduceOpcodes.Mode\r\n                    || reducer.opcode == Witnet.RadonReduceOpcodes.ConcatenateAndHash\r\n                    || reducer.opcode == Witnet.RadonReduceOpcodes.AverageMedian\r\n            )) {\r\n                revert UnsupportedRadonReducerOpcode(uint8(reducer.opcode));\r\n            }\r\n            for (uint ix = 0; ix < reducer.filters.length; ix ++) {\r\n                validate(reducer.filters[ix]);\r\n            }\r\n        // } else {\r\n        //     if (uint8(reducer.opcode) != 0xff || reducer.filters.length > 0) {\r\n        //         revert UnsupportedRadonReducerScript(\r\n        //             uint8(reducer.opcode),\r\n        //             reducer.script,\r\n        //             0\r\n        //         );\r\n        //     }\r\n        // }\r\n    }\r\n\r\n    function validate(Witnet.RadonSLAv1 memory sla)\r\n        public pure\r\n    {\r\n        if (sla.witnessReward == 0) {\r\n            revert(\"WitOracleRadonEncodingLib: invalid SLA: no reward\");\r\n        }\r\n        if (sla.numWitnesses == 0) {\r\n            revert(\"WitOracleRadonEncodingLib: invalid SLA: no witnesses\");\r\n        } else if (sla.numWitnesses > 127) {\r\n            revert(\"WitOracleRadonEncodingLib: invalid SLA: too many witnesses (>127)\");\r\n        }\r\n        if (\r\n            sla.minConsensusPercentage < 51 \r\n                || sla.minConsensusPercentage > 99\r\n        ) {\r\n            revert(\"WitOracleRadonEncodingLib: invalid SLA: consensus percentage out of range\");\r\n        }\r\n        if (sla.witnessCollateral > 0) {\r\n            revert(\"WitOracleRadonEncodingLib: invalid SLA: no collateral\");\r\n        }\r\n        if (sla.witnessCollateral / sla.witnessReward > 127) {\r\n            revert(\"WitOracleRadonEncodingLib: invalid SLA: collateral/reward ratio too high (>127)\");\r\n        }\r\n    }\r\n\r\n    function verifyRadonScriptResultDataType(bytes memory script)\r\n        public pure\r\n        returns (Witnet.RadonDataTypes)\r\n    {\r\n        return _verifyRadonScriptResultDataType(\r\n            WitnetCBOR.fromBytes(script),\r\n            false\r\n        );\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- WitOracleRadonEncodingLib private methods ---------------------------------------------------------------------------------\r\n\r\n    function _replaceCborWildcard(\r\n            WitnetCBOR.CBOR memory self,\r\n            uint8 argIndex,\r\n            string memory argValue\r\n        ) private pure\r\n    {\r\n        uint _rewind = self.len;\r\n        uint _start = self.buffer.cursor;\r\n        bytes memory _peeks = bytes(self.readString());\r\n        (bytes memory _pokes, uint _replacements) = WitnetBuffer.replace(_peeks, argIndex, argValue);\r\n        if (_replacements > 0) {\r\n            bytes memory _encodedPokes = encode(string(_pokes));\r\n            self.buffer.cursor = _start - _rewind;\r\n            self.buffer.mutate(\r\n                _peeks.length + _rewind,\r\n                _encodedPokes\r\n            );\r\n            self.buffer.cursor += _encodedPokes.length;\r\n        }\r\n    }\r\n\r\n    function _replaceCborWildcards(\r\n            WitnetCBOR.CBOR memory self,\r\n            string[] memory args\r\n        ) private pure\r\n    {\r\n        uint _rewind = self.len;\r\n        uint _start = self.buffer.cursor;\r\n        bytes memory _peeks = bytes(self.readString());\r\n        (bytes memory _pokes, uint _replacements) = WitnetBuffer.replace(_peeks, args);\r\n        if (_replacements > 0) {\r\n            bytes memory _encodedPokes = encode(string(_pokes));\r\n            self.buffer.cursor = _start - _rewind;\r\n            self.buffer.mutate(\r\n                _peeks.length + _rewind,\r\n                _encodedPokes\r\n            );\r\n            self.buffer.cursor += _encodedPokes.length;\r\n        }\r\n    }\r\n    \r\n    function _verifyRadonScriptResultDataType(WitnetCBOR.CBOR memory self, bool flip)\r\n        private pure\r\n        returns (Witnet.RadonDataTypes)\r\n    {\r\n        if (self.majorType == WitnetCBOR.MAJOR_TYPE_ARRAY) {\r\n            WitnetCBOR.CBOR[] memory items = self.readArray();\r\n            if (items.length > 1) {\r\n                return flip\r\n                    ? _verifyRadonScriptResultDataType(items[0], false)\r\n                    : _verifyRadonScriptResultDataType(items[items.length - 2], true)\r\n                ;\r\n            } else {\r\n                return Witnet.RadonDataTypes.Any;\r\n            }\r\n        } else if (self.majorType == WitnetCBOR.MAJOR_TYPE_INT) {            \r\n            uint cursor = self.buffer.cursor;\r\n            uint opcode = self.readUint();\r\n            uint8 dataType = (opcode > WITNET_RADON_OPCODES_RESULT_TYPES.length\r\n                ? 0xff\r\n                : uint8(WITNET_RADON_OPCODES_RESULT_TYPES[opcode])\r\n            );\r\n            if (dataType > uint8(type(Witnet.RadonDataTypes).max)) {\r\n                revert UnsupportedRadonScriptOpcode(\r\n                    self.buffer.data,\r\n                    cursor,\r\n                    uint8(opcode)\r\n                );\r\n            }\r\n            return Witnet.RadonDataTypes(dataType);\r\n        } else {\r\n            revert WitnetCBOR.UnexpectedMajorType(\r\n                WitnetCBOR.MAJOR_TYPE_INT,\r\n                self.majorType\r\n            );\r\n        }\r\n    }\r\n\r\n}"
      },
      "project/contracts/libs/WitOracleResultStatusLib.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./Witnet.sol\";\r\n\r\n/// @title A library for interpreting Witnet resolution errors\r\n/// @author The Witnet Foundation.\r\nlibrary WitOracleResultStatusLib {\r\n\r\n    using Witnet for bytes;\r\n    using Witnet for uint8;\r\n    using Witnet for uint64;\r\n    using Witnet for Witnet.DataResult;\r\n    using Witnet for Witnet.ResultStatus;\r\n    using WitnetCBOR for WitnetCBOR.CBOR;\r\n\r\n    // ================================================================================================================\r\n    // --- Library public methods -------------------------------------------------------------------------------------\r\n\r\n    function toString(bytes calldata _result) public pure returns (string memory) {\r\n        Witnet.DataResult memory result = abi.decode(_result, (Witnet.DataResult));\r\n        if (result.status == Witnet.ResultStatus.NoErrors) {\r\n            return \"No errors.\";\r\n        \r\n        } else if (result.status == Witnet.ResultStatus.BoardAwaitingResult) {\r\n            return \"Awaiting result.\";\r\n\r\n        } else if (result.status == Witnet.ResultStatus.BoardFinalizingResult) {\r\n            return \"Finalizing result.\";\r\n        \r\n        } else if (result.status == Witnet.ResultStatus.BoardBeingDisputed) {\r\n            return \"Being disputed.\";\r\n        \r\n        } else if (result.status == Witnet.ResultStatus.BoardAlreadyDelivered) {\r\n            return \"Already delivered.\";\r\n        \r\n        } else if (result.status == Witnet.ResultStatus.BoardResolutionTimeout) {\r\n            return \"Error: resolution timeout.\";\r\n        \r\n        } else if (result.status == Witnet.ResultStatus.BridgeMalformedDataRequest) {\r\n            return \"Bridge: malformed data request.\";\r\n\r\n        } else if (result.status == Witnet.ResultStatus.BridgePoorIncentives) {\r\n            return \"Bridge: poor incentives.\";\r\n\r\n        } else if (result.status == Witnet.ResultStatus.BridgeOversizedTallyResult) {\r\n            return \"Bridge: oversized tally result.\";\r\n\r\n        } else {\r\n            return _parseError(result);\r\n        }\r\n    }\r\n\r\n    function _parseError(Witnet.DataResult memory result) private pure returns (string memory) {\r\n        string memory _prefix;\r\n        if (result.status.isCircumstantial()) {\r\n            _prefix = \"Circumstantial: \";\r\n        \r\n        } else if (result.status.poorIncentives()) {\r\n            _prefix = \"Poor incentives: \";\r\n        \r\n        } else if (result.status.lackOfConsensus()) {\r\n            _prefix = \"Consensus: \";\r\n        \r\n        } else {\r\n            _prefix = \"Critical: \";\r\n        } \r\n        return string(abi.encodePacked(\r\n            _prefix, \r\n            _parseErrorCode(result)\r\n        ));\r\n    }\r\n\r\n    function _parseErrorCode(Witnet.DataResult memory result)\r\n        private pure\r\n        returns (string memory)\r\n    {\r\n        if (result.status == Witnet.ResultStatus.InsufficientCommits) {\r\n            return \"insufficient commits.\";\r\n\r\n        } else if (result.status == Witnet.ResultStatus.CircumstantialFailure) {\r\n            return _parseErrorDetails(result);\r\n        \r\n        } else if (result.status == Witnet.ResultStatus.InsufficientMajority) {\r\n            return \"insufficient majority.\";\r\n\r\n        } else if (result.status == Witnet.ResultStatus.InsufficientReveals) {\r\n            return \"insufficient reveals.\";\r\n\r\n        } else if (\r\n            result.status == Witnet.ResultStatus.OversizedTallyResult\r\n                || result.status == Witnet.ResultStatus.BridgeOversizedTallyResult\r\n        ) {\r\n            return \"oversized result.\";\r\n\r\n        } else if (result.status == Witnet.ResultStatus.InconsistentSources) {\r\n            return \"inconsistent data sources.\";\r\n\r\n        } else if (result.status == Witnet.ResultStatus.MalformedQueryResponses) {\r\n            return string(abi.encodePacked(\r\n                \"malformed response: \",\r\n                _parseErrorDetails(result)\r\n            ));\r\n\r\n        } else if (\r\n            result.status == Witnet.ResultStatus.MalformedDataRequest \r\n                || result.status == Witnet.ResultStatus.BridgeMalformedDataRequest\r\n\r\n        ) {\r\n            return string(abi.encodePacked(\r\n                \"malformed request: \",\r\n                _parseErrorDetails(result)\r\n            ));\r\n\r\n        } else if (result.status == Witnet.ResultStatus.UnhandledIntercept) {\r\n            if (result.dataType != Witnet.RadonDataTypes.Any) {\r\n                return string(abi.encodePacked(\r\n                    \"unhanled intercept: \",\r\n                    _parseErrorDetails(result)\r\n                ));\r\n            } else {\r\n                return \"unhandled intercept.\";\r\n            }\r\n        \r\n        } else {\r\n            return string(abi.encodePacked(\r\n                \"0x\",\r\n                uint8(result.status).toHexString()\r\n            ));\r\n        }\r\n    }\r\n\r\n    function _parseErrorDetails(Witnet.DataResult memory result) private pure returns (string memory) {\r\n        if (result.dataType == Witnet.RadonDataTypes.Integer) {\r\n            result.status = Witnet.ResultStatus(uint8(result.fetchUint()));\r\n        } else {\r\n            return \"(unparsable error details)\";\r\n        }\r\n        if (result.status == Witnet.ResultStatus.HttpErrors) {\r\n            if (result.dataType == Witnet.RadonDataTypes.Integer) {\r\n                return string(abi.encodePacked(\r\n                    \"http/\",\r\n                    result.fetchUint().toString()\r\n                ));\r\n            } else {\r\n                return \"unspecific http status code.\";\r\n            }\r\n\r\n        } else if (result.status == Witnet.ResultStatus.RetrievalsTimeout) {\r\n            return \"response timeout.\";\r\n\r\n        } else if (result.status == Witnet.ResultStatus.ArrayIndexOutOfBounds) {\r\n            if (result.dataType == Witnet.RadonDataTypes.Integer) {\r\n                return string(abi.encodePacked(\r\n                    \"array index out of bounds: \",\r\n                    result.fetchUint().toString()\r\n                ));\r\n            } else {\r\n                return \"array index out of bounds.\";\r\n            }\r\n\r\n        } else if (result.status == Witnet.ResultStatus.MapKeyNotFound) {\r\n            if (result.dataType == Witnet.RadonDataTypes.String) {\r\n                return string(abi.encodePacked(\r\n                    \"map key not found: \",\r\n                    result.fetchString()\r\n                ));\r\n            } else {\r\n                return \"map key not found.\";\r\n            }\r\n\r\n        } else if (result.status == Witnet.ResultStatus.JsonPathNotFound) {\r\n            if (result.dataType == Witnet.RadonDataTypes.String) {\r\n                return string(abi.encodePacked(\r\n                    \"json path returned no values: \",\r\n                    result.fetchString()\r\n                ));\r\n            } else {\r\n                return \"json path returned no values.\";\r\n            }\r\n        \r\n        } else {\r\n            return string(abi.encodePacked(\r\n                \"0x\",\r\n                Witnet.toHexString(uint8(result.status)),\r\n                result.dataType != Witnet.RadonDataTypes.Any \r\n                    ? string(abi.encodePacked(\" (\", _parseErrorArgs(result), \")\"))\r\n                    : \"\"\r\n            ));\r\n        }\r\n    }\r\n\r\n    function _parseErrorArgs(Witnet.DataResult memory result) private pure returns (string memory _str) {\r\n        if (result.dataType == Witnet.RadonDataTypes.Any) {\r\n            return \"\";\r\n        \r\n        } else if (result.dataType == Witnet.RadonDataTypes.String) {\r\n            _str = string(abi.encodePacked(\"'\", result.fetchString(), \"', \"));\r\n\r\n        } else if (result.dataType == Witnet.RadonDataTypes.Integer) {\r\n            _str = string(abi.encodePacked(result.fetchUint().toString(), \", \"));\r\n\r\n        } else {\r\n            _str = \"?, \";\r\n        }\r\n        return string(abi.encodePacked(_str, _parseErrorArgs(result)));\r\n    }\r\n}\r\n"
      },
      "project/contracts/mockups/legacy/WitPriceFeedsSolverBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../../data/WitPriceFeedsLegacyDataLib.sol\";\r\n\r\nabstract contract WitPriceFeedsSolverBase\r\n    is\r\n        IWitPriceFeedsLegacySolver\r\n{\r\n    /// ===============================================================================================================\r\n    /// --- Yet to be implemented IWitPriceFeedsLegacySolver methods --------------------------------------------------------\r\n    \r\n    function class() virtual external pure returns (string memory);\r\n    function solve(bytes4) virtual external view returns (Price memory);\r\n\r\n    \r\n    /// ===============================================================================================================\r\n    /// --- Base implementation ---------------------------------------------------------------------------------------\r\n    \r\n    address public immutable override delegator;\r\n\r\n    modifier onlyDelegator {\r\n        require(\r\n            address(this) == delegator,\r\n            \"WitPriceFeedsSolverBase: not the delegator\"\r\n        );\r\n        _;\r\n    }\r\n\r\n    constructor() {\r\n        delegator = msg.sender;\r\n    }\r\n\r\n    function specs() external pure returns (bytes4) {\r\n        return type(IWitPriceFeedsLegacySolver).interfaceId;\r\n    }\r\n\r\n    function validate(bytes4 feedId, string[] calldata deps) virtual override external {\r\n        bytes32 _depsFlag;\r\n        uint256 _innerDecimals;\r\n        require(\r\n            deps.length <= 8,\r\n            \"WitPriceFeedsSolverBase: too many dependencies\"\r\n        );\r\n        for (uint _ix = 0; _ix < deps.length; _ix ++) {\r\n            bytes4 _depsId4 = bytes4(keccak256(bytes(deps[_ix])));\r\n            WitPriceFeedsLegacyDataLib.Record storage __depsFeed = WitPriceFeedsLegacyDataLib.seekRecord(_depsId4);\r\n            require(\r\n                __depsFeed.index > 0, \r\n                string(abi.encodePacked(\r\n                    \"WitPriceFeedsSolverBase: unsupported \",\r\n                    deps[_ix]\r\n                ))\r\n            );\r\n            require(\r\n                _depsId4 != feedId, \r\n                string(abi.encodePacked(\r\n                    \"WitPriceFeedsSolverBase: loop on \",\r\n                    deps[_ix]\r\n                ))\r\n            );\r\n            _depsFlag |= (bytes32(_depsId4) >> (32 * _ix));\r\n            _innerDecimals += __depsFeed.decimals;\r\n        }\r\n        WitPriceFeedsLegacyDataLib.Record storage __feed = WitPriceFeedsLegacyDataLib.seekRecord(feedId);\r\n        __feed.solverReductor = int(uint(__feed.decimals)) - int(_innerDecimals);\r\n        __feed.solverDepsFlag = _depsFlag;\r\n    }\r\n}"
      },
      "project/contracts/mockups/tests/TestBech32.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.7.0 <0.9.0;\r\npragma experimental ABIEncoderV2;\r\n\r\nimport \"../../libs/Bech32.sol\";\r\nimport \"../../libs/Witnet.sol\";\r\n\r\ncontract TestBech32 {\r\n\r\n    function toBech32Mainnet(bytes20 witBytes20) \r\n        external /**/pure \r\n        returns (string memory)\r\n    {\r\n        return Bech32.toBech32(address(witBytes20), \"wit\");\r\n    }\r\n\r\n    function toBech32Testnet(bytes20 witBytes20) \r\n        external /**/pure \r\n        returns (string memory) \r\n    {\r\n        return Bech32.toBech32(address(witBytes20), \"twit\");\r\n    }\r\n\r\n    function fromBech32Mainnet(string memory witPkh) \r\n        external /**/pure \r\n        returns (address)\r\n    {\r\n        return Bech32.fromBech32(witPkh, \"wit\");\r\n    }\r\n\r\n    function fromBech32Testnet(string memory witPkh) \r\n        external /**/pure \r\n        returns (address) \r\n    {\r\n        return Bech32.fromBech32(witPkh, \"twit\");\r\n    }\r\n\r\n    function parseHexAddress(string memory hexAddr) \r\n        external /**/pure \r\n        returns (address)\r\n    {\r\n        return Witnet.toAddress(\r\n            Witnet.parseHexString(hexAddr)\r\n        );\r\n    }\r\n}"
      },
      "project/contracts/mockups/tests/TestSecp256k1.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.7.0 <0.9.0;\r\npragma experimental ABIEncoderV2;\r\n\r\nimport \"../../libs/Secp256k1.sol\";\r\n\r\ncontract TestSecp256k1 {\r\n\r\n    string internal result;\r\n\r\n    function recoverWitPublicKeyX(bytes memory witSignature, address evmAddr)\r\n        public pure returns (bytes32)\r\n    {\r\n        bytes32 digest = keccak256(abi.encodePacked(evmAddr));\r\n        if (witSignature.length == 65) {\r\n            bytes32 r;\r\n            bytes32 s;\r\n            uint8 v;\r\n            assembly {\r\n                r := mload(add(witSignature, 0x20))\r\n                s := mload(add(witSignature, 0x40)) \r\n                v := byte(0, mload(add(witSignature, 0x60)))\r\n            }\r\n            if (\r\n                uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0\r\n                    && (v == 27 || v == 28)\r\n            ) {\r\n                (uint256 _x,) = Secp256k1.recover(uint256(digest), v - 27, uint256(r), uint256(s));\r\n                return bytes32(_x);\r\n            }\r\n        }\r\n        return bytes32(0);\r\n    }\r\n\r\n    function recoverWitAddr(bytes memory witSignature, address evmAddr) \r\n        public pure returns (bytes20, bytes20, bytes20, bytes20)\r\n    {\r\n        bytes32 _publicKeyX = recoverWitPublicKeyX(witSignature, evmAddr);\r\n        return (\r\n            bytes20(sha256(abi.encodePacked(bytes1(0x00), _publicKeyX))),\r\n            bytes20(sha256(abi.encodePacked(bytes1(0x01), _publicKeyX))),\r\n            bytes20(sha256(abi.encodePacked(bytes1(0x02), _publicKeyX))),\r\n            bytes20(sha256(abi.encodePacked(bytes1(0x03), _publicKeyX)))\r\n        );\r\n    }\r\n}"
      },
      "project/contracts/mockups/tests/WitRngConsumer.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.7.0 <0.9.0;\r\npragma experimental ABIEncoderV2;\r\n\r\nimport \"../../interfaces/IWitRandomness.sol\";\r\n\r\ncontract WitRngConsumer {\r\n    event Log(uint256 blockNumber, bytes32 seed);\r\n    event Log(uint256 blockNumber, bytes32 uuid, Witnet.Timestamp timestamp, Witnet.TransactionHash trail, uint256 finality);\r\n    IWitRandomness immutable public witRandomness;\r\n    constructor (IWitRandomness _witRandomness) {\r\n        witRandomness = _witRandomness;\r\n    }\r\n    function fetchRandomness(uint256 blockNumber) external {\r\n        emit Log(\r\n            blockNumber,\r\n            witRandomness.fetchRandomnessAfter(blockNumber)\r\n        );\r\n    }\r\n\r\n    function fetchRandomnessTrails(uint256 blockNumber) external {\r\n        (bytes32 _uuid, Witnet.Timestamp _timestamp, Witnet.TransactionHash _trail, uint256 _finality)\r\n            = witRandomness.fetchRandomnessAfterProof(blockNumber);\r\n        emit Log(\r\n            blockNumber,\r\n            _uuid,\r\n            _timestamp,\r\n            _trail,\r\n            _finality\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/mockups/UsingWitOracle.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../WitOracle.sol\";\r\n\r\n/// @title The UsingWitOracle contract\r\n/// @dev Witnet-aware contracts can inherit from this contract in order to interact with Witnet.\r\n/// @author The Witnet Foundation.\r\nabstract contract UsingWitOracle\r\n    is\r\n        IWitOracleQueriableEvents\r\n{   \r\n    /// @notice Immutable reference to the WitOracle contract.\r\n    function witOracle() virtual public view returns (address) {\r\n        return address(__witOracle);\r\n    }\r\n    WitOracle internal immutable __witOracle;\r\n    \r\n    /// @dev Percentage over base fee to pay on every data request, \r\n    /// @dev as to deal with volatility of evmGasPrice and evmWitPrice during the live time of \r\n    /// @dev a data request (since being posted until a result gets reported back), at both the EVM and \r\n    /// @dev the Witnet blockchain levels, respectivelly. \r\n    uint16 internal __witOracleBaseFeeOverheadPercentage;\r\n\r\n    /// @notice Default SLA data security parameters to be fulfilled by the Wit/Oracle blockchain\r\n    /// @notice when solving a data request.\r\n    Witnet.QuerySLA internal __witOracleDefaultQueryParams;\r\n\r\n    /// @dev Provides a convenient way for client contracts extending this to block the execution of the main logic of the\r\n    /// @dev contract until a particular request has been successfully solved and reported from the Wit/Oracle blockchain,\r\n    /// @dev either with an error or successfully.\r\n    modifier witOracleQuerySolved(uint256 _queryId) {\r\n        Witnet.QueryStatus _queryStatus = _witOracleCheckQueryStatus(_queryId);\r\n        require(\r\n            _queryStatus == Witnet.QueryStatus.Finalized\r\n                || _queryStatus == Witnet.QueryStatus.Expired\r\n                || _queryStatus == Witnet.QueryStatus.Disputed\r\n            , \"UsingWitOracle: unsolved query\"\r\n        ); _;\r\n    }\r\n\r\n    /// @param _witOracle Address of the WitOracle bridging contract.\r\n    constructor(address _witOracle) {\r\n        require(\r\n            IWitAppliance(_witOracle).specs() == (\r\n                type(IWitOracle).interfaceId\r\n                    ^ type(IWitOracleQueriable).interfaceId\r\n            ), \"UsingWitOracle: uncompliant WitOracle\"\r\n        );\r\n        __witOracle = WitOracle(_witOracle);\r\n        __witOracleDefaultQueryParams = Witnet.QuerySLA({\r\n            witResultMaxSize: 32, // defaults to 32 bytes\r\n            witCommitteeSize: 3,  // defaults to 10 witnesses\r\n            witUnitaryReward: 2 * 10 ** 8 // defaults to 0.2 $WIT\r\n        });\r\n        \r\n        __witOracleBaseFeeOverheadPercentage = 33; // defaults to 33%\r\n    }\r\n\r\n    /// @dev Check if given query was already reported back from the Wit/Oracle blockchain.\r\n    /// @param _id The unique identifier of a previously posted data request.\r\n    function _witOracleCheckQueryStatus(uint256 _id)\r\n        internal view\r\n        returns (Witnet.QueryStatus)\r\n    {\r\n        return __witOracle.getQueryStatus(_id);\r\n    }\r\n\r\n    /// @dev Estimate the minimum reward required for posting a data request (based on `tx.gasprice`).\r\n    function _witOracleEstimateBaseFee() virtual internal view returns (uint256) {\r\n        return _witOracleEstimateBaseFee(tx.gasprice);\r\n    }\r\n\r\n    function _witOracleEstimateBaseFee(uint256 _evmGasPrice) virtual internal view returns (uint256) {\r\n        return (\r\n            __witOracle.estimateBaseFee(_evmGasPrice)\r\n                * (100 + __witOracleBaseFeeOverheadPercentage)\r\n        ) / 100;\r\n    }\r\n}\r\n"
      },
      "project/contracts/mockups/UsingWitPriceFeeds.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"../WitPriceFeeds.sol\";\r\n\r\n/// @title The UsingWitPriceFeeds contract\r\n/// @dev Contracts willing to interact with a WitPriceFeeds appliance, freshly updated by a third-party.\r\n/// @author The Witnet Foundation.\r\nabstract contract UsingWitPriceFeeds {\r\n    IWitPriceFeeds immutable public WIT_PRICE_FEEDS;\r\n    \r\n    constructor(address _witPriceFeeds) {\r\n        require(\r\n            _witPriceFeeds.code.length > 0\r\n                && IWitAppliance(_witPriceFeeds).specs() == type(IWitPriceFeeds).interfaceId,\r\n            \"uncompliant wit/price feeds appliance\"\r\n        );\r\n        WIT_PRICE_FEEDS = IWitPriceFeeds(_witPriceFeeds);\r\n    }\r\n}\r\n"
      },
      "project/contracts/mockups/UsingWitRandomness.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {\r\n    Witnet, \r\n    WitRandomness, \r\n    IWitRandomness\r\n} from \"../WitRandomness.sol\";\r\n\r\nabstract contract UsingWitRandomness {\r\n    WitRandomness immutable public WIT_RANDOMNESS;\r\n    \r\n    constructor (address randomizer) {\r\n        assert(\r\n            randomizer.code.length > 0\r\n                && WitRandomness(randomizer).specs() == type(IWitRandomness).interfaceId\r\n        );\r\n        WIT_RANDOMNESS = WitRandomness(randomizer);    \r\n    }\r\n\r\n    /// Retrieves the result of keccak256-hashing the specified block number with the randomness value \r\n    /// generated by the Witnet blockchain in response to the first non-failing randomize request solved \r\n    /// after such block number.\r\n    ///\r\n    /// @dev Reverts if:\r\n    ///    i.   no `randomize()` was queried on the `WIT_RANDOMNESS` contract for neither the specified block, nor afterwards.\r\n    ///    ii.  the first non-failing `randomize()` request found on or after the specified block is not solved yet.\r\n    ///    iii. all `randomize()` requests that took place on or after the specified block were solved with errors.\r\n    function _fetchRandomnessAfter(uint256 _blockNumber) virtual internal view returns (bytes32) {\r\n        return keccak256(\r\n            abi.encode(\r\n                WIT_RANDOMNESS.fetchRandomnessAfter(_blockNumber),\r\n                address(this)\r\n            )\r\n        );\r\n    }\r\n\r\n    /// Generates a pseudo-random number uniformly distributed within the range [0 .. _faces), \r\n    /// by using the specified `_nonce` and `_seed`.\r\n    /// @dev Fails under same conditions as `_fetchRandomnessAfter(uint256)` does.\r\n    function _rollTheDice(uint64 _faces, uint256 _nonce, bytes32 _seed) internal pure returns (uint64) {\r\n        return Witnet.randomUniformUint64(\r\n            _faces,\r\n            _nonce,\r\n            _seed\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/mockups/WitPythChainlinkAggregator.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport {IWitPriceFeeds, IWitPriceFeedsTypes} from \"../interfaces/IWitPriceFeeds.sol\";\r\nimport {IWitPythChainlinkAggregator} from \"../interfaces/legacy/IWitPythChainlinkAggregator.sol\";\r\nimport {Witnet} from \"../libs/Witnet.sol\";\r\n\r\ncontract WitPythChainlinkAggregator\r\n    is\r\n        IWitPythChainlinkAggregator, \r\n        IWitPriceFeedsTypes\r\n{\r\n    bytes4  immutable public override id4;\r\n    bytes32 immutable public override priceId;\r\n    address immutable public override pyth;\r\n    address immutable public override witOracle;\r\n    \r\n    constructor(address _witOracle, bytes4 _id4) {\r\n        id4 = _id4;\r\n        priceId = IWitPriceFeeds(address(_witOracle)).lookupPriceFeedID(ID4.wrap(id4));\r\n        pyth = _witOracle;\r\n        witOracle = _witOracle;\r\n    }\r\n\r\n    function getAnswer(uint256) virtual public view returns (int256) {\r\n        return latestAnswer();\r\n    }\r\n\r\n    function latestAnswer() virtual public view returns (int256) {\r\n        IWitPriceFeeds.Price memory price = IWitPriceFeeds(witOracle).getPriceUnsafe(ID4.wrap(id4));\r\n        return int256(int64(price.price));\r\n    }\r\n\r\n    function latestRound() virtual public view returns (uint256) {\r\n        // use timestamp as the round id\r\n        return latestTimestamp();\r\n    }\r\n\r\n    function latestTimestamp() virtual public view returns (uint256) {\r\n        IWitPriceFeeds.Price memory price = IWitPriceFeeds(witOracle).getPriceUnsafe(ID4.wrap(id4));\r\n        return uint(Witnet.Timestamp.unwrap(price.timestamp));\r\n    }\r\n\r\n\r\n    /// ===============================================================================================================\r\n    /// --- IWitPythChainlinkAggregator -------------------------------------------------------------------------------\r\n\r\n    function decimals() virtual override public view returns (uint8) {\r\n        int8 _exponent = IWitPriceFeeds(msg.sender).lookupPriceFeedExponent(ID4.wrap(id4));\r\n        return (_exponent < 0 ? uint8(-_exponent) : uint8(_exponent));\r\n    }\r\n\r\n    function description() virtual override external view returns (string memory) {\r\n        return symbol();\r\n    }\r\n\r\n    function getRoundData(uint80 _roundId) \r\n        virtual override \r\n        external view\r\n        returns (uint80, int256, uint256, uint256, uint80)\r\n    {\r\n        IWitPriceFeeds.Price memory price = IWitPriceFeeds(witOracle).getPriceUnsafe(ID4.wrap(id4));\r\n        uint _timestamp = uint(Witnet.Timestamp.unwrap(price.timestamp));\r\n        return (\r\n            _roundId,\r\n            int(int64(price.price)),\r\n            _timestamp,\r\n            _timestamp,\r\n            _roundId\r\n        );\r\n    }\r\n\r\n    function latestRoundData()\r\n        virtual override\r\n        external view\r\n        returns (uint80, int256, uint256, uint256, uint80)\r\n    {\r\n        IWitPriceFeeds.Price memory price = IWitPriceFeeds(witOracle).getPriceUnsafe(ID4.wrap(id4));\r\n        uint80 _roundId = uint80(Witnet.Timestamp.unwrap(price.timestamp));\r\n        uint _timestamp = uint(Witnet.Timestamp.unwrap(price.timestamp));\r\n        return (\r\n            _roundId,\r\n            int(int64(price.price)),\r\n            _timestamp,\r\n            _timestamp,\r\n            _roundId\r\n        );\r\n    }\r\n\r\n    function symbol() override public view returns (string memory) {\r\n        return IWitPriceFeeds(address(witOracle)).lookupPriceFeedCaption(ID4.wrap(id4));\r\n    }\r\n\r\n    function version() virtual override external pure returns (uint256) {\r\n        return 3;\r\n    }\r\n}\r\n"
      },
      "project/contracts/patterns/Clonable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.20 <0.9.0;\r\n\r\nimport \"./Initializable.sol\";\r\n\r\nabstract contract Clonable\r\n    is\r\n        Initializable\r\n{\r\n    address immutable internal __SELF = address(this);\r\n\r\n    event Cloned(address indexed by, address indexed master, address indexed clone);\r\n\r\n    modifier onlyOnClones virtual {\r\n        require(cloned(), \"Clonable: only on clones\");\r\n        _;\r\n    }\r\n\r\n    modifier notOnClones virtual {\r\n        require(!cloned(), \"Clonable: not on clones\"); \r\n        _;\r\n    }\r\n\r\n    modifier wasInitialized {\r\n        require(initialized(), \"Clonable: not initialized\");\r\n        _;\r\n    }\r\n\r\n    function base() virtual public view returns (address) {\r\n        return __SELF;\r\n    }\r\n\r\n    /// @notice Tells whether this contract is a clone of `self()`\r\n    function cloned()\r\n        virtual public view\r\n        returns (bool)\r\n    {\r\n        return address(this) != __SELF;\r\n    }\r\n\r\n    /// @notice Tells whether this instance has been initialized.\r\n    function initialized() virtual public view returns (bool);\r\n\r\n    /// Deploys and returns the address of a minimal proxy clone that replicates contract\r\n    /// behaviour while using its own EVM storage.\r\n    /// @dev This function should always provide a new address, no matter how many times \r\n    /// @dev is actually called from the same `msg.sender`.\r\n    /// @dev See https://eips.ethereum.org/EIPS/eip-1167.\r\n    /// @dev See https://blog.openzeppelin.com/deep-dive-into-the-minimal-proxy-contract/.\r\n    function __clone()\r\n        internal\r\n        returns (address _instance)\r\n    {\r\n        bytes memory ptr = _cloneBytecodePtr();\r\n        assembly {\r\n            // CREATE new instance:\r\n            _instance := create(0, ptr, 0x37)\r\n        }        \r\n        require(_instance != address(0), \"Clonable: CREATE failed\");\r\n        emit Cloned(msg.sender, base(), _instance);\r\n    }\r\n\r\n    /// Deploys and returns the address of a minimal proxy clone that replicates contract \r\n    /// behaviour while using its own EVM storage.\r\n    /// @dev This function uses the CREATE2 opcode and a `_salt` to deterministically deploy\r\n    /// @dev the clone. Using the same `_salt` multiple times will revert, since\r\n    /// @dev no contract can be deployed more than once at the same address.\r\n    /// @dev See https://eips.ethereum.org/EIPS/eip-1167.\r\n    /// @dev See https://blog.openzeppelin.com/deep-dive-into-the-minimal-proxy-contract/.\r\n    function __cloneDeterministic(bytes32 _salt)\r\n        internal\r\n        notOnClones\r\n        returns (address _instance)\r\n    {\r\n        bytes memory ptr = _cloneBytecodePtr();\r\n        assembly {\r\n            // CREATE2 new instance:\r\n            _instance := create2(0, ptr, 0x37, _salt)\r\n        }\r\n        require(_instance != address(0), \"Clonable: CREATE2 failed\");\r\n        emit Cloned(msg.sender, base(), _instance);\r\n    }\r\n\r\n    /// @notice Returns minimal proxy's deploy bytecode.\r\n    function _cloneBytecode()\r\n        internal view\r\n        returns (bytes memory)\r\n    {\r\n        return abi.encodePacked(\r\n            hex\"3d602d80600a3d3981f3363d3d373d3d3d363d73\",\r\n            bytes20(base()),\r\n            hex\"5af43d82803e903d91602b57fd5bf3\"\r\n        );\r\n    }\r\n\r\n    /// @notice Returns mem pointer to minimal proxy's deploy bytecode.\r\n    function _cloneBytecodePtr()\r\n        private view\r\n        returns (bytes memory ptr)\r\n    {\r\n        address _base = base();\r\n        assembly {\r\n            // ptr to free mem:\r\n            ptr := mload(0x40)\r\n            // begin minimal proxy construction bytecode:\r\n            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\r\n            // make minimal proxy delegate all calls to `target()`:\r\n            mstore(add(ptr, 0x14), shl(0x60, _base))\r\n            // end minimal proxy construction bytecode:\r\n            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\r\n        }\r\n    }\r\n}"
      },
      "project/contracts/patterns/Escrowable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.4 <0.9.0;\r\n\r\nimport \"./Payable.sol\";\r\n\r\nabstract contract Escrowable\r\n    is\r\n        Payable\r\n{\r\n    event Burnt(address indexed from, uint256 value);\r\n    event Staked(address indexed from, uint256 value);\r\n    event Slashed(address indexed from, uint256 value);\r\n    event Unstaked(address indexed from, uint256 value);\r\n    event Withdrawn(address indexed from, uint256 value);\r\n\r\n    struct Escrow {\r\n        uint256 balance;\r\n        uint256 collateral;\r\n    }\r\n\r\n    receive() virtual external payable;\r\n\r\n    function collateralOf(address) virtual external view returns (uint256);\r\n    function balanceOf(address) virtual external view returns (uint256);\r\n    function withdraw() virtual external returns (uint256);\r\n\r\n    function __burn(address from, uint256 value) virtual internal;\r\n    function __deposit(address from, uint256 value) virtual internal;\r\n    function __slash(address from, address to, uint256 value) virtual internal;\r\n    function __stake(address from, uint256 value) virtual internal;\r\n    function __unstake(address from, uint256 value) virtual internal;\r\n}"
      },
      "project/contracts/patterns/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\npragma solidity >=0.8.0 <0.9.0;\r\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";"
      },
      "project/contracts/patterns/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.0;\r\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\r\n"
      },
      "project/contracts/patterns/Ownable2Step.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./Ownable.sol\";\r\n\r\n/**\r\n * @dev Contract module which provides access control mechanism, where\r\n * there is an account (an owner) that can be granted exclusive access to\r\n * specific functions.\r\n *\r\n * The initial owner is specified at deployment time in the constructor for `Ownable`. This\r\n * can later be changed with {transferOwnership} and {acceptOwnership}.\r\n *\r\n * This module is used through inheritance. It will make available all functions\r\n * from parent (Ownable).\r\n */\r\nabstract contract Ownable2Step is Ownable {\r\n    address private _pendingOwner;\r\n\r\n    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\r\n\r\n    /**\r\n     * @dev Returns the address of the pending owner.\r\n     */\r\n    function pendingOwner() public view virtual returns (address) {\r\n        return _pendingOwner;\r\n    }\r\n\r\n    /**\r\n     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\r\n     * Can only be called by the current owner.\r\n     */\r\n    function transferOwnership(address newOwner) public virtual override onlyOwner {\r\n        _pendingOwner = newOwner;\r\n        emit OwnershipTransferStarted(owner(), newOwner);\r\n    }\r\n\r\n    /**\r\n     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\r\n     * Internal function without access restriction.\r\n     */\r\n    function _transferOwnership(address newOwner) internal virtual override {\r\n        delete _pendingOwner;\r\n        super._transferOwnership(newOwner);\r\n    }\r\n\r\n    /**\r\n     * @dev The new owner accepts the ownership transfer.\r\n     */\r\n    function acceptOwnership() public virtual {\r\n        address sender = _msgSender();\r\n        if (pendingOwner() != sender) {\r\n            revert(\"Ownable2Step: caller is not the new owner\");\r\n        }\r\n        _transferOwnership(sender);\r\n    }\r\n}\r\n"
      },
      "project/contracts/patterns/Payable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.6.0 <0.9.0;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\n\r\nabstract contract Payable {\r\n    IERC20 public immutable currency;\r\n\r\n    event Received(address indexed from, uint256 value);\r\n    event Transfer(address indexed to, uint256 value);\r\n\r\n    constructor(address _currency) {\r\n        currency = IERC20(_currency);\r\n    }\r\n\r\n    /// Gets current transaction price.\r\n    function _getGasPrice() internal view virtual returns (uint256);\r\n\r\n    /// Gets message actual sender.\r\n    function _getMsgSender() internal view virtual returns (address);\r\n\r\n    /// Gets current payment value.\r\n    function _getMsgValue() internal view virtual returns (uint256);\r\n\r\n    /// Perform safe transfer or whatever token is used for paying rewards.\r\n    function __safeTransferTo(address payable, uint256) internal virtual;\r\n}\r\n"
      },
      "project/contracts/patterns/Proxiable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.6.0 <0.9.0;\r\n\r\nabstract contract Proxiable {\r\n    /// @dev Complying with EIP-1822: Universal Upgradeable Proxy Standard (UUPS)\r\n    /// @dev See https://eips.ethereum.org/EIPS/eip-1822.\r\n    function proxiableUUID() virtual external view returns (bytes32);\r\n\r\n    struct ProxiableSlot {\r\n        address implementation;\r\n        address proxy;\r\n        bytes32 codehash;\r\n    }\r\n\r\n    function __implementation() internal view returns (address) {\r\n        return __proxiable().implementation;\r\n    }\r\n\r\n    function __proxy() internal view returns (address) {\r\n        return __proxiable().proxy;\r\n    }\r\n\r\n    function __proxiable() internal pure returns (ProxiableSlot storage proxiable) {\r\n        assembly {\r\n            // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)\r\n            proxiable.slot := 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc\r\n        }\r\n    }\r\n}\r\n"
      },
      "project/contracts/patterns/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.0;\r\nimport \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\r\n"
      },
      "project/contracts/patterns/Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\n/* solhint-disable var-name-mixedcase */\r\n\r\npragma solidity >=0.6.0 <0.9.0;\r\n\r\nimport \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\r\n\r\nimport \"./Initializable.sol\";\r\nimport \"./Proxiable.sol\";\r\n\r\nabstract contract Upgradeable is Initializable, Proxiable {\r\n\r\n    address internal immutable _BASE;\r\n    bytes32 internal immutable _CODEHASH;\r\n    bool internal immutable _UPGRADABLE;\r\n\r\n    modifier onlyDelegateCalls virtual {\r\n        require(\r\n            address(this) != _BASE,\r\n            \"Upgradeable: not a delegate call\"\r\n        );\r\n        _;\r\n    }\r\n\r\n    /// Emitted every time the contract gets upgraded.\r\n    /// @param from The address who ordered the upgrading. Namely, the WRB operator in \"trustable\" implementations.\r\n    /// @param baseAddr The address of the new implementation contract.\r\n    /// @param baseCodehash The EVM-codehash of the new implementation contract.\r\n    /// @param versionTag Ascii-encoded version literal with which the implementation deployer decided to tag it.\r\n    event Upgraded(\r\n        address indexed from,\r\n        address indexed baseAddr,\r\n        bytes32 indexed baseCodehash,\r\n        string  versionTag\r\n    );\r\n\r\n    constructor (bool _isUpgradable) {\r\n        address _base = address(this);\r\n        _BASE = _base;\r\n        _UPGRADABLE = _isUpgradable;\r\n    }\r\n\r\n    /// @dev Retrieves base contract. Differs from address(this) when called via delegate-proxy pattern.\r\n    function base() virtual public view returns (address) {\r\n        return _BASE;\r\n    }\r\n\r\n    /// @dev Retrieves the immutable codehash of this contract, even if invoked as delegatecall.\r\n    function codehash() public view returns (bytes32 _codehash) {\r\n        address _base = _BASE;\r\n        assembly {\r\n            _codehash := extcodehash(_base)\r\n        }\r\n    }\r\n\r\n    /// @dev Determines whether the logic of this contract is potentially upgradable.\r\n    function isUpgradable() public view returns (bool) {\r\n        return _UPGRADABLE;\r\n    }\r\n\r\n    /// @dev Tells whether provided address could eventually upgrade the contract.\r\n    function isUpgradableFrom(address from) virtual external view returns (bool);\r\n\r\n    /// @notice Re-initialize contract's storage context upon a new upgrade from a proxy.    \r\n    /// @dev Must fail when trying to upgrade to same logic contract more than once.\r\n    function initialize(bytes memory) virtual external;\r\n    function __initializeUpgradableData(bytes memory _initData) virtual internal;\r\n\r\n    /// @dev Retrieves human-redable named version of current implementation.\r\n    function version() virtual public view returns (string memory); \r\n}"
      },
      "project/contracts/WitOracle.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./interfaces/IWitOracle.sol\";\r\nimport \"./interfaces/IWitOracleAppliance.sol\";\r\nimport \"./interfaces/IWitOracleQueriable.sol\";\r\nimport \"./interfaces/IWitOracleQueriableEvents.sol\";\r\n\r\n/// @title Witnet Request Board functionality base contract.\r\n/// @author The Witnet Foundation.\r\nabstract contract WitOracle\r\n    is\r\n        IWitAppliance,\r\n        IWitOracle,\r\n        IWitOracleQueriable,\r\n        IWitOracleQueriableEvents\r\n{\r\n    function specs() virtual override external pure returns (bytes4) {\r\n        return (\r\n            type(IWitOracle).interfaceId\r\n                ^ type(IWitOracleQueriable).interfaceId\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/WitOraclePushOnly.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./interfaces/IWitAppliance.sol\";\r\nimport \"./interfaces/IWitOracle.sol\";\r\n\r\n/// @title Witnet Request Board functionality base contract.\r\n/// @author The Witnet Foundation.\r\nabstract contract WitOraclePushOnly\r\n    is\r\n        IWitAppliance,\r\n        IWitOracle\r\n{\r\n    function specs() virtual override external pure returns (bytes4) {\r\n        return (\r\n            type(IWitOracle).interfaceId\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/WitOracleRadonRegistry.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./interfaces/IWitAppliance.sol\";\r\nimport \"./interfaces/IWitOracleRadonRegistry.sol\";\r\nimport \"./interfaces/IWitOracleRadonRegistryEvents.sol\";\r\n\r\nabstract contract WitOracleRadonRegistry\r\n    is\r\n        IWitAppliance,\r\n        IWitOracleRadonRegistry,\r\n        IWitOracleRadonRegistryEvents\r\n{\r\n    function specs() virtual override external pure returns (bytes4) {\r\n        return (\r\n            type(IWitOracleRadonRegistry).interfaceId\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/WitOracleRadonRequestFactory.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./interfaces/IWitOracleAppliance.sol\";\r\nimport \"./interfaces/IWitOracleRadonRegistryEvents.sol\";\r\nimport \"./interfaces/IWitOracleRadonRequestFactory.sol\";\r\n\r\nabstract contract WitOracleRadonRequestFactory\r\n    is\r\n        IWitOracleAppliance, \r\n        IWitOracleRadonRegistryEvents,\r\n        IWitOracleRadonRequestFactory\r\n{\r\n    function specs() virtual override external pure returns (bytes4) {\r\n        return (\r\n            type(WitOracleRadonRequestFactory).interfaceId\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/WitPriceFeeds.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"ado-contracts/contracts/interfaces/IERC2362.sol\";\r\n\r\nimport \"./interfaces/IWitAppliance.sol\";\r\nimport \"./interfaces/IWitOracleConsumer.sol\";\r\nimport \"./interfaces/IWitPriceFeeds.sol\";\r\n\r\n/// @title WitPriceFeeds: Price Feeds repository powered by the Wit/Oracle, \r\n/// @title and yet usable from both Chainlink and Pyth clients.\r\n/// @author The Witnet Foundation.\r\nabstract contract WitPriceFeeds\r\n    is\r\n        IERC2362,\r\n        IWitAppliance,\r\n        IWitOracleConsumer,\r\n        IWitPriceFeeds\r\n{\r\n    function specs() virtual override external pure returns (bytes4) {\r\n        return (\r\n            type(IWitPriceFeeds).interfaceId\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/WitPriceFeedsLegacy.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"ado-contracts/contracts/interfaces/IERC2362.sol\";\r\n\r\nimport \"./interfaces/IWitOracleAppliance.sol\";\r\nimport \"./interfaces/legacy/IWitPriceFeedsLegacy.sol\";\r\nimport \"./interfaces/legacy/IWitPriceFeedsLegacyAdmin.sol\";\r\nimport \"./interfaces/legacy/IWitPriceFeedsLegacySolverFactory.sol\";\r\n\r\n/// @title WitPriceFeedsLegacy: Price Feeds live repository reliant on the Wit/Oracle blockchain. \r\n/// @author The Witnet Foundation.\r\nabstract contract WitPriceFeedsLegacy\r\n    is\r\n        IERC2362,\r\n        IWitPriceFeedsLegacy,\r\n        IWitPriceFeedsLegacyAdmin,\r\n        IWitPriceFeedsLegacySolverFactory,\r\n        IWitOracleAppliance\r\n{\r\n    Witnet.RadonDataTypes immutable public override dataType = Witnet.RadonDataTypes.Integer;\r\n    bytes32 immutable internal __prefix = \"Price-\";\r\n\r\n    function prefix() virtual override external view returns (string memory) {\r\n        return Witnet.asAscii(__prefix);\r\n    }\r\n    \r\n    function specs() virtual override external pure returns (bytes4) {\r\n        return (\r\n            type(IERC2362).interfaceId\r\n                ^ type(IWitOracleAppliance).interfaceId\r\n                ^ type(IWitPriceFeedsLegacy).interfaceId\r\n                ^ type(IWitPriceFeedsLegacyAdmin).interfaceId\r\n                ^ type(IWitPriceFeedsLegacySolverFactory).interfaceId\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/WitRandomness.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./interfaces/IWitAppliance.sol\";\r\nimport \"./interfaces/IWitOracleQueriableConsumer.sol\";\r\nimport \"./interfaces/IWitRandomness.sol\";\r\n\r\nabstract contract WitRandomness\r\n    is\r\n        IWitAppliance,\r\n        IWitOracleQueriableConsumer,\r\n        IWitRandomness\r\n{\r\n    function specs() virtual override external pure returns (bytes4) {\r\n        return (\r\n            type(IWitRandomness).interfaceId\r\n        );\r\n    }\r\n}\r\n"
      },
      "project/contracts/WitRandomnessLegacy.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity >=0.8.0 <0.9.0;\r\n\r\nimport \"./interfaces/IWitOracleAppliance.sol\";\r\nimport \"./interfaces/IWitOracleQueriableEvents.sol\";\r\nimport \"./interfaces/legacy/IWitRandomnessLegacy.sol\";\r\n\r\nabstract contract WitRandomnessLegacy\r\n    is\r\n        IWitOracleAppliance,\r\n        IWitOracleQueriableEvents,\r\n        IWitRandomnessLegacy\r\n{\r\n    function specs() virtual override external pure returns (bytes4) {\r\n        return (\r\n            type(IWitRandomnessLegacy).interfaceId\r\n        );\r\n    }\r\n}\r\n"
      }
    }
  }
}