ETH Price: $3,624.73 (-1.56%)

Contract

0xf3B63B29A2813959a4273e920c6c5dF06bfc369A

Overview

ETH Balance

0 ETH

ETH Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
1075573012023-07-30 10:36:19491 days ago1690713379
0xf3B63B29...06bfc369A
0 ETH
1075572762023-07-30 10:35:29491 days ago1690713329
0xf3B63B29...06bfc369A
0 ETH
1075572342023-07-30 10:34:05491 days ago1690713245
0xf3B63B29...06bfc369A
0 ETH
1075571882023-07-30 10:32:33491 days ago1690713153
0xf3B63B29...06bfc369A
0 ETH
1075556862023-07-30 9:42:29491 days ago1690710149
0xf3B63B29...06bfc369A
0 ETH
1075556212023-07-30 9:40:19491 days ago1690710019
0xf3B63B29...06bfc369A
0 ETH
1075555102023-07-30 9:36:37491 days ago1690709797
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075550882023-07-30 9:22:33491 days ago1690708953
0xf3B63B29...06bfc369A
0 ETH
1075548082023-07-30 9:13:13491 days ago1690708393
0xf3B63B29...06bfc369A
0 ETH
View All Internal Transactions

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
ThalesAMM

Compiler Version
v0.8.4+commit.c7e474f2

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 25 : ThalesAMM.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// external
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";

// internal
import "../utils/proxy/solidity-0.8.0/ProxyReentrancyGuard.sol";
import "../utils/proxy/solidity-0.8.0/ProxyOwned.sol";
import "../utils/proxy/solidity-0.8.0/ProxyPausable.sol";

import "../interfaces/IPriceFeed.sol";
import "../interfaces/IThalesAMMUtils.sol";
import "../interfaces/IPositionalMarket.sol";
import "../interfaces/IPositionalMarketManager.sol";
import "../interfaces/IPosition.sol";
import "../interfaces/IStakingThales.sol";
import "../interfaces/IReferrals.sol";
import "../interfaces/ICurveSUSD.sol";

import "./LiquidityPool/ThalesAMMLiquidityPool.sol";

/// @title An AMM using BlackScholes odds algorithm to provide liqudidity for traders of UP or DOWN positions
contract ThalesAMM is Initializable, ProxyOwned, ProxyPausable, ProxyReentrancyGuard {
    using SafeERC20Upgradeable for IERC20Upgradeable;

    struct BuyPriceImpactParams {
        address market;
        IThalesAMM.Position position;
        uint amount;
        uint _availableToBuyFromAMM;
        uint _availableToBuyFromAMMOtherSide;
        ThalesAMMLiquidityPool liquidityPool;
        uint basePrice;
    }

    uint private constant ONE = 1e18;
    uint private constant ONE_PERCENT = 1e16;

    IPriceFeed public priceFeed;
    IERC20Upgradeable public sUSD;
    address public manager;

    uint public capPerMarket;
    uint public min_spread;
    uint public max_spread;

    mapping(bytes32 => uint) public impliedVolatilityPerAsset;

    uint public minimalTimeLeftToMaturity;

    mapping(address => uint) public spentOnMarket;

    address public safeBox;
    uint public safeBoxImpact;

    IStakingThales public stakingThales;

    uint public minSupportedPrice;
    uint public maxSupportedPrice;

    mapping(bytes32 => uint) private _capPerAsset;

    mapping(address => bool) public whitelistedAddresses;

    address public referrals;
    uint public referrerFee;

    ICurveSUSD public curveSUSD;

    address public usdc;
    address public usdt;
    address public dai;

    bool public curveOnrampEnabled;

    uint public maxAllowedPegSlippagePercentage;

    IThalesAMMUtils ammUtils;

    int private constant ONE_INT = 1e18;
    int private constant ONE_PERCENT_INT = 1e16;

    mapping(address => uint) public safeBoxFeePerAddress;
    mapping(address => uint) public min_spreadPerAddress;

    ThalesAMMLiquidityPool public liquidityPool;

    function initialize(
        address _owner,
        IPriceFeed _priceFeed,
        IERC20Upgradeable _sUSD,
        uint _capPerMarket,
        address _deciMath,
        uint _min_spread,
        uint _max_spread,
        uint _minimalTimeLeftToMaturity
    ) public initializer {
        setOwner(_owner);
        initNonReentrant();
        priceFeed = _priceFeed;
        sUSD = _sUSD;
        capPerMarket = _capPerMarket;
        min_spread = _min_spread;
        max_spread = _max_spread;
        minimalTimeLeftToMaturity = _minimalTimeLeftToMaturity;
    }

    // READ public methods

    /// @notice get how many positions of a certain type (UP or DOWN) can be bought from the given positional market
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @return _available how many positions of that type can be bought
    function availableToBuyFromAMM(address market, IThalesAMM.Position position) public view returns (uint _available) {
        if (isMarketInAMMTrading(market)) {
            uint basePrice = price(market, position);
            if (basePrice > 0) {
                basePrice = basePrice < minSupportedPrice ? minSupportedPrice : basePrice;
                _available = _availableToBuyFromAMMWithBasePrice(market, position, basePrice, false);
            }
        }
    }

    /// @notice get a quote in sUSD on how much the trader would need to pay to buy the amount of UP or DOWN positions
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @param amount number of positions to buy with 18 decimals
    /// @return _quote in sUSD on how much the trader would need to pay to buy the amount of UP or DOWN positions
    function buyFromAmmQuote(
        address market,
        IThalesAMM.Position position,
        uint amount
    ) public view returns (uint _quote) {
        uint basePrice = price(market, position);
        uint basePriceOtherSide = ONE - basePrice;
        if (basePrice > 0) {
            basePrice = basePrice < minSupportedPrice ? minSupportedPrice : basePrice;
            _quote = _buyFromAmmQuoteWithBasePrice(market, position, amount, basePrice, basePriceOtherSide, safeBoxImpact);
        }
    }

    /// @notice get a quote in the collateral of choice (USDC, USDT or DAI) on how much the trader would need to pay to buy the amount of UP or DOWN positions
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @param amount number of positions to buy with 18 decimals
    /// @param collateral USDT, USDC or DAI address
    /// @return collateralQuote a quote in collateral on how much the trader would need to pay to buy the amount of UP or DOWN positions
    /// @return sUSDToPay a quote in sUSD on how much the trader would need to pay to buy the amount of UP or DOWN positions
    function buyFromAmmQuoteWithDifferentCollateral(
        address market,
        IThalesAMM.Position position,
        uint amount,
        address collateral
    ) public view returns (uint collateralQuote, uint sUSDToPay) {
        int128 curveIndex = _mapCollateralToCurveIndex(collateral);
        if (curveIndex > 0 && curveOnrampEnabled) {
            sUSDToPay = buyFromAmmQuote(market, position, amount);
            //cant get a quote on how much collateral is needed from curve for sUSD,
            //so rather get how much of collateral you get for the sUSD quote and add 0.2% to that
            collateralQuote = (curveSUSD.get_dy_underlying(0, curveIndex, sUSDToPay) * (ONE + (ONE_PERCENT / 5))) / ONE;
        }
    }

    /// @notice get the skew impact applied to that side of the market on buy
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @param amount number of positions to buy with 18 decimals
    /// @return _priceImpact the skew impact applied to that side of the market
    function buyPriceImpact(
        address market,
        IThalesAMM.Position position,
        uint amount
    ) public view returns (int _priceImpact) {
        IThalesAMM.Position positionOtherSide = position == IThalesAMM.Position.Up
            ? IThalesAMM.Position.Down
            : IThalesAMM.Position.Up;
        uint basePrice = price(market, position);

        if (basePrice >= minSupportedPrice && basePrice <= maxSupportedPrice) {
            uint basePriceOtherSide = ONE - basePrice;
            uint _availableToBuyFromAMM = _availableToBuyFromAMMWithBasePrice(market, position, basePrice, true);
            uint _availableToBuyFromAMMOtherSide = _availableToBuyFromAMMWithBasePrice(
                market,
                positionOtherSide,
                basePriceOtherSide,
                true
            );
            if (amount > 0 && amount <= _availableToBuyFromAMM) {
                _priceImpact = _buyPriceImpact(
                    BuyPriceImpactParams(
                        market,
                        position,
                        amount,
                        _availableToBuyFromAMM,
                        _availableToBuyFromAMMOtherSide,
                        liquidityPool,
                        basePrice
                    )
                );
            }
        }
    }

    /// @notice get how many positions of a certain type (UP or DOWN) can be sold for the given positional market
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @return _available how many positions of that type can be sold
    function availableToSellToAMM(address market, IThalesAMM.Position position) public view returns (uint _available) {
        if (isMarketInAMMTrading(market)) {
            uint basePrice = price(market, position);
            basePrice = basePrice > maxSupportedPrice ? maxSupportedPrice : basePrice;
            _available = _availableToSellToAMM(market, position, basePrice);
        }
    }

    /// @notice get a quote in sUSD on how much the trader would receive as payment to sell the amount of UP or DOWN positions
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @param amount number of positions to buy with 18 decimals
    /// @return _quote in sUSD on how much the trader would receive as payment to sell the amount of UP or DOWN positions
    function sellToAmmQuote(
        address market,
        IThalesAMM.Position position,
        uint amount
    ) public view returns (uint _quote) {
        uint basePrice = price(market, position);
        basePrice = basePrice > maxSupportedPrice ? maxSupportedPrice : basePrice;
        uint _available = _availableToSellToAMM(market, position, basePrice);
        _quote = _sellToAmmQuote(market, position, amount, basePrice, _available);
    }

    /// @notice get the skew impact applied to that side of the market on sell
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @param amount number of positions to buy with 18 decimals
    /// @return _impact the skew impact applied to that side of the market
    function sellPriceImpact(
        address market,
        IThalesAMM.Position position,
        uint amount
    ) public view returns (uint _impact) {
        uint _available = availableToSellToAMM(market, position);
        if (amount <= _available) {
            _impact = _sellPriceImpact(market, position, amount, _available);
        }
    }

    /// @notice get the base price (odds) of a given side of the market
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @return priceToReturn the base price (odds) of a given side of the market
    function price(address market, IThalesAMM.Position position) public view returns (uint priceToReturn) {
        if (isMarketInAMMTrading(market)) {
            // add price calculation
            IPositionalMarket marketContract = IPositionalMarket(market);
            (uint maturity, ) = marketContract.times();

            uint timeLeftToMaturity = maturity - block.timestamp;
            uint timeLeftToMaturityInDays = (timeLeftToMaturity * ONE) / 86400;
            uint oraclePrice = marketContract.oraclePrice();

            (bytes32 key, uint strikePrice, ) = marketContract.getOracleDetails();

            priceToReturn =
                ammUtils.calculateOdds(oraclePrice, strikePrice, timeLeftToMaturityInDays, impliedVolatilityPerAsset[key]) /
                1e2;

            if (position == IThalesAMM.Position.Down) {
                priceToReturn = ONE - priceToReturn;
            }
        }
    }

    /// @notice check if market is supported by the AMM
    /// @param market positional market known to manager
    /// @return isTrading is market supported by the AMM
    function isMarketInAMMTrading(address market) public view returns (bool isTrading) {
        if (IPositionalMarketManager(manager).isActiveMarket(market)) {
            IPositionalMarket marketContract = IPositionalMarket(market);
            (bytes32 key, , ) = marketContract.getOracleDetails();
            (uint maturity, ) = marketContract.times();

            if (!(impliedVolatilityPerAsset[key] == 0 || maturity < block.timestamp)) {
                uint timeLeftToMaturity = maturity - block.timestamp;
                isTrading = timeLeftToMaturity > minimalTimeLeftToMaturity;
            }
        }
    }

    /// @notice get the maximum risk in sUSD the AMM will offer on a certain asset on an individual market
    /// @param asset e.g. ETH, BTC, SNX....
    /// @return _cap the maximum risk in sUSD the AMM will offer on a certain asset on an individual market
    function getCapPerAsset(bytes32 asset) public view returns (uint _cap) {
        if (!(priceFeed.rateForCurrency(asset) == 0)) {
            _cap = _capPerAsset[asset] == 0 ? capPerMarket : _capPerAsset[asset];
        }
    }

    // write methods

    /// @notice buy positions of the defined type of a given market from the AMM coming from a referrer
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @param amount how many positions
    /// @param expectedPayout how much does the buyer expect to pay (retrieved via quote)
    /// @param additionalSlippage how much of a slippage on the sUSD expectedPayout will the buyer accept
    /// @param _referrer who referred the buyer to Thales
    function buyFromAMMWithReferrer(
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint expectedPayout,
        uint additionalSlippage,
        address _referrer
    ) public nonReentrant notPaused returns (uint) {
        if (_referrer != address(0)) {
            IReferrals(referrals).setReferrer(_referrer, msg.sender);
        }
        return _buyFromAMM(market, position, amount, expectedPayout, additionalSlippage, true, 0);
    }

    /// @notice buy positions of the defined type of a given market from the AMM with USDC, USDT or DAI
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @param amount how many positions
    /// @param expectedPayout how much does the buyer expect to pay (retrieved via quote)
    /// @param collateral USDC, USDT or DAI
    /// @param additionalSlippage how much of a slippage on the sUSD expectedPayout will the buyer accept
    /// @param _referrer who referred the buyer to Thales
    function buyFromAMMWithDifferentCollateralAndReferrer(
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint expectedPayout,
        uint additionalSlippage,
        address collateral,
        address _referrer
    ) public nonReentrant notPaused returns (uint) {
        if (_referrer != address(0)) {
            IReferrals(referrals).setReferrer(_referrer, msg.sender);
        }

        int128 curveIndex = _mapCollateralToCurveIndex(collateral);
        require(curveIndex > 0 && curveOnrampEnabled, "unsupported collateral");

        (uint collateralQuote, uint susdQuote) = buyFromAmmQuoteWithDifferentCollateral(
            market,
            position,
            amount,
            collateral
        );

        uint transformedCollateralForPegCheck = collateral == usdc || collateral == usdt
            ? collateralQuote * (1e12)
            : collateralQuote;
        require(
            maxAllowedPegSlippagePercentage > 0 &&
                transformedCollateralForPegCheck >= (susdQuote * (ONE - (maxAllowedPegSlippagePercentage))) / ONE,
            "Amount below max allowed peg slippage"
        );

        require((collateralQuote * ONE) / (expectedPayout) <= (ONE + additionalSlippage), "Slippage too high!");

        IERC20Upgradeable collateralToken = IERC20Upgradeable(collateral);
        collateralToken.safeTransferFrom(msg.sender, address(this), collateralQuote);
        curveSUSD.exchange_underlying(curveIndex, 0, collateralQuote, susdQuote);

        return _buyFromAMM(market, position, amount, susdQuote, additionalSlippage, false, susdQuote);
    }

    /// @notice buy positions of the defined type of a given market from the AMM
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @param amount how many positions
    /// @param expectedPayout how much does the buyer expect to pay (retrieved via quote)
    /// @param additionalSlippage how much of a slippage on the sUSD expectedPayout will the buyer accept
    function buyFromAMM(
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint expectedPayout,
        uint additionalSlippage
    ) public nonReentrant notPaused returns (uint) {
        return _buyFromAMM(market, position, amount, expectedPayout, additionalSlippage, true, 0);
    }

    /// @notice sell positions of the defined type of a given market to the AMM
    /// @param market a Positional Market known to Market Manager
    /// @param position UP or DOWN
    /// @param amount how many positions
    /// @param expectedPayout how much does the seller to receive(retrieved via quote)
    /// @param additionalSlippage how much of a slippage on the sUSD expectedPayout will the seller accept
    function sellToAMM(
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint expectedPayout,
        uint additionalSlippage
    ) public nonReentrant notPaused returns (uint) {
        require(isMarketInAMMTrading(market), "Market is not in Trading phase");

        uint basePrice = price(market, position);
        basePrice = basePrice > maxSupportedPrice ? maxSupportedPrice : basePrice;
        uint availableToSellToAMMATM = _availableToSellToAMM(market, position, basePrice);
        require(availableToSellToAMMATM > 0 && amount <= availableToSellToAMMATM, "Not enough liquidity.");

        uint pricePaid = _sellToAmmQuote(market, position, amount, basePrice, availableToSellToAMMATM);
        require((expectedPayout * ONE) / (pricePaid) <= (ONE + (additionalSlippage)), "Slippage too high");

        address target = _getTarget(market, position);

        _transferPositions(market);

        //transfer options first to have max burn available
        IERC20Upgradeable(target).safeTransferFrom(msg.sender, address(this), amount);

        uint sUSDFromBurning = IPositionalMarketManager(manager).transformCollateral(
            IPositionalMarket(market).getMaximumBurnable(address(this))
        );
        if (sUSDFromBurning > 0) {
            IPositionalMarket(market).burnOptionsMaximum();
        }

        uint safeBoxShare = (pricePaid * ONE) / (ONE - (safeBoxImpact)) - pricePaid;
        uint referrerShare = (pricePaid * ONE) / (ONE - (referrerFee)) - pricePaid;
        if (safeBoxImpact == 0) {
            safeBoxShare = 0;
        }

        liquidityPool.commitTrade(
            market,
            IPositionalMarketManager(manager).reverseTransformCollateral(pricePaid + safeBoxShare + referrerShare)
        );
        sUSD.safeTransfer(msg.sender, pricePaid);

        if (address(stakingThales) != address(0)) {
            stakingThales.updateVolume(msg.sender, pricePaid);
        }

        _updateSpentOnMarketOnSell(market, pricePaid, sUSDFromBurning, msg.sender, safeBoxShare);

        _sendMintedPositionsAndUSDToLiquidityPool(market);

        emit SoldToAMM(msg.sender, market, position, amount, pricePaid, address(sUSD), target);
        return pricePaid;
    }

    function _transferPositions(address market) internal {
        (uint upBalance, uint downBalance) = ammUtils.getBalanceOfPositionsOnMarket(
            market,
            liquidityPool.getMarketPool(market)
        );

        liquidityPool.getOptionsForBuy(market, upBalance, IThalesAMM.Position.Up);
        liquidityPool.getOptionsForBuy(market, downBalance, IThalesAMM.Position.Down);
    }

    /// @notice Retrieve sUSD from the contract
    /// @param account whom to send the sUSD
    /// @param amount how much sUSD to retrieve
    function retrieveSUSDAmount(address payable account, uint amount) external onlyOwner {
        sUSD.safeTransfer(account, amount);
    }

    // Internal

    function _availableToSellToAMM(
        address market,
        IThalesAMM.Position position,
        uint basePrice
    ) internal view returns (uint _available) {
        uint sell_max_price = _getSellMaxPrice(basePrice);
        if (sell_max_price > 0) {
            (, uint balanceOfTheOtherSide) = ammUtils.balanceOfPositionsOnMarket(
                market,
                position,
                liquidityPool.getMarketPool(market)
            );

            // any balanceOfTheOtherSide will be burned to get sUSD back (1 to 1) at the `willPay` cost
            uint willPay = (balanceOfTheOtherSide * (sell_max_price)) / ONE;
            uint capWithBalance = _capOnMarket(market) + (balanceOfTheOtherSide);
            if (capWithBalance >= (spentOnMarket[market] + willPay)) {
                uint usdAvailable = capWithBalance - (spentOnMarket[market]) - (willPay);
                _available = (usdAvailable / (sell_max_price)) * ONE + (balanceOfTheOtherSide);
            }
        }
    }

    function _sellToAmmQuote(
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint basePrice,
        uint _available
    ) internal view returns (uint _quote) {
        if (amount <= _available) {
            basePrice = basePrice - (min_spread);

            uint tempAmount = (amount *
                ((basePrice * (ONE - (_sellPriceImpact(market, position, amount, _available)))) / ONE)) / ONE;

            uint returnQuote = (tempAmount * (ONE - (safeBoxImpact))) / ONE;
            _quote = IPositionalMarketManager(manager).transformCollateral(returnQuote);
        }
    }

    function _availableToBuyFromAMMWithBasePrice(
        address market,
        IThalesAMM.Position position,
        uint basePrice,
        bool skipCheck
    ) internal view returns (uint availableAmount) {
        if (skipCheck || basePrice < maxSupportedPrice) {
            basePrice = basePrice + min_spread;
            if (basePrice < ONE) {
                uint discountedPrice = (basePrice * (ONE - max_spread / 2)) / ONE;
                uint balance = ammUtils.balanceOfPositionOnMarket(market, position, liquidityPool.getMarketPool(market));
                uint additionalBufferFromSelling = (balance * discountedPrice) / ONE;

                if ((_capOnMarket(market) + additionalBufferFromSelling) > spentOnMarket[market]) {
                    uint availableUntilCapSUSD = _capOnMarket(market) + additionalBufferFromSelling - spentOnMarket[market];
                    if (availableUntilCapSUSD > _capOnMarket(market)) {
                        availableUntilCapSUSD = _capOnMarket(market);
                    }

                    uint midImpactPriceIncrease = ((ONE - basePrice) * (max_spread / 2)) / ONE;
                    if ((basePrice + midImpactPriceIncrease) < ONE) {
                        uint divider_price = ONE - (basePrice + midImpactPriceIncrease);

                        availableAmount = balance + ((availableUntilCapSUSD * ONE) / divider_price);
                    }
                }
            }
        }
    }

    function _buyFromAmmQuoteWithBasePrice(
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint basePrice,
        uint basePriceOtherSide,
        uint safeBoxImpactForCaller
    ) internal view returns (uint returnQuote) {
        uint _available = _availableToBuyFromAMMWithBasePrice(market, position, basePrice, false);
        uint _availableOtherSide = _availableToBuyFromAMMWithBasePrice(
            market,
            position == IThalesAMM.Position.Up ? IThalesAMM.Position.Down : IThalesAMM.Position.Up,
            basePriceOtherSide,
            true
        );

        if (amount <= _available) {
            int tempQuote;
            int skewImpact = _buyPriceImpact(
                BuyPriceImpactParams(market, position, amount, _available, _availableOtherSide, liquidityPool, basePrice)
            );
            basePrice = basePrice + (min_spreadPerAddress[msg.sender] > 0 ? min_spreadPerAddress[msg.sender] : min_spread);
            if (skewImpact >= 0) {
                int impactPrice = ((ONE_INT - int(basePrice)) * skewImpact) / ONE_INT;
                // add 2% to the price increase to avoid edge cases on the extremes
                impactPrice = (impactPrice * (ONE_INT + (ONE_PERCENT_INT * 2))) / ONE_INT;
                tempQuote = (int(amount) * (int(basePrice) + impactPrice)) / ONE_INT;
            } else {
                tempQuote = ((int(amount)) * ((int(basePrice) * (ONE_INT + skewImpact)) / ONE_INT)) / ONE_INT;
            }
            tempQuote = (tempQuote * (ONE_INT + (int(safeBoxImpactForCaller)))) / ONE_INT;
            returnQuote = IPositionalMarketManager(manager).transformCollateral(uint(tempQuote));
        }
    }

    function _getSellMaxPrice(uint basePrice) internal view returns (uint sell_max_price) {
        if (basePrice > minSupportedPrice) {
            sell_max_price = ((basePrice - min_spread) * (ONE - (max_spread / (2)))) / ONE;
        }
    }

    function _buyFromAMM(
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint expectedPayout,
        uint additionalSlippage,
        bool sendSUSD,
        uint sUSDPaidCarried
    ) internal returns (uint sUSDPaid) {
        require(isMarketInAMMTrading(market), "Market is not in Trading phase");

        sUSDPaid = sUSDPaidCarried;

        uint basePrice = price(market, position);
        uint basePriceOtherSide = ONE - basePrice;

        basePrice = basePrice < minSupportedPrice ? minSupportedPrice : basePrice;

        uint availableToBuyFromAMMatm = _availableToBuyFromAMMWithBasePrice(market, position, basePrice, false);
        require(amount > 0 && amount <= availableToBuyFromAMMatm, "Not enough liquidity.");

        if (sendSUSD) {
            sUSDPaid = _buyFromAmmQuoteWithBasePrice(
                market,
                position,
                amount,
                basePrice,
                basePriceOtherSide,
                safeBoxFeePerAddress[msg.sender] > 0 ? safeBoxFeePerAddress[msg.sender] : safeBoxImpact
            );
            require((sUSDPaid * ONE) / (expectedPayout) <= (ONE + additionalSlippage), "Slippage too high");

            sUSD.safeTransferFrom(msg.sender, address(this), sUSDPaid);
        }

        uint toMint = _getMintableAmount(market, position, amount);
        if (toMint > 0) {
            liquidityPool.commitTrade(market, toMint);
            IPositionalMarket(market).mint(toMint);
            spentOnMarket[market] = spentOnMarket[market] + toMint;
        }
        liquidityPool.getOptionsForBuy(market, amount - toMint, position);

        address target = _getTarget(market, position);
        IERC20Upgradeable(target).safeTransfer(msg.sender, amount);

        if (address(stakingThales) != address(0)) {
            stakingThales.updateVolume(msg.sender, sUSDPaid);
        }
        _updateSpentOnMarketOnBuy(market, sUSDPaid, msg.sender);

        if (amount > toMint) {
            uint discountedAmount = amount - toMint;
            uint paidForDiscountedAmount = (sUSDPaid * discountedAmount) / amount;
            emit BoughtWithDiscount(msg.sender, discountedAmount, paidForDiscountedAmount);
        }

        _sendMintedPositionsAndUSDToLiquidityPool(market);

        emit BoughtFromAmm(msg.sender, market, position, amount, sUSDPaid, address(sUSD), target);
        _handleInTheMoneyEvent(market, position, sUSDPaid, msg.sender);
    }

    function _handleInTheMoneyEvent(
        address market,
        IThalesAMM.Position position,
        uint sUSDPaid,
        address sender
    ) internal {
        (bytes32 key, uint strikePrice, ) = IPositionalMarket(market).getOracleDetails();
        uint currentAssetPrice = priceFeed.rateForCurrency(key);
        bool inTheMoney = position == IThalesAMM.Position.Up
            ? currentAssetPrice >= strikePrice
            : currentAssetPrice < strikePrice;
        emit BoughtOptionType(msg.sender, sUSDPaid, inTheMoney);
    }

    function _getTarget(address market, IThalesAMM.Position position) internal view returns (address target) {
        (IPosition up, IPosition down) = IPositionalMarket(market).getOptions();
        target = address(position == IThalesAMM.Position.Up ? up : down);
    }

    function _updateSpentOnMarketOnSell(
        address market,
        uint sUSDPaid,
        uint sUSDFromBurning,
        address seller,
        uint safeBoxShare
    ) internal {
        if (safeBoxImpact > 0) {
            sUSD.safeTransfer(safeBox, safeBoxShare);
        }

        spentOnMarket[market] =
            spentOnMarket[market] +
            (IPositionalMarketManager(manager).reverseTransformCollateral(sUSDPaid + (safeBoxShare)));
        if (spentOnMarket[market] <= IPositionalMarketManager(manager).reverseTransformCollateral(sUSDFromBurning)) {
            spentOnMarket[market] = 0;
        } else {
            spentOnMarket[market] =
                spentOnMarket[market] -
                (IPositionalMarketManager(manager).reverseTransformCollateral(sUSDFromBurning));
        }

        if (referrerFee > 0 && referrals != address(0)) {
            uint referrerShare = (sUSDPaid * ONE) / (ONE - (referrerFee)) - (sUSDPaid);
            _handleReferrer(seller, referrerShare, sUSDPaid);
        }
    }

    function _updateSpentOnMarketOnBuy(
        address market,
        uint sUSDPaid,
        address buyer
    ) internal {
        uint safeBoxShare;
        if (safeBoxImpact > 0) {
            safeBoxShare = (sUSDPaid -
                (sUSDPaid * ONE) /
                (ONE + (safeBoxFeePerAddress[msg.sender] > 0 ? safeBoxFeePerAddress[msg.sender] : safeBoxImpact)));
            sUSD.safeTransfer(safeBox, safeBoxShare);
        }

        if (
            spentOnMarket[market] <= IPositionalMarketManager(manager).reverseTransformCollateral(sUSDPaid - (safeBoxShare))
        ) {
            spentOnMarket[market] = 0;
        } else {
            spentOnMarket[market] =
                spentOnMarket[market] -
                (IPositionalMarketManager(manager).reverseTransformCollateral(sUSDPaid - (safeBoxShare)));
        }

        if (referrerFee > 0 && referrals != address(0)) {
            uint referrerShare = sUSDPaid - ((sUSDPaid * ONE) / (ONE + (referrerFee)));
            _handleReferrer(buyer, referrerShare, sUSDPaid);
        }
    }

    function _buyPriceImpact(BuyPriceImpactParams memory params) internal view returns (int priceImpact) {
        if (params.basePrice >= minSupportedPrice && params.basePrice <= maxSupportedPrice) {
            (uint balancePosition, uint balanceOtherSide) = ammUtils.balanceOfPositionsOnMarket(
                params.market,
                params.position,
                params.liquidityPool.getMarketPool(params.market)
            );

            uint balancePositionAfter = balancePosition > params.amount ? balancePosition - params.amount : 0;
            uint balanceOtherSideAfter = balanceOtherSide +
                (balancePosition > params.amount ? 0 : (params.amount - balancePosition));
            if (balancePositionAfter >= balanceOtherSideAfter) {
                priceImpact = ammUtils.calculateDiscount(
                    IThalesAMMUtils.DiscountParams(
                        balancePosition,
                        balanceOtherSide,
                        params.amount,
                        params._availableToBuyFromAMMOtherSide,
                        max_spread
                    )
                );
            } else {
                if (params.amount > balancePosition && balancePosition > 0) {
                    uint amountToBeMinted = params.amount - balancePosition;
                    uint positiveSkew = ammUtils.buyPriceImpactImbalancedSkew(
                        IThalesAMMUtils.PriceImpactParams(
                            amountToBeMinted,
                            balanceOtherSide + balancePosition,
                            0,
                            balanceOtherSide + amountToBeMinted,
                            0,
                            params._availableToBuyFromAMM - balancePosition,
                            max_spread
                        )
                    );

                    uint pricePosition = price(params.market, params.position);
                    uint priceOtherPosition = price(
                        params.market,
                        params.position == IThalesAMM.Position.Up ? IThalesAMM.Position.Down : IThalesAMM.Position.Up
                    );
                    uint skew = (priceOtherPosition * positiveSkew) / pricePosition;

                    int discount = ammUtils.calculateDiscount(
                        IThalesAMMUtils.DiscountParams(
                            balancePosition,
                            balanceOtherSide,
                            balancePosition,
                            params._availableToBuyFromAMMOtherSide,
                            max_spread
                        )
                    );

                    int discountBalance = int(balancePosition) * discount;
                    int discountMinted = int(amountToBeMinted * skew);
                    int amountInt = int(balancePosition + amountToBeMinted);

                    priceImpact = (discountBalance + discountMinted) / amountInt;

                    if (priceImpact > 0) {
                        int numerator = int(pricePosition) * priceImpact;
                        priceImpact = numerator / int(priceOtherPosition);
                    }
                } else {
                    priceImpact = int(
                        ammUtils.buyPriceImpactImbalancedSkew(
                            IThalesAMMUtils.PriceImpactParams(
                                params.amount,
                                balanceOtherSide,
                                balancePosition,
                                balanceOtherSideAfter,
                                balancePositionAfter,
                                params._availableToBuyFromAMM,
                                max_spread
                            )
                        )
                    );
                }
            }
        }
    }

    function _handleReferrer(
        address buyer,
        uint referrerShare,
        uint volume
    ) internal {
        address referrer = IReferrals(referrals).referrals(buyer);
        if (referrer != address(0) && referrerFee > 0) {
            sUSD.safeTransfer(referrer, referrerShare);
            emit ReferrerPaid(referrer, buyer, referrerShare, volume);
        }
    }

    function _sellPriceImpact(
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint available
    ) internal view returns (uint _sellImpact) {
        (uint _balancePosition, uint balanceOtherSide) = ammUtils.balanceOfPositionsOnMarket(
            market,
            position,
            liquidityPool.getMarketPool(market)
        );
        uint balancePositionAfter = _balancePosition > 0 ? _balancePosition + (amount) : balanceOtherSide > amount
            ? 0
            : amount - (balanceOtherSide);
        uint balanceOtherSideAfter = balanceOtherSide > amount ? balanceOtherSide - (amount) : 0;
        if (!(balancePositionAfter < balanceOtherSideAfter)) {
            _sellImpact = ammUtils.sellPriceImpactImbalancedSkew(
                amount,
                balanceOtherSide,
                _balancePosition,
                balanceOtherSideAfter,
                balancePositionAfter,
                available,
                max_spread
            );
        }
    }

    function _getMintableAmount(
        address market,
        IThalesAMM.Position position,
        uint amount
    ) internal view returns (uint mintable) {
        uint availableInContract = ammUtils.balanceOfPositionOnMarket(market, position, liquidityPool.getMarketPool(market));
        if (availableInContract < amount) {
            mintable = amount - availableInContract;
        }
    }

    function _capOnMarket(address market) internal view returns (uint) {
        (bytes32 key, , ) = IPositionalMarket(market).getOracleDetails();
        return getCapPerAsset(key);
    }

    function _mapCollateralToCurveIndex(address collateral) internal view returns (int128) {
        if (collateral == dai) {
            return 1;
        }
        if (collateral == usdc) {
            return 2;
        }
        if (collateral == usdt) {
            return 3;
        }
        return 0;
    }

    function _sendMintedPositionsAndUSDToLiquidityPool(address market) internal {
        address _liquidityPool = liquidityPool.getOrCreateMarketPool(market);

        if (sUSD.balanceOf(address(this)) > 0) {
            sUSD.safeTransfer(_liquidityPool, sUSD.balanceOf(address(this)));
        }

        (IPosition up, IPosition down) = IPositionalMarket(market).getOptions();

        (uint upBalance, uint downBalance) = ammUtils.getBalanceOfPositionsOnMarket(market, address(this));

        if (upBalance > 0) {
            IERC20Upgradeable(address(up)).safeTransfer(_liquidityPool, upBalance);
        }

        if (downBalance > 0) {
            IERC20Upgradeable(address(down)).safeTransfer(_liquidityPool, downBalance);
        }
    }

    // setters

    /// @notice Updates contract parametars
    /// @param _minimalTimeLeftToMaturity how long till maturity will AMM support trading on a given market
    function setMinimalTimeLeftToMaturity(uint _minimalTimeLeftToMaturity) external onlyOwner {
        minimalTimeLeftToMaturity = _minimalTimeLeftToMaturity;
        emit SetMinimalTimeLeftToMaturity(_minimalTimeLeftToMaturity);
    }

    /// @notice Updates contract parametars
    /// @param _address which can update implied volatility
    /// @param enabled update if the address can set implied volatility
    function setWhitelistedAddress(address _address, bool enabled) external onlyOwner {
        whitelistedAddresses[_address] = enabled;
    }

    /// @notice Updates contract parametars
    /// @param _address which has a specific safe box fee
    /// @param newFee the fee
    function setSafeBoxFeePerAddress(address _address, uint newFee) external onlyOwner {
        safeBoxFeePerAddress[_address] = newFee;
    }

    /// @notice Updates contract parametars
    /// @param _address which has a specific min_spread fee
    /// @param newFee the fee
    function setMinSpreadPerAddress(address _address, uint newFee) external onlyOwner {
        min_spreadPerAddress[_address] = newFee;
    }

    /// @notice Updates contract parametars
    /// @param _minspread minimum spread applied to base price
    /// @param _maxspread maximum skew impact, e.g. if all UP positions are drained, skewImpact on that side = _maxspread
    function setMinMaxSpread(uint _minspread, uint _maxspread) external onlyOwner {
        min_spread = _minspread;
        max_spread = _maxspread;
        emit SetMinSpread(_minspread);
        emit SetMaxSpread(_maxspread);
    }

    /// @notice Updates contract parametars
    /// @param _safeBox where to send a fee reserved for protocol from each trade
    /// @param _safeBoxImpact how much is the SafeBoxFee
    function setSafeBoxData(address _safeBox, uint _safeBoxImpact) external onlyOwner {
        safeBoxImpact = _safeBoxImpact;
        safeBox = _safeBox;
        emit SetSafeBoxImpact(_safeBoxImpact);
    }

    /// @notice Updates contract parametars
    /// @param _minSupportedPrice whats the max price AMM supports, e.g. 10 cents
    /// @param _maxSupportedPrice whats the max price AMM supports, e.g. 90 cents
    /// @param _capPerMarket default amount the AMM will risk on markets, overrided by capPerAsset if existing
    function setMinMaxSupportedPriceAndCap(
        uint _minSupportedPrice,
        uint _maxSupportedPrice,
        uint _capPerMarket
    ) external onlyOwner {
        minSupportedPrice = _minSupportedPrice;
        maxSupportedPrice = _maxSupportedPrice;
        capPerMarket = _capPerMarket;
        emit SetMinMaxSupportedPriceCapPerMarket(_minSupportedPrice, _maxSupportedPrice, _capPerMarket);
    }

    /// @notice Updates contract parametars. Can be set by owner or whitelisted addresses. In the future try to get it as a feed from Chainlink.
    /// @param asset e.g. ETH, BTC, SNX...
    /// @param _impliedVolatility IV for BlackScholes
    function setImpliedVolatilityPerAsset(bytes32 asset, uint _impliedVolatility) external {
        require(
            whitelistedAddresses[msg.sender] || owner == msg.sender,
            "Only whitelisted addresses or owner can change IV!"
        );
        require(_impliedVolatility > ONE * 10 && _impliedVolatility < ONE * 300, "IV outside min/max range!");
        require(priceFeed.rateForCurrency(asset) != 0, "Asset has no price!");
        impliedVolatilityPerAsset[asset] = _impliedVolatility;
        emit SetImpliedVolatilityPerAsset(asset, _impliedVolatility);
    }

    /// @notice Updates contract parametars
    /// @param _priceFeed contract from which we read prices, can be chainlink or twap
    /// @param _sUSD address of sUSD
    function setPriceFeedAndSUSD(IPriceFeed _priceFeed, IERC20Upgradeable _sUSD) external onlyOwner {
        priceFeed = _priceFeed;
        emit SetPriceFeed(address(_priceFeed));

        sUSD = _sUSD;
        emit SetSUSD(address(sUSD));
    }

    /// @notice Updates contract parametars
    /// @param _ammUtils address of AMMUtils
    function setAmmUtils(IThalesAMMUtils _ammUtils) external onlyOwner {
        ammUtils = _ammUtils;
    }

    /// @notice Updates contract parametars
    /// @param _stakingThales contract address for staking bonuses
    /// @param _referrals contract for referrals storage
    /// @param _referrerFee how much of a fee to pay to referrers
    function setStakingThalesAndReferrals(
        IStakingThales _stakingThales,
        address _referrals,
        uint _referrerFee
    ) external onlyOwner {
        stakingThales = _stakingThales;
        referrals = _referrals;
        referrerFee = _referrerFee;
    }

    /// @notice Updates contract parametars
    /// @param _manager Positional Market Manager contract
    function setPositionalMarketManager(address _manager) external onlyOwner {
        if (address(manager) != address(0)) {
            sUSD.approve(address(manager), 0);
        }
        manager = _manager;
        sUSD.approve(manager, type(uint256).max);
        emit SetPositionalMarketManager(_manager);
    }

    /// @notice Updates contract parametars
    /// @param _liquidityPool address of ThalesAMMLiquidityPool
    function setLiquidityPool(ThalesAMMLiquidityPool _liquidityPool) external onlyOwner {
        liquidityPool = _liquidityPool;
    }

    /// @notice Updates contract parametars
    /// @param _curveSUSD curve sUSD pool exchanger contract
    /// @param _dai DAI address
    /// @param _usdc USDC address
    /// @param _usdt USDT addresss
    /// @param _curveOnrampEnabled whether AMM supports curve onramp
    /// @param _maxAllowedPegSlippagePercentage maximum discount AMM accepts for sUSD purchases
    function setCurveSUSD(
        address _curveSUSD,
        address _dai,
        address _usdc,
        address _usdt,
        bool _curveOnrampEnabled,
        uint _maxAllowedPegSlippagePercentage
    ) external onlyOwner {
        curveSUSD = ICurveSUSD(_curveSUSD);
        dai = _dai;
        usdc = _usdc;
        usdt = _usdt;
        IERC20Upgradeable(dai).approve(_curveSUSD, type(uint256).max);
        IERC20Upgradeable(usdc).approve(_curveSUSD, type(uint256).max);
        IERC20Upgradeable(usdt).approve(_curveSUSD, type(uint256).max);
        // not needed unless selling into different collateral is enabled
        //sUSD.approve(_curveSUSD, type(uint256).max);
        curveOnrampEnabled = _curveOnrampEnabled;
        maxAllowedPegSlippagePercentage = _maxAllowedPegSlippagePercentage;
    }

    /// @notice Updates contract parametars
    /// @param asset e.g. ETH, BTC, SNX
    /// @param _cap how much risk can AMM take on markets for given asset
    function setCapPerAsset(bytes32 asset, uint _cap) external onlyOwner {
        _capPerAsset[asset] = _cap;
        emit SetCapPerAsset(asset, _cap);
    }

    /// @notice Send tokens from this contract to the destination address
    /// @param tokens to iterate and transfer
    /// @param account Address where to send the tokens
    /// @param amount Amount of tokens to be sent
    /// @param all ignore amount and send whole balance
    function transferTokens(
        address[] calldata tokens,
        address payable account,
        uint amount,
        bool all
    ) external onlyOwner {
        require(tokens.length > 0, "tokens array cant be empty");
        for (uint256 index = 0; index < tokens.length; index++) {
            if (all) {
                IERC20Upgradeable(tokens[index]).safeTransfer(
                    account,
                    IERC20Upgradeable(tokens[index]).balanceOf(address(this))
                );
            } else {
                IERC20Upgradeable(tokens[index]).safeTransfer(account, amount);
            }
        }
    }

    // events
    event SoldToAMM(
        address seller,
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint sUSDPaid,
        address susd,
        address asset
    );
    event BoughtFromAmm(
        address buyer,
        address market,
        IThalesAMM.Position position,
        uint amount,
        uint sUSDPaid,
        address susd,
        address asset
    );

    event BoughtWithDiscount(address buyer, uint amount, uint sUSDPaid);
    event BoughtOptionType(address buyer, uint sUSDPaid, bool inTheMoney);
    event SetPositionalMarketManager(address _manager);
    event SetSUSD(address sUSD);
    event SetPriceFeed(address _priceFeed);
    event SetImpliedVolatilityPerAsset(bytes32 asset, uint _impliedVolatility);
    event SetCapPerAsset(bytes32 asset, uint _cap);
    event SetMaxSpread(uint _spread);
    event SetMinSpread(uint _spread);
    event SetSafeBoxImpact(uint _safeBoxImpact);
    event SetSafeBox(address _safeBox);
    event SetMinimalTimeLeftToMaturity(uint _minimalTimeLeftToMaturity);
    event SetMinMaxSupportedPriceCapPerMarket(uint minPrice, uint maxPrice, uint capPerMarket);
    event ReferrerPaid(address refferer, address trader, uint amount, uint volume);
}

File 2 of 25 : SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

    function safeDecreaseAllowance(
        IERC20Upgradeable token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

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

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

File 3 of 25 : MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    /**
     * @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.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a / b + (a % b == 0 ? 0 : 1);
    }
}

File 4 of 25 : OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * 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 onlyInitializing {
        __Context_init_unchained();
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_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 {
        _transferOwnership(address(0));
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
    uint256[49] private __gap;
}

File 5 of 25 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)

pragma solidity ^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 {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
 * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() initializer {}
 * ```
 * ====
 */
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() {
        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
        // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
        // contract may have been reentered.
        require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");

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

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} modifier, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    function _isConstructor() private view returns (bool) {
        return !AddressUpgradeable.isContract(address(this));
    }
}

File 6 of 25 : SafeMathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
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) {
        unchecked {
            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) {
        unchecked {
            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) {
        unchecked {
            // 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) {
        unchecked {
            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) {
        unchecked {
            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) {
        return a + b;
    }

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

    /**
     * @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.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        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) {
        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) {
        unchecked {
            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.
     *
     * 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) {
        unchecked {
            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) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

File 7 of 25 : IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Upgradeable {
    /**
     * @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 8 of 25 : PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Context_init_unchained();
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        require(!paused(), "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        require(paused(), "Pausable: not paused");
        _;
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
    uint256[49] private __gap;
}

File 9 of 25 : ProxyReentrancyGuard.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
 * available, which can be aplied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 */
contract ProxyReentrancyGuard {
    /// @dev counter to allow mutex lock with only one SSTORE operation
    uint256 private _guardCounter;
    bool private _initialized;

    function initNonReentrant() public {
        require(!_initialized, "Already initialized");
        _initialized = true;
        _guardCounter = 1;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _guardCounter += 1;
        uint256 localCounter = _guardCounter;
        _;
        require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
    }
}

File 10 of 25 : ProxyOwned.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// Clone of syntetix contract without constructor
contract ProxyOwned {
    address public owner;
    address public nominatedOwner;
    bool private _initialized;
    bool private _transferredAtInit;

    function setOwner(address _owner) public {
        require(_owner != address(0), "Owner address cannot be 0");
        require(!_initialized, "Already initialized, use nominateNewOwner");
        _initialized = true;
        owner = _owner;
        emit OwnerChanged(address(0), _owner);
    }

    function nominateNewOwner(address _owner) external onlyOwner {
        nominatedOwner = _owner;
        emit OwnerNominated(_owner);
    }

    function acceptOwnership() external {
        require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
        emit OwnerChanged(owner, nominatedOwner);
        owner = nominatedOwner;
        nominatedOwner = address(0);
    }

    function transferOwnershipAtInit(address proxyAddress) external onlyOwner {
        require(proxyAddress != address(0), "Invalid address");
        require(!_transferredAtInit, "Already transferred");
        owner = proxyAddress;
        _transferredAtInit = true;
        emit OwnerChanged(owner, proxyAddress);
    }

    modifier onlyOwner {
        _onlyOwner();
        _;
    }

    function _onlyOwner() private view {
        require(msg.sender == owner, "Only the contract owner may perform this action");
    }

    event OwnerNominated(address newOwner);
    event OwnerChanged(address oldOwner, address newOwner);
}

File 11 of 25 : ProxyPausable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// Inheritance
import "./ProxyOwned.sol";

// Clone of syntetix contract without constructor

contract ProxyPausable is ProxyOwned {
    uint public lastPauseTime;
    bool public paused;

    

    /**
     * @notice Change the paused state of the contract
     * @dev Only the contract owner may call this.
     */
    function setPaused(bool _paused) external onlyOwner {
        // Ensure we're actually changing the state before we do anything
        if (_paused == paused) {
            return;
        }

        // Set our paused state.
        paused = _paused;

        // If applicable, set the last pause time.
        if (paused) {
            lastPauseTime = block.timestamp;
        }

        // Let everyone know that our pause state has changed.
        emit PauseChanged(paused);
    }

    event PauseChanged(bool isPaused);

    modifier notPaused {
        require(!paused, "This action cannot be performed while the contract is paused");
        _;
    }
}

File 12 of 25 : IPriceFeed.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.5.16;

interface IPriceFeed {
    // Structs
    struct RateAndUpdatedTime {
        uint216 rate;
        uint40 time;
    }

    // Mutative functions
    function addAggregator(bytes32 currencyKey, address aggregatorAddress) external;

    function removeAggregator(bytes32 currencyKey) external;

    // Views

    function rateForCurrency(bytes32 currencyKey) external view returns (uint);

    function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);

    function getRates() external view returns (uint[] memory);

    function getCurrencies() external view returns (bytes32[] memory);
}

File 13 of 25 : IThalesAMMUtils.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16;

import "../interfaces/IThalesAMM.sol";

interface IThalesAMMUtils {
    struct PriceImpactParams {
        uint amount;
        uint balanceOtherSide;
        uint balancePosition;
        uint balanceOtherSideAfter;
        uint balancePositionAfter;
        uint availableToBuyFromAMM;
        uint max_spread;
    }

    struct DiscountParams {
        uint balancePosition;
        uint balanceOtherSide;
        uint amount;
        uint availableToBuyFromAMM;
        uint max_spread;
    }

    function calculateOdds(
        uint _price,
        uint strike,
        uint timeLeftInDays,
        uint volatility
    ) external view returns (uint);

    function calculateDiscount(DiscountParams memory params) external view returns (int);

    function buyPriceImpactImbalancedSkew(PriceImpactParams memory params) external view returns (uint);

    function sellPriceImpactImbalancedSkew(
        uint amount,
        uint balanceOtherSide,
        uint _balancePosition,
        uint balanceOtherSideAfter,
        uint balancePositionAfter,
        uint available,
        uint max_spread
    ) external view returns (uint _sellImpactReturned);

    function balanceOfPositionOnMarket(
        address market,
        IThalesAMM.Position position,
        address addressToCheck
    ) external view returns (uint balance);

    function balanceOfPositionsOnMarket(
        address market,
        IThalesAMM.Position position,
        address addressToCheck
    ) external view returns (uint balance, uint balanceOtherSide);

    function getBalanceOfPositionsOnMarket(address market, address addressToCheck)
        external
        view
        returns (uint upBalance, uint downBalance);
}

File 14 of 25 : IPositionalMarket.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.5.16;

import "../interfaces/IPositionalMarketManager.sol";
import "../interfaces/IPosition.sol";
import "../interfaces/IPriceFeed.sol";

interface IPositionalMarket {
    /* ========== TYPES ========== */

    enum Phase {
        Trading,
        Maturity,
        Expiry
    }
    enum Side {
        Up,
        Down
    }

    /* ========== VIEWS / VARIABLES ========== */

    function getOptions() external view returns (IPosition up, IPosition down);

    function times() external view returns (uint maturity, uint destructino);

    function getOracleDetails()
        external
        view
        returns (
            bytes32 key,
            uint strikePrice,
            uint finalPrice
        );

    function fees() external view returns (uint poolFee, uint creatorFee);

    function deposited() external view returns (uint);

    function creator() external view returns (address);

    function resolved() external view returns (bool);

    function phase() external view returns (Phase);

    function oraclePrice() external view returns (uint);

    function oraclePriceAndTimestamp() external view returns (uint price, uint updatedAt);

    function canResolve() external view returns (bool);

    function result() external view returns (Side);

    function balancesOf(address account) external view returns (uint up, uint down);

    function totalSupplies() external view returns (uint up, uint down);

    function getMaximumBurnable(address account) external view returns (uint amount);

    /* ========== MUTATIVE FUNCTIONS ========== */

    function mint(uint value) external;

    function exerciseOptions() external returns (uint);

    function burnOptions(uint amount) external;

    function burnOptionsMaximum() external;
}

File 15 of 25 : IPositionalMarketManager.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.5.16;

import "../interfaces/IPositionalMarket.sol";

interface IPositionalMarketManager {
    /* ========== VIEWS / VARIABLES ========== */

    function durations() external view returns (uint expiryDuration, uint maxTimeToMaturity);

    function capitalRequirement() external view returns (uint);

    function marketCreationEnabled() external view returns (bool);

    function onlyAMMMintingAndBurning() external view returns (bool);

    function transformCollateral(uint value) external view returns (uint);

    function reverseTransformCollateral(uint value) external view returns (uint);

    function totalDeposited() external view returns (uint);

    function numActiveMarkets() external view returns (uint);

    function activeMarkets(uint index, uint pageSize) external view returns (address[] memory);

    function numMaturedMarkets() external view returns (uint);

    function maturedMarkets(uint index, uint pageSize) external view returns (address[] memory);

    function isActiveMarket(address candidate) external view returns (bool);

    function isKnownMarket(address candidate) external view returns (bool);

    function getThalesAMM() external view returns (address);

    /* ========== MUTATIVE FUNCTIONS ========== */

    function createMarket(
        bytes32 oracleKey,
        uint strikePrice,
        uint maturity,
        uint initialMint // initial sUSD to mint options for,
    ) external returns (IPositionalMarket);

    function resolveMarket(address market) external;

    function expireMarkets(address[] calldata market) external;

    function transferSusdTo(
        address sender,
        address receiver,
        uint amount
    ) external;
}

File 16 of 25 : IPosition.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.5.16;

import "./IPositionalMarket.sol";

interface IPosition {
    /* ========== VIEWS / VARIABLES ========== */

    function getBalanceOf(address account) external view returns (uint);

    function getTotalSupply() external view returns (uint);

    function exerciseWithAmount(address claimant, uint amount) external;
}

File 17 of 25 : IStakingThales.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.5.16;

interface IStakingThales {
    function updateVolume(address account, uint amount) external;

    /* ========== VIEWS / VARIABLES ==========  */
    function totalStakedAmount() external view returns (uint);

    function stakedBalanceOf(address account) external view returns (uint);

    function currentPeriodRewards() external view returns (uint);

    function currentPeriodFees() external view returns (uint);

    function getLastPeriodOfClaimedRewards(address account) external view returns (uint);

    function getRewardsAvailable(address account) external view returns (uint);

    function getRewardFeesAvailable(address account) external view returns (uint);

    function getAlreadyClaimedRewards(address account) external view returns (uint);

    function getContractRewardFunds() external view returns (uint);

    function getContractFeeFunds() external view returns (uint);

    function getAMMVolume(address account) external view returns (uint);
}

File 18 of 25 : IReferrals.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16;

interface IReferrals {
    function referrals(address) external view returns (address);

    function sportReferrals(address) external view returns (address);

    function setReferrer(address, address) external;
}

File 19 of 25 : ICurveSUSD.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16;

interface ICurveSUSD {
    function exchange_underlying(
        int128 i,
        int128 j,
        uint256 _dx,
        uint256 _min_dy
    ) external returns (uint256);

    function get_dy_underlying(
        int128 i,
        int128 j,
        uint256 _dx
    ) external view returns (uint256);

    //    @notice Perform an exchange between two underlying coins
    //    @param i Index value for the underlying coin to send
    //    @param j Index valie of the underlying coin to receive
    //    @param _dx Amount of `i` being exchanged
    //    @param _min_dy Minimum amount of `j` to receive
    //    @param _receiver Address that receives `j`
    //    @return Actual amount of `j` received

    // indexes:
    // 0 = sUSD 18 dec 0x8c6f28f2F1A3C87F0f938b96d27520d9751ec8d9
    // 1= DAI 18 dec 0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1
    // 2= USDC 6 dec 0x7F5c764cBc14f9669B88837ca1490cCa17c31607
    // 3= USDT 6 dec 0x94b008aA00579c1307B0EF2c499aD98a8ce58e58
}

File 20 of 25 : ThalesAMMLiquidityPool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";

import "../../utils/proxy/solidity-0.8.0/ProxyReentrancyGuard.sol";
import "../../utils/proxy/solidity-0.8.0/ProxyOwned.sol";
import "@openzeppelin/contracts-4.4.1/proxy/Clones.sol";

import "../../interfaces/IThalesAMM.sol";
import "../../interfaces/IPositionalMarket.sol";
import "../../interfaces/IStakingThales.sol";

import "./ThalesAMMLiquidityPoolRound.sol";

contract ThalesAMMLiquidityPool is Initializable, ProxyOwned, PausableUpgradeable, ProxyReentrancyGuard {
    /* ========== LIBRARIES ========== */
    using SafeERC20Upgradeable for IERC20Upgradeable;

    struct InitParams {
        address _owner;
        IThalesAMM _thalesAMM;
        IERC20Upgradeable _sUSD;
        uint _roundLength;
        uint _maxAllowedDeposit;
        uint _minDepositAmount;
        uint _maxAllowedUsers;
        bool _needsTransformingCollateral;
    }

    /* ========== CONSTANTS ========== */
    uint private constant HUNDRED = 1e20;
    uint private constant ONE = 1e18;
    uint private constant ONE_PERCENT = 1e16;

    /* ========== STATE VARIABLES ========== */

    IThalesAMM public thalesAMM;
    IERC20Upgradeable public sUSD;

    bool public started;

    uint public round;
    uint public roundLength;
    uint public firstRoundStartTime;

    mapping(uint => address) public roundPools;

    mapping(uint => address[]) public usersPerRound;
    mapping(uint => mapping(address => bool)) public userInRound;

    mapping(uint => mapping(address => uint)) public balancesPerRound;
    mapping(uint => uint) public allocationPerRound;

    mapping(address => bool) public withdrawalRequested;

    mapping(uint => address[]) public tradingMarketsPerRound;
    mapping(uint => mapping(address => bool)) public isTradingMarketInARound;

    mapping(uint => uint) public profitAndLossPerRound;
    mapping(uint => uint) public cumulativeProfitAndLoss;

    uint public maxAllowedDeposit;
    uint public minDepositAmount;
    uint public maxAllowedUsers;
    uint public usersCurrentlyInPool;

    address public defaultLiquidityProvider;

    IStakingThales public stakingThales;

    uint public stakedThalesMultiplier;

    address public poolRoundMastercopy;

    mapping(address => bool) public whitelistedDeposits;

    uint public totalDeposited;

    bool public onlyWhitelistedStakersAllowed;

    mapping(address => bool) public whitelistedStakers;

    bool public needsTransformingCollateral;

    mapping(uint => mapping(address => bool)) public marketAlreadyExercisedInRound;

    bool public roundClosingPrepared;

    uint public usersProcessedInRound;

    uint public marketsProcessedInRound;

    mapping(address => uint) public withdrawalShare;

    /* ========== CONSTRUCTOR ========== */

    function initialize(InitParams calldata params) external initializer {
        setOwner(params._owner);
        initNonReentrant();
        thalesAMM = IThalesAMM(params._thalesAMM);

        sUSD = params._sUSD;
        roundLength = params._roundLength;
        maxAllowedDeposit = params._maxAllowedDeposit;
        minDepositAmount = params._minDepositAmount;
        maxAllowedUsers = params._maxAllowedUsers;

        needsTransformingCollateral = params._needsTransformingCollateral;

        sUSD.approve(address(thalesAMM), type(uint256).max);
    }

    /// @notice Start pool and begin round #1
    function start() external onlyOwner {
        require(!started, "Liquidity pool has already started");
        require(allocationPerRound[1] > 0, "can not start with 0 deposits");

        firstRoundStartTime = block.timestamp;
        round = 1;

        address roundPool = _getOrCreateRoundPool(1);
        ThalesAMMLiquidityPoolRound(roundPool).updateRoundTimes(firstRoundStartTime, getRoundEndTime(1));

        started = true;
        emit PoolStarted();
    }

    /// @notice Deposit funds from user into pool for the next round
    /// @param amount Value to be deposited
    function deposit(uint amount) external canDeposit(amount) nonReentrant whenNotPaused roundClosingNotPrepared {
        uint nextRound = round + 1;
        address roundPool = _getOrCreateRoundPool(nextRound);
        sUSD.safeTransferFrom(msg.sender, roundPool, amount);

        if (!whitelistedDeposits[msg.sender]) {
            require(!onlyWhitelistedStakersAllowed || whitelistedStakers[msg.sender], "Only whitelisted stakers allowed");
            require(address(stakingThales) != address(0), "Staking Thales not set");
            require(
                (balancesPerRound[round][msg.sender] + amount + balancesPerRound[nextRound][msg.sender]) <=
                    _transformCollateral((stakingThales.stakedBalanceOf(msg.sender) * stakedThalesMultiplier) / ONE),
                "Not enough staked THALES"
            );
        }

        require(msg.sender != defaultLiquidityProvider, "Can't deposit directly as default liquidity provider");

        // new user enters the pool
        if (balancesPerRound[round][msg.sender] == 0 && balancesPerRound[nextRound][msg.sender] == 0) {
            require(usersCurrentlyInPool < maxAllowedUsers, "Max amount of users reached");
            usersPerRound[nextRound].push(msg.sender);
            userInRound[nextRound][msg.sender] = true;
            usersCurrentlyInPool = usersCurrentlyInPool + 1;
        }

        balancesPerRound[nextRound][msg.sender] += amount;

        allocationPerRound[nextRound] += amount;
        totalDeposited += amount;

        if (address(stakingThales) != address(0)) {
            stakingThales.updateVolume(msg.sender, amount);
        }

        emit Deposited(msg.sender, amount, round);
    }

    /// @notice get sUSD to mint for buy and store market as trading in the round
    /// @param market to trade
    /// @param amountToMint amount to get for mint
    function commitTrade(address market, uint amountToMint)
        external
        nonReentrant
        whenNotPaused
        onlyAMM
        roundClosingNotPrepared
    {
        require(started, "Pool has not started");
        require(amountToMint > 0, "Can't commit a zero trade");

        amountToMint = _transformCollateral(amountToMint);
        // add 1e-6 due to rounding issue, will be sent back to AMM at the end
        amountToMint = needsTransformingCollateral ? amountToMint + 1 : amountToMint;

        uint marketRound = getMarketRound(market);
        address liquidityPoolRound = _getOrCreateRoundPool(marketRound);

        if (marketRound == round) {
            sUSD.safeTransferFrom(liquidityPoolRound, address(thalesAMM), amountToMint);
        } else {
            uint poolBalance = sUSD.balanceOf(liquidityPoolRound);
            if (poolBalance >= amountToMint) {
                sUSD.safeTransferFrom(liquidityPoolRound, address(thalesAMM), amountToMint);
            } else {
                uint differenceToLPAsDefault = amountToMint - poolBalance;
                _depositAsDefault(differenceToLPAsDefault, liquidityPoolRound, marketRound);
                sUSD.safeTransferFrom(liquidityPoolRound, address(thalesAMM), amountToMint);
            }
        }

        if (!isTradingMarketInARound[marketRound][market]) {
            tradingMarketsPerRound[marketRound].push(market);
            isTradingMarketInARound[marketRound][market] = true;
        }
    }

    /// @notice get options that are in the LP into the AMM for the buy tx
    /// @param market to get options for
    /// @param optionsAmount to get options for
    /// @param position to get options for
    function getOptionsForBuy(
        address market,
        uint optionsAmount,
        IThalesAMM.Position position
    ) external nonReentrant whenNotPaused onlyAMM roundClosingNotPrepared {
        if (optionsAmount > 0) {
            require(started, "Pool has not started");

            uint marketRound = getMarketRound(market);
            address liquidityPoolRound = _getOrCreateRoundPool(marketRound);

            (IPosition up, IPosition down) = IPositionalMarket(market).getOptions();
            IPosition target = position == IThalesAMM.Position.Up ? up : down;

            ThalesAMMLiquidityPoolRound(liquidityPoolRound).moveOptions(
                IERC20Upgradeable(address(target)),
                optionsAmount,
                address(thalesAMM)
            );
        }
    }

    /// @notice get options that are in the LP into the AMM for the buy tx
    /// @param market to get options for
    /// @param optionsAmount to get options for
    /// @param position to get options for
    function getOptionsForBuyByAddress(
        address market,
        uint optionsAmount,
        address position
    ) external nonReentrant whenNotPaused onlyAMM roundClosingNotPrepared {
        if (optionsAmount > 0) {
            require(started, "Pool has not started");

            uint marketRound = getMarketRound(market);
            address liquidityPoolRound = _getOrCreateRoundPool(marketRound);

            ThalesAMMLiquidityPoolRound(liquidityPoolRound).moveOptions(
                IERC20Upgradeable(position),
                optionsAmount,
                address(thalesAMM)
            );
        }
    }

    /// @notice Create a round pool by market maturity date if it doesnt already exist
    /// @param market to use
    /// @return roundPool the pool for the passed market
    function getOrCreateMarketPool(address market)
        external
        onlyAMM
        nonReentrant
        whenNotPaused
        roundClosingNotPrepared
        returns (address roundPool)
    {
        uint marketRound = getMarketRound(market);
        roundPool = _getOrCreateRoundPool(marketRound);
    }

    /// @notice request withdrawal from the LP
    function withdrawalRequest() external nonReentrant canWithdraw whenNotPaused roundClosingNotPrepared {
        if (totalDeposited > balancesPerRound[round][msg.sender]) {
            totalDeposited -= balancesPerRound[round][msg.sender];
        } else {
            totalDeposited = 0;
        }

        usersCurrentlyInPool = usersCurrentlyInPool - 1;
        withdrawalRequested[msg.sender] = true;
        emit WithdrawalRequested(msg.sender);
    }

    /// @notice request partial withdrawal from the LP.
    /// @param share the percentage the user is wihdrawing from his total deposit
    function partialWithdrawalRequest(uint share) external nonReentrant canWithdraw whenNotPaused roundClosingNotPrepared {
        require(share >= ONE_PERCENT * 10 && share <= ONE_PERCENT * 90, "Share has to be between 10% and 90%");

        uint toWithdraw = (balancesPerRound[round][msg.sender] * share) / ONE;
        if (totalDeposited > toWithdraw) {
            totalDeposited -= toWithdraw;
        } else {
            totalDeposited = 0;
        }

        withdrawalRequested[msg.sender] = true;
        withdrawalShare[msg.sender] = share;
        emit WithdrawalRequested(msg.sender);
    }

    /// @notice Prepare round closing
    /// excercise options of trading markets and ensure there are no markets left unresolved
    function prepareRoundClosing() external nonReentrant whenNotPaused roundClosingNotPrepared {
        require(canCloseCurrentRound(), "Can't close current round");
        // excercise market options
        exerciseMarketsReadyToExercised();

        address roundPool = roundPools[round];
        // final balance is the final amount of sUSD in the round pool
        uint currentBalance = sUSD.balanceOf(roundPool);
        // calculate PnL

        // if no allocation for current round
        if (allocationPerRound[round] == 0) {
            profitAndLossPerRound[round] = 1;
        } else {
            profitAndLossPerRound[round] = (currentBalance * ONE) / allocationPerRound[round];
        }

        roundClosingPrepared = true;

        emit RoundClosingPrepared(round);
    }

    /// @notice Prepare round closing
    /// excercise options of trading markets and ensure there are no markets left unresolved
    function processRoundClosingBatch(uint batchSize) external nonReentrant whenNotPaused {
        require(roundClosingPrepared, "Round closing not prepared");
        require(usersProcessedInRound < usersPerRound[round].length, "All users already processed");
        require(batchSize > 0, "batchSize has to be greater than 0");

        address roundPool = roundPools[round];

        uint endCursor = usersProcessedInRound + batchSize;
        if (endCursor > usersPerRound[round].length) {
            endCursor = usersPerRound[round].length;
        }

        for (uint i = usersProcessedInRound; i < endCursor; i++) {
            address user = usersPerRound[round][i];
            uint balanceAfterCurRound = (balancesPerRound[round][user] * profitAndLossPerRound[round]) / ONE;
            if (!withdrawalRequested[user] && (profitAndLossPerRound[round] > 0)) {
                balancesPerRound[round + 1][user] = balancesPerRound[round + 1][user] + balanceAfterCurRound;
                usersPerRound[round + 1].push(user);
                if (address(stakingThales) != address(0)) {
                    stakingThales.updateVolume(user, balanceAfterCurRound);
                }
            } else {
                if (withdrawalShare[user] > 0) {
                    uint amountToClaim = (balanceAfterCurRound * withdrawalShare[user]) / ONE;
                    sUSD.safeTransferFrom(roundPool, user, amountToClaim);
                    emit Claimed(user, amountToClaim);
                    withdrawalRequested[user] = false;
                    withdrawalShare[user] = 0;
                    usersPerRound[round + 1].push(user);
                    balancesPerRound[round + 1][user] = balanceAfterCurRound - amountToClaim;
                } else {
                    balancesPerRound[round + 1][user] = 0;
                    sUSD.safeTransferFrom(roundPool, user, balanceAfterCurRound);
                    withdrawalRequested[user] = false;
                    emit Claimed(user, balanceAfterCurRound);
                }
            }
            usersProcessedInRound = usersProcessedInRound + 1;
        }

        emit RoundClosingBatchProcessed(round, batchSize);
    }

    /// @notice Close current round and begin next round,
    /// calculate profit and loss and process withdrawals
    function closeRound() external nonReentrant whenNotPaused {
        require(roundClosingPrepared, "Round closing not prepared");
        require(usersProcessedInRound == usersPerRound[round].length, "Not all users processed yet");
        // set for next round to false
        roundClosingPrepared = false;

        address roundPool = roundPools[round];

        //always claim for defaultLiquidityProvider
        if (balancesPerRound[round][defaultLiquidityProvider] > 0) {
            uint balanceAfterCurRound = (balancesPerRound[round][defaultLiquidityProvider] * profitAndLossPerRound[round]) /
                ONE;
            sUSD.safeTransferFrom(roundPool, defaultLiquidityProvider, balanceAfterCurRound);
            emit Claimed(defaultLiquidityProvider, balanceAfterCurRound);
        }

        if (round == 1) {
            cumulativeProfitAndLoss[round] = profitAndLossPerRound[round];
        } else {
            cumulativeProfitAndLoss[round] = (cumulativeProfitAndLoss[round - 1] * profitAndLossPerRound[round]) / ONE;
        }

        // start next round
        round += 1;

        //add all carried over sUSD
        allocationPerRound[round] += sUSD.balanceOf(roundPool);

        totalDeposited = allocationPerRound[round] - balancesPerRound[round][defaultLiquidityProvider];

        address roundPoolNewRound = _getOrCreateRoundPool(round);

        sUSD.safeTransferFrom(roundPool, roundPoolNewRound, sUSD.balanceOf(roundPool));

        usersProcessedInRound = 0;

        emit RoundClosed(round - 1, profitAndLossPerRound[round - 1]);
    }

    /// @notice Iterate all markets in the current round and exercise those ready to be exercised
    function exerciseMarketsReadyToExercised() public roundClosingNotPrepared {
        ThalesAMMLiquidityPoolRound poolRound = ThalesAMMLiquidityPoolRound(roundPools[round]);
        IPositionalMarket market;
        for (uint i = 0; i < tradingMarketsPerRound[round].length; i++) {
            address marketAddress = tradingMarketsPerRound[round][i];
            if (!marketAlreadyExercisedInRound[round][marketAddress]) {
                market = IPositionalMarket(marketAddress);
                if (market.resolved()) {
                    poolRound.exerciseMarketReadyToExercised(market);
                    marketAlreadyExercisedInRound[round][marketAddress] = true;
                }
            }
        }
    }

    /// @notice Exercises markets in a round
    /// @param batchSize number of markets to be processed
    function exerciseMarketsReadyToExercisedBatch(uint batchSize)
        external
        nonReentrant
        whenNotPaused
        roundClosingNotPrepared
    {
        require(batchSize > 0, "batchSize has to be greater than 0");

        ThalesAMMLiquidityPoolRound poolRound = ThalesAMMLiquidityPoolRound(roundPools[round]);
        uint count = 0;
        IPositionalMarket market;
        for (uint i = 0; i < tradingMarketsPerRound[round].length; i++) {
            if (count == batchSize) break;
            address marketAddress = tradingMarketsPerRound[round][i];
            if (!marketAlreadyExercisedInRound[round][marketAddress]) {
                market = IPositionalMarket(marketAddress);
                if (market.resolved()) {
                    poolRound.exerciseMarketReadyToExercised(market);
                    marketAlreadyExercisedInRound[round][marketAddress] = true;
                    count += 1;
                }
            }
        }
    }

    /* ========== VIEWS ========== */

    /// @notice whether the user is currently LPing
    /// @param user to check
    /// @return isUserInLP whether the user is currently LPing
    function isUserLPing(address user) external view returns (bool isUserInLP) {
        isUserInLP =
            (balancesPerRound[round][user] > 0 || balancesPerRound[round + 1][user] > 0) &&
            (!withdrawalRequested[user] || withdrawalShare[user] > 0);
    }

    /// @notice Return the maximum amount the user can deposit now
    /// @param user address to check
    /// @return maxDepositForUser the maximum amount the user can deposit in total including already deposited
    /// @return availableToDepositForUser the maximum amount the user can deposit now
    /// @return stakedThalesForUser how much THALES the user has staked
    function getMaxAvailableDepositForUser(address user)
        external
        view
        returns (
            uint maxDepositForUser,
            uint availableToDepositForUser,
            uint stakedThalesForUser
        )
    {
        uint nextRound = round + 1;
        stakedThalesForUser = stakingThales.stakedBalanceOf(user);
        maxDepositForUser = _transformCollateral((stakedThalesForUser * stakedThalesMultiplier) / ONE);
        availableToDepositForUser = maxDepositForUser > (balancesPerRound[round][user] + balancesPerRound[nextRound][user])
            ? (maxDepositForUser - balancesPerRound[round][user] - balancesPerRound[nextRound][user])
            : 0;
    }

    /// @notice Return how much the user needs to have staked to withdraw
    /// @param user address to check
    /// @return neededStaked how much the user needs to have staked to withdraw
    function getNeededStakedThalesToWithdrawForUser(address user) external view returns (uint neededStaked) {
        uint nextRound = round + 1;
        neededStaked =
            _reverseTransformCollateral((balancesPerRound[round][user] + balancesPerRound[nextRound][user]) * ONE) /
            stakedThalesMultiplier;
    }

    /// @notice get the pool address for the market
    /// @param market to check
    /// @return roundPool the pool address for the market
    function getMarketPool(address market) external view returns (address roundPool) {
        roundPool = roundPools[getMarketRound(market)];
    }

    /// @notice Checks if all conditions are met to close the round
    /// @return bool
    function canCloseCurrentRound() public view returns (bool) {
        if (!started || block.timestamp < getRoundEndTime(round)) {
            return false;
        }
        IPositionalMarket market;
        for (uint i = 0; i < tradingMarketsPerRound[round].length; i++) {
            address marketAddress = tradingMarketsPerRound[round][i];
            if (!marketAlreadyExercisedInRound[round][marketAddress]) {
                market = IPositionalMarket(marketAddress);
                if (!market.resolved()) {
                    return false;
                }
            }
        }
        return true;
    }

    /// @notice Iterate all markets in the current round and return true if at least one can be exercised
    function hasMarketsReadyToBeExercised() public view returns (bool) {
        ThalesAMMLiquidityPoolRound poolRound = ThalesAMMLiquidityPoolRound(roundPools[round]);
        IPositionalMarket market;
        for (uint i = 0; i < tradingMarketsPerRound[round].length; i++) {
            address marketAddress = tradingMarketsPerRound[round][i];
            if (!marketAlreadyExercisedInRound[round][marketAddress]) {
                market = IPositionalMarket(marketAddress);
                if (market.resolved()) {
                    (uint upBalance, uint downBalance) = market.balancesOf(address(poolRound));
                    if (upBalance > 0 || downBalance > 0) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /// @notice Return multiplied PnLs between rounds
    /// @param roundA Round number from
    /// @param roundB Round number to
    /// @return uint
    function cumulativePnLBetweenRounds(uint roundA, uint roundB) public view returns (uint) {
        return (cumulativeProfitAndLoss[roundB] * profitAndLossPerRound[roundA]) / cumulativeProfitAndLoss[roundA];
    }

    /// @notice Return the start time of the passed round
    /// @param _round number
    /// @return uint the start time of the given round
    function getRoundStartTime(uint _round) public view returns (uint) {
        return firstRoundStartTime + (_round - 1) * roundLength;
    }

    /// @notice Return the end time of the passed round
    /// @param _round number
    /// @return uint the end time of the given round
    function getRoundEndTime(uint _round) public view returns (uint) {
        return firstRoundStartTime + _round * roundLength;
    }

    /// @notice Return the round to which a market belongs to
    /// @param market to get the round for
    /// @return _round the round which the market belongs to
    function getMarketRound(address market) public view returns (uint _round) {
        IPositionalMarket marketContract = IPositionalMarket(market);
        (uint maturity, ) = marketContract.times();
        if (maturity > firstRoundStartTime) {
            _round = (maturity - firstRoundStartTime) / roundLength + 1;
        } else {
            _round = 1;
        }
    }

    /// @notice Return the count of users in current round
    /// @return _the count of users in current round
    function getUsersCountInCurrentRound() external view returns (uint) {
        return usersPerRound[round].length;
    }

    /* ========== INTERNAL FUNCTIONS ========== */

    function _transformCollateral(uint value) internal view returns (uint) {
        if (needsTransformingCollateral) {
            return value / 1e12;
        } else {
            return value;
        }
    }

    function _reverseTransformCollateral(uint value) internal view returns (uint) {
        if (needsTransformingCollateral) {
            return value * 1e12;
        } else {
            return value;
        }
    }

    function _depositAsDefault(
        uint amount,
        address roundPool,
        uint _round
    ) internal {
        require(defaultLiquidityProvider != address(0), "default liquidity provider not set");

        sUSD.safeTransferFrom(defaultLiquidityProvider, roundPool, amount);

        balancesPerRound[_round][defaultLiquidityProvider] += amount;
        allocationPerRound[_round] += amount;

        emit Deposited(defaultLiquidityProvider, amount, _round);
    }

    function _getOrCreateRoundPool(uint _round) internal returns (address roundPool) {
        roundPool = roundPools[_round];
        if (roundPool == address(0)) {
            require(poolRoundMastercopy != address(0), "Round pool mastercopy not set");
            ThalesAMMLiquidityPoolRound newRoundPool = ThalesAMMLiquidityPoolRound(Clones.clone(poolRoundMastercopy));
            newRoundPool.initialize(address(this), sUSD, _round, getRoundEndTime(_round - 1), getRoundEndTime(_round));
            roundPool = address(newRoundPool);
            roundPools[_round] = roundPool;
            emit RoundPoolCreated(_round, roundPool);
        }
    }

    /* ========== SETTERS ========== */

    function setPaused(bool _setPausing) external onlyOwner {
        _setPausing ? _pause() : _unpause();
    }

    /// @notice Set onlyWhitelistedStakersAllowed variable
    /// @param flagToSet self explanatory
    function setOnlyWhitelistedStakersAllowed(bool flagToSet) external onlyOwner {
        onlyWhitelistedStakersAllowed = flagToSet;
        emit SetOnlyWhitelistedStakersAllowed(flagToSet);
    }

    /// @notice Set _poolRoundMastercopy
    /// @param _poolRoundMastercopy to clone round pools from
    function setPoolRoundMastercopy(address _poolRoundMastercopy) external onlyOwner {
        require(_poolRoundMastercopy != address(0), "Can not set a zero address!");
        poolRoundMastercopy = _poolRoundMastercopy;
        emit PoolRoundMastercopyChanged(poolRoundMastercopy);
    }

    /// @notice Set _stakedThalesMultiplier
    /// @param _stakedThalesMultiplier the number of sUSD one can deposit per THALES staked
    function setStakedThalesMultiplier(uint _stakedThalesMultiplier) external onlyOwner {
        stakedThalesMultiplier = _stakedThalesMultiplier;
        emit StakedThalesMultiplierChanged(_stakedThalesMultiplier);
    }

    /// @notice Set IStakingThales contract
    /// @param _stakingThales IStakingThales address
    function setStakingThales(IStakingThales _stakingThales) external onlyOwner {
        stakingThales = _stakingThales;
        emit StakingThalesChanged(address(_stakingThales));
    }

    /// @notice Set max allowed deposit
    /// @param _maxAllowedDeposit Deposit value
    function setMaxAllowedDeposit(uint _maxAllowedDeposit) external onlyOwner {
        maxAllowedDeposit = _maxAllowedDeposit;
        emit MaxAllowedDepositChanged(_maxAllowedDeposit);
    }

    /// @notice Set min allowed deposit
    /// @param _minDepositAmount Deposit value
    function setMinAllowedDeposit(uint _minDepositAmount) external onlyOwner {
        minDepositAmount = _minDepositAmount;
        emit MinAllowedDepositChanged(_minDepositAmount);
    }

    /// @notice Set _maxAllowedUsers
    /// @param _maxAllowedUsers Deposit value
    function setMaxAllowedUsers(uint _maxAllowedUsers) external onlyOwner {
        maxAllowedUsers = _maxAllowedUsers;
        emit MaxAllowedUsersChanged(_maxAllowedUsers);
    }

    /// @notice Set ThalesAMM contract
    /// @param _thalesAMM ThalesAMM address
    function setThalesAmm(IThalesAMM _thalesAMM) external onlyOwner {
        require(address(_thalesAMM) != address(0), "Can not set a zero address!");
        thalesAMM = _thalesAMM;
        sUSD.approve(address(thalesAMM), type(uint256).max);
        emit ThalesAMMChanged(address(_thalesAMM));
    }

    /// @notice Set defaultLiquidityProvider wallet
    /// @param _defaultLiquidityProvider default liquidity provider
    function setDefaultLiquidityProvider(address _defaultLiquidityProvider) external onlyOwner {
        require(_defaultLiquidityProvider != address(0), "Can not set a zero address!");
        defaultLiquidityProvider = _defaultLiquidityProvider;
        emit DefaultLiquidityProviderChanged(_defaultLiquidityProvider);
    }

    /// @notice Set length of rounds
    /// @param _roundLength Length of a round in miliseconds
    function setRoundLength(uint _roundLength) external onlyOwner {
        require(!started, "Can't change round length after start");
        roundLength = _roundLength;
        emit RoundLengthChanged(_roundLength);
    }

    /// @notice set addresses which can deposit into the AMM bypassing the staking checks
    /// @param _whitelistedAddresses Addresses to set the whitelist flag for
    /// @param _flag to set
    function setWhitelistedAddresses(address[] calldata _whitelistedAddresses, bool _flag) external onlyOwner {
        require(_whitelistedAddresses.length > 0, "Whitelisted addresses cannot be empty");
        for (uint256 index = 0; index < _whitelistedAddresses.length; index++) {
            // only if current flag is different, if same skip it
            if (whitelistedDeposits[_whitelistedAddresses[index]] != _flag) {
                whitelistedDeposits[_whitelistedAddresses[index]] = _flag;
                emit AddedIntoWhitelist(_whitelistedAddresses[index], _flag);
            }
        }
    }

    /// @notice set addresses which can deposit into the AMM when only whitelisted stakers are allowed
    /// @param _whitelistedAddresses Addresses to set the whitelist flag for
    /// @param _flag to set
    function setWhitelistedStakerAddresses(address[] calldata _whitelistedAddresses, bool _flag) external onlyOwner {
        require(_whitelistedAddresses.length > 0, "Whitelisted addresses cannot be empty");
        for (uint256 index = 0; index < _whitelistedAddresses.length; index++) {
            // only if current flag is different, if same skip it
            if (whitelistedStakers[_whitelistedAddresses[index]] != _flag) {
                whitelistedStakers[_whitelistedAddresses[index]] = _flag;
                emit AddedIntoWhitelistStaker(_whitelistedAddresses[index], _flag);
            }
        }
    }

    /* ========== MODIFIERS ========== */

    modifier canDeposit(uint amount) {
        require(!withdrawalRequested[msg.sender], "Withdrawal is requested, cannot deposit");
        require(amount >= minDepositAmount, "Amount less than minDepositAmount");
        require(totalDeposited + amount <= maxAllowedDeposit, "Deposit amount exceeds AMM LP cap");
        _;
    }

    modifier canWithdraw() {
        require(started, "Pool has not started");
        require(!withdrawalRequested[msg.sender], "Withdrawal already requested");
        require(balancesPerRound[round][msg.sender] > 0, "Nothing to withdraw");
        require(balancesPerRound[round + 1][msg.sender] == 0, "Can't withdraw as you already deposited for next round");
        _;
    }

    modifier onlyAMM() {
        require(msg.sender == address(thalesAMM), "only the AMM may perform these methods");
        _;
    }

    modifier roundClosingNotPrepared() {
        require(!roundClosingPrepared, "Not allowed during roundClosingPrepared");
        _;
    }

    /* ========== EVENTS ========== */
    event PoolStarted();
    event Deposited(address user, uint amount, uint round);
    event WithdrawalRequested(address user);
    event RoundClosed(uint round, uint roundPnL);
    event Claimed(address user, uint amount);
    event RoundPoolCreated(uint _round, address roundPool);
    event PoolRoundMastercopyChanged(address newMastercopy);
    event StakedThalesMultiplierChanged(uint _stakedThalesMultiplier);
    event StakingThalesChanged(address stakingThales);
    event MaxAllowedDepositChanged(uint maxAllowedDeposit);
    event MinAllowedDepositChanged(uint minAllowedDeposit);
    event MaxAllowedUsersChanged(uint MaxAllowedUsersChanged);
    event ThalesAMMChanged(address thalesAMM);
    event DefaultLiquidityProviderChanged(address newProvider);
    event AddedIntoWhitelist(address _whitelistAddress, bool _flag);
    event AddedIntoWhitelistStaker(address _whitelistAddress, bool _flag);
    event RoundLengthChanged(uint roundLength);
    event SetOnlyWhitelistedStakersAllowed(bool flagToSet);
    event RoundClosingPrepared(uint round);
    event RoundClosingBatchProcessed(uint round, uint batchSize);
}

File 21 of 25 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)

pragma solidity ^0.8.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;
        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");

        (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");

        (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");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal 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

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 22 of 25 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

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

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
    uint256[50] private __gap;
}

File 23 of 25 : IThalesAMM.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16;

import "./IPriceFeed.sol";

interface IThalesAMM {
    enum Position {
        Up,
        Down
    }

    function manager() external view returns (address);

    function availableToBuyFromAMM(address market, Position position) external view returns (uint);

    function impliedVolatilityPerAsset(bytes32 oracleKey) external view returns (uint);

    function buyFromAmmQuote(
        address market,
        Position position,
        uint amount
    ) external view returns (uint);

    function buyFromAMM(
        address market,
        Position position,
        uint amount,
        uint expectedPayout,
        uint additionalSlippage
    ) external returns (uint);

    function availableToSellToAMM(address market, Position position) external view returns (uint);

    function sellToAmmQuote(
        address market,
        Position position,
        uint amount
    ) external view returns (uint);

    function sellToAMM(
        address market,
        Position position,
        uint amount,
        uint expectedPayout,
        uint additionalSlippage
    ) external returns (uint);

    function isMarketInAMMTrading(address market) external view returns (bool);

    function price(address market, Position position) external view returns (uint);

    function buyPriceImpact(
        address market,
        Position position,
        uint amount
    ) external view returns (int);

    function priceFeed() external view returns (IPriceFeed);
}

File 24 of 25 : Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/Clones.sol)

pragma solidity ^0.8.0;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, implementation))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            instance := create(0, ptr, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, implementation))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            instance := create2(0, ptr, 0x37, salt)
        }
        require(instance != address(0), "ERC1167: create2 failed");
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, implementation))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
            mstore(add(ptr, 0x38), shl(0x60, deployer))
            mstore(add(ptr, 0x4c), salt)
            mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
            predicted := keccak256(add(ptr, 0x37), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(address implementation, bytes32 salt)
        internal
        view
        returns (address predicted)
    {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

File 25 of 25 : ThalesAMMLiquidityPoolRound.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";

import "../../interfaces/IPositionalMarket.sol";

import "./ThalesAMMLiquidityPool.sol";

contract ThalesAMMLiquidityPoolRound {
    /* ========== LIBRARIES ========== */
    using SafeERC20Upgradeable for IERC20Upgradeable;

    /* ========== STATE VARIABLES ========== */

    ThalesAMMLiquidityPool public liquidityPool;
    IERC20Upgradeable public sUSD;

    uint public round;
    uint public roundStartTime;
    uint public roundEndTime;

    /* ========== CONSTRUCTOR ========== */

    bool public initialized;

    function initialize(
        address _liquidityPool,
        IERC20Upgradeable _sUSD,
        uint _round,
        uint _roundStartTime,
        uint _roundEndTime
    ) external {
        require(!initialized, "Already initialized");
        initialized = true;
        liquidityPool = ThalesAMMLiquidityPool(_liquidityPool);
        sUSD = _sUSD;
        round = _round;
        roundStartTime = _roundStartTime;
        roundEndTime = _roundEndTime;
        sUSD.approve(_liquidityPool, type(uint256).max);
    }

    function updateRoundTimes(uint _roundStartTime, uint _roundEndTime) external onlyLiquidityPool {
        roundStartTime = _roundStartTime;
        roundEndTime = _roundEndTime;
        emit RoundTimesUpdated(_roundStartTime, _roundEndTime);
    }

    function exerciseMarketReadyToExercised(IPositionalMarket market) external onlyLiquidityPool {
        if (market.resolved()) {
            (uint upBalance, uint downBalance) = market.balancesOf(address(this));
            if (upBalance > 0 || downBalance > 0) {
                market.exerciseOptions();
            }
        }
    }

    function moveOptions(
        IERC20Upgradeable option,
        uint optionsAmount,
        address destination
    ) external onlyLiquidityPool {
        option.safeTransfer(destination, optionsAmount);
    }

    modifier onlyLiquidityPool() {
        require(msg.sender == address(liquidityPool), "only the Pool manager may perform these methods");
        _;
    }

    event RoundTimesUpdated(uint _roundStartTime, uint _roundEndTime);
}

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

Contract Security Audit

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"buyer","type":"address"},{"indexed":false,"internalType":"address","name":"market","type":"address"},{"indexed":false,"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sUSDPaid","type":"uint256"},{"indexed":false,"internalType":"address","name":"susd","type":"address"},{"indexed":false,"internalType":"address","name":"asset","type":"address"}],"name":"BoughtFromAmm","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"buyer","type":"address"},{"indexed":false,"internalType":"uint256","name":"sUSDPaid","type":"uint256"},{"indexed":false,"internalType":"bool","name":"inTheMoney","type":"bool"}],"name":"BoughtOptionType","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"buyer","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sUSDPaid","type":"uint256"}],"name":"BoughtWithDiscount","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerNominated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"isPaused","type":"bool"}],"name":"PauseChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"refferer","type":"address"},{"indexed":false,"internalType":"address","name":"trader","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"volume","type":"uint256"}],"name":"ReferrerPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"asset","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"_cap","type":"uint256"}],"name":"SetCapPerAsset","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"asset","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"_impliedVolatility","type":"uint256"}],"name":"SetImpliedVolatilityPerAsset","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_spread","type":"uint256"}],"name":"SetMaxSpread","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"minPrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"maxPrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"capPerMarket","type":"uint256"}],"name":"SetMinMaxSupportedPriceCapPerMarket","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_spread","type":"uint256"}],"name":"SetMinSpread","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_minimalTimeLeftToMaturity","type":"uint256"}],"name":"SetMinimalTimeLeftToMaturity","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_manager","type":"address"}],"name":"SetPositionalMarketManager","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_priceFeed","type":"address"}],"name":"SetPriceFeed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sUSD","type":"address"}],"name":"SetSUSD","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_safeBox","type":"address"}],"name":"SetSafeBox","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_safeBoxImpact","type":"uint256"}],"name":"SetSafeBoxImpact","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"seller","type":"address"},{"indexed":false,"internalType":"address","name":"market","type":"address"},{"indexed":false,"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sUSDPaid","type":"uint256"},{"indexed":false,"internalType":"address","name":"susd","type":"address"},{"indexed":false,"internalType":"address","name":"asset","type":"address"}],"name":"SoldToAMM","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"}],"name":"availableToBuyFromAMM","outputs":[{"internalType":"uint256","name":"_available","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"}],"name":"availableToSellToAMM","outputs":[{"internalType":"uint256","name":"_available","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"expectedPayout","type":"uint256"},{"internalType":"uint256","name":"additionalSlippage","type":"uint256"}],"name":"buyFromAMM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"expectedPayout","type":"uint256"},{"internalType":"uint256","name":"additionalSlippage","type":"uint256"},{"internalType":"address","name":"collateral","type":"address"},{"internalType":"address","name":"_referrer","type":"address"}],"name":"buyFromAMMWithDifferentCollateralAndReferrer","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"expectedPayout","type":"uint256"},{"internalType":"uint256","name":"additionalSlippage","type":"uint256"},{"internalType":"address","name":"_referrer","type":"address"}],"name":"buyFromAMMWithReferrer","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"buyFromAmmQuote","outputs":[{"internalType":"uint256","name":"_quote","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"collateral","type":"address"}],"name":"buyFromAmmQuoteWithDifferentCollateral","outputs":[{"internalType":"uint256","name":"collateralQuote","type":"uint256"},{"internalType":"uint256","name":"sUSDToPay","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"buyPriceImpact","outputs":[{"internalType":"int256","name":"_priceImpact","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"capPerMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"curveOnrampEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"curveSUSD","outputs":[{"internalType":"contract ICurveSUSD","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dai","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"asset","type":"bytes32"}],"name":"getCapPerAsset","outputs":[{"internalType":"uint256","name":"_cap","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"impliedVolatilityPerAsset","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initNonReentrant","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"contract IPriceFeed","name":"_priceFeed","type":"address"},{"internalType":"contract IERC20Upgradeable","name":"_sUSD","type":"address"},{"internalType":"uint256","name":"_capPerMarket","type":"uint256"},{"internalType":"address","name":"_deciMath","type":"address"},{"internalType":"uint256","name":"_min_spread","type":"uint256"},{"internalType":"uint256","name":"_max_spread","type":"uint256"},{"internalType":"uint256","name":"_minimalTimeLeftToMaturity","type":"uint256"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"isMarketInAMMTrading","outputs":[{"internalType":"bool","name":"isTrading","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastPauseTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidityPool","outputs":[{"internalType":"contract ThalesAMMLiquidityPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxAllowedPegSlippagePercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxSupportedPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"max_spread","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minSupportedPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"min_spread","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"min_spreadPerAddress","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minimalTimeLeftToMaturity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"nominateNewOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"nominatedOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"}],"name":"price","outputs":[{"internalType":"uint256","name":"priceToReturn","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"priceFeed","outputs":[{"internalType":"contract IPriceFeed","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"referrals","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"referrerFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"retrieveSUSDAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sUSD","outputs":[{"internalType":"contract IERC20Upgradeable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"safeBox","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"safeBoxFeePerAddress","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"safeBoxImpact","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"sellPriceImpact","outputs":[{"internalType":"uint256","name":"_impact","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"expectedPayout","type":"uint256"},{"internalType":"uint256","name":"additionalSlippage","type":"uint256"}],"name":"sellToAMM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"enum IThalesAMM.Position","name":"position","type":"uint8"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"sellToAmmQuote","outputs":[{"internalType":"uint256","name":"_quote","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IThalesAMMUtils","name":"_ammUtils","type":"address"}],"name":"setAmmUtils","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"asset","type":"bytes32"},{"internalType":"uint256","name":"_cap","type":"uint256"}],"name":"setCapPerAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_curveSUSD","type":"address"},{"internalType":"address","name":"_dai","type":"address"},{"internalType":"address","name":"_usdc","type":"address"},{"internalType":"address","name":"_usdt","type":"address"},{"internalType":"bool","name":"_curveOnrampEnabled","type":"bool"},{"internalType":"uint256","name":"_maxAllowedPegSlippagePercentage","type":"uint256"}],"name":"setCurveSUSD","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"asset","type":"bytes32"},{"internalType":"uint256","name":"_impliedVolatility","type":"uint256"}],"name":"setImpliedVolatilityPerAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ThalesAMMLiquidityPool","name":"_liquidityPool","type":"address"}],"name":"setLiquidityPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minspread","type":"uint256"},{"internalType":"uint256","name":"_maxspread","type":"uint256"}],"name":"setMinMaxSpread","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minSupportedPrice","type":"uint256"},{"internalType":"uint256","name":"_maxSupportedPrice","type":"uint256"},{"internalType":"uint256","name":"_capPerMarket","type":"uint256"}],"name":"setMinMaxSupportedPriceAndCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"uint256","name":"newFee","type":"uint256"}],"name":"setMinSpreadPerAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minimalTimeLeftToMaturity","type":"uint256"}],"name":"setMinimalTimeLeftToMaturity","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"setOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_paused","type":"bool"}],"name":"setPaused","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_manager","type":"address"}],"name":"setPositionalMarketManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IPriceFeed","name":"_priceFeed","type":"address"},{"internalType":"contract IERC20Upgradeable","name":"_sUSD","type":"address"}],"name":"setPriceFeedAndSUSD","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_safeBox","type":"address"},{"internalType":"uint256","name":"_safeBoxImpact","type":"uint256"}],"name":"setSafeBoxData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"uint256","name":"newFee","type":"uint256"}],"name":"setSafeBoxFeePerAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IStakingThales","name":"_stakingThales","type":"address"},{"internalType":"address","name":"_referrals","type":"address"},{"internalType":"uint256","name":"_referrerFee","type":"uint256"}],"name":"setStakingThalesAndReferrals","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"bool","name":"enabled","type":"bool"}],"name":"setWhitelistedAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"spentOnMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stakingThales","outputs":[{"internalType":"contract IStakingThales","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"proxyAddress","type":"address"}],"name":"transferOwnershipAtInit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"tokens","type":"address[]"},{"internalType":"address payable","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bool","name":"all","type":"bool"}],"name":"transferTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"usdc","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"usdt","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"whitelistedAddresses","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]

608060405234801561001057600080fd5b50615f8080620000216000396000f3fe608060405234801561001057600080fd5b50600436106103fc5760003560e01c80638517020911610215578063cafb3ca211610125578063ebc79772116100b8578063f502b00311610087578063f502b003146108cd578063f8debeb7146108ed578063fb91d41c14610900578063fc1ed85714610909578063fd8a8cc61461091c57600080fd5b8063ebc797721461088c578063efb1fe3514610894578063efc15251146108a7578063f4b9fa75146108ba57600080fd5b8063d3dc7539116100f4578063d3dc75391461083f578063d4a2641b14610852578063d69fb6681461087a578063df8974d01461088357600080fd5b8063cafb3ca2146107f3578063d162492414610806578063d333ca1914610819578063d3c4297c1461082c57600080fd5b8063a5bf660d116101a8578063bf996ae311610177578063bf996ae314610787578063c2783f921461079a578063c3b83f5f146107ad578063c4dc27d7146107c0578063c8f0b4ec146107e057600080fd5b8063a5bf660d1461073b578063ad18f0da1461074e578063bbdf88ce14610761578063bf46c0b41461077457600080fd5b8063931b2040116101e4578063931b2040146106f95780639324cac7146107025780639f916c9f14610715578063a273ecf11461072857600080fd5b806385170209146106b15780638875eb84146106c45780638da5cb5b146106d757806391b4ded9146106f057600080fd5b8063481c6a7511610310578063665a11ca116102a35780636ed033f8116102725780636ed033f814610658578063741bef1a1461066b57806379ba5097146106835780637b337a361461068b578063826153491461069e57600080fd5b8063665a11ca146106205780636aaa81b6146106335780636cc5a6ff1461063c5780636e88a7bd1461064f57600080fd5b80635727a0f3116102df5780635727a0f3146105cd5780635c975abb146105e05780635ef85b26146105ed57806365f567721461060057600080fd5b8063481c6a751461058157806348663e95146105945780634a50215e146105a757806353a47bb7146105ba57600080fd5b80631fbb38e8116103935780632f48ab7d116103625780632f48ab7d14610514578063316425c31461053f5780633443b326146105485780633ce1108d1461055b5780633e413bee1461056e57600080fd5b80631fbb38e8146104c4578063270e13ef146104d85780632909f51a146104eb5780632972e8ab146104f457600080fd5b80631627540c116103cf5780631627540c1461048257806316c38b3c1461049557806319b844a6146104a85780631c37d04b146104b157600080fd5b8063018770201461040157806306c933d8146104165780630f13aae81461044e57806313af40351461046f575b600080fd5b61041461040f366004615544565b61092f565b005b610439610424366004615544565b60146020526000908152604090205460ff1681565b60405190151581526020015b60405180910390f35b61046161045c36600461570b565b610959565b604051908152602001610445565b61041461047d366004615544565b6109a3565b610414610490366004615544565b610ae3565b6104146104a3366004615972565b610b39565b61046160125481565b6104616104bf36600461570b565b610baf565b601a5461043990600160a01b900460ff1681565b6104616104e636600461570b565b610bdc565b610461601b5481565b610461610502366004615544565b601e6020526000908152604090205481565b601954610527906001600160a01b031681565b6040516001600160a01b039091168152602001610445565b610461600a5481565b6104146105563660046158c2565b610c35565b610461610569366004615798565b610c59565b601854610527906001600160a01b031681565b600754610527906001600160a01b031681565b600e54610527906001600160a01b031681565b6104146105b53660046158d4565b611252565b600154610527906001600160a01b031681565b6104396105db366004615544565b6113f3565b6003546104399060ff1681565b6104146105fb3660046159c2565b6115a3565b61046161060e366004615544565b601d6020526000908152604090205481565b601f54610527906001600160a01b031681565b61046160095481565b61046161064a36600461584a565b6117c9565b61046160165481565b6104616106663660046156d7565b611b48565b6005546105279061010090046001600160a01b031681565b610414611df0565b61041461069936600461561f565b611eed565b6104146106ac3660046159c2565b611f20565b6104146106bf3660046159aa565b611f95565b6104616106d2366004615798565b611fd2565b600054610527906201000090046001600160a01b031681565b61046160025481565b61046160115481565b600654610527906001600160a01b031681565b6104616107233660046157e6565b612046565b6104146107363660046158c2565b61213a565b601754610527906001600160a01b031681565b61041461075c366004615657565b61215e565b61041461076f366004615a3e565b612283565b61046161078236600461570b565b612332565b610414610795366004615544565b61245a565b6104616107a83660046156d7565b6125d2565b6104146107bb366004615544565b612618565b6104616107ce366004615544565b600d6020526000908152604090205481565b6104146107ee366004615ae6565b612731565b610414610801366004615a6b565b61278e565b6104146108143660046159c2565b6127cb565b610414610827366004615544565b61281b565b61041461083a3660046155a7565b612845565b601554610527906001600160a01b031681565b610865610860366004615748565b612a45565b60408051928352602083019190915201610445565b610461600f5481565b610461600c5481565b610414612b5e565b6104146108a236600461557c565b612bbc565b6104616108b53660046156d7565b612bdf565b601a54610527906001600160a01b031681565b6104616108db3660046159aa565b600b6020526000908152604090205481565b6104616108fb3660046159aa565b612c2c565b61046160085481565b6104146109173660046158c2565b612ce3565b601054610527906001600160a01b031681565b610937612d3b565b601f80546001600160a01b0319166001600160a01b0392909216919091179055565b6000806109668585611b48565b90506012548111610977578061097b565b6012545b9050600061098a868684612db5565b90506109998686868585612f90565b9695505050505050565b6001600160a01b0381166109fe5760405162461bcd60e51b815260206004820152601960248201527f4f776e657220616464726573732063616e6e6f7420626520300000000000000060448201526064015b60405180910390fd5b600154600160a01b900460ff1615610a6a5760405162461bcd60e51b815260206004820152602960248201527f416c726561647920696e697469616c697a65642c20757365206e6f6d696e617460448201526832a732bba7bbb732b960b91b60648201526084016109f5565b6001805460ff60a01b1916600160a01b179055600080546001600160a01b03831662010000810262010000600160b01b03199092169190911782556040805192835260208301919091527fb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c91015b60405180910390a150565b610aeb612d3b565b600180546001600160a01b0319166001600160a01b0383169081179091556040519081527f906a1c6bd7e3091ea86693dd029a831c19049ce77f1dce2ce0bab1cacbabce2290602001610ad8565b610b41612d3b565b60035460ff1615158115151415610b555750565b6003805460ff191682151590811790915560ff1615610b7357426002555b60035460405160ff909116151581527f8fb6c181ee25a520cf3dd6565006ef91229fcfe5a989566c2a3b8c115570cec590602001610ad8565b50565b600080610bbc85856125d2565b9050808311610bd457610bd1858585846130bc565b91505b509392505050565b600080610be98585611b48565b90506000610bff82670de0b6b3a7640000615e9d565b90508115610c2c576011548210610c165781610c1a565b6011545b91506109998686868585600f546132ce565b50509392505050565b610c3d612d3b565b6001600160a01b039091166000908152601e6020526040902055565b6000600160046000828254610c6e9190615d62565b909155505060045460035460ff1615610c995760405162461bcd60e51b81526004016109f590615c3f565b610ca2876113f3565b610cee5760405162461bcd60e51b815260206004820152601e60248201527f4d61726b6574206973206e6f7420696e2054726164696e67207068617365000060448201526064016109f5565b6000610cfa8888611b48565b90506012548111610d0b5780610d0f565b6012545b90506000610d1e898984612db5565b9050600081118015610d305750808711155b610d745760405162461bcd60e51b81526020600482015260156024820152742737ba1032b737bab3b4103634b8bab4b234ba3c9760591b60448201526064016109f5565b6000610d838a8a8a8686612f90565b9050610d9786670de0b6b3a7640000615d62565b81610daa670de0b6b3a76400008a615e3f565b610db49190615da8565b1115610df65760405162461bcd60e51b81526020600482015260116024820152700a6d8d2e0e0c2ceca40e8dede40d0d2ced607b1b60448201526064016109f5565b6000610e028b8b613570565b9050610e0d8b613617565b610e226001600160a01b03821633308c6137fa565b6007546040516314edbee160e31b81523060048201526000916001600160a01b039081169163edc892e1918f169063a76df7089060240160206040518083038186803b158015610e7157600080fd5b505afa158015610e85573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ea99190615aab565b6040518263ffffffff1660e01b8152600401610ec791815260200190565b60206040518083038186803b158015610edf57600080fd5b505afa158015610ef3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f179190615aab565b90508015610f73578b6001600160a01b031663f5571beb6040518163ffffffff1660e01b8152600401600060405180830381600087803b158015610f5a57600080fd5b505af1158015610f6e573d6000803e3d6000fd5b505050505b600083600f54670de0b6b3a7640000610f8c9190615e9d565b610f9e670de0b6b3a764000087615e3f565b610fa89190615da8565b610fb29190615e9d565b9050600084601654670de0b6b3a7640000610fcd9190615e9d565b610fdf670de0b6b3a764000088615e3f565b610fe99190615da8565b610ff39190615e9d565b9050600f546000141561100557600091505b601f60009054906101000a90046001600160a01b03166001600160a01b03166358c09cc08f600760009054906101000a90046001600160a01b03166001600160a01b03166317fd849a85878b61105b9190615d62565b6110659190615d62565b6040518263ffffffff1660e01b815260040161108391815260200190565b60206040518083038186803b15801561109b57600080fd5b505afa1580156110af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110d39190615aab565b6040518363ffffffff1660e01b81526004016110f0929190615bcf565b600060405180830381600087803b15801561110a57600080fd5b505af115801561111e573d6000803e3d6000fd5b505060065461113a92506001600160a01b03169050338761386b565b6010546001600160a01b0316156111b0576010546040516302c7739b60e01b81526001600160a01b03909116906302c7739b9061117d9033908990600401615bcf565b600060405180830381600087803b15801561119757600080fd5b505af11580156111ab573d6000803e3d6000fd5b505050505b6111bd8e8685338661388f565b6111c68e613b5a565b7f1d6ff70c632edb1e6aba7fbc0148db68c8392e30f9dfaadae2543a2543757cf6338f8f8f89600660009054906101000a90046001600160a01b03168a6040516112169796959493929190615b4f565b60405180910390a150929650505050505060045481146112485760405162461bcd60e51b81526004016109f590615c9c565b5095945050505050565b61125a612d3b565b836112a75760405162461bcd60e51b815260206004820152601a60248201527f746f6b656e732061727261792063616e7420626520656d70747900000000000060448201526064016109f5565b60005b848110156113eb5781156113b4576113af848787848181106112dc57634e487b7160e01b600052603260045260246000fd5b90506020020160208101906112f19190615544565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a082319060240160206040518083038186803b15801561133257600080fd5b505afa158015611346573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061136a9190615aab565b88888581811061138a57634e487b7160e01b600052603260045260246000fd5b905060200201602081019061139f9190615544565b6001600160a01b0316919061386b565b6113d9565b6113d9848488888581811061138a57634e487b7160e01b600052603260045260246000fd5b806113e381615ee0565b9150506112aa565b505050505050565b600754604051633761c52760e11b81526001600160a01b0383811660048301526000921690636ec38a4e9060240160206040518083038186803b15801561143957600080fd5b505afa15801561144d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611471919061598e565b1561159e5760008290506000816001600160a01b03166341bc7b1f6040518163ffffffff1660e01b815260040160606040518083038186803b1580156114b657600080fd5b505afa1580156114ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114ee91906159e3565b505090506000826001600160a01b0316639e3b34bf6040518163ffffffff1660e01b8152600401604080518083038186803b15801561152c57600080fd5b505afa158015611540573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115649190615ac3565b506000838152600b6020526040902054909150158061158257504281105b61159a5760006115924283615e9d565b600c54109450505b5050505b919050565b3360009081526014602052604090205460ff16806115d157506000546201000090046001600160a01b031633145b6116385760405162461bcd60e51b815260206004820152603260248201527f4f6e6c792077686974656c697374656420616464726573736573206f72206f776044820152716e65722063616e206368616e67652049562160701b60648201526084016109f5565b61164b670de0b6b3a7640000600a615e3f565b8111801561166b5750611668670de0b6b3a764000061012c615e3f565b81105b6116b75760405162461bcd60e51b815260206004820152601960248201527f4956206f757473696465206d696e2f6d61782072616e6765210000000000000060448201526064016109f5565b6005546040516315905ec160e31b8152600481018490526101009091046001600160a01b03169063ac82f6089060240160206040518083038186803b1580156116ff57600080fd5b505afa158015611713573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117379190615aab565b6117795760405162461bcd60e51b8152602060048201526013602482015272417373657420686173206e6f2070726963652160681b60448201526064016109f5565b6000828152600b602090815260409182902083905581518481529081018390527f715e0a52c0b74c77d2d2012a363ac95b494302ad2abb78ac7406ec93451f1adb91015b60405180910390a15050565b60006001600460008282546117de9190615d62565b909155505060045460035460ff16156118095760405162461bcd60e51b81526004016109f590615c3f565b6001600160a01b0383161561187e5760155460405163bbddaca360e01b81526001600160a01b0385811660048301523360248301529091169063bbddaca390604401600060405180830381600087803b15801561186557600080fd5b505af1158015611879573d6000803e3d6000fd5b505050505b600061188985613e2d565b9050600081600f0b1380156118a75750601a54600160a01b900460ff165b6118ec5760405162461bcd60e51b81526020600482015260166024820152751d5b9cdd5c1c1bdc9d19590818dbdb1b185d195c985b60521b60448201526064016109f5565b6000806118fb8c8c8c8a612a45565b60185491935091506000906001600160a01b038981169116148061192c57506019546001600160a01b038981169116145b6119365782611945565b6119458364e8d4a51000615e3f565b90506000601b5411801561198b5750670de0b6b3a7640000601b54670de0b6b3a76400006119739190615e9d565b61197d9084615e3f565b6119879190615da8565b8110155b6119e55760405162461bcd60e51b815260206004820152602560248201527f416d6f756e742062656c6f77206d617820616c6c6f7765642070656720736c69604482015264707061676560d81b60648201526084016109f5565b6119f789670de0b6b3a7640000615d62565b8a611a0a670de0b6b3a764000086615e3f565b611a149190615da8565b1115611a575760405162461bcd60e51b8152602060048201526012602482015271536c69707061676520746f6f20686967682160701b60448201526064016109f5565b87611a6d6001600160a01b0382163330876137fa565b601754604051635320bf6b60e11b8152600f87900b60048201526000602482015260448101869052606481018590526001600160a01b039091169063a6417ed690608401602060405180830381600087803b158015611acb57600080fd5b505af1158015611adf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b039190615aab565b50611b148e8e8e868e600089613e92565b965050505050506004548114611b3c5760405162461bcd60e51b81526004016109f590615c9c565b50979650505050505050565b6000611b53836113f3565b15611dea5760008390506000816001600160a01b0316639e3b34bf6040518163ffffffff1660e01b8152600401604080518083038186803b158015611b9757600080fd5b505afa158015611bab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bcf9190615ac3565b5090506000611bde4283615e9d565b9050600062015180611bf8670de0b6b3a764000084615e3f565b611c029190615da8565b90506000846001600160a01b031663668aa8246040518163ffffffff1660e01b815260040160206040518083038186803b158015611c3f57600080fd5b505afa158015611c53573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c779190615aab565b9050600080866001600160a01b03166341bc7b1f6040518163ffffffff1660e01b815260040160606040518083038186803b158015611cb557600080fd5b505afa158015611cc9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ced91906159e3565b50601c546000838152600b602052604090819020549051631519a0dd60e31b815260048101889052602481018490526044810189905260648082019290925293955091935090916001600160a01b039091169063a8cd06e89060840160206040518083038186803b158015611d6157600080fd5b505afa158015611d75573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d999190615aab565b611da39190615da8565b97506001896001811115611dc757634e487b7160e01b600052602160045260246000fd5b1415611de257611ddf88670de0b6b3a7640000615e9d565b97505b505050505050505b92915050565b6001546001600160a01b03163314611e685760405162461bcd60e51b815260206004820152603560248201527f596f75206d757374206265206e6f6d696e61746564206265666f726520796f7560448201527402063616e20616363657074206f776e65727368697605c1b60648201526084016109f5565b60005460015460408051620100009093046001600160a01b03908116845290911660208301527fb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c910160405180910390a1600180546000805462010000600160b01b0319166001600160a01b03831662010000021790556001600160a01b0319169055565b611ef5612d3b565b6001600160a01b03919091166000908152601460205260409020805460ff1916911515919091179055565b611f28612d3b565b6009829055600a8190556040518281527f1e6a338a58debcc786781a079c4459466b102ad0156cc84f51d25ef7dd8cb9b09060200160405180910390a16040518181527f4af6d03c4624e0a6b868b8f6453e047f23f3ea15e9d08c938bd4c445d7ef19b3906020016117bd565b611f9d612d3b565b600c8190556040518181527fdc469b5583fa9b7ebd3245e1665334cd758c4bef4c5a132c62baca85effacfec90602001610ad8565b6000600160046000828254611fe79190615d62565b909155505060045460035460ff16156120125760405162461bcd60e51b81526004016109f590615c3f565b612023878787878760016000613e92565b915060045481146112485760405162461bcd60e51b81526004016109f590615c9c565b600060016004600082825461205b9190615d62565b909155505060045460035460ff16156120865760405162461bcd60e51b81526004016109f590615c3f565b6001600160a01b038316156120fb5760155460405163bbddaca360e01b81526001600160a01b0385811660048301523360248301529091169063bbddaca390604401600060405180830381600087803b1580156120e257600080fd5b505af11580156120f6573d6000803e3d6000fd5b505050505b61210c888888888860016000613e92565b9150600454811461212f5760405162461bcd60e51b81526004016109f590615c9c565b509695505050505050565b612142612d3b565b6001600160a01b039091166000908152601d6020526040902055565b600054610100900460ff166121795760005460ff161561217d565b303b155b6121e05760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016109f5565b600054610100900460ff16158015612202576000805461ffff19166101011790555b61220b896109a3565b612213612b5e565b60058054610100600160a81b0319166101006001600160a01b038b81169190910291909117909155600680546001600160a01b03191691891691909117905560088690556009849055600a839055600c8290558015612278576000805461ff00191690555b505050505050505050565b61228b612d3b565b60058054610100600160a81b0319166101006001600160a01b038516908102919091179091556040519081527ff724a45d041687842411f2b977ef22ab8f43c8f1104f4592b42a00f9b34a643d9060200160405180910390a1600680546001600160a01b0319166001600160a01b0383169081179091556040519081527f74a8764fc8d62d2d844c8c54426bd94ad034e0e92abdf5280ff75e2cbd678fb6906020016117bd565b6000808084600181111561235657634e487b7160e01b600052602160045260246000fd5b14612362576000612365565b60015b905060006123738686611b48565b9050601154811015801561238957506012548111155b15610c2c5760006123a282670de0b6b3a7640000615e9d565b905060006123b3888885600161436b565b905060006123c4898685600161436b565b90506000871180156123d65750818711155b1561244e5761244b6040518060e001604052808b6001600160a01b031681526020018a600181111561241857634e487b7160e01b600052602160045260246000fd5b8152602081018a90526040810185905260608101849052601f546001600160a01b0316608082015260a001869052614640565b95505b50505050509392505050565b612462612d3b565b6007546001600160a01b0316156124fe5760065460075460405163095ea7b360e01b81526001600160a01b039283169263095ea7b3926124aa92911690600090600401615bcf565b602060405180830381600087803b1580156124c457600080fd5b505af11580156124d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124fc919061598e565b505b600780546001600160a01b0319166001600160a01b0383811691821790925560065460405163095ea7b360e01b815292169163095ea7b3916125469160001990600401615bcf565b602060405180830381600087803b15801561256057600080fd5b505af1158015612574573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612598919061598e565b506040516001600160a01b03821681527f9987372437ace1af79923f26b948aa04afef92b2b7786144c5aae621ea84eb0a90602001610ad8565b60006125dd836113f3565b15611dea5760006125ee8484611b48565b905060125481116125ff5780612603565b6012545b9050612610848483612db5565b949350505050565b612620612d3b565b6001600160a01b0381166126685760405162461bcd60e51b815260206004820152600f60248201526e496e76616c6964206164647265737360881b60448201526064016109f5565b600154600160a81b900460ff16156126b85760405162461bcd60e51b8152602060048201526013602482015272105b1c9958591e481d1c985b9cd9995c9c9959606a1b60448201526064016109f5565b600080546001600160a01b038381166201000081810262010000600160b01b031990941693909317938490556001805460ff60a81b1916600160a81b1790556040805193909404909116825260208201527fb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c9101610ad8565b612739612d3b565b60118390556012829055600881905560408051848152602081018490529081018290527f0e8c2ebd67ea2d796a34f02c777ec06f5faedd1669b272dc08dc7875486ae0809060600160405180910390a1505050565b612796612d3b565b601080546001600160a01b039485166001600160a01b0319918216179091556015805493909416921691909117909155601655565b6127d3612d3b565b60008281526013602090815260409182902083905581518481529081018390527f5af395595015797b4d0f26b77c38dd4831298dabc7906ee3d62b80fa75d35c1e91016117bd565b612823612d3b565b601c80546001600160a01b0319166001600160a01b0392909216919091179055565b61284d612d3b565b601780546001600160a01b038089166001600160a01b031992831617909255601a8054888416908316811790915560188054888516908416179055601980549387169390921692909217905560405163095ea7b360e01b815263095ea7b3906128be90899060001990600401615bcf565b602060405180830381600087803b1580156128d857600080fd5b505af11580156128ec573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612910919061598e565b5060185460405163095ea7b360e01b81526001600160a01b039091169063095ea7b39061294590899060001990600401615bcf565b602060405180830381600087803b15801561295f57600080fd5b505af1158015612973573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612997919061598e565b5060195460405163095ea7b360e01b81526001600160a01b039091169063095ea7b3906129cc90899060001990600401615bcf565b602060405180830381600087803b1580156129e657600080fd5b505af11580156129fa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a1e919061598e565b50601a8054921515600160a01b0260ff60a01b1990931692909217909155601b5550505050565b6000806000612a5384613e2d565b9050600081600f0b138015612a715750601a54600160a01b900460ff165b15612b5457612a81878787610bdc565b9150670de0b6b3a7640000612a9e6005662386f26fc10000615da8565b612ab090670de0b6b3a7640000615d62565b6017546040516307211ef760e01b815260006004820152600f85900b6024820152604481018690526001600160a01b03909116906307211ef79060640160206040518083038186803b158015612b0557600080fd5b505afa158015612b19573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b3d9190615aab565b612b479190615e3f565b612b519190615da8565b92505b5094509492505050565b60055460ff1615612ba75760405162461bcd60e51b8152602060048201526013602482015272105b1c9958591e481a5b9a5d1a585b1a5e9959606a1b60448201526064016109f5565b6005805460ff19166001908117909155600455565b612bc4612d3b565b600654612bdb906001600160a01b0316838361386b565b5050565b6000612bea836113f3565b15611dea576000612bfb8484611b48565b90508015612c25576011548110612c125780612c16565b6011545b9050612610848483600061436b565b5092915050565b6005546040516315905ec160e31b81526004810183905260009161010090046001600160a01b03169063ac82f6089060240160206040518083038186803b158015612c7657600080fd5b505afa158015612c8a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cae9190615aab565b1561159e5760008281526013602052604090205415612cdb57600082815260136020526040902054611dea565b505060085490565b612ceb612d3b565b600f819055600e80546001600160a01b0319166001600160a01b0384161790556040518181527f01edd423db862fb00774918e3b06d9c1dd3db9a99b5a194c439d2f141876f444906020016117bd565b6000546201000090046001600160a01b03163314612db35760405162461bcd60e51b815260206004820152602f60248201527f4f6e6c792074686520636f6e7472616374206f776e6572206d6179207065726660448201526e37b936903a3434b99030b1ba34b7b760891b60648201526084016109f5565b565b600080612dc183614c4c565b90508015610bd457601c54601f5460405163c2edfc7360e01b81526001600160a01b038881166004830152600093811692636116ad1e928a928a92169063c2edfc739060240160206040518083038186803b158015612e1f57600080fd5b505afa158015612e33573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e579190615560565b6040518463ffffffff1660e01b8152600401612e7593929190615b9f565b604080518083038186803b158015612e8c57600080fd5b505afa158015612ea0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ec49190615ac3565b915060009050670de0b6b3a7640000612edd8484615e3f565b612ee79190615da8565b9050600082612ef589614ca3565b612eff9190615d62565b6001600160a01b0389166000908152600d6020526040902054909150612f26908390615d62565b8110612f85576001600160a01b0388166000908152600d60205260408120548390612f519084615e9d565b612f5b9190615e9d565b905083670de0b6b3a7640000612f718784615da8565b612f7b9190615e3f565b61244b9190615d62565b505050509392505050565b60008184116130b357600954612fa69084615e9d565b92506000670de0b6b3a764000080612fc0898989886130bc565b612fd290670de0b6b3a7640000615e9d565b612fdc9087615e3f565b612fe69190615da8565b612ff09087615e3f565b612ffa9190615da8565b90506000670de0b6b3a7640000600f54670de0b6b3a764000061301d9190615e9d565b6130279084615e3f565b6130319190615da8565b60075460405163edc892e160e01b8152600481018390529192506001600160a01b03169063edc892e19060240160206040518083038186803b15801561307657600080fd5b505afa15801561308a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130ae9190615aab565b925050505b95945050505050565b601c54601f5460405163c2edfc7360e01b81526001600160a01b0387811660048301526000938493849391831692636116ad1e928b928b92169063c2edfc739060240160206040518083038186803b15801561311757600080fd5b505afa15801561312b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061314f9190615560565b6040518463ffffffff1660e01b815260040161316d93929190615b9f565b604080518083038186803b15801561318457600080fd5b505afa158015613198573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131bc9190615ac3565b9150915060008083116131e6578582116131df576131da8287615e9d565b6131f0565b60006131f0565b6131f08684615d62565b9050600086831161320257600061320c565b61320c8784615e9d565b90508082106132c257601c54600a546040516327b76a6b60e21b8152600481018a90526024810186905260448101879052606481018490526084810185905260a4810189905260c48101919091526001600160a01b0390911690639edda9ac9060e40160206040518083038186803b15801561328757600080fd5b505afa15801561329b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132bf9190615aab565b94505b50505050949350505050565b6000806132de888887600061436b565b9050600061331e89828a600181111561330757634e487b7160e01b600052602160045260246000fd5b14613313576000613316565b60015b87600161436b565b90508187116135645760008061339a6040518060e001604052808d6001600160a01b031681526020018c600181111561336757634e487b7160e01b600052602160045260246000fd5b8152602081018c90526040810187905260608101869052601f546001600160a01b0316608082015260a0018a9052614640565b336000908152601e60205260409020549091506133b9576009546133ca565b336000908152601e60205260409020545b6133d49089615d62565b97506000811261347c576000670de0b6b3a7640000826133f48b83615e5e565b6133fe9190615dbc565b6134089190615d7a565b9050670de0b6b3a7640000613425662386f26fc100006002615dbc565b61343790670de0b6b3a7640000615d21565b6134419083615dbc565b61344b9190615d7a565b9050670de0b6b3a7640000613460828b615d21565b61346a908c615dbc565b6134749190615d7a565b9250506134bb565b670de0b6b3a7640000806134908382615d21565b61349a908b615dbc565b6134a49190615d7a565b6134ae908b615dbc565b6134b89190615d7a565b91505b670de0b6b3a76400006134ce8782615d21565b6134d89084615dbc565b6134e29190615d7a565b60075460405163edc892e160e01b8152600481018390529193506001600160a01b03169063edc892e19060240160206040518083038186803b15801561352757600080fd5b505afa15801561353b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061355f9190615aab565b945050505b50509695505050505050565b6000806000846001600160a01b031663cc2ee1966040518163ffffffff1660e01b8152600401604080518083038186803b1580156135ad57600080fd5b505afa1580156135c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135e59190615a10565b9092509050600084600181111561360c57634e487b7160e01b600052602160045260246000fd5b14610bd457806130b3565b601c54601f5460405163c2edfc7360e01b81526001600160a01b03848116600483015260009384939082169263ea25928a928792169063c2edfc739060240160206040518083038186803b15801561366e57600080fd5b505afa158015613682573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136a69190615560565b6040516001600160e01b031960e085901b1681526001600160a01b03928316600482015291166024820152604401604080518083038186803b1580156136eb57600080fd5b505afa1580156136ff573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137239190615ac3565b601f54604051631051f9d160e31b81529294509092506001600160a01b03169063828fce889061375c9086908690600090600401615be8565b600060405180830381600087803b15801561377657600080fd5b505af115801561378a573d6000803e3d6000fd5b5050601f54604051631051f9d160e31b81526001600160a01b03909116925063828fce8891506137c39086908590600190600401615be8565b600060405180830381600087803b1580156137dd57600080fd5b505af11580156137f1573d6000803e3d6000fd5b50505050505050565b6040516001600160a01b03808516602483015283166044820152606481018290526138659085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614d2b565b50505050565b61388a8363a9059cbb60e01b848460405160240161382e929190615bcf565b505050565b600f54156138b457600e546006546138b4916001600160a01b0391821691168361386b565b6007546001600160a01b03166317fd849a6138cf8387615d62565b6040518263ffffffff1660e01b81526004016138ed91815260200190565b60206040518083038186803b15801561390557600080fd5b505afa158015613919573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061393d9190615aab565b6001600160a01b0386166000908152600d60205260409020546139609190615d62565b6001600160a01b038681166000908152600d602052604090819020929092556007549151630bfec24d60e11b8152600481018690529116906317fd849a9060240160206040518083038186803b1580156139b957600080fd5b505afa1580156139cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139f19190615aab565b6001600160a01b0386166000908152600d602052604090205411613a2d576001600160a01b0385166000908152600d6020526040812055613ae6565b600754604051630bfec24d60e11b8152600481018590526001600160a01b03909116906317fd849a9060240160206040518083038186803b158015613a7157600080fd5b505afa158015613a85573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613aa99190615aab565b6001600160a01b0386166000908152600d6020526040902054613acc9190615e9d565b6001600160a01b0386166000908152600d60205260409020555b6000601654118015613b0257506015546001600160a01b031615155b15613b5357600084601654670de0b6b3a7640000613b209190615e9d565b613b32670de0b6b3a764000088615e3f565b613b3c9190615da8565b613b469190615e9d565b90506113eb838287614dfd565b5050505050565b601f5460405163f475f13b60e01b81526001600160a01b038381166004830152600092169063f475f13b90602401602060405180830381600087803b158015613ba257600080fd5b505af1158015613bb6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613bda9190615560565b6006546040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a082319060240160206040518083038186803b158015613c2357600080fd5b505afa158015613c37573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c5b9190615aab565b1115613cf5576006546040516370a0823160e01b8152306004820152613cf59183916001600160a01b03909116906370a082319060240160206040518083038186803b158015613caa57600080fd5b505afa158015613cbe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ce29190615aab565b6006546001600160a01b0316919061386b565b600080836001600160a01b031663cc2ee1966040518163ffffffff1660e01b8152600401604080518083038186803b158015613d3057600080fd5b505afa158015613d44573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d689190615a10565b601c54604051637512c94560e11b81526001600160a01b038881166004830152306024830152939550919350600092839291169063ea25928a90604401604080518083038186803b158015613dbc57600080fd5b505afa158015613dd0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613df49190615ac3565b90925090508115613e1357613e136001600160a01b038516868461386b565b80156113eb576113eb6001600160a01b038416868361386b565b601a546000906001600160a01b0383811691161415613e4e57506001919050565b6018546001600160a01b0383811691161415613e6c57506002919050565b6019546001600160a01b0383811691161415613e8a57506003919050565b506000919050565b6000613e9d886113f3565b613ee95760405162461bcd60e51b815260206004820152601e60248201527f4d61726b6574206973206e6f7420696e2054726164696e67207068617365000060448201526064016109f5565b50806000613ef78989611b48565b90506000613f0d82670de0b6b3a7640000615e9d565b90506011548210613f1e5781613f22565b6011545b91506000613f338b8b85600061436b565b9050600089118015613f455750808911155b613f895760405162461bcd60e51b81526020600482015260156024820152742737ba1032b737bab3b4103634b8bab4b234ba3c9760591b60448201526064016109f5565b851561405957336000908152601d6020526040902054613fce908c908c908c9087908790613fb957600f546132ce565b336000908152601d60205260409020546132ce565b9350613fe287670de0b6b3a7640000615d62565b88613ff5670de0b6b3a764000087615e3f565b613fff9190615da8565b11156140415760405162461bcd60e51b81526020600482015260116024820152700a6d8d2e0e0c2ceca40e8dede40d0d2ced607b1b60448201526064016109f5565b600654614059906001600160a01b03163330876137fa565b60006140668c8c8c614f0b565b9050801561416a57601f54604051630163027360e61b81526001600160a01b03909116906358c09cc0906140a0908f908590600401615bcf565b600060405180830381600087803b1580156140ba57600080fd5b505af11580156140ce573d6000803e3d6000fd5b505060405163140e25ad60e31b8152600481018490526001600160a01b038f16925063a0712d689150602401600060405180830381600087803b15801561411457600080fd5b505af1158015614128573d6000803e3d6000fd5b5050506001600160a01b038d166000908152600d602052604090205461415091508290615d62565b6001600160a01b038d166000908152600d60205260409020555b601f546001600160a01b031663828fce888d614186848e615e9d565b8e6040518463ffffffff1660e01b81526004016141a593929190615be8565b600060405180830381600087803b1580156141bf57600080fd5b505af11580156141d3573d6000803e3d6000fd5b5050505060006141e38d8d613570565b90506141f96001600160a01b038216338d61386b565b6010546001600160a01b03161561426f576010546040516302c7739b60e01b81526001600160a01b03909116906302c7739b9061423c9033908a90600401615bcf565b600060405180830381600087803b15801561425657600080fd5b505af115801561426a573d6000803e3d6000fd5b505050505b61427a8d873361501f565b818b11156142ee57600061428e838d615e9d565b905060008c61429d838a615e3f565b6142a79190615da8565b60408051338152602081018590529081018290529091507ff8a5b21533fcaaeee91cd7b3c6ccbaa3f4ab6dd200e61bc560713565b20b1e9a9060600160405180910390a150505b6142f78d613b5a565b7ff3bfbc0822d1ed667a2b298e71e0304f2c1f4685398189d7c39e412f733150f4338e8e8e8a600660009054906101000a90046001600160a01b0316876040516143479796959493929190615b4f565b60405180910390a161435b8d8d88336152a6565b5050505050979650505050505050565b6000818061437a575060125483105b156126105760095461438c9084615d62565b9250670de0b6b3a7640000831015612610576000670de0b6b3a76400006002600a546143b89190615da8565b6143ca90670de0b6b3a7640000615e9d565b6143d49086615e3f565b6143de9190615da8565b601c54601f5460405163c2edfc7360e01b81526001600160a01b038a811660048301529394506000939283169263e468265c928b928b929091169063c2edfc739060240160206040518083038186803b15801561443a57600080fd5b505afa15801561444e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906144729190615560565b6040518463ffffffff1660e01b815260040161449093929190615b9f565b60206040518083038186803b1580156144a857600080fd5b505afa1580156144bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906144e09190615aab565b90506000670de0b6b3a76400006144f78484615e3f565b6145019190615da8565b6001600160a01b0389166000908152600d6020526040902054909150816145278a614ca3565b6145319190615d62565b1115614635576001600160a01b0388166000908152600d60205260408120548261455a8b614ca3565b6145649190615d62565b61456e9190615e9d565b905061457989614ca3565b81111561458c5761458989614ca3565b90505b6000670de0b6b3a76400006002600a546145a69190615da8565b6145b88a670de0b6b3a7640000615e9d565b6145c29190615e3f565b6145cc9190615da8565b9050670de0b6b3a76400006145e1828a615d62565b10156146325760006145f3828a615d62565b61460590670de0b6b3a7640000615e9d565b90508061461a670de0b6b3a764000085615e3f565b6146249190615da8565b61462e9086615d62565b9650505b50505b505050949350505050565b60006011548260c001511015801561465e57506012548260c0015111155b1561159e57601c548251602084015160a085015160405163c2edfc7360e01b81526001600160a01b038085166004830152600095869590821694636116ad1e94919390929091169063c2edfc739060240160206040518083038186803b1580156146c757600080fd5b505afa1580156146db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906146ff9190615560565b6040518463ffffffff1660e01b815260040161471d93929190615b9f565b604080518083038186803b15801561473457600080fd5b505afa158015614748573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061476c9190615ac3565b91509150600084604001518311614784576000614793565b60408501516147939084615e9d565b90506000856040015184116147b7578386604001516147b29190615e9d565b6147ba565b60005b6147c49084615d62565b905080821061489e57601c546040805160a08101825286815260208101868152898301518284019081526080808c015160608501908152600a549185019182529451632888a20d60e01b8152935160048501529151602484015251604483015291516064820152905160848201526001600160a01b0390911690632888a20d9060a40160206040518083038186803b15801561485f57600080fd5b505afa158015614873573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906148979190615aab565b9450614c43565b8386604001511180156148b15750600084115b15614b875760008487604001516148c89190615e9d565b601c546040805160e081019091528281529192506000916001600160a01b039091169063f5f9c25790602081016148ff8a8a615d62565b815260006020820152604001614915868a615d62565b815260200160008152602001898c606001516149319190615e9d565b8152602001600a548152506040518263ffffffff1660e01b81526004016149589190615cd3565b60206040518083038186803b15801561497057600080fd5b505afa158015614984573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906149a89190615aab565b905060006149be89600001518a60200151611b48565b8951909150600090614a0290828c6020015160018111156149ef57634e487b7160e01b600052602160045260246000fd5b146149fb576000611b48565b6001611b48565b9050600082614a118584615e3f565b614a1b9190615da8565b90506000601c60009054906101000a90046001600160a01b03166001600160a01b0316632888a20d6040518060a001604052808d81526020018c81526020018d81526020018f608001518152602001600a548152506040518263ffffffff1660e01b8152600401614ac19190600060a082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015292915050565b60206040518083038186803b158015614ad957600080fd5b505afa158015614aed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614b119190615aab565b90506000614b1f828c615dbc565b90506000614b2d8489615e3f565b90506000614b3b898e615d62565b905080614b488385615d21565b614b529190615d7a565b9d5060008e1315614b79576000614b698f89615dbc565b9050614b758782615d7a565b9e50505b505050505050505050614c43565b601c546040805160e0810182528882015181526020810186905280820187905260608082018590526080820186905289015160a0820152600a5460c0820152905163f5f9c25760e01b81526001600160a01b039092169163f5f9c25791614bf091600401615cd3565b60206040518083038186803b158015614c0857600080fd5b505afa158015614c1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614c409190615aab565b94505b50505050919050565b600060115482111561159e57670de0b6b3a76400006002600a54614c709190615da8565b614c8290670de0b6b3a7640000615e9d565b600954614c8f9085615e9d565b614c999190615e3f565b611dea9190615da8565b600080826001600160a01b03166341bc7b1f6040518163ffffffff1660e01b815260040160606040518083038186803b158015614cdf57600080fd5b505afa158015614cf3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614d1791906159e3565b50509050614d2481612c2c565b9392505050565b6000614d80826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661542a9092919063ffffffff16565b80519091501561388a5780806020019051810190614d9e919061598e565b61388a5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016109f5565b601554604051639ca423b360e01b81526001600160a01b0385811660048301526000921690639ca423b39060240160206040518083038186803b158015614e4357600080fd5b505afa158015614e57573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614e7b9190615560565b90506001600160a01b03811615801590614e9757506000601654115b1561386557600654614eb3906001600160a01b0316828561386b565b604080516001600160a01b03808416825286166020820152908101849052606081018390527f8fa68a6a8e2fc9ff758a6e64afba8bc2f66fb082999a2c5225c8c49633faded49060800160405180910390a150505050565b601c54601f5460405163c2edfc7360e01b81526001600160a01b03868116600483015260009384939082169263e468265c928992899291169063c2edfc739060240160206040518083038186803b158015614f6557600080fd5b505afa158015614f79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614f9d9190615560565b6040518463ffffffff1660e01b8152600401614fbb93929190615b9f565b60206040518083038186803b158015614fd357600080fd5b505afa158015614fe7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061500b9190615aab565b905082811015610bd457610bd18184615e9d565b600f54600090156150af57336000908152601d602052604090205461504657600f54615057565b336000908152601d60205260409020545b61506990670de0b6b3a7640000615d62565b61507b670de0b6b3a764000085615e3f565b6150859190615da8565b61508f9084615e9d565b600e546006549192506150af916001600160a01b0390811691168361386b565b6007546001600160a01b03166317fd849a6150ca8386615e9d565b6040518263ffffffff1660e01b81526004016150e891815260200190565b60206040518083038186803b15801561510057600080fd5b505afa158015615114573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906151389190615aab565b6001600160a01b0385166000908152600d602052604090205411615174576001600160a01b0384166000908152600d602052604081205561523a565b6007546001600160a01b03166317fd849a61518f8386615e9d565b6040518263ffffffff1660e01b81526004016151ad91815260200190565b60206040518083038186803b1580156151c557600080fd5b505afa1580156151d9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906151fd9190615aab565b6001600160a01b0385166000908152600d60205260409020546152209190615e9d565b6001600160a01b0385166000908152600d60205260409020555b600060165411801561525657506015546001600160a01b031615155b15613865576000601654670de0b6b3a76400006152739190615d62565b615285670de0b6b3a764000086615e3f565b61528f9190615da8565b6152999085615e9d565b9050613b53838286614dfd565b600080856001600160a01b03166341bc7b1f6040518163ffffffff1660e01b815260040160606040518083038186803b1580156152e257600080fd5b505afa1580156152f6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061531a91906159e3565b506005546040516315905ec160e31b8152600481018490529294509092506000916101009091046001600160a01b03169063ac82f6089060240160206040518083038186803b15801561536c57600080fd5b505afa158015615380573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906153a49190615aab565b90506000808760018111156153c957634e487b7160e01b600052602160045260246000fd5b146153d6578282106153db565b828210155b60408051338152602081018990528215158183015290519192507f80631c28c8a8100630a9d2bce38b276a55426b59f4d47fb06072105118083ec1919081900360600190a15050505050505050565b6060612610848460008585843b6154835760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016109f5565b600080866001600160a01b0316858760405161549f9190615b33565b60006040518083038185875af1925050503d80600081146154dc576040519150601f19603f3d011682016040523d82523d6000602084013e6154e1565b606091505b50915091506154f18282866154fc565b979650505050505050565b6060831561550b575081614d24565b82511561551b5782518084602001fd5b8160405162461bcd60e51b81526004016109f59190615c0c565b80356002811061159e57600080fd5b600060208284031215615555578081fd5b8135614d2481615f27565b600060208284031215615571578081fd5b8151614d2481615f27565b6000806040838503121561558e578081fd5b823561559981615f27565b946020939093013593505050565b60008060008060008060c087890312156155bf578182fd5b86356155ca81615f27565b955060208701356155da81615f27565b945060408701356155ea81615f27565b935060608701356155fa81615f27565b9250608087013561560a81615f3c565b8092505060a087013590509295509295509295565b60008060408385031215615631578182fd5b823561563c81615f27565b9150602083013561564c81615f3c565b809150509250929050565b600080600080600080600080610100898b031215615673578182fd5b883561567e81615f27565b9750602089013561568e81615f27565b9650604089013561569e81615f27565b95506060890135945060808901356156b581615f27565b979a969950949793969560a0850135955060c08501359460e001359350915050565b600080604083850312156156e9578182fd5b82356156f481615f27565b915061570260208401615535565b90509250929050565b60008060006060848603121561571f578081fd5b833561572a81615f27565b925061573860208501615535565b9150604084013590509250925092565b6000806000806080858703121561575d578182fd5b843561576881615f27565b935061577660208601615535565b925060408501359150606085013561578d81615f27565b939692955090935050565b600080600080600060a086880312156157af578283fd5b85356157ba81615f27565b94506157c860208701615535565b94979496505050506040830135926060810135926080909101359150565b60008060008060008060c087890312156157fe578384fd5b863561580981615f27565b955061581760208801615535565b945060408701359350606087013592506080870135915060a087013561583c81615f27565b809150509295509295509295565b600080600080600080600060e0888a031215615864578081fd5b873561586f81615f27565b965061587d60208901615535565b955060408801359450606088013593506080880135925060a08801356158a281615f27565b915060c08801356158b281615f27565b8091505092959891949750929550565b6000806040838503121561558e578182fd5b6000806000806000608086880312156158eb578283fd5b853567ffffffffffffffff80821115615902578485fd5b818801915088601f830112615915578485fd5b813581811115615923578586fd5b8960208260051b8501011115615937578586fd5b6020928301975095505086013561594d81615f27565b925060408601359150606086013561596481615f3c565b809150509295509295909350565b600060208284031215615983578081fd5b8135614d2481615f3c565b60006020828403121561599f578081fd5b8151614d2481615f3c565b6000602082840312156159bb578081fd5b5035919050565b600080604083850312156159d4578182fd5b50508035926020909101359150565b6000806000606084860312156159f7578081fd5b8351925060208401519150604084015190509250925092565b60008060408385031215615a22578182fd5b8251615a2d81615f27565b602084015190925061564c81615f27565b60008060408385031215615a50578182fd5b8235615a5b81615f27565b9150602083013561564c81615f27565b600080600060608486031215615a7f578081fd5b8335615a8a81615f27565b92506020840135615a9a81615f27565b929592945050506040919091013590565b600060208284031215615abc578081fd5b5051919050565b60008060408385031215615ad5578182fd5b505080516020909101519092909150565b600080600060608486031215615afa578081fd5b505081359360208301359350604090920135919050565b60028110615b2f57634e487b7160e01b600052602160045260246000fd5b9052565b60008251615b45818460208701615eb4565b9190910192915050565b6001600160a01b038881168252878116602083015260e0820190615b766040840189615b11565b86606084015285608084015280851660a084015280841660c08401525098975050505050505050565b6001600160a01b0384811682526060820190615bbe6020840186615b11565b808416604084015250949350505050565b6001600160a01b03929092168252602082015260400190565b6001600160a01b038416815260208101839052606081016126106040830184615b11565b6020815260008251806020840152615c2b816040850160208701615eb4565b601f01601f19169190910160400192915050565b6020808252603c908201527f5468697320616374696f6e2063616e6e6f7420626520706572666f726d65642060408201527f7768696c652074686520636f6e74726163742069732070617573656400000000606082015260800190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b600060e082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015292915050565b600080821280156001600160ff1b0384900385131615615d4357615d43615efb565b600160ff1b8390038412811615615d5c57615d5c615efb565b50500190565b60008219821115615d7557615d75615efb565b500190565b600082615d8957615d89615f11565b600160ff1b821460001984141615615da357615da3615efb565b500590565b600082615db757615db7615f11565b500490565b60006001600160ff1b0381841382841380821686840486111615615de257615de2615efb565b600160ff1b84871282811687830589121615615e0057615e00615efb565b858712925087820587128484161615615e1b57615e1b615efb565b87850587128184161615615e3157615e31615efb565b505050929093029392505050565b6000816000190483118215151615615e5957615e59615efb565b500290565b60008083128015600160ff1b850184121615615e7c57615e7c615efb565b6001600160ff1b0384018313811615615e9757615e97615efb565b50500390565b600082821015615eaf57615eaf615efb565b500390565b60005b83811015615ecf578181015183820152602001615eb7565b838111156138655750506000910152565b6000600019821415615ef457615ef4615efb565b5060010190565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052601260045260246000fd5b6001600160a01b0381168114610bac57600080fd5b8015158114610bac57600080fdfea2646970667358221220ba0f21cd9672c0c2d6d6f62f09152af48401095a3f651825bc00257b0d65f23964736f6c63430008040033

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106103fc5760003560e01c80638517020911610215578063cafb3ca211610125578063ebc79772116100b8578063f502b00311610087578063f502b003146108cd578063f8debeb7146108ed578063fb91d41c14610900578063fc1ed85714610909578063fd8a8cc61461091c57600080fd5b8063ebc797721461088c578063efb1fe3514610894578063efc15251146108a7578063f4b9fa75146108ba57600080fd5b8063d3dc7539116100f4578063d3dc75391461083f578063d4a2641b14610852578063d69fb6681461087a578063df8974d01461088357600080fd5b8063cafb3ca2146107f3578063d162492414610806578063d333ca1914610819578063d3c4297c1461082c57600080fd5b8063a5bf660d116101a8578063bf996ae311610177578063bf996ae314610787578063c2783f921461079a578063c3b83f5f146107ad578063c4dc27d7146107c0578063c8f0b4ec146107e057600080fd5b8063a5bf660d1461073b578063ad18f0da1461074e578063bbdf88ce14610761578063bf46c0b41461077457600080fd5b8063931b2040116101e4578063931b2040146106f95780639324cac7146107025780639f916c9f14610715578063a273ecf11461072857600080fd5b806385170209146106b15780638875eb84146106c45780638da5cb5b146106d757806391b4ded9146106f057600080fd5b8063481c6a7511610310578063665a11ca116102a35780636ed033f8116102725780636ed033f814610658578063741bef1a1461066b57806379ba5097146106835780637b337a361461068b578063826153491461069e57600080fd5b8063665a11ca146106205780636aaa81b6146106335780636cc5a6ff1461063c5780636e88a7bd1461064f57600080fd5b80635727a0f3116102df5780635727a0f3146105cd5780635c975abb146105e05780635ef85b26146105ed57806365f567721461060057600080fd5b8063481c6a751461058157806348663e95146105945780634a50215e146105a757806353a47bb7146105ba57600080fd5b80631fbb38e8116103935780632f48ab7d116103625780632f48ab7d14610514578063316425c31461053f5780633443b326146105485780633ce1108d1461055b5780633e413bee1461056e57600080fd5b80631fbb38e8146104c4578063270e13ef146104d85780632909f51a146104eb5780632972e8ab146104f457600080fd5b80631627540c116103cf5780631627540c1461048257806316c38b3c1461049557806319b844a6146104a85780631c37d04b146104b157600080fd5b8063018770201461040157806306c933d8146104165780630f13aae81461044e57806313af40351461046f575b600080fd5b61041461040f366004615544565b61092f565b005b610439610424366004615544565b60146020526000908152604090205460ff1681565b60405190151581526020015b60405180910390f35b61046161045c36600461570b565b610959565b604051908152602001610445565b61041461047d366004615544565b6109a3565b610414610490366004615544565b610ae3565b6104146104a3366004615972565b610b39565b61046160125481565b6104616104bf36600461570b565b610baf565b601a5461043990600160a01b900460ff1681565b6104616104e636600461570b565b610bdc565b610461601b5481565b610461610502366004615544565b601e6020526000908152604090205481565b601954610527906001600160a01b031681565b6040516001600160a01b039091168152602001610445565b610461600a5481565b6104146105563660046158c2565b610c35565b610461610569366004615798565b610c59565b601854610527906001600160a01b031681565b600754610527906001600160a01b031681565b600e54610527906001600160a01b031681565b6104146105b53660046158d4565b611252565b600154610527906001600160a01b031681565b6104396105db366004615544565b6113f3565b6003546104399060ff1681565b6104146105fb3660046159c2565b6115a3565b61046161060e366004615544565b601d6020526000908152604090205481565b601f54610527906001600160a01b031681565b61046160095481565b61046161064a36600461584a565b6117c9565b61046160165481565b6104616106663660046156d7565b611b48565b6005546105279061010090046001600160a01b031681565b610414611df0565b61041461069936600461561f565b611eed565b6104146106ac3660046159c2565b611f20565b6104146106bf3660046159aa565b611f95565b6104616106d2366004615798565b611fd2565b600054610527906201000090046001600160a01b031681565b61046160025481565b61046160115481565b600654610527906001600160a01b031681565b6104616107233660046157e6565b612046565b6104146107363660046158c2565b61213a565b601754610527906001600160a01b031681565b61041461075c366004615657565b61215e565b61041461076f366004615a3e565b612283565b61046161078236600461570b565b612332565b610414610795366004615544565b61245a565b6104616107a83660046156d7565b6125d2565b6104146107bb366004615544565b612618565b6104616107ce366004615544565b600d6020526000908152604090205481565b6104146107ee366004615ae6565b612731565b610414610801366004615a6b565b61278e565b6104146108143660046159c2565b6127cb565b610414610827366004615544565b61281b565b61041461083a3660046155a7565b612845565b601554610527906001600160a01b031681565b610865610860366004615748565b612a45565b60408051928352602083019190915201610445565b610461600f5481565b610461600c5481565b610414612b5e565b6104146108a236600461557c565b612bbc565b6104616108b53660046156d7565b612bdf565b601a54610527906001600160a01b031681565b6104616108db3660046159aa565b600b6020526000908152604090205481565b6104616108fb3660046159aa565b612c2c565b61046160085481565b6104146109173660046158c2565b612ce3565b601054610527906001600160a01b031681565b610937612d3b565b601f80546001600160a01b0319166001600160a01b0392909216919091179055565b6000806109668585611b48565b90506012548111610977578061097b565b6012545b9050600061098a868684612db5565b90506109998686868585612f90565b9695505050505050565b6001600160a01b0381166109fe5760405162461bcd60e51b815260206004820152601960248201527f4f776e657220616464726573732063616e6e6f7420626520300000000000000060448201526064015b60405180910390fd5b600154600160a01b900460ff1615610a6a5760405162461bcd60e51b815260206004820152602960248201527f416c726561647920696e697469616c697a65642c20757365206e6f6d696e617460448201526832a732bba7bbb732b960b91b60648201526084016109f5565b6001805460ff60a01b1916600160a01b179055600080546001600160a01b03831662010000810262010000600160b01b03199092169190911782556040805192835260208301919091527fb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c91015b60405180910390a150565b610aeb612d3b565b600180546001600160a01b0319166001600160a01b0383169081179091556040519081527f906a1c6bd7e3091ea86693dd029a831c19049ce77f1dce2ce0bab1cacbabce2290602001610ad8565b610b41612d3b565b60035460ff1615158115151415610b555750565b6003805460ff191682151590811790915560ff1615610b7357426002555b60035460405160ff909116151581527f8fb6c181ee25a520cf3dd6565006ef91229fcfe5a989566c2a3b8c115570cec590602001610ad8565b50565b600080610bbc85856125d2565b9050808311610bd457610bd1858585846130bc565b91505b509392505050565b600080610be98585611b48565b90506000610bff82670de0b6b3a7640000615e9d565b90508115610c2c576011548210610c165781610c1a565b6011545b91506109998686868585600f546132ce565b50509392505050565b610c3d612d3b565b6001600160a01b039091166000908152601e6020526040902055565b6000600160046000828254610c6e9190615d62565b909155505060045460035460ff1615610c995760405162461bcd60e51b81526004016109f590615c3f565b610ca2876113f3565b610cee5760405162461bcd60e51b815260206004820152601e60248201527f4d61726b6574206973206e6f7420696e2054726164696e67207068617365000060448201526064016109f5565b6000610cfa8888611b48565b90506012548111610d0b5780610d0f565b6012545b90506000610d1e898984612db5565b9050600081118015610d305750808711155b610d745760405162461bcd60e51b81526020600482015260156024820152742737ba1032b737bab3b4103634b8bab4b234ba3c9760591b60448201526064016109f5565b6000610d838a8a8a8686612f90565b9050610d9786670de0b6b3a7640000615d62565b81610daa670de0b6b3a76400008a615e3f565b610db49190615da8565b1115610df65760405162461bcd60e51b81526020600482015260116024820152700a6d8d2e0e0c2ceca40e8dede40d0d2ced607b1b60448201526064016109f5565b6000610e028b8b613570565b9050610e0d8b613617565b610e226001600160a01b03821633308c6137fa565b6007546040516314edbee160e31b81523060048201526000916001600160a01b039081169163edc892e1918f169063a76df7089060240160206040518083038186803b158015610e7157600080fd5b505afa158015610e85573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ea99190615aab565b6040518263ffffffff1660e01b8152600401610ec791815260200190565b60206040518083038186803b158015610edf57600080fd5b505afa158015610ef3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f179190615aab565b90508015610f73578b6001600160a01b031663f5571beb6040518163ffffffff1660e01b8152600401600060405180830381600087803b158015610f5a57600080fd5b505af1158015610f6e573d6000803e3d6000fd5b505050505b600083600f54670de0b6b3a7640000610f8c9190615e9d565b610f9e670de0b6b3a764000087615e3f565b610fa89190615da8565b610fb29190615e9d565b9050600084601654670de0b6b3a7640000610fcd9190615e9d565b610fdf670de0b6b3a764000088615e3f565b610fe99190615da8565b610ff39190615e9d565b9050600f546000141561100557600091505b601f60009054906101000a90046001600160a01b03166001600160a01b03166358c09cc08f600760009054906101000a90046001600160a01b03166001600160a01b03166317fd849a85878b61105b9190615d62565b6110659190615d62565b6040518263ffffffff1660e01b815260040161108391815260200190565b60206040518083038186803b15801561109b57600080fd5b505afa1580156110af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110d39190615aab565b6040518363ffffffff1660e01b81526004016110f0929190615bcf565b600060405180830381600087803b15801561110a57600080fd5b505af115801561111e573d6000803e3d6000fd5b505060065461113a92506001600160a01b03169050338761386b565b6010546001600160a01b0316156111b0576010546040516302c7739b60e01b81526001600160a01b03909116906302c7739b9061117d9033908990600401615bcf565b600060405180830381600087803b15801561119757600080fd5b505af11580156111ab573d6000803e3d6000fd5b505050505b6111bd8e8685338661388f565b6111c68e613b5a565b7f1d6ff70c632edb1e6aba7fbc0148db68c8392e30f9dfaadae2543a2543757cf6338f8f8f89600660009054906101000a90046001600160a01b03168a6040516112169796959493929190615b4f565b60405180910390a150929650505050505060045481146112485760405162461bcd60e51b81526004016109f590615c9c565b5095945050505050565b61125a612d3b565b836112a75760405162461bcd60e51b815260206004820152601a60248201527f746f6b656e732061727261792063616e7420626520656d70747900000000000060448201526064016109f5565b60005b848110156113eb5781156113b4576113af848787848181106112dc57634e487b7160e01b600052603260045260246000fd5b90506020020160208101906112f19190615544565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a082319060240160206040518083038186803b15801561133257600080fd5b505afa158015611346573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061136a9190615aab565b88888581811061138a57634e487b7160e01b600052603260045260246000fd5b905060200201602081019061139f9190615544565b6001600160a01b0316919061386b565b6113d9565b6113d9848488888581811061138a57634e487b7160e01b600052603260045260246000fd5b806113e381615ee0565b9150506112aa565b505050505050565b600754604051633761c52760e11b81526001600160a01b0383811660048301526000921690636ec38a4e9060240160206040518083038186803b15801561143957600080fd5b505afa15801561144d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611471919061598e565b1561159e5760008290506000816001600160a01b03166341bc7b1f6040518163ffffffff1660e01b815260040160606040518083038186803b1580156114b657600080fd5b505afa1580156114ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114ee91906159e3565b505090506000826001600160a01b0316639e3b34bf6040518163ffffffff1660e01b8152600401604080518083038186803b15801561152c57600080fd5b505afa158015611540573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115649190615ac3565b506000838152600b6020526040902054909150158061158257504281105b61159a5760006115924283615e9d565b600c54109450505b5050505b919050565b3360009081526014602052604090205460ff16806115d157506000546201000090046001600160a01b031633145b6116385760405162461bcd60e51b815260206004820152603260248201527f4f6e6c792077686974656c697374656420616464726573736573206f72206f776044820152716e65722063616e206368616e67652049562160701b60648201526084016109f5565b61164b670de0b6b3a7640000600a615e3f565b8111801561166b5750611668670de0b6b3a764000061012c615e3f565b81105b6116b75760405162461bcd60e51b815260206004820152601960248201527f4956206f757473696465206d696e2f6d61782072616e6765210000000000000060448201526064016109f5565b6005546040516315905ec160e31b8152600481018490526101009091046001600160a01b03169063ac82f6089060240160206040518083038186803b1580156116ff57600080fd5b505afa158015611713573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117379190615aab565b6117795760405162461bcd60e51b8152602060048201526013602482015272417373657420686173206e6f2070726963652160681b60448201526064016109f5565b6000828152600b602090815260409182902083905581518481529081018390527f715e0a52c0b74c77d2d2012a363ac95b494302ad2abb78ac7406ec93451f1adb91015b60405180910390a15050565b60006001600460008282546117de9190615d62565b909155505060045460035460ff16156118095760405162461bcd60e51b81526004016109f590615c3f565b6001600160a01b0383161561187e5760155460405163bbddaca360e01b81526001600160a01b0385811660048301523360248301529091169063bbddaca390604401600060405180830381600087803b15801561186557600080fd5b505af1158015611879573d6000803e3d6000fd5b505050505b600061188985613e2d565b9050600081600f0b1380156118a75750601a54600160a01b900460ff165b6118ec5760405162461bcd60e51b81526020600482015260166024820152751d5b9cdd5c1c1bdc9d19590818dbdb1b185d195c985b60521b60448201526064016109f5565b6000806118fb8c8c8c8a612a45565b60185491935091506000906001600160a01b038981169116148061192c57506019546001600160a01b038981169116145b6119365782611945565b6119458364e8d4a51000615e3f565b90506000601b5411801561198b5750670de0b6b3a7640000601b54670de0b6b3a76400006119739190615e9d565b61197d9084615e3f565b6119879190615da8565b8110155b6119e55760405162461bcd60e51b815260206004820152602560248201527f416d6f756e742062656c6f77206d617820616c6c6f7765642070656720736c69604482015264707061676560d81b60648201526084016109f5565b6119f789670de0b6b3a7640000615d62565b8a611a0a670de0b6b3a764000086615e3f565b611a149190615da8565b1115611a575760405162461bcd60e51b8152602060048201526012602482015271536c69707061676520746f6f20686967682160701b60448201526064016109f5565b87611a6d6001600160a01b0382163330876137fa565b601754604051635320bf6b60e11b8152600f87900b60048201526000602482015260448101869052606481018590526001600160a01b039091169063a6417ed690608401602060405180830381600087803b158015611acb57600080fd5b505af1158015611adf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b039190615aab565b50611b148e8e8e868e600089613e92565b965050505050506004548114611b3c5760405162461bcd60e51b81526004016109f590615c9c565b50979650505050505050565b6000611b53836113f3565b15611dea5760008390506000816001600160a01b0316639e3b34bf6040518163ffffffff1660e01b8152600401604080518083038186803b158015611b9757600080fd5b505afa158015611bab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bcf9190615ac3565b5090506000611bde4283615e9d565b9050600062015180611bf8670de0b6b3a764000084615e3f565b611c029190615da8565b90506000846001600160a01b031663668aa8246040518163ffffffff1660e01b815260040160206040518083038186803b158015611c3f57600080fd5b505afa158015611c53573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c779190615aab565b9050600080866001600160a01b03166341bc7b1f6040518163ffffffff1660e01b815260040160606040518083038186803b158015611cb557600080fd5b505afa158015611cc9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ced91906159e3565b50601c546000838152600b602052604090819020549051631519a0dd60e31b815260048101889052602481018490526044810189905260648082019290925293955091935090916001600160a01b039091169063a8cd06e89060840160206040518083038186803b158015611d6157600080fd5b505afa158015611d75573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d999190615aab565b611da39190615da8565b97506001896001811115611dc757634e487b7160e01b600052602160045260246000fd5b1415611de257611ddf88670de0b6b3a7640000615e9d565b97505b505050505050505b92915050565b6001546001600160a01b03163314611e685760405162461bcd60e51b815260206004820152603560248201527f596f75206d757374206265206e6f6d696e61746564206265666f726520796f7560448201527402063616e20616363657074206f776e65727368697605c1b60648201526084016109f5565b60005460015460408051620100009093046001600160a01b03908116845290911660208301527fb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c910160405180910390a1600180546000805462010000600160b01b0319166001600160a01b03831662010000021790556001600160a01b0319169055565b611ef5612d3b565b6001600160a01b03919091166000908152601460205260409020805460ff1916911515919091179055565b611f28612d3b565b6009829055600a8190556040518281527f1e6a338a58debcc786781a079c4459466b102ad0156cc84f51d25ef7dd8cb9b09060200160405180910390a16040518181527f4af6d03c4624e0a6b868b8f6453e047f23f3ea15e9d08c938bd4c445d7ef19b3906020016117bd565b611f9d612d3b565b600c8190556040518181527fdc469b5583fa9b7ebd3245e1665334cd758c4bef4c5a132c62baca85effacfec90602001610ad8565b6000600160046000828254611fe79190615d62565b909155505060045460035460ff16156120125760405162461bcd60e51b81526004016109f590615c3f565b612023878787878760016000613e92565b915060045481146112485760405162461bcd60e51b81526004016109f590615c9c565b600060016004600082825461205b9190615d62565b909155505060045460035460ff16156120865760405162461bcd60e51b81526004016109f590615c3f565b6001600160a01b038316156120fb5760155460405163bbddaca360e01b81526001600160a01b0385811660048301523360248301529091169063bbddaca390604401600060405180830381600087803b1580156120e257600080fd5b505af11580156120f6573d6000803e3d6000fd5b505050505b61210c888888888860016000613e92565b9150600454811461212f5760405162461bcd60e51b81526004016109f590615c9c565b509695505050505050565b612142612d3b565b6001600160a01b039091166000908152601d6020526040902055565b600054610100900460ff166121795760005460ff161561217d565b303b155b6121e05760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016109f5565b600054610100900460ff16158015612202576000805461ffff19166101011790555b61220b896109a3565b612213612b5e565b60058054610100600160a81b0319166101006001600160a01b038b81169190910291909117909155600680546001600160a01b03191691891691909117905560088690556009849055600a839055600c8290558015612278576000805461ff00191690555b505050505050505050565b61228b612d3b565b60058054610100600160a81b0319166101006001600160a01b038516908102919091179091556040519081527ff724a45d041687842411f2b977ef22ab8f43c8f1104f4592b42a00f9b34a643d9060200160405180910390a1600680546001600160a01b0319166001600160a01b0383169081179091556040519081527f74a8764fc8d62d2d844c8c54426bd94ad034e0e92abdf5280ff75e2cbd678fb6906020016117bd565b6000808084600181111561235657634e487b7160e01b600052602160045260246000fd5b14612362576000612365565b60015b905060006123738686611b48565b9050601154811015801561238957506012548111155b15610c2c5760006123a282670de0b6b3a7640000615e9d565b905060006123b3888885600161436b565b905060006123c4898685600161436b565b90506000871180156123d65750818711155b1561244e5761244b6040518060e001604052808b6001600160a01b031681526020018a600181111561241857634e487b7160e01b600052602160045260246000fd5b8152602081018a90526040810185905260608101849052601f546001600160a01b0316608082015260a001869052614640565b95505b50505050509392505050565b612462612d3b565b6007546001600160a01b0316156124fe5760065460075460405163095ea7b360e01b81526001600160a01b039283169263095ea7b3926124aa92911690600090600401615bcf565b602060405180830381600087803b1580156124c457600080fd5b505af11580156124d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124fc919061598e565b505b600780546001600160a01b0319166001600160a01b0383811691821790925560065460405163095ea7b360e01b815292169163095ea7b3916125469160001990600401615bcf565b602060405180830381600087803b15801561256057600080fd5b505af1158015612574573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612598919061598e565b506040516001600160a01b03821681527f9987372437ace1af79923f26b948aa04afef92b2b7786144c5aae621ea84eb0a90602001610ad8565b60006125dd836113f3565b15611dea5760006125ee8484611b48565b905060125481116125ff5780612603565b6012545b9050612610848483612db5565b949350505050565b612620612d3b565b6001600160a01b0381166126685760405162461bcd60e51b815260206004820152600f60248201526e496e76616c6964206164647265737360881b60448201526064016109f5565b600154600160a81b900460ff16156126b85760405162461bcd60e51b8152602060048201526013602482015272105b1c9958591e481d1c985b9cd9995c9c9959606a1b60448201526064016109f5565b600080546001600160a01b038381166201000081810262010000600160b01b031990941693909317938490556001805460ff60a81b1916600160a81b1790556040805193909404909116825260208201527fb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c9101610ad8565b612739612d3b565b60118390556012829055600881905560408051848152602081018490529081018290527f0e8c2ebd67ea2d796a34f02c777ec06f5faedd1669b272dc08dc7875486ae0809060600160405180910390a1505050565b612796612d3b565b601080546001600160a01b039485166001600160a01b0319918216179091556015805493909416921691909117909155601655565b6127d3612d3b565b60008281526013602090815260409182902083905581518481529081018390527f5af395595015797b4d0f26b77c38dd4831298dabc7906ee3d62b80fa75d35c1e91016117bd565b612823612d3b565b601c80546001600160a01b0319166001600160a01b0392909216919091179055565b61284d612d3b565b601780546001600160a01b038089166001600160a01b031992831617909255601a8054888416908316811790915560188054888516908416179055601980549387169390921692909217905560405163095ea7b360e01b815263095ea7b3906128be90899060001990600401615bcf565b602060405180830381600087803b1580156128d857600080fd5b505af11580156128ec573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612910919061598e565b5060185460405163095ea7b360e01b81526001600160a01b039091169063095ea7b39061294590899060001990600401615bcf565b602060405180830381600087803b15801561295f57600080fd5b505af1158015612973573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612997919061598e565b5060195460405163095ea7b360e01b81526001600160a01b039091169063095ea7b3906129cc90899060001990600401615bcf565b602060405180830381600087803b1580156129e657600080fd5b505af11580156129fa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a1e919061598e565b50601a8054921515600160a01b0260ff60a01b1990931692909217909155601b5550505050565b6000806000612a5384613e2d565b9050600081600f0b138015612a715750601a54600160a01b900460ff165b15612b5457612a81878787610bdc565b9150670de0b6b3a7640000612a9e6005662386f26fc10000615da8565b612ab090670de0b6b3a7640000615d62565b6017546040516307211ef760e01b815260006004820152600f85900b6024820152604481018690526001600160a01b03909116906307211ef79060640160206040518083038186803b158015612b0557600080fd5b505afa158015612b19573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b3d9190615aab565b612b479190615e3f565b612b519190615da8565b92505b5094509492505050565b60055460ff1615612ba75760405162461bcd60e51b8152602060048201526013602482015272105b1c9958591e481a5b9a5d1a585b1a5e9959606a1b60448201526064016109f5565b6005805460ff19166001908117909155600455565b612bc4612d3b565b600654612bdb906001600160a01b0316838361386b565b5050565b6000612bea836113f3565b15611dea576000612bfb8484611b48565b90508015612c25576011548110612c125780612c16565b6011545b9050612610848483600061436b565b5092915050565b6005546040516315905ec160e31b81526004810183905260009161010090046001600160a01b03169063ac82f6089060240160206040518083038186803b158015612c7657600080fd5b505afa158015612c8a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cae9190615aab565b1561159e5760008281526013602052604090205415612cdb57600082815260136020526040902054611dea565b505060085490565b612ceb612d3b565b600f819055600e80546001600160a01b0319166001600160a01b0384161790556040518181527f01edd423db862fb00774918e3b06d9c1dd3db9a99b5a194c439d2f141876f444906020016117bd565b6000546201000090046001600160a01b03163314612db35760405162461bcd60e51b815260206004820152602f60248201527f4f6e6c792074686520636f6e7472616374206f776e6572206d6179207065726660448201526e37b936903a3434b99030b1ba34b7b760891b60648201526084016109f5565b565b600080612dc183614c4c565b90508015610bd457601c54601f5460405163c2edfc7360e01b81526001600160a01b038881166004830152600093811692636116ad1e928a928a92169063c2edfc739060240160206040518083038186803b158015612e1f57600080fd5b505afa158015612e33573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e579190615560565b6040518463ffffffff1660e01b8152600401612e7593929190615b9f565b604080518083038186803b158015612e8c57600080fd5b505afa158015612ea0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ec49190615ac3565b915060009050670de0b6b3a7640000612edd8484615e3f565b612ee79190615da8565b9050600082612ef589614ca3565b612eff9190615d62565b6001600160a01b0389166000908152600d6020526040902054909150612f26908390615d62565b8110612f85576001600160a01b0388166000908152600d60205260408120548390612f519084615e9d565b612f5b9190615e9d565b905083670de0b6b3a7640000612f718784615da8565b612f7b9190615e3f565b61244b9190615d62565b505050509392505050565b60008184116130b357600954612fa69084615e9d565b92506000670de0b6b3a764000080612fc0898989886130bc565b612fd290670de0b6b3a7640000615e9d565b612fdc9087615e3f565b612fe69190615da8565b612ff09087615e3f565b612ffa9190615da8565b90506000670de0b6b3a7640000600f54670de0b6b3a764000061301d9190615e9d565b6130279084615e3f565b6130319190615da8565b60075460405163edc892e160e01b8152600481018390529192506001600160a01b03169063edc892e19060240160206040518083038186803b15801561307657600080fd5b505afa15801561308a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130ae9190615aab565b925050505b95945050505050565b601c54601f5460405163c2edfc7360e01b81526001600160a01b0387811660048301526000938493849391831692636116ad1e928b928b92169063c2edfc739060240160206040518083038186803b15801561311757600080fd5b505afa15801561312b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061314f9190615560565b6040518463ffffffff1660e01b815260040161316d93929190615b9f565b604080518083038186803b15801561318457600080fd5b505afa158015613198573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131bc9190615ac3565b9150915060008083116131e6578582116131df576131da8287615e9d565b6131f0565b60006131f0565b6131f08684615d62565b9050600086831161320257600061320c565b61320c8784615e9d565b90508082106132c257601c54600a546040516327b76a6b60e21b8152600481018a90526024810186905260448101879052606481018490526084810185905260a4810189905260c48101919091526001600160a01b0390911690639edda9ac9060e40160206040518083038186803b15801561328757600080fd5b505afa15801561329b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132bf9190615aab565b94505b50505050949350505050565b6000806132de888887600061436b565b9050600061331e89828a600181111561330757634e487b7160e01b600052602160045260246000fd5b14613313576000613316565b60015b87600161436b565b90508187116135645760008061339a6040518060e001604052808d6001600160a01b031681526020018c600181111561336757634e487b7160e01b600052602160045260246000fd5b8152602081018c90526040810187905260608101869052601f546001600160a01b0316608082015260a0018a9052614640565b336000908152601e60205260409020549091506133b9576009546133ca565b336000908152601e60205260409020545b6133d49089615d62565b97506000811261347c576000670de0b6b3a7640000826133f48b83615e5e565b6133fe9190615dbc565b6134089190615d7a565b9050670de0b6b3a7640000613425662386f26fc100006002615dbc565b61343790670de0b6b3a7640000615d21565b6134419083615dbc565b61344b9190615d7a565b9050670de0b6b3a7640000613460828b615d21565b61346a908c615dbc565b6134749190615d7a565b9250506134bb565b670de0b6b3a7640000806134908382615d21565b61349a908b615dbc565b6134a49190615d7a565b6134ae908b615dbc565b6134b89190615d7a565b91505b670de0b6b3a76400006134ce8782615d21565b6134d89084615dbc565b6134e29190615d7a565b60075460405163edc892e160e01b8152600481018390529193506001600160a01b03169063edc892e19060240160206040518083038186803b15801561352757600080fd5b505afa15801561353b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061355f9190615aab565b945050505b50509695505050505050565b6000806000846001600160a01b031663cc2ee1966040518163ffffffff1660e01b8152600401604080518083038186803b1580156135ad57600080fd5b505afa1580156135c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135e59190615a10565b9092509050600084600181111561360c57634e487b7160e01b600052602160045260246000fd5b14610bd457806130b3565b601c54601f5460405163c2edfc7360e01b81526001600160a01b03848116600483015260009384939082169263ea25928a928792169063c2edfc739060240160206040518083038186803b15801561366e57600080fd5b505afa158015613682573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136a69190615560565b6040516001600160e01b031960e085901b1681526001600160a01b03928316600482015291166024820152604401604080518083038186803b1580156136eb57600080fd5b505afa1580156136ff573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137239190615ac3565b601f54604051631051f9d160e31b81529294509092506001600160a01b03169063828fce889061375c9086908690600090600401615be8565b600060405180830381600087803b15801561377657600080fd5b505af115801561378a573d6000803e3d6000fd5b5050601f54604051631051f9d160e31b81526001600160a01b03909116925063828fce8891506137c39086908590600190600401615be8565b600060405180830381600087803b1580156137dd57600080fd5b505af11580156137f1573d6000803e3d6000fd5b50505050505050565b6040516001600160a01b03808516602483015283166044820152606481018290526138659085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614d2b565b50505050565b61388a8363a9059cbb60e01b848460405160240161382e929190615bcf565b505050565b600f54156138b457600e546006546138b4916001600160a01b0391821691168361386b565b6007546001600160a01b03166317fd849a6138cf8387615d62565b6040518263ffffffff1660e01b81526004016138ed91815260200190565b60206040518083038186803b15801561390557600080fd5b505afa158015613919573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061393d9190615aab565b6001600160a01b0386166000908152600d60205260409020546139609190615d62565b6001600160a01b038681166000908152600d602052604090819020929092556007549151630bfec24d60e11b8152600481018690529116906317fd849a9060240160206040518083038186803b1580156139b957600080fd5b505afa1580156139cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139f19190615aab565b6001600160a01b0386166000908152600d602052604090205411613a2d576001600160a01b0385166000908152600d6020526040812055613ae6565b600754604051630bfec24d60e11b8152600481018590526001600160a01b03909116906317fd849a9060240160206040518083038186803b158015613a7157600080fd5b505afa158015613a85573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613aa99190615aab565b6001600160a01b0386166000908152600d6020526040902054613acc9190615e9d565b6001600160a01b0386166000908152600d60205260409020555b6000601654118015613b0257506015546001600160a01b031615155b15613b5357600084601654670de0b6b3a7640000613b209190615e9d565b613b32670de0b6b3a764000088615e3f565b613b3c9190615da8565b613b469190615e9d565b90506113eb838287614dfd565b5050505050565b601f5460405163f475f13b60e01b81526001600160a01b038381166004830152600092169063f475f13b90602401602060405180830381600087803b158015613ba257600080fd5b505af1158015613bb6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613bda9190615560565b6006546040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a082319060240160206040518083038186803b158015613c2357600080fd5b505afa158015613c37573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c5b9190615aab565b1115613cf5576006546040516370a0823160e01b8152306004820152613cf59183916001600160a01b03909116906370a082319060240160206040518083038186803b158015613caa57600080fd5b505afa158015613cbe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ce29190615aab565b6006546001600160a01b0316919061386b565b600080836001600160a01b031663cc2ee1966040518163ffffffff1660e01b8152600401604080518083038186803b158015613d3057600080fd5b505afa158015613d44573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d689190615a10565b601c54604051637512c94560e11b81526001600160a01b038881166004830152306024830152939550919350600092839291169063ea25928a90604401604080518083038186803b158015613dbc57600080fd5b505afa158015613dd0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613df49190615ac3565b90925090508115613e1357613e136001600160a01b038516868461386b565b80156113eb576113eb6001600160a01b038416868361386b565b601a546000906001600160a01b0383811691161415613e4e57506001919050565b6018546001600160a01b0383811691161415613e6c57506002919050565b6019546001600160a01b0383811691161415613e8a57506003919050565b506000919050565b6000613e9d886113f3565b613ee95760405162461bcd60e51b815260206004820152601e60248201527f4d61726b6574206973206e6f7420696e2054726164696e67207068617365000060448201526064016109f5565b50806000613ef78989611b48565b90506000613f0d82670de0b6b3a7640000615e9d565b90506011548210613f1e5781613f22565b6011545b91506000613f338b8b85600061436b565b9050600089118015613f455750808911155b613f895760405162461bcd60e51b81526020600482015260156024820152742737ba1032b737bab3b4103634b8bab4b234ba3c9760591b60448201526064016109f5565b851561405957336000908152601d6020526040902054613fce908c908c908c9087908790613fb957600f546132ce565b336000908152601d60205260409020546132ce565b9350613fe287670de0b6b3a7640000615d62565b88613ff5670de0b6b3a764000087615e3f565b613fff9190615da8565b11156140415760405162461bcd60e51b81526020600482015260116024820152700a6d8d2e0e0c2ceca40e8dede40d0d2ced607b1b60448201526064016109f5565b600654614059906001600160a01b03163330876137fa565b60006140668c8c8c614f0b565b9050801561416a57601f54604051630163027360e61b81526001600160a01b03909116906358c09cc0906140a0908f908590600401615bcf565b600060405180830381600087803b1580156140ba57600080fd5b505af11580156140ce573d6000803e3d6000fd5b505060405163140e25ad60e31b8152600481018490526001600160a01b038f16925063a0712d689150602401600060405180830381600087803b15801561411457600080fd5b505af1158015614128573d6000803e3d6000fd5b5050506001600160a01b038d166000908152600d602052604090205461415091508290615d62565b6001600160a01b038d166000908152600d60205260409020555b601f546001600160a01b031663828fce888d614186848e615e9d565b8e6040518463ffffffff1660e01b81526004016141a593929190615be8565b600060405180830381600087803b1580156141bf57600080fd5b505af11580156141d3573d6000803e3d6000fd5b5050505060006141e38d8d613570565b90506141f96001600160a01b038216338d61386b565b6010546001600160a01b03161561426f576010546040516302c7739b60e01b81526001600160a01b03909116906302c7739b9061423c9033908a90600401615bcf565b600060405180830381600087803b15801561425657600080fd5b505af115801561426a573d6000803e3d6000fd5b505050505b61427a8d873361501f565b818b11156142ee57600061428e838d615e9d565b905060008c61429d838a615e3f565b6142a79190615da8565b60408051338152602081018590529081018290529091507ff8a5b21533fcaaeee91cd7b3c6ccbaa3f4ab6dd200e61bc560713565b20b1e9a9060600160405180910390a150505b6142f78d613b5a565b7ff3bfbc0822d1ed667a2b298e71e0304f2c1f4685398189d7c39e412f733150f4338e8e8e8a600660009054906101000a90046001600160a01b0316876040516143479796959493929190615b4f565b60405180910390a161435b8d8d88336152a6565b5050505050979650505050505050565b6000818061437a575060125483105b156126105760095461438c9084615d62565b9250670de0b6b3a7640000831015612610576000670de0b6b3a76400006002600a546143b89190615da8565b6143ca90670de0b6b3a7640000615e9d565b6143d49086615e3f565b6143de9190615da8565b601c54601f5460405163c2edfc7360e01b81526001600160a01b038a811660048301529394506000939283169263e468265c928b928b929091169063c2edfc739060240160206040518083038186803b15801561443a57600080fd5b505afa15801561444e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906144729190615560565b6040518463ffffffff1660e01b815260040161449093929190615b9f565b60206040518083038186803b1580156144a857600080fd5b505afa1580156144bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906144e09190615aab565b90506000670de0b6b3a76400006144f78484615e3f565b6145019190615da8565b6001600160a01b0389166000908152600d6020526040902054909150816145278a614ca3565b6145319190615d62565b1115614635576001600160a01b0388166000908152600d60205260408120548261455a8b614ca3565b6145649190615d62565b61456e9190615e9d565b905061457989614ca3565b81111561458c5761458989614ca3565b90505b6000670de0b6b3a76400006002600a546145a69190615da8565b6145b88a670de0b6b3a7640000615e9d565b6145c29190615e3f565b6145cc9190615da8565b9050670de0b6b3a76400006145e1828a615d62565b10156146325760006145f3828a615d62565b61460590670de0b6b3a7640000615e9d565b90508061461a670de0b6b3a764000085615e3f565b6146249190615da8565b61462e9086615d62565b9650505b50505b505050949350505050565b60006011548260c001511015801561465e57506012548260c0015111155b1561159e57601c548251602084015160a085015160405163c2edfc7360e01b81526001600160a01b038085166004830152600095869590821694636116ad1e94919390929091169063c2edfc739060240160206040518083038186803b1580156146c757600080fd5b505afa1580156146db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906146ff9190615560565b6040518463ffffffff1660e01b815260040161471d93929190615b9f565b604080518083038186803b15801561473457600080fd5b505afa158015614748573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061476c9190615ac3565b91509150600084604001518311614784576000614793565b60408501516147939084615e9d565b90506000856040015184116147b7578386604001516147b29190615e9d565b6147ba565b60005b6147c49084615d62565b905080821061489e57601c546040805160a08101825286815260208101868152898301518284019081526080808c015160608501908152600a549185019182529451632888a20d60e01b8152935160048501529151602484015251604483015291516064820152905160848201526001600160a01b0390911690632888a20d9060a40160206040518083038186803b15801561485f57600080fd5b505afa158015614873573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906148979190615aab565b9450614c43565b8386604001511180156148b15750600084115b15614b875760008487604001516148c89190615e9d565b601c546040805160e081019091528281529192506000916001600160a01b039091169063f5f9c25790602081016148ff8a8a615d62565b815260006020820152604001614915868a615d62565b815260200160008152602001898c606001516149319190615e9d565b8152602001600a548152506040518263ffffffff1660e01b81526004016149589190615cd3565b60206040518083038186803b15801561497057600080fd5b505afa158015614984573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906149a89190615aab565b905060006149be89600001518a60200151611b48565b8951909150600090614a0290828c6020015160018111156149ef57634e487b7160e01b600052602160045260246000fd5b146149fb576000611b48565b6001611b48565b9050600082614a118584615e3f565b614a1b9190615da8565b90506000601c60009054906101000a90046001600160a01b03166001600160a01b0316632888a20d6040518060a001604052808d81526020018c81526020018d81526020018f608001518152602001600a548152506040518263ffffffff1660e01b8152600401614ac19190600060a082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015292915050565b60206040518083038186803b158015614ad957600080fd5b505afa158015614aed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614b119190615aab565b90506000614b1f828c615dbc565b90506000614b2d8489615e3f565b90506000614b3b898e615d62565b905080614b488385615d21565b614b529190615d7a565b9d5060008e1315614b79576000614b698f89615dbc565b9050614b758782615d7a565b9e50505b505050505050505050614c43565b601c546040805160e0810182528882015181526020810186905280820187905260608082018590526080820186905289015160a0820152600a5460c0820152905163f5f9c25760e01b81526001600160a01b039092169163f5f9c25791614bf091600401615cd3565b60206040518083038186803b158015614c0857600080fd5b505afa158015614c1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614c409190615aab565b94505b50505050919050565b600060115482111561159e57670de0b6b3a76400006002600a54614c709190615da8565b614c8290670de0b6b3a7640000615e9d565b600954614c8f9085615e9d565b614c999190615e3f565b611dea9190615da8565b600080826001600160a01b03166341bc7b1f6040518163ffffffff1660e01b815260040160606040518083038186803b158015614cdf57600080fd5b505afa158015614cf3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614d1791906159e3565b50509050614d2481612c2c565b9392505050565b6000614d80826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661542a9092919063ffffffff16565b80519091501561388a5780806020019051810190614d9e919061598e565b61388a5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016109f5565b601554604051639ca423b360e01b81526001600160a01b0385811660048301526000921690639ca423b39060240160206040518083038186803b158015614e4357600080fd5b505afa158015614e57573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614e7b9190615560565b90506001600160a01b03811615801590614e9757506000601654115b1561386557600654614eb3906001600160a01b0316828561386b565b604080516001600160a01b03808416825286166020820152908101849052606081018390527f8fa68a6a8e2fc9ff758a6e64afba8bc2f66fb082999a2c5225c8c49633faded49060800160405180910390a150505050565b601c54601f5460405163c2edfc7360e01b81526001600160a01b03868116600483015260009384939082169263e468265c928992899291169063c2edfc739060240160206040518083038186803b158015614f6557600080fd5b505afa158015614f79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614f9d9190615560565b6040518463ffffffff1660e01b8152600401614fbb93929190615b9f565b60206040518083038186803b158015614fd357600080fd5b505afa158015614fe7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061500b9190615aab565b905082811015610bd457610bd18184615e9d565b600f54600090156150af57336000908152601d602052604090205461504657600f54615057565b336000908152601d60205260409020545b61506990670de0b6b3a7640000615d62565b61507b670de0b6b3a764000085615e3f565b6150859190615da8565b61508f9084615e9d565b600e546006549192506150af916001600160a01b0390811691168361386b565b6007546001600160a01b03166317fd849a6150ca8386615e9d565b6040518263ffffffff1660e01b81526004016150e891815260200190565b60206040518083038186803b15801561510057600080fd5b505afa158015615114573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906151389190615aab565b6001600160a01b0385166000908152600d602052604090205411615174576001600160a01b0384166000908152600d602052604081205561523a565b6007546001600160a01b03166317fd849a61518f8386615e9d565b6040518263ffffffff1660e01b81526004016151ad91815260200190565b60206040518083038186803b1580156151c557600080fd5b505afa1580156151d9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906151fd9190615aab565b6001600160a01b0385166000908152600d60205260409020546152209190615e9d565b6001600160a01b0385166000908152600d60205260409020555b600060165411801561525657506015546001600160a01b031615155b15613865576000601654670de0b6b3a76400006152739190615d62565b615285670de0b6b3a764000086615e3f565b61528f9190615da8565b6152999085615e9d565b9050613b53838286614dfd565b600080856001600160a01b03166341bc7b1f6040518163ffffffff1660e01b815260040160606040518083038186803b1580156152e257600080fd5b505afa1580156152f6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061531a91906159e3565b506005546040516315905ec160e31b8152600481018490529294509092506000916101009091046001600160a01b03169063ac82f6089060240160206040518083038186803b15801561536c57600080fd5b505afa158015615380573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906153a49190615aab565b90506000808760018111156153c957634e487b7160e01b600052602160045260246000fd5b146153d6578282106153db565b828210155b60408051338152602081018990528215158183015290519192507f80631c28c8a8100630a9d2bce38b276a55426b59f4d47fb06072105118083ec1919081900360600190a15050505050505050565b6060612610848460008585843b6154835760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016109f5565b600080866001600160a01b0316858760405161549f9190615b33565b60006040518083038185875af1925050503d80600081146154dc576040519150601f19603f3d011682016040523d82523d6000602084013e6154e1565b606091505b50915091506154f18282866154fc565b979650505050505050565b6060831561550b575081614d24565b82511561551b5782518084602001fd5b8160405162461bcd60e51b81526004016109f59190615c0c565b80356002811061159e57600080fd5b600060208284031215615555578081fd5b8135614d2481615f27565b600060208284031215615571578081fd5b8151614d2481615f27565b6000806040838503121561558e578081fd5b823561559981615f27565b946020939093013593505050565b60008060008060008060c087890312156155bf578182fd5b86356155ca81615f27565b955060208701356155da81615f27565b945060408701356155ea81615f27565b935060608701356155fa81615f27565b9250608087013561560a81615f3c565b8092505060a087013590509295509295509295565b60008060408385031215615631578182fd5b823561563c81615f27565b9150602083013561564c81615f3c565b809150509250929050565b600080600080600080600080610100898b031215615673578182fd5b883561567e81615f27565b9750602089013561568e81615f27565b9650604089013561569e81615f27565b95506060890135945060808901356156b581615f27565b979a969950949793969560a0850135955060c08501359460e001359350915050565b600080604083850312156156e9578182fd5b82356156f481615f27565b915061570260208401615535565b90509250929050565b60008060006060848603121561571f578081fd5b833561572a81615f27565b925061573860208501615535565b9150604084013590509250925092565b6000806000806080858703121561575d578182fd5b843561576881615f27565b935061577660208601615535565b925060408501359150606085013561578d81615f27565b939692955090935050565b600080600080600060a086880312156157af578283fd5b85356157ba81615f27565b94506157c860208701615535565b94979496505050506040830135926060810135926080909101359150565b60008060008060008060c087890312156157fe578384fd5b863561580981615f27565b955061581760208801615535565b945060408701359350606087013592506080870135915060a087013561583c81615f27565b809150509295509295509295565b600080600080600080600060e0888a031215615864578081fd5b873561586f81615f27565b965061587d60208901615535565b955060408801359450606088013593506080880135925060a08801356158a281615f27565b915060c08801356158b281615f27565b8091505092959891949750929550565b6000806040838503121561558e578182fd5b6000806000806000608086880312156158eb578283fd5b853567ffffffffffffffff80821115615902578485fd5b818801915088601f830112615915578485fd5b813581811115615923578586fd5b8960208260051b8501011115615937578586fd5b6020928301975095505086013561594d81615f27565b925060408601359150606086013561596481615f3c565b809150509295509295909350565b600060208284031215615983578081fd5b8135614d2481615f3c565b60006020828403121561599f578081fd5b8151614d2481615f3c565b6000602082840312156159bb578081fd5b5035919050565b600080604083850312156159d4578182fd5b50508035926020909101359150565b6000806000606084860312156159f7578081fd5b8351925060208401519150604084015190509250925092565b60008060408385031215615a22578182fd5b8251615a2d81615f27565b602084015190925061564c81615f27565b60008060408385031215615a50578182fd5b8235615a5b81615f27565b9150602083013561564c81615f27565b600080600060608486031215615a7f578081fd5b8335615a8a81615f27565b92506020840135615a9a81615f27565b929592945050506040919091013590565b600060208284031215615abc578081fd5b5051919050565b60008060408385031215615ad5578182fd5b505080516020909101519092909150565b600080600060608486031215615afa578081fd5b505081359360208301359350604090920135919050565b60028110615b2f57634e487b7160e01b600052602160045260246000fd5b9052565b60008251615b45818460208701615eb4565b9190910192915050565b6001600160a01b038881168252878116602083015260e0820190615b766040840189615b11565b86606084015285608084015280851660a084015280841660c08401525098975050505050505050565b6001600160a01b0384811682526060820190615bbe6020840186615b11565b808416604084015250949350505050565b6001600160a01b03929092168252602082015260400190565b6001600160a01b038416815260208101839052606081016126106040830184615b11565b6020815260008251806020840152615c2b816040850160208701615eb4565b601f01601f19169190910160400192915050565b6020808252603c908201527f5468697320616374696f6e2063616e6e6f7420626520706572666f726d65642060408201527f7768696c652074686520636f6e74726163742069732070617573656400000000606082015260800190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b600060e082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015292915050565b600080821280156001600160ff1b0384900385131615615d4357615d43615efb565b600160ff1b8390038412811615615d5c57615d5c615efb565b50500190565b60008219821115615d7557615d75615efb565b500190565b600082615d8957615d89615f11565b600160ff1b821460001984141615615da357615da3615efb565b500590565b600082615db757615db7615f11565b500490565b60006001600160ff1b0381841382841380821686840486111615615de257615de2615efb565b600160ff1b84871282811687830589121615615e0057615e00615efb565b858712925087820587128484161615615e1b57615e1b615efb565b87850587128184161615615e3157615e31615efb565b505050929093029392505050565b6000816000190483118215151615615e5957615e59615efb565b500290565b60008083128015600160ff1b850184121615615e7c57615e7c615efb565b6001600160ff1b0384018313811615615e9757615e97615efb565b50500390565b600082821015615eaf57615eaf615efb565b500390565b60005b83811015615ecf578181015183820152602001615eb7565b838111156138655750506000910152565b6000600019821415615ef457615ef4615efb565b5060010190565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052601260045260246000fd5b6001600160a01b0381168114610bac57600080fd5b8015158114610bac57600080fdfea2646970667358221220ba0f21cd9672c0c2d6d6f62f09152af48401095a3f651825bc00257b0d65f23964736f6c63430008040033

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  ]

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.