// File: contracts/CollectableDust.sol




// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/EnumerableSet.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import '../interfaces/ICollectableDust.sol';

abstract
contract CollectableDust is ICollectableDust {
  using EnumerableSet for EnumerableSet.AddressSet;

  address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
  EnumerableSet.AddressSet internal protocolTokens;

  constructor() public {}

  function _addProtocolToken(address _token) internal {
    require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol');
    protocolTokens.add(_token);
  }

  function _removeProtocolToken(address _token) internal {
    require(protocolTokens.contains(_token), 'collectable-dust/token-not-part-of-the-protocol');
    protocolTokens.remove(_token);
  }

  function _sendDust(
    address _to,
    address _token,
    uint256 _amount
  ) internal {
    require(_to != address(0), 'collectable-dust/cant-send-dust-to-zero-address');
    require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol');
    if (_token == ETH_ADDRESS) {
      payable(_to).transfer(_amount);
    } else {
      IERC20(_token).transfer(_to, _amount);
    }
    emit DustSent(_to, _token, _amount);
  }
}
// File: @openzeppelin/contracts/utils/Address.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.2;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies in extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain`call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
      return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
        return _functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        return _functionCallWithValue(target, data, value, errorMessage);
    }

    function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
        require(isContract(target), "Address: call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

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



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
 * (`UintSet`) are supported.
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;

        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping (bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) { // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
            // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.

            bytes32 lastvalue = set._values[lastIndex];

            // Move the last value to the index where the value to delete is
            set._values[toDeleteIndex] = lastvalue;
            // Update the index for the moved value
            set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        require(set._values.length > index, "EnumerableSet: index out of bounds");
        return set._values[index];
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(value)));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(value)));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(value)));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint256(_at(set._inner, index)));
    }


    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

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

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// File: interfaces/ICollectableDust.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

interface ICollectableDust {
  event DustSent(address _to, address token, uint256 amount);

  function sendDust(address _to, address _token, uint256 _amount) external;
}

// File: contracts/zTreasury/V2/zTreasuryV2.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';

import '../../../interfaces/zTreasury/V2/IZTreasuryV2.sol';

import '../../Governable.sol';
import '../../Manageable.sol';
import '../../CollectableDust.sol';

import './zTreasuryV2Metadata.sol';
import './zTreasuryV2ProtocolParameters.sol';

contract zTreasuryV2 is 
  Governable, 
  Manageable,
  CollectableDust,
  zTreasuryV2Metadata,
  zTreasuryV2ProtocolParameters, 
  IZTreasuryV2 {

  using SafeERC20 for IERC20;

  uint256 public override lastEarningsDistribution = 0;
  uint256 public override totalEarningsDistributed = 0;
  
  constructor(
    address _governor,
    address _manager,
    address _zGov,
    address _lotManager,
    address _maintainer,
    address _zToken,
    uint256 _maintainerShare,
    uint256 _governanceShare,
    uint256[] memory _initialDistributionValues
  ) public 
    zTreasuryV2ProtocolParameters(
      _zGov,
      _lotManager,
      _maintainer, 
      _zToken,
      _maintainerShare,
      _governanceShare
    )
    Governable(_governor)
    Manageable(_manager)
    CollectableDust() {
      lastEarningsDistribution = _initialDistributionValues[0];
      totalEarningsDistributed = _initialDistributionValues[1];
      _addProtocolToken(_zToken);
  }

  // Modifiers
  modifier onlyManagerOrLotManager {
    require(msg.sender == manager || msg.sender == lotManager, 'zTreasuryV2::only-manager-or-lot-manager');
    _;
  }
  
  function distributeEarnings() external override onlyManagerOrLotManager {
    uint256 _balance = zToken.balanceOf(address(this));
    
    // Send zToken to maintainer
    uint256 _maintainerEarnings = _balance.mul(maintainerShare).div(SHARES_PRECISION).div(100);
    zToken.safeTransfer(maintainer, _maintainerEarnings);

    // Send zToken to zGov
    uint256 _governanceEarnings = _balance.sub(_maintainerEarnings);
    zToken.safeApprove(address(zGov), 0);
    zToken.safeApprove(address(zGov), _governanceEarnings);

    // Notify governance reward amount to distribute
    zGov.notifyRewardAmount(_governanceEarnings);

    // Set last time distributed
    lastEarningsDistribution = block.timestamp;
    totalEarningsDistributed = totalEarningsDistributed.add(_balance);

    // Emit event
    emit EarningsDistributed(_maintainerEarnings, _governanceEarnings, totalEarningsDistributed);
  }

  // zTreasuryProtocolParameters
  function setZGov(address _zGov) external override onlyGovernor {
    _setZGov(_zGov);
  }

  function setLotManager(address _lotManager) external override onlyGovernor {
    _setLotManager(_lotManager);
  }

  function setMaintainer(address _maintainer) external override onlyGovernor {
    _setMaintainer(_maintainer);
  }

  function setZToken(address _zToken) external override onlyGovernor {
    require(address(zToken) != _zToken, 'zTreasuryV2::setZToken::same-ztoken');
    _removeProtocolToken(address(zToken));
    _addProtocolToken(address(_zToken));
    _setZToken(_zToken);
  }

  function setShares(uint256 _maintainerShare, uint256 _governanceShare) external override onlyGovernor {
    _setShares(_maintainerShare, _governanceShare);
  }

  // Governable
  function setPendingGovernor(address _pendingGovernor) external override onlyGovernor {
    _setPendingGovernor(_pendingGovernor);
  }

  function acceptGovernor() external override onlyPendingGovernor {
    _acceptGovernor();
  }

  // Manageable
  function setPendingManager(address _pendingManager) external override onlyManager {
    _setPendingManager(_pendingManager);
  }

  function acceptManager() external override onlyPendingManager {
    _acceptManager();
  }

  // Collectable Dust
  function sendDust(
    address _to,
    address _token,
    uint256 _amount
  ) external override onlyGovernor {
    _sendDust(_to, _token, _amount);
  }
}

// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using SafeMath for uint256;
    using Address for address;

    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        // solhint-disable-next-line max-line-length
        require((value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 newAllowance = token.allowance(address(this), spender).add(value);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) { // Return data is optional
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

// File: interfaces/zTreasury/V2/IZTreasuryV2.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

import './IZTreasuryV2Metadata.sol';
import './IZTreasuryV2ProtocolParameters.sol';

interface IZTreasuryV2 is IZTreasuryV2ProtocolParameters, IZTreasuryV2Metadata {
  event EarningsDistributed(
    uint256 maintainerRewards, 
    uint256 governanceRewards, 
    uint256 totalEarningsDistributed
  );

  function lastEarningsDistribution() external returns (uint256);
  function totalEarningsDistributed() external returns (uint256);
  function distributeEarnings() external;
}
// File: contracts/Governable.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '../interfaces/IGovernable.sol';

abstract
contract Governable is IGovernable {
  address public governor;
  address public pendingGovernor;

  constructor(address _governor) public {
    require(_governor != address(0), 'governable/governor-should-not-be-zero-address');
    governor = _governor;
  }

  function _setPendingGovernor(address _pendingGovernor) internal {
    require(_pendingGovernor != address(0), 'governable/pending-governor-should-not-be-zero-addres');
    pendingGovernor = _pendingGovernor;
    emit PendingGovernorSet(_pendingGovernor);
  }

  function _acceptGovernor() internal {
    governor = pendingGovernor;
    pendingGovernor = address(0);
    emit GovernorAccepted();
  }

  modifier onlyGovernor {
    require(msg.sender == governor, 'governable/only-governor');
    _;
  }

  modifier onlyPendingGovernor {
    require(msg.sender == pendingGovernor, 'governable/only-pending-governor');
    _;
  }
}
// File: contracts/Manageable.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '../interfaces/IManageable.sol';

abstract
contract Manageable is IManageable {
  address public manager;
  address public pendingManager;

  constructor(address _manager) public {
    require(_manager != address(0), 'manageable/manager-should-not-be-zero-address');
    manager = _manager;
  }

  function _setPendingManager(address _pendingManager) internal {
    require(_pendingManager != address(0), 'manageable/pending-manager-should-not-be-zero-addres');
    pendingManager = _pendingManager;
    emit PendingManagerSet(_pendingManager);
  }

  function _acceptManager() internal {
    manager = pendingManager;
    pendingManager = address(0);
    emit ManagerAccepted();
  }

  modifier onlyManager {
    require(msg.sender == manager, 'manageable/only-manager');
    _;
  }

  modifier onlyPendingManager {
    require(msg.sender == pendingManager, 'manageable/only-pending-manager');
    _;
  }
}
// File: contracts/zTreasury/V2/zTreasuryV2Metadata.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';

import '../../../interfaces/zTreasury/V2/IZTreasuryV2Metadata.sol';

contract zTreasuryV2Metadata is IZTreasuryV2Metadata {
  function isZTreasury() external override pure returns (bool) {
    return true;
  }
}
// File: contracts/zTreasury/V2/zTreasuryV2ProtocolParameters.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import '../../../interfaces/LotManager/ILotManagerMetadata.sol';
import '../../../interfaces/zTreasury/V2/IZTreasuryV2ProtocolParameters.sol';

abstract
contract zTreasuryV2ProtocolParameters is IZTreasuryV2ProtocolParameters {
  using SafeMath for uint256;
  
  uint256 public constant override SHARES_PRECISION = 10000;
  uint256 public constant override MAX_MAINTAINER_SHARE = 25 * SHARES_PRECISION;

  IERC20 public override zToken; // zhegic
  zGovernance public override zGov; // zgov

  address public override lotManager;
  address public override maintainer;

  uint256 public override maintainerShare;
  uint256 public override governanceShare;
  
  constructor(
    address _zGov,
    address _lotManager,
    address _maintainer,
    address _zToken,
    uint256 _maintainerShare,
    uint256 _governanceShare
  ) public {
    _setZGov(_zGov);
    _setLotManager(_lotManager);
    _setMaintainer(_maintainer);
    _setZToken(_zToken);
    _setShares(_maintainerShare, _governanceShare);
  }
  
  function _setZGov(address _zGov) internal {
    require(_zGov != address(0), 'zTreasuryV2ProtocolParameters::_setZGov::no-zero-address');
    zGov = zGovernance(_zGov);
    emit ZGovSet(_zGov);
  }

  function _setLotManager(address _lotManager) internal {
    require(_lotManager != address(0), 'zTreasuryV2ProtocolParameters::_setLotManager::no-zero-address');
    require(ILotManagerMetadata(_lotManager).isLotManager(), 'zTreasuryV2ProtocolParameters::_setLotManager::not-lot-manager');
    lotManager = _lotManager;
    emit LotManagerSet(_lotManager);
  }

  function _setMaintainer(address _maintainer) internal {
    require(_maintainer != address(0), 'zTreasuryV2ProtocolParameters::_setMaintainer::no-zero-address');
    maintainer = _maintainer;
    emit MaintainerSet(_maintainer);
  }

  function _setZToken(address _zToken) internal {
    require(_zToken != address(0), 'zTreasuryV2ProtocolParameters::_setZToken::no-zero-address');
    zToken = IERC20(_zToken);
    emit ZTokenSet(_zToken);
  }

  function _setShares(uint256 _maintainerShare, uint256 _governanceShare) internal {
    require(_maintainerShare.add(_governanceShare) == SHARES_PRECISION.mul(100), 'zTreasuryV2ProtocolParameters::_setShares::not-100-percent');
    require(_maintainerShare <= MAX_MAINTAINER_SHARE, 'zTreasuryV2ProtocolParameters::_setShares::exceeds-max-mantainer-share');
    maintainerShare = _maintainerShare;
    governanceShare = _governanceShare;
    emit SharesSet(_maintainerShare, _governanceShare);
  }
}
// File: @openzeppelin/contracts/math/SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

// File: interfaces/zTreasury/V2/IZTreasuryV2Metadata.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

interface IZTreasuryV2Metadata {
  function isZTreasury() external pure returns (bool);
}

// File: interfaces/zTreasury/V2/IZTreasuryV2ProtocolParameters.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

interface zGovernance {
  function notifyRewardAmount(uint) external;
}

interface IZTreasuryV2ProtocolParameters {
  event ZGovSet(address zGov);
  event LotManagerSet(address lotManager);
  event MaintainerSet(address maintainer);
  event ZTokenSet(address zToken);
  event SharesSet(uint256 maintainerShare, uint256 governanceShare);

  function zToken() external returns (IERC20);

  function zGov() external returns (zGovernance);
  function lotManager() external returns (address);
  function maintainer() external returns (address);

  function SHARES_PRECISION() external returns (uint256);
  function MAX_MAINTAINER_SHARE() external returns (uint256);
  function maintainerShare() external returns (uint256);
  function governanceShare() external returns (uint256);

  function setZGov(address _zGov) external;
  function setLotManager(address _lotManager) external;
  function setMaintainer(address _maintainer) external;
  function setZToken(address _zToken) external;
  function setShares(uint256 _maintainerShare, uint256 _governanceShare) external;
}
// File: interfaces/IGovernable.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

interface IGovernable {
  event PendingGovernorSet(address pendingGovernor);
  event GovernorAccepted();

  function setPendingGovernor(address _pendingGovernor) external;
  function acceptGovernor() external;
}

// File: interfaces/IManageable.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

interface IManageable {
  event PendingManagerSet(address pendingManager);
  event ManagerAccepted();

  function setPendingManager(address _pendingManager) external;
  function acceptManager() external;
}

// File: interfaces/LotManager/ILotManagerMetadata.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

interface ILotManagerMetadata {
  function isLotManager() external pure returns (bool);
  function getName() external pure returns (string memory);
}

// File: contracts/LotManager/V2/LotManagerV2ProtocolParameters.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import '../../../interfaces/HegicPool/IHegicPoolV2.sol';
import '../../../interfaces/IHegicStaking.sol';

import '../../../interfaces/zTreasury/V2/IZTreasuryV2.sol';
import '../../../interfaces/LotManager/V2/ILotManagerV2ProtocolParameters.sol';

abstract
contract LotManagerV2ProtocolParameters is ILotManagerV2ProtocolParameters {

  uint256 public constant override LOT_PRICE = 888_000e18;

  uint256 public constant override FEE_PRECISION = 10000;
  uint256 public constant override MAX_PERFORMANCE_FEE = 50 * FEE_PRECISION;
  
  address public override uniswapV2 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

  uint256 public override performanceFee;
  IZTreasuryV2 public override zTreasury;

  address public override weth;
  address public override wbtc;
  IHegicStaking public override hegicStakingETH;
  IHegicStaking public override hegicStakingWBTC;

  IHegicPoolV2 public override pool;
  IERC20 public override token;

  constructor(
    uint256 _performanceFee,
    address _zTreasury,
    address _pool,
    address _weth,
    address _wbtc,
    address _hegicStakingETH,
    address _hegicStakingWBTC
  ) public {
    _setPerformanceFee(_performanceFee);
    _setZTreasury(_zTreasury);
    _setPool(_pool);
    _setWETH(_weth);
    _setWBTC(_wbtc);
    _setHegicStaking(_hegicStakingETH, _hegicStakingWBTC);
  }

  function lotPrice() external override view returns (uint256) {
    return LOT_PRICE;
  }

  function getPool() external override view returns (address) {
    return address(pool);
  }

  function _setPerformanceFee(uint256 _performanceFee) internal {
    require(_performanceFee <= MAX_PERFORMANCE_FEE, 'LotManagerV2ProtocolParameters::_setPerformanceFee::bigger-than-max');
    performanceFee = _performanceFee;
    emit PerformanceFeeSet(_performanceFee);
  }
  
  function _setZTreasury(address _zTreasury) internal {
    require(_zTreasury != address(0), 'LotManagerV2ProtocolParameters::_setZTreasury::not-zero-address');
    require(IZTreasuryV2(_zTreasury).isZTreasury(), 'LotManagerV2ProtocolParameters::_setZTreasury::not-treasury');
    zTreasury = IZTreasuryV2(_zTreasury);
    emit ZTreasurySet(_zTreasury);
  }

  function _setPool(address _pool) internal {
    require(_pool != address(0), 'LotManagerV2ProtocolParameters::_setPool::not-zero-address');
    require(IHegicPoolMetadata(_pool).isHegicPool(), 'LotManagerV2ProtocolParameters::_setPool::not-setting-a-hegic-pool');
    pool = IHegicPoolV2(_pool);
    token = IERC20(pool.getToken());
    emit PoolSet(_pool, address(token));
  }

  function _setWETH(address _weth) internal {
    require(_weth != address(0), 'LotManagerV2ProtocolParameters::_setWETH::not-zero-address');
    weth = _weth;
    emit WETHSet(_weth);
  }

  function _setWBTC(address _wbtc) internal {
    require(_wbtc != address(0), 'LotManagerV2ProtocolParameters::_setWBTC::not-zero-address');
    wbtc = _wbtc;
    emit WBTCSet(_wbtc);
  }

  function _setHegicStaking(
    address _hegicStakingETH,
    address _hegicStakingWBTC
  ) internal {
    require(
      _hegicStakingETH != address(0) && 
      _hegicStakingWBTC != address(0), 
      'LotManagerV2ProtocolParameters::_setHegicStaking::not-zero-addresses'
    );

    hegicStakingETH = IHegicStaking(_hegicStakingETH);
    hegicStakingWBTC = IHegicStaking(_hegicStakingWBTC);

    emit HegicStakingSet(_hegicStakingETH, _hegicStakingWBTC);
  }
}
// File: interfaces/HegicPool/IHegicPoolV2.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

import '../IGovernable.sol';
import '../IManageable.sol';
import '../ICollectableDust.sol';

import './IHegicPoolMetadata.sol';
import './IHegicPoolProtocolParameters.sol';

interface IHegicPoolV2 is
  IGovernable,
  IManageable,
  ICollectableDust,
  IHegicPoolMetadata,
  IHegicPoolProtocolParameters {

  // Governance events
  event LotManagerSet(address lotManager);
  event PoolMigrated(address pool, uint256 balance);

  // Protocol events
  event RewardsClaimed(uint256 rewards);
  event LotsBought(uint256 eth, uint256 wbtc);

  // User events
  event Deposited(address depositor, uint256 tokenAmount, uint256 mintedShares);
  event Withdrew(address withdrawer, uint256 burntShares, uint256 withdrawedTokens, uint256 withdrawFee);

  function getToken() external view returns (address);
  function getZToken() external view returns (address);
  function getLotManager() external view returns (address);
  function migrate(address newPool) external;

  // User interactions
  function deposit(uint256 amount) external returns (uint256 shares);
  function depositAll() external returns (uint256 shares);
  function withdraw(uint256 shares) external returns (uint256 underlyingToWithdraw);
  function withdrawAll() external returns (uint256 underlyingToWithdraw);

  // State queries
  function unusedUnderlyingBalance() external view returns (uint256);
  function totalUnderlying() external view returns (uint256);
  function getPricePerFullShare() external view returns (uint256);

  // Lot Managment
  function setLotManager(address lotManager) external;
  function claimRewards() external returns (uint rewards);
  function buyLots(uint256 eth, uint256 wbtc) external returns (bool);
}

// File: interfaces/IHegicStaking.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IHegicStaking is IERC20 {    
    event Claim(address indexed acount, uint amount);
    event Profit(uint amount);

    function lockupPeriod() external view returns (uint256);
    function lastBoughtTimestamp(address) external view returns (uint256);

    function claimProfit() external returns (uint profit);
    function buy(uint amount) external;
    function sell(uint amount) external;
    function profitOf(address account) external view returns (uint);
}
// File: interfaces/LotManager/V2/ILotManagerV2ProtocolParameters.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

import '../../../interfaces/zTreasury/V2/IZTreasuryV2.sol';
import '../../../interfaces/HegicPool/IHegicPoolV2.sol';
import '../../../interfaces/IHegicStaking.sol';

interface ILotManagerV2ProtocolParameters {
  event PerformanceFeeSet(uint256 _performanceFee);
  event ZTreasurySet(address _zTreasury);
  event PoolSet(address _pool, address _token);
  event WETHSet(address _weth);
  event WBTCSet(address _wbtc);
  event HegicStakingSet(address _hegicStakingETH, address _hegicStakingWBTc);

  function uniswapV2() external returns (address);
  function LOT_PRICE() external returns (uint256);
  function FEE_PRECISION() external returns (uint256);
  function MAX_PERFORMANCE_FEE() external returns (uint256);
  function lotPrice() external view returns (uint256); // deprecated for LOT_PRICE
  function getPool() external view returns (address); // deprecated for pool

  function performanceFee() external returns (uint256);
  function zTreasury() external returns (IZTreasuryV2);

  function weth() external returns (address);
  function wbtc() external returns (address);
  function hegicStakingETH() external returns (IHegicStaking);
  function hegicStakingWBTC() external returns (IHegicStaking);

  function pool() external returns (IHegicPoolV2);
  function token() external returns (IERC20);

  function setPerformanceFee(uint256 _performanceFee) external;
  function setZTreasury(address _zTreasury) external;
  function setPool(address _pool) external;
  function setWETH(address _weth) external;
  function setWBTC(address _wbtc) external;
  function setHegicStaking(address _hegicStakingETH, address _hetgicStakingWBTC) external;
}
// File: interfaces/HegicPool/IHegicPoolMetadata.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

interface IHegicPoolMetadata {
  function isHegicPool() external pure returns (bool);
  function getName() external pure returns (string memory);
}

// File: interfaces/HegicPool/IHegicPoolProtocolParameters.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

interface IHegicPoolProtocolParameters {
  event MinTokenReservesSet(uint256 minTokenReserves);
  event WithdrawCooldownSet(uint256 withdrawCooldown);
  event WidthawFeeSet(uint256 withdrawFee);
  function setMinTokenReserves(uint256 minTokenReserves) external;
  function setWithdrawCooldown(uint256 withdrawCooldown) external;
  function setWithdrawFee(uint256 withdrawFee) external;
}

// File: contracts/LotManager/V2/LotManagerV2.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/math/SafeMath.sol';

import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';

import '../../../interfaces/LotManager/V2/ILotManagerV2.sol';
import '../../../interfaces/IWETH9.sol';

import '../../Governable.sol';
import '../../Manageable.sol';
import '../../CollectableDust.sol';

import '../LotManagerMetadata.sol';
import './LotManagerV2ProtocolParameters.sol';
import './LotManagerV2LotsHandler.sol';
import './LotManagerV2RewardsHandler.sol';
import './LotManagerV2Migrable.sol';
import './LotManagerV2Unwindable.sol';

contract LotManagerV2 is
  Governable,
  Manageable,
  CollectableDust,
  LotManagerMetadata,
  LotManagerV2ProtocolParameters,
  LotManagerV2LotsHandler,
  LotManagerV2RewardsHandler,
  LotManagerV2Migrable,
  LotManagerV2Unwindable,
  ILotManagerV2 {

  constructor(
    address _governor,
    address _manager,
    uint256 _performanceFee,
    address _zTreasury,
    address _pool,
    address _weth,
    address _wbtc,
    address[2] memory _hegicStakings
  ) public
    Governable(_governor)
    Manageable(_manager)
    CollectableDust()
    LotManagerMetadata()
    LotManagerV2ProtocolParameters(
      _performanceFee,
      _zTreasury,
      _pool,
      _weth,
      _wbtc,
      _hegicStakings[0],
      _hegicStakings[1])
    LotManagerV2LotsHandler()
    LotManagerV2RewardsHandler()
    LotManagerV2Migrable()
    LotManagerV2Unwindable() {
    _addProtocolToken(_pool);
    _addProtocolToken(address(token));
    _addProtocolToken(_weth);
    _addProtocolToken(_wbtc);
    _addProtocolToken(_hegicStakings[0]);
    _addProtocolToken(_hegicStakings[1]);
  }

  // Modifiers
  modifier onlyManagerOrPool {
    require(msg.sender == address(pool) || msg.sender == manager, 'LotManagerV2::only-manager-or-pool');
    _;
  }

  modifier onlyPool {
    require(msg.sender == address(pool), 'LotManagerV2::only-pool');
    _;
  }

  // Unwind
  function unwind(uint256 _amount) external override onlyPool returns (uint256 _total) {
    return _unwind(_amount);
  }

  // Rewards handler
  function claimRewards() external override onlyManagerOrPool returns (uint256 _totalRewards) {
    return _claimRewards();
  }

  // Lot Handler
  function buyLots(uint256 _ethLots, uint256 _wbtcLots) external override onlyPool returns (bool) {
    return _buyLots(_ethLots, _wbtcLots);
  }

  function sellLots(uint256 _ethLots, uint256 _wbtcLots) external override onlyGovernor returns (bool) {
    return _sellLots(_ethLots, _wbtcLots);
  }

  function rebalanceLots(uint256 _ethLots, uint256 _wbtcLots) external override onlyManagerOrPool returns (bool) {
    return _rebalanceLots(_ethLots, _wbtcLots);
  }

  // Protocol Parameters
  function setPerformanceFee(uint256 _peformanceFee) external override onlyGovernor {
    _setPerformanceFee(_peformanceFee);
  }

  function setZTreasury(address _zTreasury) external override onlyGovernor {
    _setZTreasury(_zTreasury);
  }

  function setPool(address _pool) external override onlyGovernor {
    _removeProtocolToken(address(pool));
    _removeProtocolToken(address(token));
    _setPool(_pool);
    _addProtocolToken(_pool);
    _addProtocolToken(address(token));
  }

  function setWETH(address _weth) external override onlyGovernor {
    _removeProtocolToken(weth);
    _addProtocolToken(_weth);
    _setWETH(_weth);
  }

  function setWBTC(address _wbtc) external override onlyGovernor {
    _removeProtocolToken(wbtc);
    _addProtocolToken(_wbtc);
    _setWBTC(_wbtc);
  }

  function setHegicStaking(
    address _hegicStakingETH, 
    address _hegicStakingWBTC
  ) external override onlyGovernor {
    if (address(hegicStakingETH) != _hegicStakingETH) {
      _removeProtocolToken(address(hegicStakingETH));
      _addProtocolToken(_hegicStakingETH);
    }
    if (address(hegicStakingWBTC) != _hegicStakingWBTC) {
      _removeProtocolToken(address(hegicStakingWBTC));
      _addProtocolToken(_hegicStakingWBTC);
    }
    _setHegicStaking(
      _hegicStakingETH,
      _hegicStakingWBTC
    );
  }

  // Migrable
  function migrate(address _newLotManager) external override virtual onlyGovernor {
    _migrate(_newLotManager);
  }

  // Governable
  function setPendingGovernor(address _pendingGovernor) external override onlyGovernor {
    _setPendingGovernor(_pendingGovernor);
  }

  function acceptGovernor() external override onlyPendingGovernor {
    _acceptGovernor();
  }

  // Manageable
  function setPendingManager(address _pendingManager) external override onlyManager {
    _setPendingManager(_pendingManager);
  }

  function acceptManager() external override onlyPendingManager {
    _acceptManager();
  }

  // Collectable Dust
  function sendDust(
    address _to,
    address _token,
    uint256 _amount
  ) external override onlyGovernor {
    _sendDust(_to, _token, _amount);
  }
}

// File: @openzeppelin/contracts/token/ERC20/ERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of returning `false` on failure. This behavior is nonetheless conventional
 * and does not conflict with the expectations of ERC20 applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20 {
    using SafeMath for uint256;
    using Address for address;

    mapping (address => uint256) private _balances;

    mapping (address => mapping (address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    /**
     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
     * a default value of 18.
     *
     * To select a different value for {decimals}, use {_setupDecimals}.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */
    constructor (string memory name, string memory symbol) public {
        _name = name;
        _symbol = symbol;
        _decimals = 18;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5,05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
     * called.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view returns (uint8) {
        return _decimals;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20};
     *
     * Requirements:
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(address sender, address recipient, uint256 amount) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements
     *
     * - `to` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
        _totalSupply = _totalSupply.sub(amount);
        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Sets {decimals} to a value other than the default one of 18.
     *
     * WARNING: This function should only be called from the constructor. Most
     * applications that interact with token contracts will not expect
     * {decimals} to ever change, and may work incorrectly if it does.
     */
    function _setupDecimals(uint8 decimals_) internal {
        _decimals = decimals_;
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be to transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}

// File: interfaces/LotManager/V2/ILotManagerV2.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '../../IGovernable.sol';
import '../../IManageable.sol';
import '../../ICollectableDust.sol';

import '../ILotManagerMetadata.sol';

import './ILotManagerV2ProtocolParameters.sol';
import './ILotManagerV2LotsHandler.sol';
import './ILotManagerV2RewardsHandler.sol';
import './ILotManagerV2Migrable.sol';
import './ILotManagerV2Unwindable.sol';

interface ILotManagerV2 is 
  IGovernable,
  IManageable,
  ICollectableDust,
  ILotManagerMetadata, 
  ILotManagerV2ProtocolParameters, 
  ILotManagerV2LotsHandler,
  ILotManagerV2RewardsHandler,
  ILotManagerV2Migrable,
  ILotManagerV2Unwindable { }
// File: interfaces/IWETH9.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;

interface IWETH9 {
    function deposit() external payable;
    function balanceOf(address account) external view returns (uint);
    function transfer(address recipient, uint amount) external returns (bool);
    function approve(address spender, uint amount) external returns (bool);
}
// File: contracts/LotManager/LotManagerMetadata.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '../../interfaces/LotManager/ILotManagerMetadata.sol';

contract LotManagerMetadata is ILotManagerMetadata {
  function isLotManager() external override pure returns (bool) {
    return true;
  }
  function getName() external override pure returns (string memory) {
    return 'LotManager';
  }
}
// File: contracts/LotManager/V2/LotManagerV2LotsHandler.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/math/SafeMath.sol';

import '../../../interfaces/LotManager/V2/ILotManagerV2LotsHandler.sol';

import './LotManagerV2ProtocolParameters.sol';

abstract
contract LotManagerV2LotsHandler is 
  LotManagerV2ProtocolParameters, 
  ILotManagerV2LotsHandler {

  using SafeMath for uint256;

  function balanceOfUnderlying() public override view returns (uint256 _underlyingBalance) {
    (uint256 _ethLots, uint256 _wbtcLots) = balanceOfLots();
    return _ethLots.add(_wbtcLots).mul(LOT_PRICE);
  }

  function balanceOfLots() public override view returns (uint256 _ethLots, uint256 _wbtcLots) {
    return (
      hegicStakingETH.balanceOf(address(this)),
      hegicStakingWBTC.balanceOf(address(this))
    );
  }

  function profitOfLots() public override view returns (uint256 _ethProfit, uint256 _wbtcProfit) {
    return (
      hegicStakingETH.profitOf(address(this)),
      hegicStakingWBTC.profitOf(address(this))
    );
  }

  function _buyLots(uint256 _ethLots, uint256 _wbtcLots) internal returns (bool) {
    // Get allowance
    uint256 allowance = token.allowance(address(pool), address(this));
    // Check if Allowance exceeds lot contract cost
    uint256 lotsCosts = _ethLots.add(_wbtcLots).mul(LOT_PRICE);
    require (allowance >= lotsCosts, 'LotManagerV2LotsHandler::_buyLots::not-enough-allowance');
    // Buy lot by transfering tokens
    token.transferFrom(address(pool), address(this), lotsCosts);

    // Buys Lot(s) (defaults buys ETH lot)
    if (_ethLots > 0) _buyETHLots(_ethLots);
    if (_wbtcLots > 0) _buyWBTCLots(_wbtcLots);

    // Transfer unused tokens(underlying) back to the pool
    token.transfer(address(pool), token.balanceOf(address(this)));

    return true;
  }

  function _buyETHLots(uint256 _ethLots) internal {
    // Allow hegicStakingETH to spend allowance
    token.approve(address(hegicStakingETH), 0);
    token.approve(address(hegicStakingETH), _ethLots * LOT_PRICE);
    hegicStakingETH.buy(_ethLots);
    emit ETHLotBought(_ethLots);
  }

  function _buyWBTCLots(uint256 _wbtcLots) internal {
    // Allow hegicStakingWBTC to spend allowance
    token.approve(address(hegicStakingWBTC), 0);
    token.approve(address(hegicStakingWBTC), _wbtcLots * LOT_PRICE);
    hegicStakingWBTC.buy(_wbtcLots);
    emit WBTCLotBought(_wbtcLots);
  }

  function _sellLots(uint256 _ethLots, uint256 _wbtcLots) internal returns (bool) {
    // Sells Lot(s) used for unwinding/rebalancing
    (uint256 _ownedETHLots, uint256 _ownedWBTCLots) = balanceOfLots();
    require (_ethLots <= _ownedETHLots && _wbtcLots <= _ownedWBTCLots, 'LotManagerV2LotsHandler::_sellLots::not-enough-lots');
    if (_ethLots > 0) _sellETHLots(_ethLots);
    if (_wbtcLots > 0) _sellWBTCLots(_wbtcLots);

    // Transfer all underlying back to pool
    token.transfer(address(pool), token.balanceOf(address(this)));

    return true;
  }

  function _sellETHLots(uint256 _eth) internal {
    hegicStakingETH.sell(_eth);
    emit ETHLotSold(_eth);
  }

  function _sellWBTCLots(uint256 _wbtc) internal {
    hegicStakingWBTC.sell(_wbtc);
    emit WBTCLotSold(_wbtc);
  }

  function _rebalanceLots(uint _ethLots, uint256 _wbtcLots) internal returns (bool) {
    (uint256 _ownedETHLots, uint256 _ownedWBTCLots) = balanceOfLots();
    require(
      _ethLots.add(_wbtcLots) == _ownedETHLots.add(_ownedWBTCLots) &&
      _ethLots != _ownedETHLots &&
      _wbtcLots != _ownedWBTCLots, 
      'LotManagerV2LotsHandler::_rebalanceLots::not-rebalancing-lots'
    );

    uint256 lotsDelta;
    if (_ethLots > _ownedETHLots) {
      lotsDelta = _ethLots.sub(_ownedETHLots);
      _sellWBTCLots(lotsDelta);
      _buyETHLots(lotsDelta);
    } else if (_wbtcLots > _ownedWBTCLots) {
      lotsDelta = _wbtcLots.sub(_ownedWBTCLots);
      _sellETHLots(lotsDelta);
      _buyWBTCLots(lotsDelta);
    }

    emit LotsRebalanced(_ethLots, _wbtcLots);
    return true;
  }
}
// File: contracts/LotManager/V2/LotManagerV2RewardsHandler.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/math/SafeMath.sol';

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';

import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';

import '../../../interfaces/LotManager/V2/ILotManagerV2RewardsHandler.sol';
import '../../../interfaces/IWETH9.sol';

import './LotManagerV2ProtocolParameters.sol';
import './LotManagerV2LotsHandler.sol';

abstract
contract LotManagerV2RewardsHandler is 
  LotManagerV2ProtocolParameters, 
  LotManagerV2LotsHandler,
  ILotManagerV2RewardsHandler {

  using SafeMath for uint256;
  using SafeERC20 for IERC20;

  receive() external payable { }

  function claimableRewards() public override view returns (uint256) {
    (uint256 _ethProfit, uint256 _wbtcProfit) = profitOfLots();

    if (_wbtcProfit > 0) {
      _ethProfit = _ethProfit.add(_getAmountOut(_wbtcProfit, wbtc, weth));
    }

    if (_ethProfit == 0) return 0;

    return _getAmountOut(_ethProfit, weth, address(token));
  }
    
  function _claimRewards() internal returns (uint256 _totalRewards) {
    (uint256 _ethProfit, uint256 _wbtcProfit) = profitOfLots();
    require(_ethProfit > 0 || _wbtcProfit > 0, 'LotManagerV2RewardsHandler::_claimRewards::no-proft-available');

    // Claim x888 Lot Rewards in WBTC if there is profit
    if (_wbtcProfit > 0) {
      hegicStakingWBTC.claimProfit();

      if (_ethProfit == 0) {
        // Swaps WBTC for Hegic
        _swapWBTCForToken();
      } else {
        // Swaps WBTC for WETH
        _swapWBTCForWETH();
      }
    }

    // If there is ETH profit
    if (_ethProfit > 0) {
      // Claim it
      hegicStakingETH.claimProfit();

      // Swap eth for weth
      IWETH9(weth).deposit{value:payable(address(this)).balance}();

      // Swap all WETH for Hegic
      _swapWETHForToken();
    }

    // Gets amount of tokens as rewards
    _totalRewards = token.balanceOf(address(this));

    // Take fee in HEGIC
    uint256 _fee = _totalRewards.mul(performanceFee).div(FEE_PRECISION).div(100);

    // Deposit fee in Pool to get zHEGIC
    token.approve(address(pool), 0);
    token.approve(address(pool), _fee);
    pool.deposit(_fee);

    // Transfer zHegic to feeRecipient
    IERC20 zToken = IERC20(pool.getZToken());
    zToken.transfer(address(zTreasury), zToken.balanceOf(address(this)));
    zTreasury.distributeEarnings();

    // Transfer HEGIC _totalRewards minus _fee to pool
    token.transfer(address(pool), _totalRewards.sub(_fee));

    emit RewardsClaimed(_totalRewards, _fee);
  }

  function _swapWBTCForWETH() internal {
    uint256 _wbtcBalance = IERC20(wbtc).balanceOf(address(this));

    address[] memory _path = new address[](2);
    _path[0] = wbtc;
    _path[1] = weth;

    // Swap wbtc for weth
    _swap(_wbtcBalance, _path);
  }

  function _swapWBTCForToken() internal {
    uint256 _wbtcBalance = IERC20(wbtc).balanceOf(address(this));

    address[] memory _path = new address[](3);
    _path[0] = wbtc;
    _path[1] = weth;
    _path[2] = address(token);

    // Swap wbtc for token
    _swap(_wbtcBalance, _path);
  }

  function _swapWETHForToken() internal {
    uint256 _wethBalance = IERC20(weth).balanceOf(address(this));

    address[] memory _path = new address[](2);
    _path[0] = weth;
    _path[1] = address(token);

    // Swap weth for token
    _swap(_wethBalance, _path);
  }

  function _swap(
    uint256 _amount,
    address[] memory _path
  ) internal {
    // Approve given erc20
    IERC20(_path[0]).safeApprove(uniswapV2, 0);
    IERC20(_path[0]).safeApprove(uniswapV2, _amount);
    // Swap it
    IUniswapV2Router02(uniswapV2).swapExactTokensForTokens(
      _amount,
      0,
      _path,
      address(this),
      now.add(1800)
    );
  }

  function _getAmountOut(
    uint256 _amountIn,
    address _fromToken,
    address _toToken
  ) internal view returns (uint256) {
    IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(uniswapV2);
    IUniswapV2Factory uniswapV2Factory = IUniswapV2Factory(uniswapV2Router.factory());
    IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(uniswapV2Factory.getPair(_fromToken, _toToken));
    (uint112 _reserve0, uint112 _reserve1,) = uniswapV2Pair.getReserves();
    (uint112 _reserveFromToken, uint112 _reserveToToken) = (_fromToken < _toToken) ? (_reserve0, _reserve1) : (_reserve1, _reserve0);
    return uniswapV2Router.getAmountOut(_amountIn, _reserveFromToken, _reserveToToken);
  }
}

// File: contracts/LotManager/V2/LotManagerV2Migrable.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/math/SafeMath.sol';

import '../../../interfaces/LotManager/ILotManagerMetadata.sol';
import '../../../interfaces/LotManager/V2/ILotManagerV2ProtocolParameters.sol';
import '../../../interfaces/LotManager/V2/ILotManagerV2Migrable.sol';

import './LotManagerV2ProtocolParameters.sol';

abstract
contract LotManagerV2Migrable is 
  LotManagerV2ProtocolParameters, 
  ILotManagerV2Migrable {
  
  function _migrate(address _newLotManager) internal {
    require(_newLotManager != address(0) && ILotManagerMetadata(_newLotManager).isLotManager(), 'LotManagerV2Migrable::_migrate::not-a-lot-manager');
    require(address(ILotManagerV2ProtocolParameters(_newLotManager).pool()) == address(pool), 'LotManagerV2Migrable::_migrate::migrate-pool-discrepancy');
    hegicStakingETH.transfer(_newLotManager, hegicStakingETH.balanceOf(address(this)));
    hegicStakingWBTC.transfer(_newLotManager, hegicStakingWBTC.balanceOf(address(this)));
    token.transfer(address(pool), token.balanceOf(address(this)));
    emit LotManagerMigrated(_newLotManager);
  }
}

// File: contracts/LotManager/V2/LotManagerV2Unwindable.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '../../../interfaces/LotManager/V2/ILotManagerV2Unwindable.sol';
import './LotManagerV2LotsHandler.sol';

abstract
contract LotManagerV2Unwindable is 
  LotManagerV2LotsHandler, 
  ILotManagerV2Unwindable {
  
  function _unwind(uint256 _amount) internal returns (uint256 _total) {
    (uint256 _ethLots, uint256 _wbtcLots) = balanceOfLots();
    require (_ethLots > 0 || _wbtcLots > 0, 'LotManagerV2Unwindable::_unwind::no-lots');

    bool areETHLotsUnlocked = hegicStakingETH.lastBoughtTimestamp(address(this)).add(hegicStakingETH.lockupPeriod()) <= block.timestamp;
    bool areWBTCLotsUnlocked = hegicStakingWBTC.lastBoughtTimestamp(address(this)).add(hegicStakingWBTC.lockupPeriod()) <= block.timestamp;
    require (areETHLotsUnlocked || areWBTCLotsUnlocked, 'LotManagerV2Unwindable::_unwind::no-unlocked-lots');
    _ethLots = areETHLotsUnlocked ? _ethLots : 0;
    _wbtcLots = areWBTCLotsUnlocked ? _wbtcLots : 0;
    uint256 _lotsToSell = _amount.div(LOT_PRICE).add(_amount.mod(LOT_PRICE) == 0 ? 0 : 1);
    require (_ethLots.add(_wbtcLots) >= _lotsToSell, 'LotManagerV2Unwindable::_unwind::not-enough-unlocked-lots');

    uint256 _totalSold = 0;

    if (_ethLots > 0) {
      _ethLots = _ethLots < _lotsToSell.sub(_totalSold) ? _ethLots : _lotsToSell.sub(_totalSold);
      _sellETHLots(_ethLots);
      _totalSold = _totalSold.add(_ethLots);
    }

    if (_wbtcLots > 0) {
      _wbtcLots = _wbtcLots < _lotsToSell.sub(_totalSold) ? _wbtcLots : _lotsToSell.sub(_totalSold);
      _sellWBTCLots(_wbtcLots);
      _totalSold = _totalSold.add(_wbtcLots);
    }

    require(_totalSold == _lotsToSell, 'LotManagerV2Unwindable::_unwind::not-enough-lots-sold');

    _total = _lotsToSell.mul(LOT_PRICE);

    require(_total >= _amount, 'LotManagerV2Unwindable::_unwind::not-enough-tokens-aquired');

    token.transfer(address(pool), _total);

    emit Unwound(_total);
  }
}

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



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with GSN meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

// File: interfaces/LotManager/V2/ILotManagerV2LotsHandler.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

interface ILotManagerV2LotsHandler {
  event ETHLotBought(uint256 amount);
  event WBTCLotBought(uint256 amount);
  event ETHLotSold(uint256 amount);
  event WBTCLotSold(uint256 amount);
  event LotsRebalanced(uint256 _ethLots, uint256 _wbtcLots);
  
  function balanceOfUnderlying() external view returns (uint256 _underlyingBalance);
  function balanceOfLots() external view returns (uint256 _ethLots, uint256 _wbtcLots);
  function profitOfLots() external view returns (uint256 _ethProfit, uint256 _wbtcProfit);
  function buyLots(uint256 _ethLots, uint256 _wbtcLots) external returns (bool);
  function sellLots(uint256 _ethLots, uint256 _wbtcLots) external returns (bool);
  function rebalanceLots(uint256 _ethLots, uint256 _wbtcLots) external returns (bool);
}
// File: interfaces/LotManager/V2/ILotManagerV2RewardsHandler.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

interface ILotManagerV2RewardsHandler {
  event RewardsClaimed(uint256 rewards, uint256 fees);

  function claimRewards() external returns (uint256 _totalRewards);
  function claimableRewards() external view returns (uint256 _amountOut);
}

// File: interfaces/LotManager/V2/ILotManagerV2Migrable.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

interface ILotManagerV2Migrable {
  event LotManagerMigrated(address newLotManager);

  function migrate(address newLotManager) external;
}
// File: interfaces/LotManager/V2/ILotManagerV2Unwindable.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

interface ILotManagerV2Unwindable {
  event Unwound(uint256 amount);

  function unwind(uint256 _amount) external returns (uint256 _total);
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol



pragma solidity >=0.5.0;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol



pragma solidity >=0.5.0;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol



pragma solidity >=0.6.2;

import './IUniswapV2Router01.sol';

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol



pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}

// File: contracts/LotManager/V2/LotManagerV2.1.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/math/SafeMath.sol';

import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';

import '../../../interfaces/LotManager/V2/ILotManagerV2.sol';
import '../../../interfaces/IWETH9.sol';

import '../../Governable.sol';
import '../../Manageable.sol';
import '../../CollectableDust.sol';

import '../LotManagerMetadata.sol';
import './LotManagerV2ProtocolParameters.sol';
import './LotManagerV2LotsHandler.sol';
import './LotManagerV2RewardsHandler.sol';
import './LotManagerV2Migrable.sol';
import './LotManagerV2Unwindable.sol';

contract LotManagerV2Dot1 is
  Governable,
  Manageable,
  CollectableDust,
  LotManagerMetadata,
  LotManagerV2ProtocolParameters,
  LotManagerV2LotsHandler,
  LotManagerV2RewardsHandler,
  LotManagerV2Migrable,
  LotManagerV2Unwindable,
  ILotManagerV2 {

  constructor(
    address _governor,
    address _manager,
    uint256 _performanceFee,
    address _zTreasury,
    address _pool,
    address _weth,
    address _wbtc,
    address[2] memory _hegicStakings
  ) public
    Governable(_governor)
    Manageable(_manager)
    CollectableDust()
    LotManagerMetadata()
    LotManagerV2ProtocolParameters(
      _performanceFee,
      _zTreasury,
      _pool,
      _weth,
      _wbtc,
      _hegicStakings[0],
      _hegicStakings[1])
    LotManagerV2LotsHandler()
    LotManagerV2RewardsHandler()
    LotManagerV2Migrable()
    LotManagerV2Unwindable() {
    _addProtocolToken(_pool);
    _addProtocolToken(address(token));
    _addProtocolToken(_weth);
    _addProtocolToken(_wbtc);
    _addProtocolToken(_hegicStakings[0]);
    _addProtocolToken(_hegicStakings[1]);
  }

  // Modifiers
  modifier onlyManagerOrPool {
    require(msg.sender == manager || msg.sender == address(pool), 'LotManagerV2::only-manager-or-pool');
    _;
  }

  modifier onlyGovernorOrPool {
    require(msg.sender == governor || msg.sender == address(pool), 'LotManagerV2::only-governor-or-pool');
    _;
  }

  modifier onlyPool {
    require(msg.sender == address(pool), 'LotManagerV2::only-pool');
    _;
  }

  // Unwind
  function unwind(uint256 _amount) external override onlyPool returns (uint256 _total) {
    return _unwind(_amount);
  }

  // Rewards handler
  function claimRewards() external override onlyManagerOrPool returns (uint256 _totalRewards) {
    return _claimRewards();
  }

  // Lot Handler
  function buyLots(uint256 _ethLots, uint256 _wbtcLots) external override onlyPool returns (bool) {
    return _buyLots(_ethLots, _wbtcLots);
  }

  function sellLots(uint256 _ethLots, uint256 _wbtcLots) external override onlyGovernor returns (bool) {
    return _sellLots(_ethLots, _wbtcLots);
  }

  function rebalanceLots(uint256 _ethLots, uint256 _wbtcLots) external override onlyManagerOrPool returns (bool) {
    return _rebalanceLots(_ethLots, _wbtcLots);
  }

  // Protocol Parameters
  function setPerformanceFee(uint256 _peformanceFee) external override onlyGovernor {
    _setPerformanceFee(_peformanceFee);
  }

  function setZTreasury(address _zTreasury) external override onlyGovernor {
    _setZTreasury(_zTreasury);
  }

  function setPool(address _pool) external override onlyGovernorOrPool {
    _removeProtocolToken(address(pool));
    _removeProtocolToken(address(token));
    _setPool(_pool);
    _addProtocolToken(_pool);
    _addProtocolToken(address(token));
  }

  function setWETH(address _weth) external override onlyGovernor {
    _removeProtocolToken(weth);
    _addProtocolToken(_weth);
    _setWETH(_weth);
  }

  function setWBTC(address _wbtc) external override onlyGovernor {
    _removeProtocolToken(wbtc);
    _addProtocolToken(_wbtc);
    _setWBTC(_wbtc);
  }

  function setHegicStaking(
    address _hegicStakingETH, 
    address _hegicStakingWBTC
  ) external override onlyGovernor {
    if (address(hegicStakingETH) != _hegicStakingETH) {
      _removeProtocolToken(address(hegicStakingETH));
      _addProtocolToken(_hegicStakingETH);
    }
    if (address(hegicStakingWBTC) != _hegicStakingWBTC) {
      _removeProtocolToken(address(hegicStakingWBTC));
      _addProtocolToken(_hegicStakingWBTC);
    }
    _setHegicStaking(
      _hegicStakingETH,
      _hegicStakingWBTC
    );
  }

  // Migrable
  function migrate(address _newLotManager) external override onlyGovernor {
    _migrate(_newLotManager);
  }

  // Governable
  function setPendingGovernor(address _pendingGovernor) external override onlyGovernor {
    _setPendingGovernor(_pendingGovernor);
  }

  function acceptGovernor() external override onlyPendingGovernor {
    _acceptGovernor();
  }

  // Manageable
  function setPendingManager(address _pendingManager) external override onlyManager {
    _setPendingManager(_pendingManager);
  }

  function acceptManager() external override onlyPendingManager {
    _acceptManager();
  }

  // Collectable Dust
  function sendDust(
    address _to,
    address _token,
    uint256 _amount
  ) external override onlyGovernor {
    _sendDust(_to, _token, _amount);
  }
}

// File: contracts/zHEGIC.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.8;

import '@openzeppelin/contracts/token/ERC20/ERC20.sol';

import '../interfaces/HegicPool/IHegicPoolMetadata.sol';
import './Governable.sol';

contract zHEGIC is ERC20, Governable {

  IHegicPoolMetadata public pool;

  constructor() public
    ERC20('zHEGIC', 'zHEGIC')
    Governable(msg.sender) {
  }

  modifier onlyPool {
    require(msg.sender == address(pool), 'zHEGIC/only-pool');
    _;
  }

  modifier onlyPoolOrGovernor {
    require(msg.sender == address(pool) || msg.sender == governor, 'zHEGIC/only-pool-or-governor');
    _;
  }

  function setPool(address _newPool) external onlyPoolOrGovernor {
    require(IHegicPoolMetadata(_newPool).isHegicPool(), 'zHEGIC/not-setting-a-hegic-pool');
    pool = IHegicPoolMetadata(_newPool);
  }

  function mint(address account, uint256 amount) external onlyPool {
    _mint(account, amount);
  }

  function burn(address account, uint256 amount) external onlyPool {
    _burn(account, amount);
  }

  // Governable
  function setPendingGovernor(address _pendingGovernor) external override onlyGovernor {
    _setPendingGovernor(_pendingGovernor);
  }

  function acceptGovernor() external override onlyPendingGovernor {
    _acceptGovernor();
  }
}