ETH Price: $2,271.02 (-1.28%)

Contract

0x8f4491ED76bE9680ec801CBc070fA12067B5071a

Overview

ETH Balance

0 ETH

ETH Value

$0.00

Sponsored

Transaction Hash
Method
Block
From
To
0x60a06040437202972022-11-30 3:23:51648 days ago1669778631IN
 Create: LyraOptionMarketWrapperAssetGuard
0 ETH0.0018921674270.001

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073178102023-07-24 21:33:17411 days ago1690234397
0x8f4491ED...067B5071a
0 ETH
1073177222023-07-24 21:30:21411 days ago1690234221
0x8f4491ED...067B5071a
0 ETH
1073177222023-07-24 21:30:21411 days ago1690234221
0x8f4491ED...067B5071a
0 ETH
1073177222023-07-24 21:30:21411 days ago1690234221
0x8f4491ED...067B5071a
0 ETH
1073177222023-07-24 21:30:21411 days ago1690234221
0x8f4491ED...067B5071a
0 ETH
1073177222023-07-24 21:30:21411 days ago1690234221
0x8f4491ED...067B5071a
0 ETH
1073177222023-07-24 21:30:21411 days ago1690234221
0x8f4491ED...067B5071a
0 ETH
1073177222023-07-24 21:30:21411 days ago1690234221
0x8f4491ED...067B5071a
0 ETH
1073177222023-07-24 21:30:21411 days ago1690234221
0x8f4491ED...067B5071a
0 ETH
1071891152023-07-21 22:03:27414 days ago1689977007
0x8f4491ED...067B5071a
0 ETH
1071891152023-07-21 22:03:27414 days ago1689977007
0x8f4491ED...067B5071a
0 ETH
View All Internal Transactions

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
LyraOptionMarketWrapperAssetGuard

Compiler Version
v0.7.6+commit.7338295f

Optimization Enabled:
Yes with 20 runs

Other Settings:
default evmVersion
File 1 of 42 : LyraOptionMarketWrapperAssetGuard.sol
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.7.6;
pragma abicoder v2;

import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

import "./ERC20Guard.sol";
import "../contractGuards/LyraOptionMarketWrapperContractGuard.sol";
import "../../utils/lyra/DhedgeOptionMarketWrapperForLyra.sol";
import "../../interfaces/IERC20Extended.sol";
import "../../interfaces/IPoolLogic.sol";
import "../../interfaces/IHasAssetInfo.sol";
import "../../interfaces/lyra/IOptionMarketViewer.sol";
import "../../interfaces/lyra/IOptionGreekCache.sol";
import "../../interfaces/lyra/ISynthetixAdapter.sol";
import "../../interfaces/lyra/ILiquidityPool.sol";
import "../../interfaces/lyra/IOptionMarket.sol";

/// @title Lyra OptionMarketWrapper asset guard
/// @dev Asset type = 100
contract LyraOptionMarketWrapperAssetGuard is ERC20Guard {
  using SafeMath for uint256;

  DhedgeOptionMarketWrapperForLyra public immutable dhedgeLyraWrapper;
  uint256 public constant PRICE_GWAV_DURATION = 10 minutes;
  uint256 public constant CHECK_GWAV_DURATION = 6 hours;
  uint256 public constant GWAV_DIVERGENCE_CB_AMOUNT_DENOMINATOR = 1000;
  // 5%
  uint256 public constant GWAV_DIVERGENCE_CB_AMOUNT_NUMERATOR = (GWAV_DIVERGENCE_CB_AMOUNT_DENOMINATOR / 100) * 5;

  constructor(DhedgeOptionMarketWrapperForLyra _dhedgeLyraWrapper) {
    dhedgeLyraWrapper = _dhedgeLyraWrapper;
  }

  function marketViewer() public view returns (IOptionMarketViewer) {
    return dhedgeLyraWrapper.getOptionMarketViewer();
  }

  function getGWAVCallPrice(address optionMarket, uint256 strikeId) public view returns (uint256 callPrice) {
    ILyraRegistry.OptionMarketAddresses memory c = dhedgeLyraWrapper.lyraRegistry().getMarketAddresses(optionMarket);

    (callPrice, ) = IGWAVOracle(c.gwavOracle).optionPriceGWAV(strikeId, PRICE_GWAV_DURATION);
    (uint256 checkCallPrice, ) = IGWAVOracle(c.gwavOracle).optionPriceGWAV(strikeId, CHECK_GWAV_DURATION);

    assertNoGWAVDivergence(callPrice, checkCallPrice);
  }

  function getGWAVPutPrice(address optionMarket, uint256 strikeId) public view returns (uint256 putPrice) {
    ILyraRegistry.OptionMarketAddresses memory c = dhedgeLyraWrapper.lyraRegistry().getMarketAddresses(optionMarket);

    (, putPrice) = IGWAVOracle(c.gwavOracle).optionPriceGWAV(strikeId, PRICE_GWAV_DURATION);
    (, uint256 checkPutPrice) = IGWAVOracle(c.gwavOracle).optionPriceGWAV(strikeId, CHECK_GWAV_DURATION);

    assertNoGWAVDivergence(putPrice, checkPutPrice);
  }

  function assertNoGWAVDivergence(uint256 price1, uint256 price2) public pure {
    uint256 difference = price1 > price2 ? price1 - price2 : price2 - price1;
    uint256 acceptableDifference = price1.mul(GWAV_DIVERGENCE_CB_AMOUNT_NUMERATOR).div(
      GWAV_DIVERGENCE_CB_AMOUNT_DENOMINATOR
    );
    require(difference <= acceptableDifference, "gwav divergence too high");
  }

  /// @notice Creates transaction data for withdrawing staked tokens
  /// @dev The same interface can be used for other types of stakeable tokens
  /// @param pool Pool address
  /// @param asset lyra option market wrapper contract address
  /// @param portion The fraction of total staked asset to withdraw
  /// @return withdrawAsset and
  /// @return withdrawBalance are used to withdraw portion of asset balance to investor
  /// @return transactions is used to execute the staked withdrawal transaction in PoolLogic
  function withdrawProcessing(
    address pool,
    address asset,
    uint256 portion,
    address to
  )
    external
    virtual
    override
    returns (
      address withdrawAsset,
      uint256 withdrawBalance,
      MultiTransaction[] memory transactions
    )
  {
    // settle expired positions
    address lyraOptionMarketWrapperContractGuard = IHasGuardInfo(IPoolLogic(pool).factory()).getContractGuard(asset);
    LyraOptionMarketWrapperContractGuard(lyraOptionMarketWrapperContractGuard).settleExpiredAndFilterActivePositions(
      pool
    );

    // get active positions
    LyraOptionMarketWrapperContractGuard.OptionPosition[] memory positions = LyraOptionMarketWrapperContractGuard(
      lyraOptionMarketWrapperContractGuard
    ).getOptionPositions(pool);

    // create the transactions array
    transactions = new MultiTransaction[](positions.length * 2);
    uint256 txCount;
    for (uint256 i = 0; i < positions.length; i++) {
      // Transfer the Option NFT ownership to the wrapper contract.
      // We need to do this because before we call `forceClose` on a position we don't know exactly how much the withdrawer will receive back.
      IOptionMarketViewer.OptionMarketAddresses memory optionMarketAddresses = marketViewer().marketAddresses(
        positions[i].optionMarket
      );
      transactions[txCount].to = address(optionMarketAddresses.optionToken);
      transactions[txCount].txData = abi.encodeWithSelector(
        IERC721.transferFrom.selector,
        pool,
        dhedgeLyraWrapper,
        positions[i].positionId
      );
      txCount++;

      // DhedgeOptionMarketWrapperForLyra will return the nft after forceClosing the withdrawers portion
      transactions[txCount].to = address(dhedgeLyraWrapper);
      transactions[txCount].txData = abi.encodeWithSelector(
        DhedgeOptionMarketWrapperForLyra.tryCloseAndForceClosePosition.selector,
        positions[i],
        portion,
        to // recipient
      );
      txCount++;
    }

    return (withdrawAsset, withdrawBalance, transactions);
  }

  /// @notice Returns decimal of the Lyra option market asset
  /// @dev Returns decimal 18
  function getDecimals(address) external pure override returns (uint256 decimals) {
    decimals = 18;
  }

  /// @notice Returns the balance of the managed asset
  /// @dev May include any external balance in staking contracts
  /// @param pool address of the pool
  /// @param asset lyra option market wrapper contract address
  /// @return balance The asset balance of given pool
  function getBalance(address pool, address asset) public view override returns (uint256 balance) {
    address factory = IPoolLogic(pool).factory();
    address lyraContractGuard = IHasGuardInfo(factory).getContractGuard(asset);

    LyraOptionMarketWrapperContractGuard.OptionPosition[] memory positions = LyraOptionMarketWrapperContractGuard(
      lyraContractGuard
    ).getOptionPositions(pool);

    for (uint256 i = 0; i < positions.length; i++) {
      IOptionMarketViewer.OptionMarketAddresses memory optionMarketAddresses = marketViewer().marketAddresses(
        positions[i].optionMarket
      );

      IOptionToken.OptionPosition memory position = IOptionToken(optionMarketAddresses.optionToken).positions(
        positions[i].positionId
      );

      if (position.state == IOptionToken.PositionState.ACTIVE) {
        uint256 basePrice = dhedgeLyraWrapper.getSynthetixAdapter().getSpotPriceForMarket(positions[i].optionMarket);
        (uint256 strikePrice, uint256 priceAtExpiry, uint256 ammShortCallBaseProfitRatio) = IOptionMarket(
          positions[i].optionMarket
        ).getSettlementParameters(position.strikeId);

        uint256 marketValue;
        if (priceAtExpiry != 0) {
          // option is expired
          if (position.optionType == IOptionMarket.OptionType.LONG_CALL) {
            marketValue = (priceAtExpiry > strikePrice)
              ? position.amount.mul(priceAtExpiry.sub(strikePrice)).div(1e18)
              : 0;
          } else if (position.optionType == IOptionMarket.OptionType.LONG_PUT) {
            marketValue = (strikePrice > priceAtExpiry)
              ? position.amount.mul(strikePrice.sub(priceAtExpiry)).div(1e18)
              : 0;
          } else if (position.optionType == IOptionMarket.OptionType.SHORT_CALL_BASE) {
            uint256 ammProfit = position.amount.mul(ammShortCallBaseProfitRatio).div(1e18);
            marketValue = position.collateral > ammProfit
              ? (position.collateral.sub(ammProfit)).mul(basePrice).div(1e18)
              : 0;
          } else if (position.optionType == IOptionMarket.OptionType.SHORT_CALL_QUOTE) {
            uint256 ammProfit = (priceAtExpiry > strikePrice)
              ? position.amount.mul(priceAtExpiry.sub(strikePrice)).div(1e18)
              : 0;
            marketValue = position.collateral > ammProfit ? position.collateral.sub(ammProfit) : 0;
          } else if (position.optionType == IOptionMarket.OptionType.SHORT_PUT_QUOTE) {
            uint256 ammProfit = (strikePrice > priceAtExpiry)
              ? position.amount.mul(strikePrice.sub(priceAtExpiry)).div(1e18)
              : 0;
            marketValue = position.collateral > ammProfit ? position.collateral.sub(ammProfit) : 0;
          } else {
            revert("invalid option type");
          }
        } else {
          if (position.optionType == IOptionMarket.OptionType.LONG_CALL) {
            // position.amount.multiplyDecimal(callPrice)
            marketValue = position.amount.mul(getGWAVCallPrice(positions[i].optionMarket, position.strikeId)).div(1e18);
          } else if (position.optionType == IOptionMarket.OptionType.LONG_PUT) {
            // position.amount.multiplyDecimal(putPrice)
            marketValue = position.amount.mul(getGWAVPutPrice(positions[i].optionMarket, position.strikeId)).div(1e18);
          } else if (position.optionType == IOptionMarket.OptionType.SHORT_CALL_BASE) {
            // position.collateral.multiplyDecimal(basePrice) - position.amount.multiplyDecimal(callPrice)
            uint256 collateralValue = position.collateral.mul(basePrice).div(1e18);
            uint256 callValue = position.amount.mul(getGWAVCallPrice(positions[i].optionMarket, position.strikeId)).div(
              1e18
            );
            marketValue = collateralValue > callValue ? collateralValue.sub(callValue) : 0;
          } else if (position.optionType == IOptionMarket.OptionType.SHORT_CALL_QUOTE) {
            // position.collateral - position.amount.multiplyDecimal(callPrice)
            uint256 collateralValue = position.collateral;
            uint256 callValue = position.amount.mul(getGWAVCallPrice(positions[i].optionMarket, position.strikeId)).div(
              1e18
            );
            marketValue = collateralValue > callValue ? collateralValue.sub(callValue) : 0;
          } else if (position.optionType == IOptionMarket.OptionType.SHORT_PUT_QUOTE) {
            // position.collateral - position.amount.multiplyDecimal(putPrice)
            uint256 collateralValue = position.collateral;
            uint256 putValue = position.amount.mul(getGWAVPutPrice(positions[i].optionMarket, position.strikeId)).div(
              1e18
            );
            marketValue = collateralValue > putValue ? collateralValue.sub(putValue) : 0;
          } else {
            revert("invalid option type");
          }
        }
        balance = balance.add(marketValue);
      }
    }
  }
}

File 2 of 42 : IERC20Extended.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;

// With aditional optional views

interface IERC20Extended {
  // ERC20 Optional Views
  function name() external view returns (string memory);

  function symbol() external view returns (string memory);

  function decimals() external view returns (uint8);

  // Views
  function totalSupply() external view returns (uint256);

  function balanceOf(address owner) external view returns (uint256);

  function scaledBalanceOf(address user) external view returns (uint256);

  function allowance(address owner, address spender) external view returns (uint256);

  // Mutative functions
  function transfer(address to, uint256 value) external returns (bool);

  function approve(address spender, uint256 value) external returns (bool);

  function transferFrom(
    address from,
    address to,
    uint256 value
  ) external returns (bool);

  // Events
  event Transfer(address indexed from, address indexed to, uint256 value);

  event Approval(address indexed owner, address indexed spender, uint256 value);
}

File 3 of 42 : IPoolLogic.sol
//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

interface IPoolLogic {
  function factory() external view returns (address);

  function poolManagerLogic() external view returns (address);

  function setPoolManagerLogic(address _poolManagerLogic) external returns (bool);

  function availableManagerFee() external view returns (uint256 fee);

  function tokenPrice() external view returns (uint256 price);

  function tokenPriceWithoutManagerFee() external view returns (uint256 price);

  function mintManagerFee() external;

  function deposit(address _asset, uint256 _amount) external returns (uint256 liquidityMinted);

  function depositFor(
    address _recipient,
    address _asset,
    uint256 _amount
  ) external returns (uint256 liquidityMinted);

  function depositForWithCustomCooldown(
    address _recipient,
    address _asset,
    uint256 _amount,
    uint256 _cooldown
  ) external returns (uint256 liquidityMinted);

  function withdraw(uint256 _fundTokenAmount) external;

  function transfer(address to, uint256 value) external returns (bool);

  function balanceOf(address owner) external view returns (uint256);

  function approve(address spender, uint256 amount) external returns (bool);

  function symbol() external view returns (string memory);

  function transferFrom(
    address from,
    address to,
    uint256 value
  ) external returns (bool);

  function getExitRemainingCooldown(address sender) external view returns (uint256 remaining);
}

File 4 of 42 : IHasAssetInfo.sol
//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

interface IHasAssetInfo {
  function isValidAsset(address asset) external view returns (bool);

  function getAssetPrice(address asset) external view returns (uint256);

  function getAssetType(address asset) external view returns (uint16);

  function getMaximumSupportedAssetCount() external view returns (uint256);
}

File 5 of 42 : ERC20Guard.sol
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import "../../utils/TxDataUtils.sol";
import "../../interfaces/guards/IAssetGuard.sol";
import "../../interfaces/guards/IGuard.sol";
import "../../interfaces/IERC20Extended.sol"; // includes decimals()
import "../../interfaces/IPoolManagerLogic.sol";
import "../../interfaces/IHasSupportedAsset.sol";
import "../../interfaces/IHasGuardInfo.sol";
import "../../interfaces/IManaged.sol";

/// @title Generic ERC20 asset guard
/// @dev Asset type = 0
/// @dev A generic ERC20 guard asset is Not stakeable ie. no 'getWithdrawStakedTx()' function
contract ERC20Guard is TxDataUtils, IGuard, IAssetGuard {
  using SafeMathUpgradeable for uint256;

  event Approve(address fundAddress, address manager, address spender, uint256 amount, uint256 time);

  /// @notice Transaction guard for approving assets
  /// @dev Parses the manager transaction data to ensure transaction is valid
  /// @param _poolManagerLogic Pool address
  /// @param data Transaction call data attempt by manager
  /// @return txType transaction type described in PoolLogic
  /// @return isPublic if the transaction is public or private
  function txGuard(
    address _poolManagerLogic,
    address, // to
    bytes calldata data
  )
    external
    override
    returns (
      uint16 txType, // transaction type
      bool // isPublic
    )
  {
    bytes4 method = getMethod(data);

    if (method == bytes4(keccak256("approve(address,uint256)"))) {
      address spender = convert32toAddress(getInput(data, 0));
      uint256 amount = uint256(getInput(data, 1));

      IPoolManagerLogic poolManagerLogic = IPoolManagerLogic(_poolManagerLogic);

      address factory = poolManagerLogic.factory();
      address spenderGuard = IHasGuardInfo(factory).getContractGuard(spender);
      require(spenderGuard != address(0) && spenderGuard != address(this), "unsupported spender approval"); // checks that the spender is an approved address

      emit Approve(
        poolManagerLogic.poolLogic(),
        IManaged(_poolManagerLogic).manager(),
        spender,
        amount,
        block.timestamp
      );

      txType = 1; // 'Approve' type
    }

    return (txType, false);
  }

  /// @notice Creates transaction data for withdrawing tokens
  /// @dev Withdrawal processing is not applicable for this guard
  /// @return withdrawAsset and
  /// @return withdrawBalance are used to withdraw portion of asset balance to investor
  /// @return transactions is used to execute the withdrawal transaction in PoolLogic
  function withdrawProcessing(
    address pool,
    address asset,
    uint256 portion,
    address // to
  )
    external
    virtual
    override
    returns (
      address withdrawAsset,
      uint256 withdrawBalance,
      MultiTransaction[] memory transactions
    )
  {
    withdrawAsset = asset;
    uint256 totalAssetBalance = getBalance(pool, asset);
    withdrawBalance = totalAssetBalance.mul(portion).div(10**18);
    return (withdrawAsset, withdrawBalance, transactions);
  }

  /// @notice Returns the balance of the managed asset
  /// @dev May include any external balance in staking contracts
  /// @return balance The asset balance of given pool
  function getBalance(address pool, address asset) public view virtual override returns (uint256 balance) {
    // The base ERC20 guard has no externally staked tokens
    balance = IERC20(asset).balanceOf(pool);
  }

  /// @notice Returns the decimal of the managed asset
  /// @param asset Address of the managed asset
  /// @return decimals The decimal of given asset
  function getDecimals(address asset) external view virtual override returns (uint256 decimals) {
    decimals = IERC20Extended(asset).decimals();
  }

  /// @notice Necessary check for remove asset
  /// @param pool Address of the pool
  /// @param asset Address of the remove asset
  function removeAssetCheck(address pool, address asset) public view virtual override {
    uint256 balance = getBalance(pool, asset);
    require(balance == 0, "cannot remove non-empty asset");
  }
}

File 6 of 42 : DhedgeOptionMarketWrapperForLyra.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

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

import "../../guards/contractGuards/LyraOptionMarketWrapperContractGuard.sol";
import "../../interfaces/aave/v2/ILendingPool.sol";
import "../../interfaces/lyra/ILyraRegistry.sol";
import "../../interfaces/lyra/IOptionMarketViewer.sol";
import "../../interfaces/lyra/IOptionMarketWrapper.sol";
import "../../interfaces/lyra/IOptionToken.sol";
import "../../interfaces/lyra/ISynthetixAdapter.sol";
import "../../interfaces/lyra/IGWAVOracle.sol";
import "../../interfaces/synthetix/ISynthetix.sol";
import "../../interfaces/synthetix/IExchanger.sol";
import "../../interfaces/IPoolLogic.sol";
import "../../interfaces/IHasGuardInfo.sol";

contract DhedgeOptionMarketWrapperForLyra {
  using SafeMath for uint256;

  bytes32 public constant MARKET_VIEWER = "MARKET_VIEWER";
  bytes32 public constant MARKET_WRAPPER = "MARKET_WRAPPER";
  bytes32 public constant SYNTHETIX_ADAPTER = "SYNTHETIX_ADAPTER";

  ILyraRegistry public immutable lyraRegistry;
  ILendingPool public immutable aaveLendingPool;

  constructor(ILyraRegistry _lyraRegistry, address _aaveLendingPool) {
    lyraRegistry = _lyraRegistry;
    aaveLendingPool = ILendingPool(_aaveLendingPool);
  }

  function getOptionMarketViewer() public view returns (IOptionMarketViewer) {
    return IOptionMarketViewer(lyraRegistry.getGlobalAddress(MARKET_VIEWER));
  }

  function getOptionMarketWrapper() public view returns (IOptionMarketWrapper) {
    return IOptionMarketWrapper(lyraRegistry.getGlobalAddress(MARKET_WRAPPER));
  }

  function getSynthetixAdapter() public view returns (ISynthetixAdapter) {
    return ISynthetixAdapter(lyraRegistry.getGlobalAddress(SYNTHETIX_ADAPTER));
  }

  function _encodeCloseParams(
    IOptionMarketViewer.OptionMarketAddresses memory optionMarketAddresses,
    IOptionToken.OptionPosition memory position,
    uint256 portion
  ) internal pure returns (IOptionMarketWrapper.OptionPositionParams memory params) {
    return
      IOptionMarketWrapper.OptionPositionParams({
        optionMarket: IOptionMarket(optionMarketAddresses.optionMarket),
        strikeId: position.strikeId,
        positionId: position.positionId,
        iterations: 1,
        currentCollateral: position.collateral,
        setCollateralTo: position.collateral.sub(position.collateral.mul(portion).div(10**18)),
        optionType: position.optionType,
        amount: position.amount.mul(portion).div(10**18),
        minCost: 0,
        maxCost: type(uint256).max,
        inputAmount: 0,
        inputAsset: IERC20(optionMarketAddresses.quoteAsset)
      });
  }

  /// @notice This function is to close lyra option position - called from PoolLogic contract
  /// @dev the original Lyra close/forceClose position functions doesn't accept recipient address
  ///      this function will accept a recipient address and withdraw the funds to the recipient directly.
  /// @param dhedgeStoredPosition the position information dhedge stores
  /// @param portion the portion of the withdrawer
  /// @param recipient the recipient address for withdrawn funds
  function tryCloseAndForceClosePosition(
    LyraOptionMarketWrapperContractGuard.OptionPosition memory dhedgeStoredPosition,
    uint256 portion,
    address recipient
  ) external {
    IOptionMarketViewer.OptionMarketAddresses memory optionMarketAddresses = getOptionMarketViewer().marketAddresses(
      address(dhedgeStoredPosition.optionMarket)
    );
    IOptionToken.OptionPosition memory position = optionMarketAddresses.optionToken.positions(
      dhedgeStoredPosition.positionId
    );

    IOptionMarketWrapper.OptionPositionParams memory closeParams = _encodeCloseParams(
      optionMarketAddresses,
      position,
      portion
    );

    if (
      closeParams.optionType == IOptionMarket.OptionType.SHORT_CALL_BASE ||
      closeParams.optionType == IOptionMarket.OptionType.SHORT_CALL_QUOTE ||
      closeParams.optionType == IOptionMarket.OptionType.SHORT_PUT_QUOTE
    ) {
      // check minimum collateral amount after withdraw
      (uint256 strikePrice, uint256 expiry) = closeParams.optionMarket.getStrikeAndExpiry(position.strikeId);
      uint256 spotPrice = getSynthetixAdapter().getSpotPriceForMarket(address(closeParams.optionMarket));
      uint256 minCollateralAfterWithdraw = optionMarketAddresses.greekCache.getMinCollateral(
        closeParams.optionType,
        strikePrice,
        expiry,
        spotPrice,
        position.amount.sub(closeParams.amount)
      );

      // check if the position collateral is less than the minimum collateral amount
      // then it will close position fully and withdraw to the pool address directly
      if (closeParams.setCollateralTo < minCollateralAfterWithdraw) {
        closeParams.setCollateralTo = 0;
        closeParams.amount = position.amount;
        recipient = msg.sender;
      }
    }

    IOptionMarketWrapper optionMarketWrapper = getOptionMarketWrapper();

    optionMarketAddresses.optionToken.approve(address(optionMarketWrapper), closeParams.positionId);
    if (closeParams.optionType == IOptionMarket.OptionType.SHORT_CALL_BASE) {
      // to close SHORT_CALL_BASE options, it requires to provide option fees in quote asset.
      // 1. we flashloan quote asset from Aave
      // 2. close option position
      // 3. we get base asset once we close the option position.
      // 4. we swap base asset into quote asset to repay flahsloan amount + premium

      uint256 amountToFlashloan = getAmountOfQuoteToBorrow(closeParams);

      address[] memory borrowAssets = new address[](1);
      borrowAssets[0] = address(optionMarketAddresses.quoteAsset);
      uint256[] memory borrowAmounts = new uint256[](1);
      borrowAmounts[0] = amountToFlashloan;
      uint256[] memory modes = new uint256[](1);
      bytes memory flashloanParams = abi.encode(closeParams);
      aaveLendingPool.flashLoan(address(this), borrowAssets, borrowAmounts, modes, address(this), flashloanParams, 196);
    } else {
      // solhint-disable-next-line no-empty-blocks
      try optionMarketWrapper.closePosition(closeParams) {} catch {
        optionMarketWrapper.forceClosePosition(closeParams);
      }
    }

    // transfer withdrawn assets to recipient
    optionMarketAddresses.quoteAsset.transfer(recipient, optionMarketAddresses.quoteAsset.balanceOf(address(this)));
    optionMarketAddresses.baseAsset.transfer(recipient, optionMarketAddresses.baseAsset.balanceOf(address(this)));

    // transfer position nft back to msg.sender
    if (
      optionMarketAddresses.optionToken.getPositionState(closeParams.positionId) == IOptionToken.PositionState.ACTIVE
    ) {
      optionMarketAddresses.optionToken.transferFrom(address(this), msg.sender, closeParams.positionId);
    } else {
      address poolLogic = msg.sender;
      address factory = IPoolLogic(poolLogic).factory();
      address lyraOptionMarketWrapperContractGuard = IHasGuardInfo(factory).getContractGuard(
        address(optionMarketWrapper)
      );
      LyraOptionMarketWrapperContractGuard(lyraOptionMarketWrapperContractGuard).removeClosedPosition(
        poolLogic,
        address(closeParams.optionMarket),
        closeParams.positionId
      );
    }
  }

  /// @notice execute function of aave flash loan
  /// @dev This function is called after your contract has received the flash loaned amount
  /// @param assets the loaned assets
  /// @param amounts the loaned amounts per each asset
  /// @param premiums the additional owed amount per each asset
  /// @param originator the origin caller address of the flash loan
  /// @param params Variadic packed params to pass to the receiver as extra information
  function executeOperation(
    address[] memory assets,
    uint256[] memory amounts,
    uint256[] memory premiums,
    address originator,
    bytes memory params
  ) external returns (bool success) {
    require(msg.sender == address(aaveLendingPool) && originator == address(this), "invalid flashloan origin");
    require(assets.length == 1 && amounts.length == 1 && premiums.length == 1, "invalid length");

    IOptionMarketWrapper optionMarketWrapper = getOptionMarketWrapper();
    IOptionMarketWrapper.OptionPositionParams memory closeParams = abi.decode(
      params,
      (IOptionMarketWrapper.OptionPositionParams)
    );
    IOptionMarketWrapper.OptionMarketContracts memory optionMarketAddresses = optionMarketWrapper.marketContracts(
      closeParams.optionMarket
    );

    require(assets[0] == address(optionMarketAddresses.quoteAsset), "invalid asset");

    // close option position
    {
      optionMarketAddresses.quoteAsset.approve(address(optionMarketWrapper), amounts[0]);
      closeParams.inputAmount = amounts[0];
      // solhint-disable-next-line no-empty-blocks
      try optionMarketWrapper.closePosition(closeParams) {} catch {
        optionMarketWrapper.forceClosePosition(closeParams);
      }
    }

    // swap base assets to quote assets
    {
      uint256 baseAssetAmount = optionMarketAddresses.baseAsset.balanceOf(address(this));
      ISynthetixAdapter synthetixAdapter = getSynthetixAdapter();
      bytes32 synthQuoteKey = synthetixAdapter.quoteKey(address(closeParams.optionMarket));
      bytes32 synthBaseKey = synthetixAdapter.baseKey(address(closeParams.optionMarket));
      address synthetix = synthetixAdapter.synthetix();
      optionMarketAddresses.baseAsset.approve(synthetix, baseAssetAmount);
      ISynthetix(synthetix).exchange(synthBaseKey, baseAssetAmount, synthQuoteKey);
    }

    // payback amounts + premiums
    {
      optionMarketAddresses.quoteAsset.approve(address(aaveLendingPool), amounts[0].add(premiums[0]));
    }

    return true;
  }

  function getAmountOfQuoteToBorrow(IOptionMarketWrapper.OptionPositionParams memory closeParams)
    public
    view
    returns (uint256)
  {
    uint256 expectedCollateralReturned = closeParams.currentCollateral - closeParams.setCollateralTo;
    ISynthetixAdapter synthetixAdapter = getSynthetixAdapter();
    bytes32 synthQuoteKey = synthetixAdapter.quoteKey(address(closeParams.optionMarket));
    bytes32 synthBaseKey = synthetixAdapter.baseKey(address(closeParams.optionMarket));
    IExchanger exchanger = synthetixAdapter.exchanger();
    (uint256 amountReceived, , ) = exchanger.getAmountsForExchange(
      expectedCollateralReturned,
      synthBaseKey,
      synthQuoteKey
    );
    // we return 99% because we need a margin to cover flash fees
    return amountReceived.mul(99).div(100);
  }
}

File 7 of 42 : LyraOptionMarketWrapperContractGuard.sol
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.7.6;
pragma abicoder v2;

import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import "../../utils/TxDataUtils.sol";
import "../../utils/tracker/DhedgeNftTrackerStorage.sol";
import "../../interfaces/guards/ITxTrackingGuard.sol";
import "../../interfaces/IPoolLogic.sol";
import "../../interfaces/IPoolManagerLogic.sol";
import "../../interfaces/IHasSupportedAsset.sol";
import "../../interfaces/lyra/IOptionMarket.sol";
import "../../interfaces/lyra/IOptionMarketViewer.sol";
import "../../interfaces/lyra/IOptionMarketWrapper.sol";
import "../../interfaces/lyra/IShortCollateral.sol";
import "../../interfaces/lyra/ILyraRegistry.sol";
import "../../interfaces/synthetix/IAddressResolver.sol";

/// @title Transaction guard for Lyra OptionMarketWrapper
contract LyraOptionMarketWrapperContractGuard is TxDataUtils, ITxTrackingGuard {
  using SafeMathUpgradeable for uint256;

  bytes32 public constant NFT_TYPE = keccak256("LYRA_NFT_TYPE");
  address public immutable nftTracker;
  uint256 public immutable maxPositionCount;

  bytes32 public constant MARKET_VIEWER = "MARKET_VIEWER";
  bytes32 public constant MARKET_WRAPPER = "MARKET_WRAPPER";
  bytes32 public constant SYNTHETIX_ADAPTER = "SYNTHETIX_ADAPTER";

  struct OptionPosition {
    address optionMarket;
    uint256 positionId;
  }

  bool public override isTxTrackingGuard = true;
  ILyraRegistry public immutable lyraRegistry;

  constructor(
    ILyraRegistry _lyraRegistry,
    address _nftTracker,
    uint256 _maxPositionCount
  ) {
    lyraRegistry = _lyraRegistry;
    nftTracker = _nftTracker;
    maxPositionCount = _maxPositionCount;
  }

  function marketViewer() public view returns (IOptionMarketViewer) {
    return IOptionMarketViewer(lyraRegistry.getGlobalAddress(MARKET_VIEWER));
  }

  function marketWrapper() public view returns (address) {
    return lyraRegistry.getGlobalAddress(MARKET_WRAPPER);
  }

  function getOptionPositions(address poolLogic) public view returns (OptionPosition[] memory optionPositions) {
    bytes[] memory data = DhedgeNftTrackerStorage(nftTracker).getAllData(NFT_TYPE, poolLogic);
    optionPositions = new OptionPosition[](data.length);
    for (uint256 i = 0; i < data.length; i++) {
      optionPositions[i] = abi.decode(data[i], (OptionPosition));
    }
  }

  /// @notice Transaction guard for OptionMarketWrapper - used for Toros
  /// @dev It supports close/open/forceClose position
  /// @param _poolManagerLogic the pool manager logic
  /// @param data the transaction data
  /// @return txType the transaction type of a given transaction data.
  /// @return isPublic if the transaction is public or private
  function txGuard(
    address _poolManagerLogic,
    address to,
    bytes calldata data
  )
    public
    virtual
    override
    returns (
      uint16 txType,
      bool // isPublic
    )
  {
    IHasSupportedAsset poolManagerLogicAssets = IHasSupportedAsset(_poolManagerLogic);
    require(poolManagerLogicAssets.isSupportedAsset(to), "lyra not enabled");

    settleExpiredAndFilterActivePositions(IPoolManagerLogic(_poolManagerLogic).poolLogic());

    bytes4 method = getMethod(data);
    if (method == IOptionMarketWrapper.openPosition.selector) {
      IOptionMarketWrapper.OptionPositionParams memory params = abi.decode(
        getParams(data),
        (IOptionMarketWrapper.OptionPositionParams)
      );

      _checkSupportedAsset(poolManagerLogicAssets, params.optionType, address(params.optionMarket));
      txType = 26;

      settleExpiredAndFilterActivePositions(IPoolManagerLogic(_poolManagerLogic).poolLogic());
    } else if (method == IOptionMarketWrapper.closePosition.selector) {
      IOptionMarketWrapper.OptionPositionParams memory params = abi.decode(
        getParams(data),
        (IOptionMarketWrapper.OptionPositionParams)
      );

      _checkSupportedAsset(poolManagerLogicAssets, params.optionType, address(params.optionMarket));
      txType = 27;

      settleExpiredAndFilterActivePositions(IPoolManagerLogic(_poolManagerLogic).poolLogic());
    } else if (method == IOptionMarketWrapper.forceClosePosition.selector) {
      IOptionMarketWrapper.OptionPositionParams memory params = abi.decode(
        getParams(data),
        (IOptionMarketWrapper.OptionPositionParams)
      );

      _checkSupportedAsset(poolManagerLogicAssets, params.optionType, address(params.optionMarket));
      txType = 28;

      settleExpiredAndFilterActivePositions(IPoolManagerLogic(_poolManagerLogic).poolLogic());
    }

    return (txType, false);
  }

  function _checkSupportedAsset(
    IHasSupportedAsset poolManagerLogic,
    IOptionMarket.OptionType optionType,
    address optionMarket
  ) internal view {
    IOptionMarketViewer.OptionMarketAddresses memory optionMarketAddresses = marketViewer().marketAddresses(
      optionMarket
    );

    // if short-call-base option type, check base asset
    if (optionType == IOptionMarket.OptionType.SHORT_CALL_BASE) {
      require(poolManagerLogic.isSupportedAsset(address(optionMarketAddresses.baseAsset)), "unsupported base asset");
    } else {
      // otherwise, check quote asset
      require(poolManagerLogic.isSupportedAsset(address(optionMarketAddresses.quoteAsset)), "unsupported quote asset");
    }
  }

  /// @notice This function is called after execution transaction (used to track transactions)
  /// @dev It supports close/open/forceClose position
  /// @param _poolManagerLogic the pool manager logic
  /// @param data the transaction data
  function afterTxGuard(
    address _poolManagerLogic,
    address, // to
    bytes calldata data
  ) public virtual override {
    address poolLogic = IPoolManagerLogic(_poolManagerLogic).poolLogic();
    require(msg.sender == poolLogic, "not pool logic");

    IOptionMarketWrapper.OptionPositionParams memory params = abi.decode(
      getParams(data),
      (IOptionMarketWrapper.OptionPositionParams)
    );
    afterTxGuardHandle(poolLogic, address(params.optionMarket), params.positionId);
  }

  function afterTxGuardHandle(
    address poolLogic,
    address optionMarket,
    uint256 positionId
  ) internal {
    IOptionMarketViewer.OptionMarketAddresses memory optionMarketAddresses = marketViewer().marketAddresses(
      optionMarket
    );
    // If the manager is not specifying a positionId it means he must be creating a new position
    // We use the optionMakets "nextId" to determine the last Id created and store that for the pool
    // "nextId" starts from 1 so the positionId starts from 1.
    if (positionId == 0) {
      // New position created, We use the nextId sub 1 as this code runs after the creation of the option.
      DhedgeNftTrackerStorage(nftTracker).addData(
        marketWrapper(),
        NFT_TYPE,
        poolLogic,
        abi.encode(
          OptionPosition({
            optionMarket: optionMarket,
            positionId: IOptionToken(optionMarketAddresses.optionToken).nextId().sub(1)
          })
        )
      );

      require(
        DhedgeNftTrackerStorage(nftTracker).getDataCount(NFT_TYPE, poolLogic) <= maxPositionCount,
        "exceed maximum position count"
      );

      // If the manager is specifying a positionId it must mean he is trying to make changes to an existing one
      // We detect if it is closed and remove it from storage
    } else {
      IOptionToken.PositionState positionState = IOptionToken(optionMarketAddresses.optionToken).getPositionState(
        positionId
      );

      // find option position from nft tracker
      OptionPosition[] memory optionPositions = getOptionPositions(poolLogic);
      uint256 i;
      for (i = 0; i < optionPositions.length; i++) {
        if (optionPositions[i].optionMarket == optionMarket && optionPositions[i].positionId == positionId) {
          break;
        }
      }

      require(i < optionPositions.length, "position is not in track");

      if (positionState != IOptionToken.PositionState.ACTIVE) {
        // If the position is not active remove it from nft tracker
        DhedgeNftTrackerStorage(nftTracker).removeData(marketWrapper(), NFT_TYPE, poolLogic, i);
      }
    }
  }

  function removeClosedPosition(
    address poolLogic,
    address optionMarket,
    uint256 positionId
  ) external {
    OptionPosition[] memory optionPositions = getOptionPositions(poolLogic);
    // We need to find which array index is the position we want to delete
    for (uint256 i = 0; i < optionPositions.length; i++) {
      if (optionPositions[i].optionMarket == optionMarket && optionPositions[i].positionId == positionId) {
        IOptionMarketViewer.OptionMarketAddresses memory optionMarketAddresses = marketViewer().marketAddresses(
          optionMarket
        );

        // Once we find it we check to make sure the postion is not active
        require(
          IOptionToken(optionMarketAddresses.optionToken).getPositionState(positionId) !=
            IOptionToken.PositionState.ACTIVE,
          "not closed position"
        );

        DhedgeNftTrackerStorage(nftTracker).removeData(marketWrapper(), NFT_TYPE, poolLogic, i);
        break;
      }
    }
  }

  function settleExpiredAndFilterActivePositions(address poolLogic) public {
    IHasSupportedAsset poolManagerLogicAssets = IHasSupportedAsset(IPoolLogic(poolLogic).poolManagerLogic());

    OptionPosition[] memory optionPositions = getOptionPositions(poolLogic);

    // 1. we filter active option positions
    // 2. we settle expired option positions
    // 3. we removed expired/inactive option positions from nft tracker
    for (uint256 i = optionPositions.length; i > 0; i--) {
      uint256 index = i - 1;
      IOptionMarketViewer.OptionMarketAddresses memory optionMarketAddresses = marketViewer().marketAddresses(
        optionPositions[index].optionMarket
      );
      IOptionToken.OptionPosition memory position = IOptionToken(optionMarketAddresses.optionToken).positions(
        optionPositions[index].positionId
      );
      if (position.state == IOptionToken.PositionState.ACTIVE) {
        (, uint256 priceAtExpiry, ) = IOptionMarket(optionPositions[index].optionMarket).getSettlementParameters(
          position.strikeId
        );

        if (priceAtExpiry == 0) {
          continue;
        }

        // settlement will return base or quote asset back to the pool
        // we check if quote/base asset is supported for option position type
        _checkSupportedAsset(poolManagerLogicAssets, position.optionType, optionPositions[index].optionMarket);

        uint256[] memory positionsToSettle = new uint256[](1);
        positionsToSettle[0] = optionPositions[index].positionId;
        IShortCollateral(optionMarketAddresses.shortCollateral).settleOptions(positionsToSettle);
      }

      DhedgeNftTrackerStorage(nftTracker).removeData(marketWrapper(), NFT_TYPE, poolLogic, index);
    }
  }
}

File 8 of 42 : IOptionGreekCache.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;

import "./IOptionMarket.sol";

interface IOptionGreekCache {
  function isGlobalCacheStale(uint256 spotPrice) external view returns (bool);

  function isBoardCacheStale(uint256 boardId) external view returns (bool);

  function updateBoardCachedGreeks(uint256 boardId) external;

  function getMinCollateral(
    IOptionMarket.OptionType optionType,
    uint256 strikePrice,
    uint256 expiry,
    uint256 spotPrice,
    uint256 amount
  ) external view returns (uint256 minCollateral);
}

File 9 of 42 : ISynthetixAdapter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IOptionMarket.sol";
import "../synthetix/IExchanger.sol";

interface ISynthetixAdapter {
  function synthetix() external view returns (address);

  function exchanger() external view returns (IExchanger);

  function addressResolver() external view returns (address);

  function quoteKey(address) external view returns (bytes32);

  function baseKey(address) external view returns (bytes32);

  function getSpotPriceForMarket(address) external view returns (uint256);
}

File 10 of 42 : IOptionMarket.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

interface IOptionMarket {
  enum TradeDirection {
    OPEN,
    CLOSE,
    LIQUIDATE
  }

  enum OptionType {
    LONG_CALL,
    LONG_PUT,
    SHORT_CALL_BASE,
    SHORT_CALL_QUOTE,
    SHORT_PUT_QUOTE
  }

  struct Strike {
    // strike listing identifier
    uint256 id;
    // strike price
    uint256 strikePrice;
    // volatility component specific to the strike listing (boardIv * skew = vol of strike)
    uint256 skew;
    // total user long call exposure
    uint256 longCall;
    // total user short call (base collateral) exposure
    uint256 shortCallBase;
    // total user short call (quote collateral) exposure
    uint256 shortCallQuote;
    // total user long put exposure
    uint256 longPut;
    // total user short put (quote collateral) exposure
    uint256 shortPut;
    // id of board to which strike belongs
    uint256 boardId;
  }

  function getStrike(uint256 strikeId) external view returns (Strike memory);

  function getStrikeAndExpiry(uint256 strikeId) external view returns (uint256 strikePrice, uint256 expiry);

  function getSettlementParameters(uint256 strikeId)
    external
    view
    returns (
      uint256 strikePrice,
      uint256 priceAtExpiry,
      uint256 strikeToBaseReturned
    );
}

File 11 of 42 : ILiquidityPool.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;

interface ILiquidityPool {
  // solhint-disable-next-line func-name-mixedcase
  function CBTimestamp() external view returns (uint256);
}

File 12 of 42 : IOptionMarketViewer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IOptionToken.sol";
import "./IOptionMarket.sol";
import "./IOptionGreekCache.sol";

interface IOptionMarketViewer {
  struct MarketOptionPositions {
    address market;
    IOptionToken.OptionPosition[] positions;
  }

  struct OptionMarketAddresses {
    address liquidityPool;
    address liquidityTokens;
    IOptionGreekCache greekCache;
    IOptionMarket optionMarket;
    address optionMarketPricer;
    IOptionToken optionToken;
    address shortCollateral;
    address poolHedger;
    IERC20 quoteAsset;
    IERC20 baseAsset;
  }

  function synthetixAdapter() external view returns (address);

  function getOwnerPositions(address owner) external view returns (IOptionToken.OptionPosition[] memory);

  function getMarketAddresses() external view returns (OptionMarketAddresses[] memory);

  function marketAddresses(address market) external view returns (OptionMarketAddresses memory);
}

File 13 of 42 : SafeMath.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.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, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        uint256 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b > a) return (false, 0);
        return (true, a - b);
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
        uint256 c = a * b;
        if (c / a != b) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a / b);
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a % b);
    }

    /**
     * @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) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @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) {
        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, reverting 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) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting 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) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * 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);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * 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);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * 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 14 of 42 : IERC721.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

File 15 of 42 : TxDataUtils.sol
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@uniswap/v3-periphery/contracts/libraries/BytesLib.sol";

contract TxDataUtils {
  using BytesLib for bytes;
  using SafeMathUpgradeable for uint256;

  function getMethod(bytes memory data) public pure returns (bytes4) {
    return read4left(data, 0);
  }

  function getParams(bytes memory data) public pure returns (bytes memory) {
    return data.slice(4, data.length - 4);
  }

  function getInput(bytes memory data, uint8 inputNum) public pure returns (bytes32) {
    return read32(data, 32 * inputNum + 4, 32);
  }

  function getBytes(
    bytes memory data,
    uint8 inputNum,
    uint256 offset
  ) public pure returns (bytes memory) {
    require(offset < 20, "invalid offset"); // offset is in byte32 slots, not bytes
    offset = offset * 32; // convert offset to bytes
    uint256 bytesLenPos = uint256(read32(data, 32 * inputNum + 4 + offset, 32));
    uint256 bytesLen = uint256(read32(data, bytesLenPos + 4 + offset, 32));
    return data.slice(bytesLenPos + 4 + offset + 32, bytesLen);
  }

  function getArrayLast(bytes memory data, uint8 inputNum) public pure returns (bytes32) {
    bytes32 arrayPos = read32(data, 32 * inputNum + 4, 32);
    bytes32 arrayLen = read32(data, uint256(arrayPos) + 4, 32);
    require(arrayLen > 0, "input is not array");
    return read32(data, uint256(arrayPos) + 4 + (uint256(arrayLen) * 32), 32);
  }

  function getArrayLength(bytes memory data, uint8 inputNum) public pure returns (uint256) {
    bytes32 arrayPos = read32(data, 32 * inputNum + 4, 32);
    return uint256(read32(data, uint256(arrayPos) + 4, 32));
  }

  function getArrayIndex(
    bytes memory data,
    uint8 inputNum,
    uint8 arrayIndex
  ) public pure returns (bytes32) {
    bytes32 arrayPos = read32(data, 32 * inputNum + 4, 32);
    bytes32 arrayLen = read32(data, uint256(arrayPos) + 4, 32);
    require(arrayLen > 0, "input is not array");
    require(uint256(arrayLen) > arrayIndex, "invalid array position");
    return read32(data, uint256(arrayPos) + 4 + ((1 + uint256(arrayIndex)) * 32), 32);
  }

  function read4left(bytes memory data, uint256 offset) public pure returns (bytes4 o) {
    require(data.length >= offset + 4, "Reading bytes out of bounds");
    assembly {
      o := mload(add(data, add(32, offset)))
    }
  }

  function read32(
    bytes memory data,
    uint256 offset,
    uint256 length
  ) public pure returns (bytes32 o) {
    require(data.length >= offset + length, "Reading bytes out of bounds");
    assembly {
      o := mload(add(data, add(32, offset)))
      let lb := sub(32, length)
      if lb {
        o := div(o, exp(2, mul(lb, 8)))
      }
    }
  }

  function convert32toAddress(bytes32 data) public pure returns (address o) {
    return address(uint160(uint256(data)));
  }

  function sliceUint(bytes memory data, uint256 start) internal pure returns (uint256) {
    require(data.length >= start + 32, "slicing out of range");
    uint256 x;
    assembly {
      x := mload(add(data, add(0x20, start)))
    }
    return x;
  }
}

File 16 of 42 : IHasSupportedAsset.sol
//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

pragma experimental ABIEncoderV2;

interface IHasSupportedAsset {
  struct Asset {
    address asset;
    bool isDeposit;
  }

  function getSupportedAssets() external view returns (Asset[] memory);

  function isSupportedAsset(address asset) external view returns (bool);
}

File 17 of 42 : IHasGuardInfo.sol
//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

interface IHasGuardInfo {
  // Get guard
  function getContractGuard(address extContract) external view returns (address);

  // Get asset guard
  function getAssetGuard(address extContract) external view returns (address);

  // Get mapped addresses from Governance
  function getAddress(bytes32 name) external view returns (address);
}

File 18 of 42 : IPoolManagerLogic.sol
//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

interface IPoolManagerLogic {
  function poolLogic() external view returns (address);

  function isDepositAsset(address asset) external view returns (bool);

  function validateAsset(address asset) external view returns (bool);

  function assetValue(address asset) external view returns (uint256);

  function assetValue(address asset, uint256 amount) external view returns (uint256);

  function assetBalance(address asset) external view returns (uint256 balance);

  function factory() external view returns (address);

  function setPoolLogic(address fundAddress) external returns (bool);

  function totalFundValue() external view returns (uint256);

  function isMemberAllowed(address member) external view returns (bool);

  function getFee()
    external
    view
    returns (
      uint256,
      uint256,
      uint256
    );

  function minDepositUSD() external view returns (uint256);
}

File 19 of 42 : IManaged.sol
//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

interface IManaged {
  function manager() external view returns (address);

  function trader() external view returns (address);

  function managerName() external view returns (string memory);
}

File 20 of 42 : IAssetGuard.sol
//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "../IHasSupportedAsset.sol";

interface IAssetGuard {
  struct MultiTransaction {
    address to;
    bytes txData;
  }

  function withdrawProcessing(
    address pool,
    address asset,
    uint256 withdrawPortion,
    address to
  )
    external
    returns (
      address,
      uint256,
      MultiTransaction[] memory transactions
    );

  function getBalance(address pool, address asset) external view returns (uint256 balance);

  function getDecimals(address asset) external view returns (uint256 decimals);

  function removeAssetCheck(address poolLogic, address asset) external view;
}

File 21 of 42 : IGuard.sol
//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

interface IGuard {
  event ExchangeFrom(address fundAddress, address sourceAsset, uint256 sourceAmount, address dstAsset, uint256 time);
  event ExchangeTo(address fundAddress, address sourceAsset, address dstAsset, uint256 dstAmount, uint256 time);

  function txGuard(
    address poolManagerLogic,
    address to,
    bytes calldata data
  ) external returns (uint16 txType, bool isPublic);
}

File 22 of 42 : SafeMathUpgradeable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.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 SafeMathUpgradeable {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        uint256 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b > a) return (false, 0);
        return (true, a - b);
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
        uint256 c = a * b;
        if (c / a != b) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a / b);
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a % b);
    }

    /**
     * @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) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @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) {
        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, reverting 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) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting 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) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * 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);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * 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);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * 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 23 of 42 : IERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.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 24 of 42 : BytesLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <[email protected]>
 *
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity >=0.5.0 <0.8.0;

library BytesLib {
    function slice(
        bytes memory _bytes,
        uint256 _start,
        uint256 _length
    ) internal pure returns (bytes memory) {
        require(_length + 31 >= _length, 'slice_overflow');
        require(_start + _length >= _start, 'slice_overflow');
        require(_bytes.length >= _start + _length, 'slice_outOfBounds');

        bytes memory tempBytes;

        assembly {
            switch iszero(_length)
                case 0 {
                    // Get a location of some free memory and store it in tempBytes as
                    // Solidity does for memory variables.
                    tempBytes := mload(0x40)

                    // The first word of the slice result is potentially a partial
                    // word read from the original array. To read it, we calculate
                    // the length of that partial word and start copying that many
                    // bytes into the array. The first word we copy will start with
                    // data we don't care about, but the last `lengthmod` bytes will
                    // land at the beginning of the contents of the new array. When
                    // we're done copying, we overwrite the full first word with
                    // the actual length of the slice.
                    let lengthmod := and(_length, 31)

                    // The multiplication in the next line is necessary
                    // because when slicing multiples of 32 bytes (lengthmod == 0)
                    // the following copy loop was copying the origin's length
                    // and then ending prematurely not copying everything it should.
                    let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                    let end := add(mc, _length)

                    for {
                        // The multiplication in the next line has the same exact purpose
                        // as the one above.
                        let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                    } lt(mc, end) {
                        mc := add(mc, 0x20)
                        cc := add(cc, 0x20)
                    } {
                        mstore(mc, mload(cc))
                    }

                    mstore(tempBytes, _length)

                    //update free-memory pointer
                    //allocating the array padded to 32 bytes like the compiler does now
                    mstore(0x40, and(add(mc, 31), not(31)))
                }
                //if we want a zero-length slice let's just return a zero-length array
                default {
                    tempBytes := mload(0x40)
                    //zero out the 32 bytes slice we are about to return
                    //we need to do it because Solidity does not garbage collect
                    mstore(tempBytes, 0)

                    mstore(0x40, add(tempBytes, 0x20))
                }
        }

        return tempBytes;
    }

    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
        require(_start + 20 >= _start, 'toAddress_overflow');
        require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
        address tempAddress;

        assembly {
            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
        }

        return tempAddress;
    }

    function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
        require(_start + 3 >= _start, 'toUint24_overflow');
        require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
        uint24 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x3), _start))
        }

        return tempUint;
    }
}

File 25 of 42 : IOptionToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;

import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol";

import "./IOptionMarket.sol";

interface IOptionToken is IERC721Enumerable {
  enum PositionState {
    EMPTY,
    ACTIVE,
    CLOSED,
    LIQUIDATED,
    SETTLED,
    MERGED
  }

  enum PositionUpdatedType {
    OPENED,
    ADJUSTED,
    CLOSED,
    SPLIT_FROM,
    SPLIT_INTO,
    MERGED,
    MERGED_INTO,
    SETTLED,
    LIQUIDATED,
    TRANSFER
  }

  struct OptionPosition {
    uint256 positionId;
    uint256 strikeId;
    IOptionMarket.OptionType optionType;
    uint256 amount;
    uint256 collateral;
    PositionState state;
  }

  struct PositionWithOwner {
    uint256 positionId;
    uint256 strikeId;
    IOptionMarket.OptionType optionType;
    uint256 amount;
    uint256 collateral;
    PositionState state;
    address owner;
  }

  function nextId() external view returns (uint256);

  function getOwnerPositions(address target) external view returns (OptionPosition[] memory);

  function positions(uint256 positionId) external view returns (OptionPosition memory);

  function getPositionState(uint256 positionId) external view returns (PositionState);

  function getPositionWithOwner(uint256 positionId) external view returns (PositionWithOwner memory);
}

File 26 of 42 : IOptionMarketWrapper.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IOptionMarket.sol";
import "./IOptionToken.sol";

interface IOptionMarketWrapper {
  struct OptionMarketContracts {
    IERC20 quoteAsset;
    IERC20 baseAsset;
    IOptionToken optionToken;
  }

  struct OptionPositionParams {
    IOptionMarket optionMarket;
    uint256 strikeId; // The id of the relevant OptionListing
    uint256 positionId;
    uint256 iterations;
    uint256 setCollateralTo;
    uint256 currentCollateral;
    IOptionMarket.OptionType optionType; // Is the trade a long/short & call/put?
    uint256 amount; // The amount the user has requested to close
    uint256 minCost; // Min amount for the cost of the trade
    uint256 maxCost; // Max amount for the cost of the trade
    uint256 inputAmount; // Amount of stable coins the user can use
    IERC20 inputAsset; // Address of coin user wants to open with
  }

  struct ReturnDetails {
    address market;
    uint256 positionId;
    address owner;
    uint256 amount;
    uint256 totalCost;
    uint256 totalFee;
    int256 swapFee;
    address token;
  }

  function openPosition(OptionPositionParams memory params) external returns (ReturnDetails memory returnDetails);

  function closePosition(OptionPositionParams memory params) external returns (ReturnDetails memory returnDetails);

  function forceClosePosition(OptionPositionParams memory params) external returns (ReturnDetails memory returnDetails);

  function marketContracts(IOptionMarket market) external view returns (OptionMarketContracts memory);

  function idToMarket(uint8 id) external view returns (address optionMarket);

  function idToERC(uint8 id) external view returns (address token);

  function openLong(uint256 params) external returns (uint256 totalCost);

  function addLong(uint256 params) external returns (uint256 totalCost);

  function reduceLong(uint256 params) external returns (uint256 totalReceived);

  function closeLong(uint256 params) external returns (uint256 totalReceived);

  function openShort(uint256 params) external returns (uint256 totalReceived);

  function addShort(uint256 params) external returns (uint256 totalReceived);

  function reduceShort(uint256 params) external returns (uint256 totalCost);

  function closeShort(uint256 params) external returns (uint256 totalCost);
}

File 27 of 42 : ILyraRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IOptionToken.sol";
import "./IOptionMarket.sol";
import "./IOptionGreekCache.sol";

interface ILyraRegistry {
  struct OptionMarketAddresses {
    address liquidityPool;
    address liquidityToken;
    IOptionGreekCache greekCache;
    IOptionMarket optionMarket;
    address optionMarketPricer;
    IOptionToken optionToken;
    address poolHedger;
    address shortCollateral;
    address gwavOracle;
    IERC20 quoteAsset;
    IERC20 baseAsset;
  }

  function getMarketAddresses(address market) external view returns (OptionMarketAddresses memory);

  function getGlobalAddress(bytes32 contractName) external view returns (address globalContract);

  function optionMarkets(uint256 index) external view returns (address);
}

File 28 of 42 : IGWAVOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;

interface IGWAVOracle {
  function deltaGWAV(uint256 strikeId, uint256 secondsAgo) external view returns (int256 callDelta);

  function optionPriceGWAV(uint256 strikeId, uint256 secondsAgo)
    external
    view
    returns (uint256 callPrice, uint256 putPrice);
}

File 29 of 42 : IExchanger.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;

interface IExchanger {
  function settle(address from, bytes32 currencyKey)
    external
    returns (
      uint256 reclaimed,
      uint256 refunded,
      uint256 numEntries
    );

  function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint256);

  function getAmountsForExchange(
    uint256 sourceAmount,
    bytes32 sourceCurrencyKey,
    bytes32 destinationCurrencyKey
  )
    external
    view
    returns (
      uint256 amountReceived,
      uint256 fee,
      uint256 exchangeFeeRate
    );
}

File 30 of 42 : ISynthetix.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;

interface ISynthetix {
  function exchange(
    bytes32 sourceCurrencyKey,
    uint256 sourceAmount,
    bytes32 destinationCurrencyKey
  ) external returns (uint256 amountReceived);

  function exchangeWithTracking(
    bytes32 sourceCurrencyKey,
    uint256 sourceAmount,
    bytes32 destinationCurrencyKey,
    address originator,
    bytes32 trackingCode
  ) external returns (uint256 amountReceived);

  function synths(bytes32 key) external view returns (address synthTokenAddress);

  function synthsByAddress(address asset) external view returns (bytes32 key);

  function settle(bytes32 currencyKey)
    external
    returns (
      uint256 reclaimed,
      uint256 refunded,
      uint256 numEntriesSettled
    );
}

File 31 of 42 : ILendingPool.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

interface ILendingPool {
  struct UserConfigurationMap {
    uint256 data;
  }

  struct ReserveConfigurationMap {
    //bit 0-15: LTV
    //bit 16-31: Liq. threshold
    //bit 32-47: Liq. bonus
    //bit 48-55: Decimals
    //bit 56: Reserve is active
    //bit 57: reserve is frozen
    //bit 58: borrowing is enabled
    //bit 59: stable rate borrowing enabled
    //bit 60-63: reserved
    //bit 64-79: reserve factor
    uint256 data;
  }

  struct ReserveData {
    //stores the reserve configuration
    ReserveConfigurationMap configuration;
    //the liquidity index. Expressed in ray
    uint128 liquidityIndex;
    //variable borrow index. Expressed in ray
    uint128 variableBorrowIndex;
    //the current supply rate. Expressed in ray
    uint128 currentLiquidityRate;
    //the current variable borrow rate. Expressed in ray
    uint128 currentVariableBorrowRate;
    //the current stable borrow rate. Expressed in ray
    uint128 currentStableBorrowRate;
    uint40 lastUpdateTimestamp;
    //tokens addresses
    address aTokenAddress;
    address stableDebtTokenAddress;
    address variableDebtTokenAddress;
    //address of the interest rate strategy
    address interestRateStrategyAddress;
    //the id of the reserve. Represents the position in the list of the active reserves
    uint8 id;
  }

  function deposit(
    address asset,
    uint256 amount,
    address onBehalfOf,
    uint16 referralCode
  ) external;

  function withdraw(
    address asset,
    uint256 amount,
    address to
  ) external returns (uint256);

  function borrow(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    uint16 referralCode,
    address onBehalfOf
  ) external;

  function repay(
    address asset,
    uint256 amount,
    uint256 rateMode,
    address onBehalfOf
  ) external returns (uint256);

  function flashLoan(
    address receiverAddress,
    address[] memory assets,
    uint256[] memory amounts,
    uint256[] memory modes,
    address onBehalfOf,
    bytes memory params,
    uint16 referralCode
  ) external;

  function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;

  function rebalanceStableBorrowRate(address asset, address user) external;

  function swapBorrowRateMode(address asset, uint256 rateMode) external;

  function getUserConfiguration(address user) external view returns (UserConfigurationMap memory);

  function getConfiguration(address asset) external view returns (ReserveConfigurationMap memory);

  function getUserAccountData(address user)
    external
    view
    returns (
      uint256 totalCollateralETH,
      uint256 totalDebtETH,
      uint256 availableBorrowsETH,
      uint256 currentLiquidationThreshold,
      uint256 ltv,
      uint256 healthFactor
    );

  function getReserveData(address asset) external view returns (ReserveData memory);
}

File 32 of 42 : Math.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow, so we distribute
        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
    }
}

File 33 of 42 : IERC721Enumerable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {

    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

File 34 of 42 : IERC165.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

File 35 of 42 : DhedgeNftTrackerStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

import "../../interfaces/IHasGuardInfo.sol";

contract DhedgeNftTrackerStorage is OwnableUpgradeable {
  address public poolFactory; // dhedge pool factory
  mapping(bytes32 => mapping(address => bytes[])) internal _nftTrackData; // keccak of NFT_TYPE -> poolAddress -> data[]

  // solhint-disable-next-line no-empty-blocks
  function initialize(address _poolFactory) external initializer {
    __Ownable_init();
    poolFactory = _poolFactory;
  }

  /// @notice implementations should not be left unintialized
  // solhint-disable-next-line no-empty-blocks
  function implInitializer() external initializer {}

  modifier checkContractGuard(address _guardedContract) {
    require(IHasGuardInfo(poolFactory).getContractGuard(_guardedContract) == msg.sender, "not correct contract guard");

    _;
  }

  /**
   * @notice record new NFT data
   * @dev only called by authorized guard
   * @param _nftType keccak of NFT_TYPE
   * @param _pool the poolLogic address
   * @param _data the nft track data to be recorded in storage
   */
  function addData(
    address _guardedContract,
    bytes32 _nftType,
    address _pool,
    bytes memory _data
  ) external checkContractGuard(_guardedContract) {
    _nftTrackData[_nftType][_pool].push(_data);
  }

  /**
   * @notice delete NFT data
   * @dev only called by authorized guard
   * @param _nftType keccak of NFT_TYPE
   * @param _pool the poolLogic address
   * @param _index the nft track data index to be removed from storage
   */
  function removeData(
    address _guardedContract,
    bytes32 _nftType,
    address _pool,
    uint256 _index
  ) external checkContractGuard(_guardedContract) {
    uint256 length = _nftTrackData[_nftType][_pool].length;
    require(_index < length, "invalid index");

    _nftTrackData[_nftType][_pool][_index] = _nftTrackData[_nftType][_pool][length - 1];
    _nftTrackData[_nftType][_pool].pop();
  }

  /**
   * @notice returns tracked nft by index
   * @param _nftType keccak of NFT_TYPE
   * @param _pool the poolLogic address
   * @param _index the index of nft track data
   * @return data the nft track data of given NFT_TYPE & poolLogic & index
   */
  function getData(
    bytes32 _nftType,
    address _pool,
    uint256 _index
  ) external view returns (bytes memory) {
    return _nftTrackData[_nftType][_pool][_index];
  }

  /**
   * @notice returns all tracked nfts by NFT_TYPE & poolLogic
   * @param _nftType keccak of NFT_TYPE
   * @param _pool the poolLogic address
   * @return data all tracked nfts of given NFT_TYPE & poolLogic
   */
  function getAllData(bytes32 _nftType, address _pool) external view returns (bytes[] memory) {
    return _nftTrackData[_nftType][_pool];
  }

  /**
   * @notice returns all tracked nfts by NFT_TYPE & poolLogic
   * @param _nftType keccak of NFT_TYPE
   * @param _pool the poolLogic address
   * @return count all tracked nfts count of given NFT_TYPE & poolLogic
   */
  function getDataCount(bytes32 _nftType, address _pool) external view returns (uint256) {
    return _nftTrackData[_nftType][_pool].length;
  }
}

File 36 of 42 : IAddressResolver.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;

interface IAddressResolver {
  function getSynth(bytes32 key) external view returns (address);

  function getAddress(bytes32 name) external view returns (address);
}

File 37 of 42 : IShortCollateral.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;

interface IShortCollateral {
  function settleOptions(uint256[] memory positionIds) external;
}

File 38 of 42 : ITxTrackingGuard.sol
//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2021 dHEDGE DAO
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

import "./IGuard.sol";

interface ITxTrackingGuard is IGuard {
  function isTxTrackingGuard() external view returns (bool);

  function afterTxGuard(
    address poolManagerLogic,
    address to,
    bytes calldata data
  ) external;
}

File 39 of 42 : OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal initializer {
        __Context_init_unchained();
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal initializer {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
    uint256[49] private __gap;
}

File 40 of 42 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with 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 ContextUpgradeable is Initializable {
    function __Context_init() internal initializer {
        __Context_init_unchained();
    }

    function __Context_init_unchained() internal initializer {
    }
    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;
    }
    uint256[50] private __gap;
}

File 41 of 42 : Initializable.sol
// SPDX-License-Identifier: MIT

// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;

import "../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 */
abstract contract Initializable {

    /**
     * @dev Indicates that the contract has been initialized.
     */
    bool private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Modifier to protect an initializer function from being invoked twice.
     */
    modifier initializer() {
        require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");

        bool isTopLevelCall = !_initializing;
        if (isTopLevelCall) {
            _initializing = true;
            _initialized = true;
        }

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }

    /// @dev Returns true if and only if the function is running in the constructor
    function _isConstructor() private view returns (bool) {
        return !AddressUpgradeable.isContract(address(this));
    }
}

File 42 of 42 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @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 on 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");
        require(isContract(target), "Address: call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        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);
            }
        }
    }
}

Settings
{
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "optimizer": {
    "enabled": true,
    "runs": 20
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract DhedgeOptionMarketWrapperForLyra","name":"_dhedgeLyraWrapper","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"fundAddress","type":"address"},{"indexed":false,"internalType":"address","name":"manager","type":"address"},{"indexed":false,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"time","type":"uint256"}],"name":"Approve","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"fundAddress","type":"address"},{"indexed":false,"internalType":"address","name":"sourceAsset","type":"address"},{"indexed":false,"internalType":"uint256","name":"sourceAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"dstAsset","type":"address"},{"indexed":false,"internalType":"uint256","name":"time","type":"uint256"}],"name":"ExchangeFrom","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"fundAddress","type":"address"},{"indexed":false,"internalType":"address","name":"sourceAsset","type":"address"},{"indexed":false,"internalType":"address","name":"dstAsset","type":"address"},{"indexed":false,"internalType":"uint256","name":"dstAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"time","type":"uint256"}],"name":"ExchangeTo","type":"event"},{"inputs":[],"name":"CHECK_GWAV_DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GWAV_DIVERGENCE_CB_AMOUNT_DENOMINATOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GWAV_DIVERGENCE_CB_AMOUNT_NUMERATOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRICE_GWAV_DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"price1","type":"uint256"},{"internalType":"uint256","name":"price2","type":"uint256"}],"name":"assertNoGWAVDivergence","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes32","name":"data","type":"bytes32"}],"name":"convert32toAddress","outputs":[{"internalType":"address","name":"o","type":"address"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"dhedgeLyraWrapper","outputs":[{"internalType":"contract DhedgeOptionMarketWrapperForLyra","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint8","name":"inputNum","type":"uint8"},{"internalType":"uint8","name":"arrayIndex","type":"uint8"}],"name":"getArrayIndex","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint8","name":"inputNum","type":"uint8"}],"name":"getArrayLast","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint8","name":"inputNum","type":"uint8"}],"name":"getArrayLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"address","name":"asset","type":"address"}],"name":"getBalance","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint8","name":"inputNum","type":"uint8"},{"internalType":"uint256","name":"offset","type":"uint256"}],"name":"getBytes","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"getDecimals","outputs":[{"internalType":"uint256","name":"decimals","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"optionMarket","type":"address"},{"internalType":"uint256","name":"strikeId","type":"uint256"}],"name":"getGWAVCallPrice","outputs":[{"internalType":"uint256","name":"callPrice","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"optionMarket","type":"address"},{"internalType":"uint256","name":"strikeId","type":"uint256"}],"name":"getGWAVPutPrice","outputs":[{"internalType":"uint256","name":"putPrice","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint8","name":"inputNum","type":"uint8"}],"name":"getInput","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"getMethod","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"getParams","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"marketViewer","outputs":[{"internalType":"contract IOptionMarketViewer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"length","type":"uint256"}],"name":"read32","outputs":[{"internalType":"bytes32","name":"o","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint256","name":"offset","type":"uint256"}],"name":"read4left","outputs":[{"internalType":"bytes4","name":"o","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"address","name":"asset","type":"address"}],"name":"removeAssetCheck","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolManagerLogic","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"txGuard","outputs":[{"internalType":"uint16","name":"txType","type":"uint16"},{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"address","name":"asset","type":"address"},{"internalType":"uint256","name":"portion","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"withdrawProcessing","outputs":[{"internalType":"address","name":"withdrawAsset","type":"address"},{"internalType":"uint256","name":"withdrawBalance","type":"uint256"},{"components":[{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"txData","type":"bytes"}],"internalType":"struct IAssetGuard.MultiTransaction[]","name":"transactions","type":"tuple[]"}],"stateMutability":"nonpayable","type":"function"}]

60a06040523480156200001157600080fd5b5060405162002ae638038062002ae683398101604081905262000034916200004a565b60601b6001600160601b0319166080526200007a565b6000602082840312156200005c578081fd5b81516001600160a01b038116811462000073578182fd5b9392505050565b60805160601c612a30620000b660003980610c5a5280610cfb5280610dde5280611012528061105752806115ac5280611be75250612a306000f3fe608060405234801561001057600080fd5b50600436106101285760003560e01c806309ff5c7d1461012d5780631053f9521461015657806312408202146101765780631eba30771461017e578063293d80631461019e57806341dc16c3146101be5780636179309d146101d1578063669b3320146101f257806368901513146101fa5780636d5fae541461020d5780636f8ae202146102225780637bbbb29a146102445780637ddce5b51461025757806382f86acc1461025f57806383ac7d6e14610272578063998546e314610285578063a7354cf414610298578063abc183e1146102a0578063c3c6279f146102a8578063cf54aaa0146102bb578063d4fac45d146102ce578063db896b57146102e1578063e4e6ea58146102f4578063f3a95013146102fc575b600080fd5b61014061013b366004612362565b61030f565b60405161014d919061284b565b60405180910390f35b6101696101643660046123ad565b6103a2565b60405161014d9190612869565b61014061043a565b61019161018c36600461228b565b610440565b60405161014d9190612751565b6101b16101ac3660046122d5565b610447565b60405161014d9190612854565b6101406101cc366004612401565b6104a9565b6101e46101df3660046120a7565b610587565b60405161014d92919061297a565b6101406108ec565b6101696102083660046122a3565b6108f2565b61022061021b36600461206f565b61090d565b005b610235610230366004612133565b61093e565b60405161014d939291906127bd565b610140610252366004612185565b610dd9565b610191611010565b61014061026d366004612362565b611034565b610140610280366004612185565b611052565b610140610293366004612362565b611281565b6101406112b2565b6101406112b8565b6101b16102b63660046122a3565b6112bd565b6101406102c9366004612037565b6112ca565b6101406102dc36600461206f565b6112d0565b6101406102ef366004612317565b611b64565b610191611be3565b61022061030a366004612695565b611c7b565b600080610327848460200260040160ff166020611b64565b9050600061033a85600484016020611b64565b905080610383576040805162461bcd60e51b8152602060048201526012602482015271696e707574206973206e6f7420617272617960701b604482015290519081900360640190fd5b610397856020808402850160040190611b64565b925050505b92915050565b6060601482106103ea576040805162461bcd60e51b815260206004820152600e60248201526d1a5b9d985b1a59081bd9999cd95d60921b604482015290519081900360640190fd5b816020029150600061040985848660200260040160ff16016020611b64565b9050600061041e868584016004016020611b64565b90506104308660248487010183611ccd565b9695505050505050565b6103e881565b805b919050565b600081600401835110156104a0576040805162461bcd60e51b815260206004820152601b60248201527a52656164696e67206279746573206f7574206f6620626f756e647360281b604482015290519081900360640190fd5b50016020015190565b6000806104c1858560200260040160ff166020611b64565b905060006104d486600484016020611b64565b90508061051d576040805162461bcd60e51b8152602060048201526012602482015271696e707574206973206e6f7420617272617960701b604482015290519081900360640190fd5b60ff8416811161056d576040805162461bcd60e51b815260206004820152601660248201527534b73b30b634b21030b93930bc903837b9b4ba34b7b760511b604482015290519081900360640190fd5b610430866020600160ff8816018102850160040190611b64565b60008060006105cb85858080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506112bd92505050565b90506001600160e01b0319811663095ea7b360e01b14156108de57600061062a61018c87878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509250611034915050565b9050600061067087878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525060019250611034915050565b60001c905060008990506000816001600160a01b031663c45a01556040518163ffffffff1660e01b815260040160206040518083038186803b1580156106b557600080fd5b505afa1580156106c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106ed9190612053565b90506000816001600160a01b0316634f8419b9866040518263ffffffff1660e01b815260040161071d9190612751565b60206040518083038186803b15801561073557600080fd5b505afa158015610749573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061076d9190612053565b90506001600160a01b0381161580159061079057506001600160a01b0381163014155b6107b55760405162461bcd60e51b81526004016107ac906128e0565b60405180910390fd5b7f5343b378d69227c1bc2016fd44e8104f0ffa7729f4f4f4110e349a2db0a0d0c8836001600160a01b03166339b81fd96040518163ffffffff1660e01b815260040160206040518083038186803b15801561080f57600080fd5b505afa158015610823573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108479190612053565b8d6001600160a01b031663481c6a756040518163ffffffff1660e01b815260040160206040518083038186803b15801561088057600080fd5b505afa158015610894573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b89190612053565b8787426040516108cc959493929190612765565b60405180910390a16001975050505050505b506000905094509492505050565b61546081565b606061039c60048084510384611ccd9092919063ffffffff16565b600061091983836112d0565b905080156109395760405162461bcd60e51b81526004016107ac9061287c565b505050565b60008060606000876001600160a01b031663c45a01556040518163ffffffff1660e01b815260040160206040518083038186803b15801561097e57600080fd5b505afa158015610992573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109b69190612053565b6001600160a01b0316634f8419b9886040518263ffffffff1660e01b81526004016109e19190612751565b60206040518083038186803b1580156109f957600080fd5b505afa158015610a0d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a319190612053565b604051632182a60960e11b81529091506001600160a01b038216906343054c1290610a60908b90600401612751565b600060405180830381600087803b158015610a7a57600080fd5b505af1158015610a8e573d6000803e3d6000fd5b50506040516375d1447560e01b8152600092506001600160a01b03841691506375d1447590610ac1908c90600401612751565b60006040518083038186803b158015610ad957600080fd5b505afa158015610aed573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610b1591908101906121b0565b905080516002026001600160401b0381118015610b3157600080fd5b50604051908082528060200260200182016040528015610b6b57816020015b610b58611f90565b815260200190600190039081610b505790505b5092506000805b8251811015610dcb576000610b85611be3565b6001600160a01b031663c71b7e53858481518110610b9f57fe5b6020026020010151600001516040518263ffffffff1660e01b8152600401610bc79190612751565b6101406040518083038186803b158015610be057600080fd5b505afa158015610bf4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c189190612539565b90508060a00151868481518110610c2b57fe5b6020026020010151600001906001600160a01b031690816001600160a01b0316815250506323b872dd60e01b8c7f0000000000000000000000000000000000000000000000000000000000000000868581518110610c8557fe5b602002602001015160200151604051602401610ca393929190612799565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b038381831617835250505050868481518110610ce257fe5b60200260200101516020018190525082806001019350507f0000000000000000000000000000000000000000000000000000000000000000868481518110610d2657fe5b60209081029190910101516001600160a01b039091169052835163152b831d60e21b90859084908110610d5557fe5b60200260200101518b8b604051602401610d7193929190612948565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b038381831617835250505050868481518110610db057fe5b60209081029190910181015101525060019182019101610b72565b505050509450945094915050565b6000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663ee9e0e6a6040518163ffffffff1660e01b815260040160206040518083038186803b158015610e3557600080fd5b505afa158015610e49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e6d9190612053565b6001600160a01b031663c4158a51856040518263ffffffff1660e01b8152600401610e989190612751565b6101606040518083038186803b158015610eb157600080fd5b505afa158015610ec5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ee9919061245c565b61010081015160405163ca4ca66760e01b81529192506001600160a01b03169063ca4ca66790610f2190869061025890600401612990565b604080518083038186803b158015610f3857600080fd5b505afa158015610f4c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f7091906126b6565b61010083015160405163ca4ca66760e01b8152919450600092506001600160a01b03169063ca4ca66790610fac90879061546090600401612990565b604080518083038186803b158015610fc357600080fd5b505afa158015610fd7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ffb91906126b6565b9150506110088382611c7b565b505092915050565b7f000000000000000000000000000000000000000000000000000000000000000081565b600061104b838360200260040160ff166020611b64565b9392505050565b6000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663ee9e0e6a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156110ae57600080fd5b505afa1580156110c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110e69190612053565b6001600160a01b031663c4158a51856040518263ffffffff1660e01b81526004016111119190612751565b6101606040518083038186803b15801561112a57600080fd5b505afa15801561113e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611162919061245c565b61010081015160405163ca4ca66760e01b81529192506001600160a01b03169063ca4ca6679061119a90869061025890600401612990565b604080518083038186803b1580156111b157600080fd5b505afa1580156111c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111e991906126b6565b508092505060008161010001516001600160a01b031663ca4ca667856154606040518363ffffffff1660e01b8152600401611225929190612990565b604080518083038186803b15801561123c57600080fd5b505afa158015611250573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061127491906126b6565b5090506110088382611c7b565b600080611299848460200260040160ff166020611b64565b90506112aa84600483016020611b64565b949350505050565b61025881565b603281565b600061039c826000610447565b50601290565b600080836001600160a01b031663c45a01556040518163ffffffff1660e01b815260040160206040518083038186803b15801561130c57600080fd5b505afa158015611320573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113449190612053565b90506000816001600160a01b0316634f8419b9856040518263ffffffff1660e01b81526004016113749190612751565b60206040518083038186803b15801561138c57600080fd5b505afa1580156113a0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113c49190612053565b90506000816001600160a01b03166375d14475876040518263ffffffff1660e01b81526004016113f49190612751565b60006040518083038186803b15801561140c57600080fd5b505afa158015611420573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261144891908101906121b0565b905060005b8151811015611b5a576000611460611be3565b6001600160a01b031663c71b7e5384848151811061147a57fe5b6020026020010151600001516040518263ffffffff1660e01b81526004016114a29190612751565b6101406040518083038186803b1580156114bb57600080fd5b505afa1580156114cf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114f39190612539565b905060008160a001516001600160a01b03166399fbab8885858151811061151657fe5b6020026020010151602001516040518263ffffffff1660e01b815260040161153e919061284b565b60c06040518083038186803b15801561155657600080fd5b505afa15801561156a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061158e91906125f9565b905060018160a0015160058111156115a257fe5b1415611b505760007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663ab78ac996040518163ffffffff1660e01b815260040160206040518083038186803b15801561160357600080fd5b505afa158015611617573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061163b9190612053565b6001600160a01b0316637dbae64886868151811061165557fe5b6020026020010151600001516040518263ffffffff1660e01b815260040161167d9190612751565b60206040518083038186803b15801561169557600080fd5b505afa1580156116a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116cd919061267d565b905060008060008787815181106116e057fe5b6020026020010151600001516001600160a01b0316631fdb6cbd86602001516040518263ffffffff1660e01b815260040161171b919061284b565b60606040518083038186803b15801561173357600080fd5b505afa158015611747573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061176b91906126d9565b9250925092506000826000146119645760008660400151600481111561178d57fe5b14156117d2578383116117a15760006117cb565b6117cb670de0b6b3a76400006117c56117ba8688611e1e565b60608a015190611e7b565b90611ed4565b905061195f565b6001866040015160048111156117e457fe5b1415611811578284116117f85760006117cb565b6117cb670de0b6b3a76400006117c56117ba8787611e1e565b60028660400151600481111561182357fe5b141561189757600061184e670de0b6b3a76400006117c5858a60600151611e7b90919063ffffffff16565b90508087608001511161186257600061188f565b61188f670de0b6b3a76400006117c588611889858c60800151611e1e90919063ffffffff16565b90611e7b565b91505061195f565b6003866040015160048111156118a957fe5b14156119065760008484116118bf5760006118e3565b6118e3670de0b6b3a76400006117c56118d88789611e1e565b60608b015190611e7b565b9050808760800151116118f757600061188f565b608087015161188f9082611e1e565b60048660400151600481111561191857fe5b141561194757600083851161192e5760006118e3565b6118e3670de0b6b3a76400006117c56118d88888611e1e565b60405162461bcd60e51b81526004016107ac906128b3565b611b3e565b60008660400151600481111561197657fe5b14156119b7576119b0670de0b6b3a76400006117c56117ba8c8c8151811061199a57fe5b6020026020010151600001518a60200151611052565b9050611b3e565b6001866040015160048111156119c957fe5b1415611a03576119b0670de0b6b3a76400006117c56117ba8c8c815181106119ed57fe5b6020026020010151600001518a60200151610dd9565b600286604001516004811115611a1557fe5b1415611aa6576000611a40670de0b6b3a76400006117c5888a60800151611e7b90919063ffffffff16565b90506000611a83670de0b6b3a76400006117c5611a788e8e81518110611a6257fe5b6020026020010151600001518c60200151611052565b60608c015190611e7b565b9050808211611a93576000611a9d565b611a9d8282611e1e565b92505050611b3e565b600386604001516004811115611ab857fe5b1415611ae7576000866080015190506000611a83670de0b6b3a76400006117c5611a788e8e81518110611a6257fe5b600486604001516004811115611af957fe5b1415611947576000866080015190506000611a83670de0b6b3a76400006117c5611a788e8e81518110611b2857fe5b6020026020010151600001518c60200151610dd9565b611b488c82611f38565b9b5050505050505b505060010161144d565b5050505092915050565b600081830184511015611bbc576040805162461bcd60e51b815260206004820152601b60248201527a52656164696e67206279746573206f7574206f6620626f756e647360281b604482015290519081900360640190fd5b826020018401519050816020038015611bdb576008810260020a820491505b509392505050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316634f4630da6040518163ffffffff1660e01b815260040160206040518083038186803b158015611c3e57600080fd5b505afa158015611c52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c769190612053565b905090565b6000818311611c8c57828203611c90565b8183035b90506000611ca56103e86117c5866032611e7b565b905080821115611cc75760405162461bcd60e51b81526004016107ac90612916565b50505050565b60608182601f011015611d18576040805162461bcd60e51b815260206004820152600e60248201526d736c6963655f6f766572666c6f7760901b604482015290519081900360640190fd5b828284011015611d60576040805162461bcd60e51b815260206004820152600e60248201526d736c6963655f6f766572666c6f7760901b604482015290519081900360640190fd5b81830184511015611dac576040805162461bcd60e51b8152602060048201526011602482015270736c6963655f6f75744f66426f756e647360781b604482015290519081900360640190fd5b606082158015611dcb5760405191506000825260208201604052611e15565b6040519150601f8416801560200281840101858101878315602002848b0101015b81831015611e04578051835260209283019201611dec565b5050858452601f01601f1916604052505b50949350505050565b600082821115611e75576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b600082611e8a5750600061039c565b82820282848281611e9757fe5b041461104b5760405162461bcd60e51b81526004018080602001828103825260218152602001806129da6021913960400191505060405180910390fd5b6000808211611f27576040805162461bcd60e51b815260206004820152601a602482015279536166654d6174683a206469766973696f6e206279207a65726f60301b604482015290519081900360640190fd5b818381611f3057fe5b049392505050565b60008282018381101561104b576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b60408051808201909152600081526060602082015290565b8051610442816129c1565b600082601f830112611fc3578081fd5b81356001600160401b03811115611fd657fe5b611fe9601f8201601f191660200161299e565b818152846020838601011115611ffd578283fd5b816020850160208301379081016020019190915292915050565b80516006811061044257600080fd5b803560ff8116811461044257600080fd5b600060208284031215612048578081fd5b813561104b816129c1565b600060208284031215612064578081fd5b815161104b816129c1565b60008060408385031215612081578081fd5b823561208c816129c1565b9150602083013561209c816129c1565b809150509250929050565b600080600080606085870312156120bc578182fd5b84356120c7816129c1565b935060208501356120d7816129c1565b925060408501356001600160401b03808211156120f2578384fd5b818701915087601f830112612105578384fd5b813581811115612113578485fd5b886020828501011115612124578485fd5b95989497505060200194505050565b60008060008060808587031215612148578182fd5b8435612153816129c1565b93506020850135612163816129c1565b925060408501359150606085013561217a816129c1565b939692955090935050565b60008060408385031215612197578182fd5b82356121a2816129c1565b946020939093013593505050565b600060208083850312156121c2578182fd5b82516001600160401b03808211156121d8578384fd5b818501915085601f8301126121eb578384fd5b8151818111156121f757fe5b612204848583020161299e565b818152848101908486016040808502870188018b1015612222578889fd5b8896505b8487101561227c5780828c03121561223c578889fd5b8051818101818110888211171561224f57fe5b8252825161225c816129c1565b815282890151898201528452600196909601959287019290810190612226565b50909998505050505050505050565b60006020828403121561229c578081fd5b5035919050565b6000602082840312156122b4578081fd5b81356001600160401b038111156122c9578182fd5b6112aa84828501611fb3565b600080604083850312156122e7578182fd5b82356001600160401b038111156122fc578283fd5b61230885828601611fb3565b95602094909401359450505050565b60008060006060848603121561232b578081fd5b83356001600160401b03811115612340578182fd5b61234c86828701611fb3565b9660208601359650604090950135949350505050565b60008060408385031215612374578182fd5b82356001600160401b03811115612389578283fd5b61239585828601611fb3565b9250506123a460208401612026565b90509250929050565b6000806000606084860312156123c1578081fd5b83356001600160401b038111156123d6578182fd5b6123e286828701611fb3565b9350506123f160208501612026565b9150604084013590509250925092565b600080600060608486031215612415578081fd5b83356001600160401b0381111561242a578182fd5b61243686828701611fb3565b93505061244560208501612026565b915061245360408501612026565b90509250925092565b600061016080838503121561246f578182fd5b6124788161299e565b905061248383611fa8565b815261249160208401611fa8565b60208201526124a260408401611fa8565b60408201526124b360608401611fa8565b60608201526124c460808401611fa8565b60808201526124d560a08401611fa8565b60a08201526124e660c08401611fa8565b60c08201526124f760e08401611fa8565b60e082015261010061250a818501611fa8565b9082015261012061251c848201611fa8565b9082015261014061252e848201611fa8565b908201529392505050565b600061014080838503121561254c578182fd5b6125558161299e565b905061256083611fa8565b815261256e60208401611fa8565b602082015261257f60408401611fa8565b604082015261259060608401611fa8565b60608201526125a160808401611fa8565b60808201526125b260a08401611fa8565b60a08201526125c360c08401611fa8565b60c08201526125d460e08401611fa8565b60e08201526101006125e7818501611fa8565b9082015261012061252e848201611fa8565b600060c0828403121561260a578081fd5b60405160c081018181106001600160401b038211171561262657fe5b8060405250825181526020830151602082015260408301516005811061264a578283fd5b80604083015250606083015160608201526080830151608082015261267160a08401612017565b60a08201529392505050565b60006020828403121561268e578081fd5b5051919050565b600080604083850312156126a7578182fd5b50508035926020909101359150565b600080604083850312156126c8578182fd5b505080516020909101519092909150565b6000806000606084860312156126ed578081fd5b8351925060208401519150604084015190509250925092565b60008151808452815b8181101561272b5760208185018101518683018201520161270f565b8181111561273c5782602083870101525b50601f01601f19169290920160200192915050565b6001600160a01b0391909116815260200190565b6001600160a01b03958616815293851660208501529190931660408301526060820192909252608081019190915260a00190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b60006060820160018060a01b03808716845260208681860152604060608187015283875180865260808801915060808482028901019550838901875b8281101561283a57898803607f190184528151805188168952860151868901869052612827868a0182612706565b98505092850192908501906001016127f9565b50959b9a5050505050505050505050565b90815260200190565b6001600160e01b031991909116815260200190565b60006020825261104b6020830184612706565b6020808252601d908201527f63616e6e6f742072656d6f7665206e6f6e2d656d707479206173736574000000604082015260600190565b602080825260139082015272696e76616c6964206f7074696f6e207479706560681b604082015260600190565b6020808252601c908201527b1d5b9cdd5c1c1bdc9d1959081cdc195b99195c88185c1c1c9bdd985b60221b604082015260600190565b6020808252601890820152770ceeec2ec40c8d2eccae4cecadcc6ca40e8dede40d0d2ced60431b604082015260600190565b83516001600160a01b039081168252602094850151948201949094526040810192909252909116606082015260800190565b61ffff9290921682521515602082015260400190565b918252602082015260400190565b6040518181016001600160401b03811182821017156129b957fe5b604052919050565b6001600160a01b03811681146129d657600080fd5b5056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a2646970667358221220d004ca992020696a842c980d649b0244cae11fa610df8ad94ac9e3ce5f985b9064736f6c63430007060033000000000000000000000000befa33261ce1df58f47e274165cf85d504336421

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101285760003560e01c806309ff5c7d1461012d5780631053f9521461015657806312408202146101765780631eba30771461017e578063293d80631461019e57806341dc16c3146101be5780636179309d146101d1578063669b3320146101f257806368901513146101fa5780636d5fae541461020d5780636f8ae202146102225780637bbbb29a146102445780637ddce5b51461025757806382f86acc1461025f57806383ac7d6e14610272578063998546e314610285578063a7354cf414610298578063abc183e1146102a0578063c3c6279f146102a8578063cf54aaa0146102bb578063d4fac45d146102ce578063db896b57146102e1578063e4e6ea58146102f4578063f3a95013146102fc575b600080fd5b61014061013b366004612362565b61030f565b60405161014d919061284b565b60405180910390f35b6101696101643660046123ad565b6103a2565b60405161014d9190612869565b61014061043a565b61019161018c36600461228b565b610440565b60405161014d9190612751565b6101b16101ac3660046122d5565b610447565b60405161014d9190612854565b6101406101cc366004612401565b6104a9565b6101e46101df3660046120a7565b610587565b60405161014d92919061297a565b6101406108ec565b6101696102083660046122a3565b6108f2565b61022061021b36600461206f565b61090d565b005b610235610230366004612133565b61093e565b60405161014d939291906127bd565b610140610252366004612185565b610dd9565b610191611010565b61014061026d366004612362565b611034565b610140610280366004612185565b611052565b610140610293366004612362565b611281565b6101406112b2565b6101406112b8565b6101b16102b63660046122a3565b6112bd565b6101406102c9366004612037565b6112ca565b6101406102dc36600461206f565b6112d0565b6101406102ef366004612317565b611b64565b610191611be3565b61022061030a366004612695565b611c7b565b600080610327848460200260040160ff166020611b64565b9050600061033a85600484016020611b64565b905080610383576040805162461bcd60e51b8152602060048201526012602482015271696e707574206973206e6f7420617272617960701b604482015290519081900360640190fd5b610397856020808402850160040190611b64565b925050505b92915050565b6060601482106103ea576040805162461bcd60e51b815260206004820152600e60248201526d1a5b9d985b1a59081bd9999cd95d60921b604482015290519081900360640190fd5b816020029150600061040985848660200260040160ff16016020611b64565b9050600061041e868584016004016020611b64565b90506104308660248487010183611ccd565b9695505050505050565b6103e881565b805b919050565b600081600401835110156104a0576040805162461bcd60e51b815260206004820152601b60248201527a52656164696e67206279746573206f7574206f6620626f756e647360281b604482015290519081900360640190fd5b50016020015190565b6000806104c1858560200260040160ff166020611b64565b905060006104d486600484016020611b64565b90508061051d576040805162461bcd60e51b8152602060048201526012602482015271696e707574206973206e6f7420617272617960701b604482015290519081900360640190fd5b60ff8416811161056d576040805162461bcd60e51b815260206004820152601660248201527534b73b30b634b21030b93930bc903837b9b4ba34b7b760511b604482015290519081900360640190fd5b610430866020600160ff8816018102850160040190611b64565b60008060006105cb85858080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506112bd92505050565b90506001600160e01b0319811663095ea7b360e01b14156108de57600061062a61018c87878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509250611034915050565b9050600061067087878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525060019250611034915050565b60001c905060008990506000816001600160a01b031663c45a01556040518163ffffffff1660e01b815260040160206040518083038186803b1580156106b557600080fd5b505afa1580156106c9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106ed9190612053565b90506000816001600160a01b0316634f8419b9866040518263ffffffff1660e01b815260040161071d9190612751565b60206040518083038186803b15801561073557600080fd5b505afa158015610749573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061076d9190612053565b90506001600160a01b0381161580159061079057506001600160a01b0381163014155b6107b55760405162461bcd60e51b81526004016107ac906128e0565b60405180910390fd5b7f5343b378d69227c1bc2016fd44e8104f0ffa7729f4f4f4110e349a2db0a0d0c8836001600160a01b03166339b81fd96040518163ffffffff1660e01b815260040160206040518083038186803b15801561080f57600080fd5b505afa158015610823573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108479190612053565b8d6001600160a01b031663481c6a756040518163ffffffff1660e01b815260040160206040518083038186803b15801561088057600080fd5b505afa158015610894573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b89190612053565b8787426040516108cc959493929190612765565b60405180910390a16001975050505050505b506000905094509492505050565b61546081565b606061039c60048084510384611ccd9092919063ffffffff16565b600061091983836112d0565b905080156109395760405162461bcd60e51b81526004016107ac9061287c565b505050565b60008060606000876001600160a01b031663c45a01556040518163ffffffff1660e01b815260040160206040518083038186803b15801561097e57600080fd5b505afa158015610992573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109b69190612053565b6001600160a01b0316634f8419b9886040518263ffffffff1660e01b81526004016109e19190612751565b60206040518083038186803b1580156109f957600080fd5b505afa158015610a0d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a319190612053565b604051632182a60960e11b81529091506001600160a01b038216906343054c1290610a60908b90600401612751565b600060405180830381600087803b158015610a7a57600080fd5b505af1158015610a8e573d6000803e3d6000fd5b50506040516375d1447560e01b8152600092506001600160a01b03841691506375d1447590610ac1908c90600401612751565b60006040518083038186803b158015610ad957600080fd5b505afa158015610aed573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610b1591908101906121b0565b905080516002026001600160401b0381118015610b3157600080fd5b50604051908082528060200260200182016040528015610b6b57816020015b610b58611f90565b815260200190600190039081610b505790505b5092506000805b8251811015610dcb576000610b85611be3565b6001600160a01b031663c71b7e53858481518110610b9f57fe5b6020026020010151600001516040518263ffffffff1660e01b8152600401610bc79190612751565b6101406040518083038186803b158015610be057600080fd5b505afa158015610bf4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c189190612539565b90508060a00151868481518110610c2b57fe5b6020026020010151600001906001600160a01b031690816001600160a01b0316815250506323b872dd60e01b8c7f000000000000000000000000befa33261ce1df58f47e274165cf85d504336421868581518110610c8557fe5b602002602001015160200151604051602401610ca393929190612799565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b038381831617835250505050868481518110610ce257fe5b60200260200101516020018190525082806001019350507f000000000000000000000000befa33261ce1df58f47e274165cf85d504336421868481518110610d2657fe5b60209081029190910101516001600160a01b039091169052835163152b831d60e21b90859084908110610d5557fe5b60200260200101518b8b604051602401610d7193929190612948565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b038381831617835250505050868481518110610db057fe5b60209081029190910181015101525060019182019101610b72565b505050509450945094915050565b6000807f000000000000000000000000befa33261ce1df58f47e274165cf85d5043364216001600160a01b031663ee9e0e6a6040518163ffffffff1660e01b815260040160206040518083038186803b158015610e3557600080fd5b505afa158015610e49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e6d9190612053565b6001600160a01b031663c4158a51856040518263ffffffff1660e01b8152600401610e989190612751565b6101606040518083038186803b158015610eb157600080fd5b505afa158015610ec5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ee9919061245c565b61010081015160405163ca4ca66760e01b81529192506001600160a01b03169063ca4ca66790610f2190869061025890600401612990565b604080518083038186803b158015610f3857600080fd5b505afa158015610f4c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f7091906126b6565b61010083015160405163ca4ca66760e01b8152919450600092506001600160a01b03169063ca4ca66790610fac90879061546090600401612990565b604080518083038186803b158015610fc357600080fd5b505afa158015610fd7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ffb91906126b6565b9150506110088382611c7b565b505092915050565b7f000000000000000000000000befa33261ce1df58f47e274165cf85d50433642181565b600061104b838360200260040160ff166020611b64565b9392505050565b6000807f000000000000000000000000befa33261ce1df58f47e274165cf85d5043364216001600160a01b031663ee9e0e6a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156110ae57600080fd5b505afa1580156110c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110e69190612053565b6001600160a01b031663c4158a51856040518263ffffffff1660e01b81526004016111119190612751565b6101606040518083038186803b15801561112a57600080fd5b505afa15801561113e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611162919061245c565b61010081015160405163ca4ca66760e01b81529192506001600160a01b03169063ca4ca6679061119a90869061025890600401612990565b604080518083038186803b1580156111b157600080fd5b505afa1580156111c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111e991906126b6565b508092505060008161010001516001600160a01b031663ca4ca667856154606040518363ffffffff1660e01b8152600401611225929190612990565b604080518083038186803b15801561123c57600080fd5b505afa158015611250573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061127491906126b6565b5090506110088382611c7b565b600080611299848460200260040160ff166020611b64565b90506112aa84600483016020611b64565b949350505050565b61025881565b603281565b600061039c826000610447565b50601290565b600080836001600160a01b031663c45a01556040518163ffffffff1660e01b815260040160206040518083038186803b15801561130c57600080fd5b505afa158015611320573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113449190612053565b90506000816001600160a01b0316634f8419b9856040518263ffffffff1660e01b81526004016113749190612751565b60206040518083038186803b15801561138c57600080fd5b505afa1580156113a0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113c49190612053565b90506000816001600160a01b03166375d14475876040518263ffffffff1660e01b81526004016113f49190612751565b60006040518083038186803b15801561140c57600080fd5b505afa158015611420573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261144891908101906121b0565b905060005b8151811015611b5a576000611460611be3565b6001600160a01b031663c71b7e5384848151811061147a57fe5b6020026020010151600001516040518263ffffffff1660e01b81526004016114a29190612751565b6101406040518083038186803b1580156114bb57600080fd5b505afa1580156114cf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114f39190612539565b905060008160a001516001600160a01b03166399fbab8885858151811061151657fe5b6020026020010151602001516040518263ffffffff1660e01b815260040161153e919061284b565b60c06040518083038186803b15801561155657600080fd5b505afa15801561156a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061158e91906125f9565b905060018160a0015160058111156115a257fe5b1415611b505760007f000000000000000000000000befa33261ce1df58f47e274165cf85d5043364216001600160a01b031663ab78ac996040518163ffffffff1660e01b815260040160206040518083038186803b15801561160357600080fd5b505afa158015611617573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061163b9190612053565b6001600160a01b0316637dbae64886868151811061165557fe5b6020026020010151600001516040518263ffffffff1660e01b815260040161167d9190612751565b60206040518083038186803b15801561169557600080fd5b505afa1580156116a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116cd919061267d565b905060008060008787815181106116e057fe5b6020026020010151600001516001600160a01b0316631fdb6cbd86602001516040518263ffffffff1660e01b815260040161171b919061284b565b60606040518083038186803b15801561173357600080fd5b505afa158015611747573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061176b91906126d9565b9250925092506000826000146119645760008660400151600481111561178d57fe5b14156117d2578383116117a15760006117cb565b6117cb670de0b6b3a76400006117c56117ba8688611e1e565b60608a015190611e7b565b90611ed4565b905061195f565b6001866040015160048111156117e457fe5b1415611811578284116117f85760006117cb565b6117cb670de0b6b3a76400006117c56117ba8787611e1e565b60028660400151600481111561182357fe5b141561189757600061184e670de0b6b3a76400006117c5858a60600151611e7b90919063ffffffff16565b90508087608001511161186257600061188f565b61188f670de0b6b3a76400006117c588611889858c60800151611e1e90919063ffffffff16565b90611e7b565b91505061195f565b6003866040015160048111156118a957fe5b14156119065760008484116118bf5760006118e3565b6118e3670de0b6b3a76400006117c56118d88789611e1e565b60608b015190611e7b565b9050808760800151116118f757600061188f565b608087015161188f9082611e1e565b60048660400151600481111561191857fe5b141561194757600083851161192e5760006118e3565b6118e3670de0b6b3a76400006117c56118d88888611e1e565b60405162461bcd60e51b81526004016107ac906128b3565b611b3e565b60008660400151600481111561197657fe5b14156119b7576119b0670de0b6b3a76400006117c56117ba8c8c8151811061199a57fe5b6020026020010151600001518a60200151611052565b9050611b3e565b6001866040015160048111156119c957fe5b1415611a03576119b0670de0b6b3a76400006117c56117ba8c8c815181106119ed57fe5b6020026020010151600001518a60200151610dd9565b600286604001516004811115611a1557fe5b1415611aa6576000611a40670de0b6b3a76400006117c5888a60800151611e7b90919063ffffffff16565b90506000611a83670de0b6b3a76400006117c5611a788e8e81518110611a6257fe5b6020026020010151600001518c60200151611052565b60608c015190611e7b565b9050808211611a93576000611a9d565b611a9d8282611e1e565b92505050611b3e565b600386604001516004811115611ab857fe5b1415611ae7576000866080015190506000611a83670de0b6b3a76400006117c5611a788e8e81518110611a6257fe5b600486604001516004811115611af957fe5b1415611947576000866080015190506000611a83670de0b6b3a76400006117c5611a788e8e81518110611b2857fe5b6020026020010151600001518c60200151610dd9565b611b488c82611f38565b9b5050505050505b505060010161144d565b5050505092915050565b600081830184511015611bbc576040805162461bcd60e51b815260206004820152601b60248201527a52656164696e67206279746573206f7574206f6620626f756e647360281b604482015290519081900360640190fd5b826020018401519050816020038015611bdb576008810260020a820491505b509392505050565b60007f000000000000000000000000befa33261ce1df58f47e274165cf85d5043364216001600160a01b0316634f4630da6040518163ffffffff1660e01b815260040160206040518083038186803b158015611c3e57600080fd5b505afa158015611c52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c769190612053565b905090565b6000818311611c8c57828203611c90565b8183035b90506000611ca56103e86117c5866032611e7b565b905080821115611cc75760405162461bcd60e51b81526004016107ac90612916565b50505050565b60608182601f011015611d18576040805162461bcd60e51b815260206004820152600e60248201526d736c6963655f6f766572666c6f7760901b604482015290519081900360640190fd5b828284011015611d60576040805162461bcd60e51b815260206004820152600e60248201526d736c6963655f6f766572666c6f7760901b604482015290519081900360640190fd5b81830184511015611dac576040805162461bcd60e51b8152602060048201526011602482015270736c6963655f6f75744f66426f756e647360781b604482015290519081900360640190fd5b606082158015611dcb5760405191506000825260208201604052611e15565b6040519150601f8416801560200281840101858101878315602002848b0101015b81831015611e04578051835260209283019201611dec565b5050858452601f01601f1916604052505b50949350505050565b600082821115611e75576040805162461bcd60e51b815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b600082611e8a5750600061039c565b82820282848281611e9757fe5b041461104b5760405162461bcd60e51b81526004018080602001828103825260218152602001806129da6021913960400191505060405180910390fd5b6000808211611f27576040805162461bcd60e51b815260206004820152601a602482015279536166654d6174683a206469766973696f6e206279207a65726f60301b604482015290519081900360640190fd5b818381611f3057fe5b049392505050565b60008282018381101561104b576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b60408051808201909152600081526060602082015290565b8051610442816129c1565b600082601f830112611fc3578081fd5b81356001600160401b03811115611fd657fe5b611fe9601f8201601f191660200161299e565b818152846020838601011115611ffd578283fd5b816020850160208301379081016020019190915292915050565b80516006811061044257600080fd5b803560ff8116811461044257600080fd5b600060208284031215612048578081fd5b813561104b816129c1565b600060208284031215612064578081fd5b815161104b816129c1565b60008060408385031215612081578081fd5b823561208c816129c1565b9150602083013561209c816129c1565b809150509250929050565b600080600080606085870312156120bc578182fd5b84356120c7816129c1565b935060208501356120d7816129c1565b925060408501356001600160401b03808211156120f2578384fd5b818701915087601f830112612105578384fd5b813581811115612113578485fd5b886020828501011115612124578485fd5b95989497505060200194505050565b60008060008060808587031215612148578182fd5b8435612153816129c1565b93506020850135612163816129c1565b925060408501359150606085013561217a816129c1565b939692955090935050565b60008060408385031215612197578182fd5b82356121a2816129c1565b946020939093013593505050565b600060208083850312156121c2578182fd5b82516001600160401b03808211156121d8578384fd5b818501915085601f8301126121eb578384fd5b8151818111156121f757fe5b612204848583020161299e565b818152848101908486016040808502870188018b1015612222578889fd5b8896505b8487101561227c5780828c03121561223c578889fd5b8051818101818110888211171561224f57fe5b8252825161225c816129c1565b815282890151898201528452600196909601959287019290810190612226565b50909998505050505050505050565b60006020828403121561229c578081fd5b5035919050565b6000602082840312156122b4578081fd5b81356001600160401b038111156122c9578182fd5b6112aa84828501611fb3565b600080604083850312156122e7578182fd5b82356001600160401b038111156122fc578283fd5b61230885828601611fb3565b95602094909401359450505050565b60008060006060848603121561232b578081fd5b83356001600160401b03811115612340578182fd5b61234c86828701611fb3565b9660208601359650604090950135949350505050565b60008060408385031215612374578182fd5b82356001600160401b03811115612389578283fd5b61239585828601611fb3565b9250506123a460208401612026565b90509250929050565b6000806000606084860312156123c1578081fd5b83356001600160401b038111156123d6578182fd5b6123e286828701611fb3565b9350506123f160208501612026565b9150604084013590509250925092565b600080600060608486031215612415578081fd5b83356001600160401b0381111561242a578182fd5b61243686828701611fb3565b93505061244560208501612026565b915061245360408501612026565b90509250925092565b600061016080838503121561246f578182fd5b6124788161299e565b905061248383611fa8565b815261249160208401611fa8565b60208201526124a260408401611fa8565b60408201526124b360608401611fa8565b60608201526124c460808401611fa8565b60808201526124d560a08401611fa8565b60a08201526124e660c08401611fa8565b60c08201526124f760e08401611fa8565b60e082015261010061250a818501611fa8565b9082015261012061251c848201611fa8565b9082015261014061252e848201611fa8565b908201529392505050565b600061014080838503121561254c578182fd5b6125558161299e565b905061256083611fa8565b815261256e60208401611fa8565b602082015261257f60408401611fa8565b604082015261259060608401611fa8565b60608201526125a160808401611fa8565b60808201526125b260a08401611fa8565b60a08201526125c360c08401611fa8565b60c08201526125d460e08401611fa8565b60e08201526101006125e7818501611fa8565b9082015261012061252e848201611fa8565b600060c0828403121561260a578081fd5b60405160c081018181106001600160401b038211171561262657fe5b8060405250825181526020830151602082015260408301516005811061264a578283fd5b80604083015250606083015160608201526080830151608082015261267160a08401612017565b60a08201529392505050565b60006020828403121561268e578081fd5b5051919050565b600080604083850312156126a7578182fd5b50508035926020909101359150565b600080604083850312156126c8578182fd5b505080516020909101519092909150565b6000806000606084860312156126ed578081fd5b8351925060208401519150604084015190509250925092565b60008151808452815b8181101561272b5760208185018101518683018201520161270f565b8181111561273c5782602083870101525b50601f01601f19169290920160200192915050565b6001600160a01b0391909116815260200190565b6001600160a01b03958616815293851660208501529190931660408301526060820192909252608081019190915260a00190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b60006060820160018060a01b03808716845260208681860152604060608187015283875180865260808801915060808482028901019550838901875b8281101561283a57898803607f190184528151805188168952860151868901869052612827868a0182612706565b98505092850192908501906001016127f9565b50959b9a5050505050505050505050565b90815260200190565b6001600160e01b031991909116815260200190565b60006020825261104b6020830184612706565b6020808252601d908201527f63616e6e6f742072656d6f7665206e6f6e2d656d707479206173736574000000604082015260600190565b602080825260139082015272696e76616c6964206f7074696f6e207479706560681b604082015260600190565b6020808252601c908201527b1d5b9cdd5c1c1bdc9d1959081cdc195b99195c88185c1c1c9bdd985b60221b604082015260600190565b6020808252601890820152770ceeec2ec40c8d2eccae4cecadcc6ca40e8dede40d0d2ced60431b604082015260600190565b83516001600160a01b039081168252602094850151948201949094526040810192909252909116606082015260800190565b61ffff9290921682521515602082015260400190565b918252602082015260400190565b6040518181016001600160401b03811182821017156129b957fe5b604052919050565b6001600160a01b03811681146129d657600080fd5b5056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a2646970667358221220d004ca992020696a842c980d649b0244cae11fa610df8ad94ac9e3ce5f985b9064736f6c63430007060033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000befa33261ce1df58f47e274165cf85d504336421

-----Decoded View---------------
Arg [0] : _dhedgeLyraWrapper (address): 0xBEFa33261Ce1dF58F47e274165Cf85D504336421

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000befa33261ce1df58f47e274165cf85d504336421


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.