Contract 0xb97F5a34696adf30db822612379235c3c53B714A 1

 

Contract Overview

Balance:
0 MATIC

MATIC Value:
$0.00

Token:
 
Txn Hash Method
Block
From
To
Value [Txn Fee]
0x354be869ac4484822a991df631196a80a90ed53d2489fe637458e45db2e11568Rebalance285466322022-05-20 11:30:362 hrs 14 mins ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.07562776364 74.36
0xad163e9eedcf90527f5f855b1e352857e0ead021d39ae47711beb5ac3cf2d60cRebalance285401952022-05-20 7:30:256 hrs 14 mins ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.03997339643 39.71
0xfea5000568fad1ed117b63ecdb1f0eeac238a28805657453c888a4ff85a567c5Rebalance285333222022-05-20 3:30:0610 hrs 14 mins ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.056329258865 55.385
0xe2df9c68f0fc9449f4d044bd5aa41ffa561e5c41ce5a999bfa8e0b858631c3b5Rebalance285266192022-05-19 23:29:5414 hrs 14 mins ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.06835586329 67.21
0xb5928d53b95d518d98308185a17826f04c3197328136b57b37216914e57475c3Rebalance285197352022-05-19 19:29:3518 hrs 15 mins ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.03715652633 36.19
0x1528b519b0e561f377438b8a80b2dbea6d29e397f8cf972b3fde57887224c726Rebalance285129952022-05-19 15:29:2022 hrs 15 mins ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.11462929973 117.535
0x0e165d27a98615b995515edf3768616893c9705759e326a2beca3b49cb313f23Rebalance285061492022-05-19 11:29:061 day 2 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.132532473095 129.085
0x7bad85bab1bfa137981622ca1486ac97a194cf36982f9657a1c5f15064ae7263Rebalance284997462022-05-19 7:28:511 day 6 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.04748843583 46.255
0x9fd7f3e2e7047540c67d5b7bade9f245b9742d5f3b51980705cc5cc76af887c1Rebalance284930732022-05-19 3:28:361 day 10 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.04427160584 43.12
0x558acebcecd4c5b9d91c976b090e0052e3ee6528cdf4adf06ce14e053f7f6c65Rebalance284862862022-05-18 23:28:221 day 14 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.14921746323 145.365
0x398fd1cb60e42ea8a22d310ea388fa6b5638f753bc96f36c5acc100bb1b3509cRebalance284794912022-05-18 19:28:061 day 18 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.085324485235 83.105
0x3f741ff0205226811a01b1b24953c136a82e4514c98c3233134cb61be9b7b363Rebalance284729522022-05-18 15:28:141 day 22 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.123303432175 782.705
0x8b43a59658614163916542958f617d13d52af3ff721f4b4e40eb261bc0045f9dRebalance284729412022-05-18 15:27:521 day 22 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.805076893445 784.135
0x2d150f404ee126c5b9cf8bded5a6541581279b77a9e9b1ec8d148322534507f7Rebalance284666562022-05-18 11:27:212 days 2 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.04726163585 46.475
0x0cd5159343e4760295aa2a45a40335616f902c229ca2c5ba67f3b8e81e543feeRebalance284600992022-05-18 7:27:052 days 6 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.065279290065 64.185
0x511febfc71f1bffe0808407a0ce3d79de3d6913f2223a1b0a84097486c5b643dRebalance284536532022-05-18 3:26:522 days 10 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.0570564489 56.1
0x6fd495cc6c09d280b071207df450360778cb76734d4771f6c293e035627ad45dRebalance284469962022-05-17 23:26:362 days 14 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.069978056445 68.805
0xcd99657a3ffa3a05879165729aab853f649980fc40ee2c50a1eb5d5e20204f1aRebalance284403342022-05-17 19:26:212 days 18 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.03876325992 38.115
0xb55a135b3e34545880ed433342feed87a12b989cf7114ac57c92141cbfa82361Rebalance284338472022-05-17 15:26:052 days 22 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.10101125958 99.33
0x08a706f75755c67e37fec9c13ad6037c5f9f948396957fbb36450adc7fb1cd05Rebalance284273622022-05-17 11:25:563 days 2 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.050735489365 49.885
0xdb192c83b15ef06700643ec68261270bbd073a0868a46c75427ad07825b29257Rebalance284206352022-05-17 7:25:353 days 6 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.052637370995 51.755
0xec182b93d1f6df6f9698fd9eb55e83ff4e9ea18375d13e3b141bf4a969011e1bRebalance284139612022-05-17 3:25:203 days 10 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.045029844475 44.275
0x46cd1d7aac4101b1a6bb0c0b1072fa1dc2743c694acc65d6e63f4eeb2c8f94adRebalance284071682022-05-16 23:25:063 days 14 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.086423738775 84.975
0xaf91888c1cde68740d853d242a343eccb316c921debc5102df0c64ac004ac039Rebalance284004292022-05-16 19:24:513 days 18 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.078592461475 77.275
0x5b283e88d62e2890132a7261f7415e57974a705a4ccf763a0d37c6940c73259aRebalance283938162022-05-16 15:24:373 days 22 hrs ago0x66fcbc56db242473e50335b2f385e5816ea2cbfe IN  0xb97f5a34696adf30db822612379235c3c53b714a0 MATIC0.071656187295 70.455
[ Download CSV Export 
Parent Txn Hash Block From To Value
Loading

Similar Match Source Code
Note: This contract matches the deployed ByteCode of the Source Code for Contract 0x0f5e279313fe49F5bab1A5A8fBb5C9124e3b5b15

Contract Name:
AaveLeverageStrategyExtension

Compiler Version
v0.6.10+commit.00c0fcaf

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 16 : AaveLeverageStrategyExtension.sol
/*
    Copyright 2021 Set Labs Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    SPDX-License-Identifier: Apache License, Version 2.0
*/

pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;

import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/math/Math.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";

import { BaseExtension } from "../lib/BaseExtension.sol";
import { IBaseManager } from "../interfaces/IBaseManager.sol";
import { IChainlinkAggregatorV3 } from "../interfaces/IChainlinkAggregatorV3.sol";
import { ILeverageModule } from "../interfaces/ILeverageModule.sol";
import { IProtocolDataProvider } from "../interfaces/IProtocolDataProvider.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol";
import { StringArrayUtils } from "../lib/StringArrayUtils.sol";


/**
 * @title AaveLeverageStrategyExtension
 * @author Set Protocol
 *
 * Smart contract that enables trustless leverage tokens. This extension is paired with the AaveLeverageModule from Set protocol where module 
 * interactions are invoked via the IBaseManager contract. Any leveraged token can be constructed as long as the collateral and borrow asset 
 * is available on Aave. This extension contract also allows the operator to set an ETH reward to incentivize keepers calling the rebalance
 * function at different leverage thresholds.
 *
 */
contract AaveLeverageStrategyExtension is BaseExtension {
    using Address for address;
    using PreciseUnitMath for uint256;
    using SafeMath for uint256;
    using SafeCast for int256;
    using StringArrayUtils for string[];

    /* ============ Enums ============ */

    enum ShouldRebalance {
        NONE,                   // Indicates no rebalance action can be taken
        REBALANCE,              // Indicates rebalance() function can be successfully called
        ITERATE_REBALANCE,      // Indicates iterateRebalance() function can be successfully called
        RIPCORD                 // Indicates ripcord() function can be successfully called
    }

    /* ============ Structs ============ */

    struct ActionInfo {
        uint256 collateralBalance;                      // Balance of underlying held in Aave in base units (e.g. USDC 10e6)
        uint256 borrowBalance;                          // Balance of underlying borrowed from Aave in base units
        uint256 collateralValue;                        // Valuation in USD adjusted for decimals in precise units (10e18)
        uint256 borrowValue;                            // Valuation in USD adjusted for decimals in precise units (10e18)
        uint256 collateralPrice;                        // Price of collateral in precise units (10e18) from Chainlink
        uint256 borrowPrice;                            // Price of borrow asset in precise units (10e18) from Chainlink
        uint256 setTotalSupply;                         // Total supply of SetToken
    }

     struct LeverageInfo {
        ActionInfo action;
        uint256 currentLeverageRatio;                   // Current leverage ratio of Set
        uint256 slippageTolerance;                      // Allowable percent trade slippage in preciseUnits (1% = 10^16)
        uint256 twapMaxTradeSize;                       // Max trade size in collateral units allowed for rebalance action
        string exchangeName;                            // Exchange to use for trade
    }

    struct ContractSettings {
        ISetToken setToken;                             // Instance of leverage token
        ILeverageModule leverageModule;                 // Instance of Aave leverage module
        IProtocolDataProvider aaveProtocolDataProvider; // Instance of Aave protocol data provider
        IChainlinkAggregatorV3 collateralPriceOracle;   // Chainlink oracle feed that returns prices in 8 decimals for collateral asset
        IChainlinkAggregatorV3 borrowPriceOracle;       // Chainlink oracle feed that returns prices in 8 decimals for borrow asset
        IERC20 targetCollateralAToken;                  // Instance of target collateral aToken asset
        IERC20 targetBorrowDebtToken;                   // Instance of target borrow variable debt token asset
        address collateralAsset;                        // Address of underlying collateral
        address borrowAsset;                            // Address of underlying borrow asset
        uint256 collateralDecimalAdjustment;            // Decimal adjustment for chainlink oracle of the collateral asset. Equal to 28-collateralDecimals (10^18 * 10^18 / 10^decimals / 10^8)
        uint256 borrowDecimalAdjustment;                // Decimal adjustment for chainlink oracle of the borrowing asset. Equal to 28-borrowDecimals (10^18 * 10^18 / 10^decimals / 10^8)
    }

    struct MethodologySettings {
        uint256 targetLeverageRatio;                     // Long term target ratio in precise units (10e18)
        uint256 minLeverageRatio;                        // In precise units (10e18). If current leverage is below, rebalance target is this ratio
        uint256 maxLeverageRatio;                        // In precise units (10e18). If current leverage is above, rebalance target is this ratio
        uint256 recenteringSpeed;                        // % at which to rebalance back to target leverage in precise units (10e18)
        uint256 rebalanceInterval;                       // Period of time required since last rebalance timestamp in seconds
    }

    struct ExecutionSettings {
        uint256 unutilizedLeveragePercentage;            // Percent of max borrow left unutilized in precise units (1% = 10e16)
        uint256 slippageTolerance;                       // % in precise units to price min token receive amount from trade quantities
        uint256 twapCooldownPeriod;                      // Cooldown period required since last trade timestamp in seconds
    }

    struct ExchangeSettings {
        uint256 twapMaxTradeSize;                        // Max trade size in collateral base units
        uint256 exchangeLastTradeTimestamp;              // Timestamp of last trade made with this exchange
        uint256 incentivizedTwapMaxTradeSize;            // Max trade size for incentivized rebalances in collateral base units
        bytes leverExchangeData;                         // Arbitrary exchange data passed into rebalance function for levering up
        bytes deleverExchangeData;                       // Arbitrary exchange data passed into rebalance function for delevering
    }

    struct IncentiveSettings {
        uint256 etherReward;                             // ETH reward for incentivized rebalances
        uint256 incentivizedLeverageRatio;               // Leverage ratio for incentivized rebalances
        uint256 incentivizedSlippageTolerance;           // Slippage tolerance percentage for incentivized rebalances
        uint256 incentivizedTwapCooldownPeriod;          // TWAP cooldown in seconds for incentivized rebalances
    }

    /* ============ Events ============ */

    event Engaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional);
    event Rebalanced(
        uint256 _currentLeverageRatio,
        uint256 _newLeverageRatio,
        uint256 _chunkRebalanceNotional,
        uint256 _totalRebalanceNotional
    );
    event RebalanceIterated(
        uint256 _currentLeverageRatio,
        uint256 _newLeverageRatio,
        uint256 _chunkRebalanceNotional,
        uint256 _totalRebalanceNotional
    );
    event RipcordCalled(
        uint256 _currentLeverageRatio,
        uint256 _newLeverageRatio,
        uint256 _rebalanceNotional,
        uint256 _etherIncentive
    );
    event Disengaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional);
    event MethodologySettingsUpdated(
        uint256 _targetLeverageRatio,
        uint256 _minLeverageRatio,
        uint256 _maxLeverageRatio,
        uint256 _recenteringSpeed,
        uint256 _rebalanceInterval
    );
    event ExecutionSettingsUpdated(
        uint256 _unutilizedLeveragePercentage,
        uint256 _twapCooldownPeriod,
        uint256 _slippageTolerance
    );
    event IncentiveSettingsUpdated(
        uint256 _etherReward,
        uint256 _incentivizedLeverageRatio,
        uint256 _incentivizedSlippageTolerance,
        uint256 _incentivizedTwapCooldownPeriod
    );
    event ExchangeUpdated(
        string _exchangeName,
        uint256 twapMaxTradeSize,
        uint256 exchangeLastTradeTimestamp,
        uint256 incentivizedTwapMaxTradeSize,
        bytes leverExchangeData,
        bytes deleverExchangeData
    );
    event ExchangeAdded(
        string _exchangeName,
        uint256 twapMaxTradeSize,
        uint256 exchangeLastTradeTimestamp,
        uint256 incentivizedTwapMaxTradeSize,
        bytes leverExchangeData,
        bytes deleverExchangeData
    );
    event ExchangeRemoved(
        string _exchangeName
    );

    /* ============ Modifiers ============ */

    /**
     * Throws if rebalance is currently in TWAP`
     */
    modifier noRebalanceInProgress() {
        require(twapLeverageRatio == 0, "Rebalance is currently in progress");
        _;
    }

    /* ============ State Variables ============ */

    ContractSettings internal strategy;                             // Struct of contracts used in the strategy (SetToken, price oracles, leverage module etc)
    MethodologySettings internal methodology;                       // Struct containing methodology parameters
    ExecutionSettings internal execution;                           // Struct containing execution parameters
    mapping(string => ExchangeSettings) internal exchangeSettings;  // Mapping from exchange name to exchange settings
    IncentiveSettings internal incentive;                           // Struct containing incentive parameters for ripcord
    string[] public enabledExchanges;                               // Array containing enabled exchanges
    uint256 public twapLeverageRatio;                               // Stored leverage ratio to keep track of target between TWAP rebalances
    uint256 public globalLastTradeTimestamp;                        // Last rebalance timestamp. Current timestamp must be greater than this variable + rebalance interval to rebalance

    /* ============ Constructor ============ */

    /**
     * Instantiate addresses, methodology parameters, execution parameters, and incentive parameters.
     *
     * @param _manager                  Address of IBaseManager contract
     * @param _strategy                 Struct of contract addresses
     * @param _methodology              Struct containing methodology parameters
     * @param _execution                Struct containing execution parameters
     * @param _incentive                Struct containing incentive parameters for ripcord
     * @param _exchangeNames            List of initial exchange names
     * @param _exchangeSettings         List of structs containing exchange parameters for the initial exchanges
     */
    constructor(
        IBaseManager _manager,
        ContractSettings memory _strategy,
        MethodologySettings memory _methodology,
        ExecutionSettings memory _execution,
        IncentiveSettings memory _incentive,
        string[] memory _exchangeNames,
        ExchangeSettings[] memory _exchangeSettings
    )
        public
        BaseExtension(_manager)
    {
        strategy = _strategy;
        methodology = _methodology;
        execution = _execution;
        incentive = _incentive;

        for (uint256 i = 0; i < _exchangeNames.length; i++) {
            _validateExchangeSettings(_exchangeSettings[i]);
            exchangeSettings[_exchangeNames[i]] = _exchangeSettings[i];
            enabledExchanges.push(_exchangeNames[i]);
        }

        _validateNonExchangeSettings(methodology, execution, incentive);
    }

    /* ============ External Functions ============ */

    /**
     * OPERATOR ONLY: Engage to target leverage ratio for the first time. SetToken will borrow debt position from Aave and trade for collateral asset. If target
     * leverage ratio is above max borrow or max trade size, then TWAP is kicked off. To complete engage if TWAP, any valid caller must call iterateRebalance until target
     * is met.
     *
     * @param _exchangeName     the exchange used for trading
     */
    function engage(string memory _exchangeName) external onlyOperator {
        ActionInfo memory engageInfo = _createActionInfo();

        require(engageInfo.setTotalSupply > 0, "SetToken must have > 0 supply");
        require(engageInfo.collateralBalance > 0, "Collateral balance must be > 0");
        require(engageInfo.borrowBalance == 0, "Debt must be 0");

        LeverageInfo memory leverageInfo = LeverageInfo({
            action: engageInfo,
            currentLeverageRatio: PreciseUnitMath.preciseUnit(), // 1x leverage in precise units
            slippageTolerance: execution.slippageTolerance,
            twapMaxTradeSize: exchangeSettings[_exchangeName].twapMaxTradeSize,
            exchangeName: _exchangeName
        });

        // Calculate total rebalance units and kick off TWAP if above max borrow or max trade size
        (
            uint256 chunkRebalanceNotional,
            uint256 totalRebalanceNotional
        ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true);

        _lever(leverageInfo, chunkRebalanceNotional);

        _updateRebalanceState(
            chunkRebalanceNotional,
            totalRebalanceNotional,
            methodology.targetLeverageRatio,
            _exchangeName
        );

        emit Engaged(
            leverageInfo.currentLeverageRatio,
            methodology.targetLeverageRatio,
            chunkRebalanceNotional,
            totalRebalanceNotional
        );
    }

    /**
     * ONLY EOA AND ALLOWED CALLER: Rebalance product. If current leverage ratio is between the max and min bounds, then rebalance 
     * can only be called once the rebalance interval has elapsed since last timestamp. If outside the max and min, rebalance can be called anytime to bring leverage
     * ratio back to the max or min bounds. The methodology will determine whether to delever or lever.
     *
     * Note: If the calculated current leverage ratio is above the incentivized leverage ratio or in TWAP then rebalance cannot be called. Instead, you must call
     * ripcord() which is incentivized with a reward in Ether or iterateRebalance().
     *
     * @param _exchangeName     the exchange used for trading
     */
     function rebalance(string memory _exchangeName) external onlyEOA onlyAllowedCaller(msg.sender) {
        LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
            execution.slippageTolerance,
            exchangeSettings[_exchangeName].twapMaxTradeSize,
            _exchangeName
        );

        // use globalLastTradeTimestamps to prevent multiple rebalances being called with different exchanges during the epoch rebalance
        _validateNormalRebalance(leverageInfo, methodology.rebalanceInterval, globalLastTradeTimestamp);
        _validateNonTWAP();

        uint256 newLeverageRatio = _calculateNewLeverageRatio(leverageInfo.currentLeverageRatio);

        (
            uint256 chunkRebalanceNotional,
            uint256 totalRebalanceNotional
        ) = _handleRebalance(leverageInfo, newLeverageRatio);

        _updateRebalanceState(chunkRebalanceNotional, totalRebalanceNotional, newLeverageRatio, _exchangeName);

        emit Rebalanced(
            leverageInfo.currentLeverageRatio,
            newLeverageRatio,
            chunkRebalanceNotional,
            totalRebalanceNotional
        );
    }

    /**
     * ONLY EOA AND ALLOWED CALLER: Iterate a rebalance when in TWAP. TWAP cooldown period must have elapsed. If price moves advantageously, then exit without rebalancing
     * and clear TWAP state. This function can only be called when below incentivized leverage ratio and in TWAP state.
     *
     * @param _exchangeName     the exchange used for trading
     */
    function iterateRebalance(string memory _exchangeName) external onlyEOA onlyAllowedCaller(msg.sender) {
        LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
            execution.slippageTolerance,
            exchangeSettings[_exchangeName].twapMaxTradeSize,
            _exchangeName
        );

        // Use the exchangeLastTradeTimestamp since cooldown periods are measured on a per-exchange basis, allowing it to rebalance multiple time in quick
        // succession with different exchanges
        _validateNormalRebalance(leverageInfo, execution.twapCooldownPeriod, exchangeSettings[_exchangeName].exchangeLastTradeTimestamp);
        _validateTWAP();

        uint256 chunkRebalanceNotional;
        uint256 totalRebalanceNotional;
        if (!_isAdvantageousTWAP(leverageInfo.currentLeverageRatio)) {
            (chunkRebalanceNotional, totalRebalanceNotional) = _handleRebalance(leverageInfo, twapLeverageRatio);
        }

        // If not advantageous, then rebalance is skipped and chunk and total rebalance notional are both 0, which means TWAP state is
        // cleared
        _updateIterateState(chunkRebalanceNotional, totalRebalanceNotional, _exchangeName);

        emit RebalanceIterated(
            leverageInfo.currentLeverageRatio,
            twapLeverageRatio,
            chunkRebalanceNotional,
            totalRebalanceNotional
        );
    }

    /**
     * ONLY EOA: In case the current leverage ratio exceeds the incentivized leverage threshold, the ripcord function can be called by anyone to return leverage ratio
     * back to the max leverage ratio. This function typically would only be called during times of high downside volatility and / or normal keeper malfunctions. The caller
     * of ripcord() will receive a reward in Ether. The ripcord function uses it's own TWAP cooldown period, slippage tolerance and TWAP max trade size which are typically
     * looser than in regular rebalances.
     *
     * @param _exchangeName     the exchange used for trading
     */
    function ripcord(string memory _exchangeName) external onlyEOA {
        LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
            incentive.incentivizedSlippageTolerance,
            exchangeSettings[_exchangeName].incentivizedTwapMaxTradeSize,
            _exchangeName
        );

        // Use the exchangeLastTradeTimestamp so it can ripcord quickly with multiple exchanges
        _validateRipcord(leverageInfo, exchangeSettings[_exchangeName].exchangeLastTradeTimestamp);

        ( uint256 chunkRebalanceNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.maxLeverageRatio, false);

        _delever(leverageInfo, chunkRebalanceNotional);

        _updateRipcordState(_exchangeName);

        uint256 etherTransferred = _transferEtherRewardToCaller(incentive.etherReward);

        emit RipcordCalled(
            leverageInfo.currentLeverageRatio,
            methodology.maxLeverageRatio,
            chunkRebalanceNotional,
            etherTransferred
        );
    }

    /**
     * OPERATOR ONLY: Return leverage ratio to 1x and delever to repay loan. This can be used for upgrading or shutting down the strategy. SetToken will redeem
     * collateral position and trade for debt position to repay Aave. If the chunk rebalance size is less than the total notional size, then this function will
     * delever and repay entire borrow balance on Aave. If chunk rebalance size is above max borrow or max trade size, then operator must
     * continue to call this function to complete repayment of loan. The function iterateRebalance will not work.
     *
     * Note: Delever to 0 will likely result in additional units of the borrow asset added as equity on the SetToken due to oracle price / market price mismatch
     *
     * @param _exchangeName     the exchange used for trading
     */
    function disengage(string memory _exchangeName) external onlyOperator {
        LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
            execution.slippageTolerance,
            exchangeSettings[_exchangeName].twapMaxTradeSize,
            _exchangeName
        );

        uint256 newLeverageRatio = PreciseUnitMath.preciseUnit();

        (
            uint256 chunkRebalanceNotional,
            uint256 totalRebalanceNotional
        ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false);

        if (totalRebalanceNotional > chunkRebalanceNotional) {
            _delever(leverageInfo, chunkRebalanceNotional);
        } else {
            _deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional);
        }

        emit Disengaged(
            leverageInfo.currentLeverageRatio,
            newLeverageRatio,
            chunkRebalanceNotional,
            totalRebalanceNotional
        );
    }

    /**
     * OPERATOR ONLY: Set methodology settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
     * in a rebalance.
     *
     * @param _newMethodologySettings          Struct containing methodology parameters
     */
    function setMethodologySettings(MethodologySettings memory _newMethodologySettings) external onlyOperator noRebalanceInProgress {
        methodology = _newMethodologySettings;

        _validateNonExchangeSettings(methodology, execution, incentive);

        emit MethodologySettingsUpdated(
            methodology.targetLeverageRatio,
            methodology.minLeverageRatio,
            methodology.maxLeverageRatio,
            methodology.recenteringSpeed,
            methodology.rebalanceInterval
        );
    }

    /**
     * OPERATOR ONLY: Set execution settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
     * in a rebalance.
     *
     * @param _newExecutionSettings          Struct containing execution parameters
     */
    function setExecutionSettings(ExecutionSettings memory _newExecutionSettings) external onlyOperator noRebalanceInProgress {
        execution = _newExecutionSettings;

        _validateNonExchangeSettings(methodology, execution, incentive);

        emit ExecutionSettingsUpdated(
            execution.unutilizedLeveragePercentage,
            execution.twapCooldownPeriod,
            execution.slippageTolerance
        );
    }

    /**
     * OPERATOR ONLY: Set incentive settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
     * in a rebalance.
     *
     * @param _newIncentiveSettings          Struct containing incentive parameters
     */
    function setIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) external onlyOperator noRebalanceInProgress {
        incentive = _newIncentiveSettings;

        _validateNonExchangeSettings(methodology, execution, incentive);

        emit IncentiveSettingsUpdated(
            incentive.etherReward,
            incentive.incentivizedLeverageRatio,
            incentive.incentivizedSlippageTolerance,
            incentive.incentivizedTwapCooldownPeriod
        );
    }

    /**
     * OPERATOR ONLY: Add a new enabled exchange for trading during rebalances. New exchanges will have their exchangeLastTradeTimestamp set to 0. Adding
     * exchanges during rebalances is allowed, as it is not possible to enter an unexpected state while doing so.
     *
     * @param _exchangeName         Name of the exchange
     * @param _exchangeSettings     Struct containing exchange parameters
     */
    function addEnabledExchange(
        string memory _exchangeName,
        ExchangeSettings memory _exchangeSettings
    )
        external
        onlyOperator
    {
        require(exchangeSettings[_exchangeName].twapMaxTradeSize == 0, "Exchange already enabled");
        _validateExchangeSettings(_exchangeSettings);

        exchangeSettings[_exchangeName].twapMaxTradeSize = _exchangeSettings.twapMaxTradeSize;
        exchangeSettings[_exchangeName].incentivizedTwapMaxTradeSize = _exchangeSettings.incentivizedTwapMaxTradeSize;
        exchangeSettings[_exchangeName].leverExchangeData = _exchangeSettings.leverExchangeData;
        exchangeSettings[_exchangeName].deleverExchangeData = _exchangeSettings.deleverExchangeData;
        exchangeSettings[_exchangeName].exchangeLastTradeTimestamp = 0;

        enabledExchanges.push(_exchangeName);

        emit ExchangeAdded(
            _exchangeName,
            _exchangeSettings.twapMaxTradeSize,
            _exchangeSettings.exchangeLastTradeTimestamp,
            _exchangeSettings.incentivizedTwapMaxTradeSize,
            _exchangeSettings.leverExchangeData,
            _exchangeSettings.deleverExchangeData
        );
    }

    /**
     * OPERATOR ONLY: Removes an exchange. Reverts if the exchange is not already enabled. Removing exchanges during rebalances is allowed,
     * as it is not possible to enter an unexpected state while doing so.
     *
     * @param _exchangeName     Name of exchange to remove
     */
    function removeEnabledExchange(string memory _exchangeName) external onlyOperator {
        require(exchangeSettings[_exchangeName].twapMaxTradeSize != 0, "Exchange not enabled");

        delete exchangeSettings[_exchangeName];
        enabledExchanges.removeStorage(_exchangeName);

        emit ExchangeRemoved(_exchangeName);
    }

    /**
     * OPERATOR ONLY: Updates the settings of an exchange. Reverts if exchange is not already added. When updating an exchange, exchangeLastTradeTimestamp
     * is preserved. Updating exchanges during rebalances is allowed, as it is not possible to enter an unexpected state while doing so. Note: Need to
     * pass in all existing parameters even if only changing a few settings.
     *
     * @param _exchangeName         Name of the exchange
     * @param _exchangeSettings     Struct containing exchange parameters
     */
    function updateEnabledExchange(
        string memory _exchangeName,
        ExchangeSettings memory _exchangeSettings
    )
        external
        onlyOperator
    {
        require(exchangeSettings[_exchangeName].twapMaxTradeSize != 0, "Exchange not enabled");
        _validateExchangeSettings(_exchangeSettings);

        exchangeSettings[_exchangeName].twapMaxTradeSize = _exchangeSettings.twapMaxTradeSize;
        exchangeSettings[_exchangeName].incentivizedTwapMaxTradeSize = _exchangeSettings.incentivizedTwapMaxTradeSize;
        exchangeSettings[_exchangeName].leverExchangeData = _exchangeSettings.leverExchangeData;
        exchangeSettings[_exchangeName].deleverExchangeData = _exchangeSettings.deleverExchangeData;

        emit ExchangeUpdated(
            _exchangeName,
            _exchangeSettings.twapMaxTradeSize,
            _exchangeSettings.exchangeLastTradeTimestamp,
            _exchangeSettings.incentivizedTwapMaxTradeSize,
            _exchangeSettings.leverExchangeData,
            _exchangeSettings.deleverExchangeData
        );
    }

    /**
     * OPERATOR ONLY: Withdraw entire balance of ETH in this contract to operator. Rebalance must not be in progress
     */
    function withdrawEtherBalance() external onlyOperator noRebalanceInProgress {
        msg.sender.transfer(address(this).balance);
    }

    receive() external payable {}

    /* ============ External Getter Functions ============ */

    /**
     * Get current leverage ratio. Current leverage ratio is defined as the USD value of the collateral divided by the USD value of the SetToken. Prices for collateral
     * and borrow asset are retrieved from the Chainlink Price Oracle.
     *
     * return currentLeverageRatio         Current leverage ratio in precise units (10e18)
     */
    function getCurrentLeverageRatio() public view returns(uint256) {
        ActionInfo memory currentLeverageInfo = _createActionInfo();

        return _calculateCurrentLeverageRatio(currentLeverageInfo.collateralValue, currentLeverageInfo.borrowValue);
    }

    /**
     * Calculates the chunk rebalance size. This can be used by external contracts and keeper bots to calculate the optimal exchange to rebalance with.
     * Note: this function does not take into account timestamps, so it may return a nonzero value even when shouldRebalance would return ShouldRebalance.NONE for
     * all exchanges (since minimum delays have not elapsed)
     *
     * @param _exchangeNames    Array of exchange names to get rebalance sizes for
     *
     * @return sizes            Array of total notional chunk size. Measured in the asset that would be sold
     * @return sellAsset        Asset that would be sold during a rebalance
     * @return buyAsset         Asset that would be purchased during a rebalance
     */
    function getChunkRebalanceNotional(
        string[] calldata _exchangeNames
    )
        external
        view
        returns(uint256[] memory sizes, address sellAsset, address buyAsset)
    {

        uint256 newLeverageRatio;
        uint256 currentLeverageRatio = getCurrentLeverageRatio();
        bool isRipcord = false;

        // if over incentivized leverage ratio, always ripcord
        if (currentLeverageRatio > incentive.incentivizedLeverageRatio) {
            newLeverageRatio = methodology.maxLeverageRatio;
            isRipcord = true;
        // if we are in an ongoing twap, use the cached twapLeverageRatio as our target leverage
        } else if (twapLeverageRatio > 0) {
            newLeverageRatio = twapLeverageRatio;
        // if all else is false, then we would just use the normal rebalance new leverage ratio calculation
        } else {
            newLeverageRatio = _calculateNewLeverageRatio(currentLeverageRatio);
        }

        ActionInfo memory actionInfo = _createActionInfo();
        bool isLever = newLeverageRatio > currentLeverageRatio;

        sizes = new uint256[](_exchangeNames.length);

        for (uint256 i = 0; i < _exchangeNames.length; i++) {
    
            LeverageInfo memory leverageInfo = LeverageInfo({
                action: actionInfo,
                currentLeverageRatio: currentLeverageRatio,
                slippageTolerance: isRipcord ? incentive.incentivizedSlippageTolerance : execution.slippageTolerance,
                twapMaxTradeSize: isRipcord ?
                    exchangeSettings[_exchangeNames[i]].incentivizedTwapMaxTradeSize :
                    exchangeSettings[_exchangeNames[i]].twapMaxTradeSize,
                exchangeName: _exchangeNames[i]
            });

            (uint256 collateralNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, isLever);

            // _calculateBorrowUnits can convert both unit and notional values
            sizes[i] = isLever ? _calculateBorrowUnits(collateralNotional, leverageInfo.action) : collateralNotional;
        }

        sellAsset = isLever ? strategy.borrowAsset : strategy.collateralAsset;
        buyAsset = isLever ? strategy.collateralAsset : strategy.borrowAsset;
    }

    /**
     * Get current Ether incentive for when current leverage ratio exceeds incentivized leverage ratio and ripcord can be called. If ETH balance on the contract is
     * below the etherReward, then return the balance of ETH instead.
     *
     * return etherReward               Quantity of ETH reward in base units (10e18)
     */
    function getCurrentEtherIncentive() external view returns(uint256) {
        uint256 currentLeverageRatio = getCurrentLeverageRatio();

        if (currentLeverageRatio >= incentive.incentivizedLeverageRatio) {
            // If ETH reward is below the balance on this contract, then return ETH balance on contract instead
            return incentive.etherReward < address(this).balance ? incentive.etherReward : address(this).balance;
        } else {
            return 0;
        }
    }

    /**
     * Helper that checks if conditions are met for rebalance or ripcord. Returns an enum with 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance()
     * 3 = call ripcord()
     *
     * @return (string[] memory, ShouldRebalance[] memory)      List of exchange names and a list of enums representing whether that exchange should rebalance
     */
    function shouldRebalance() external view returns(string[] memory, ShouldRebalance[] memory) {
        uint256 currentLeverageRatio = getCurrentLeverageRatio();

        return _shouldRebalance(currentLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio);
    }

    /**
     * Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the
     * logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with
     * 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance(), 3 = call ripcord()
     *
     * @param _customMinLeverageRatio          Min leverage ratio passed in by caller
     * @param _customMaxLeverageRatio          Max leverage ratio passed in by caller
     *
     * @return (string[] memory, ShouldRebalance[] memory)      List of exchange names and a list of enums representing whether that exchange should rebalance
     */
    function shouldRebalanceWithBounds(
        uint256 _customMinLeverageRatio,
        uint256 _customMaxLeverageRatio
    )
        external
        view
        returns(string[] memory, ShouldRebalance[] memory)
    {
        require (
            _customMinLeverageRatio <= methodology.minLeverageRatio && _customMaxLeverageRatio >= methodology.maxLeverageRatio,
            "Custom bounds must be valid"
        );

        uint256 currentLeverageRatio = getCurrentLeverageRatio();

        return _shouldRebalance(currentLeverageRatio, _customMinLeverageRatio, _customMaxLeverageRatio);
    }

    /**
     * Gets the list of enabled exchanges
     */
    function getEnabledExchanges() external view returns (string[] memory) {
        return enabledExchanges;
    }

    /**
     * Explicit getter functions for parameter structs are defined as workaround to issues fetching structs that have dynamic types.
     */
    function getStrategy() external view returns (ContractSettings memory) { return strategy; }
    function getMethodology() external view returns (MethodologySettings memory) { return methodology; }
    function getExecution() external view returns (ExecutionSettings memory) { return execution; }
    function getIncentive() external view returns (IncentiveSettings memory) { return incentive; }
    function getExchangeSettings(string memory _exchangeName) external view returns (ExchangeSettings memory) {
        return exchangeSettings[_exchangeName];
    }

    /* ============ Internal Functions ============ */

    /**
     * Calculate notional rebalance quantity, whether to chunk rebalance based on max trade size and max borrow and invoke lever on AaveLeverageModule
     *
     */
     function _lever(
        LeverageInfo memory _leverageInfo,
        uint256 _chunkRebalanceNotional
    )
        internal
    {
        uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply);

        uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action);

        uint256 minReceiveCollateralUnits = _calculateMinCollateralReceiveUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance);

        bytes memory leverCallData = abi.encodeWithSignature(
            "lever(address,address,address,uint256,uint256,string,bytes)",
            address(strategy.setToken),
            strategy.borrowAsset,
            strategy.collateralAsset,
            borrowUnits,
            minReceiveCollateralUnits,
            _leverageInfo.exchangeName,
            exchangeSettings[_leverageInfo.exchangeName].leverExchangeData
        );

        invokeManager(address(strategy.leverageModule), leverCallData);
    }

    /**
     * Calculate delever units Invoke delever on AaveLeverageModule.
     */
    function _delever(
        LeverageInfo memory _leverageInfo,
        uint256 _chunkRebalanceNotional
    )
        internal
    {
        uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply);

        uint256 minRepayUnits = _calculateMinRepayUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance, _leverageInfo.action);

        bytes memory deleverCallData = abi.encodeWithSignature(
            "delever(address,address,address,uint256,uint256,string,bytes)",
            address(strategy.setToken),
            strategy.collateralAsset,
            strategy.borrowAsset,
            collateralRebalanceUnits,
            minRepayUnits,
            _leverageInfo.exchangeName,
            exchangeSettings[_leverageInfo.exchangeName].deleverExchangeData
        );

        invokeManager(address(strategy.leverageModule), deleverCallData);
    }

    /**
     * Invoke deleverToZeroBorrowBalance on AaveLeverageModule.
     */
    function _deleverToZeroBorrowBalance(
        LeverageInfo memory _leverageInfo,
        uint256 _chunkRebalanceNotional
    )
        internal
    {
        // Account for slippage tolerance in redeem quantity for the deleverToZeroBorrowBalance function
        uint256 maxCollateralRebalanceUnits = _chunkRebalanceNotional
            .preciseMul(PreciseUnitMath.preciseUnit().add(execution.slippageTolerance))
            .preciseDiv(_leverageInfo.action.setTotalSupply);

        bytes memory deleverToZeroBorrowBalanceCallData = abi.encodeWithSignature(
            "deleverToZeroBorrowBalance(address,address,address,uint256,string,bytes)",
            address(strategy.setToken),
            strategy.collateralAsset,
            strategy.borrowAsset,
            maxCollateralRebalanceUnits,
            _leverageInfo.exchangeName,
            exchangeSettings[_leverageInfo.exchangeName].deleverExchangeData
        );

        invokeManager(address(strategy.leverageModule), deleverToZeroBorrowBalanceCallData);
    }

    /**
     * Check whether to delever or lever based on the current vs new leverage ratios. Used in the rebalance() and iterateRebalance() functions
     *
     * return uint256           Calculated notional to trade
     * return uint256           Total notional to rebalance over TWAP
     */
    function _handleRebalance(LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio) internal returns(uint256, uint256) {
        uint256 chunkRebalanceNotional;
        uint256 totalRebalanceNotional;
        if (_newLeverageRatio < _leverageInfo.currentLeverageRatio) {
            (
                chunkRebalanceNotional,
                totalRebalanceNotional
            ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, false);

            _delever(_leverageInfo, chunkRebalanceNotional);
        } else {
            (
                chunkRebalanceNotional,
                totalRebalanceNotional
            ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, true);

            _lever(_leverageInfo, chunkRebalanceNotional);
        }

        return (chunkRebalanceNotional, totalRebalanceNotional);
    }

    /**
     * Create the leverage info struct to be used in internal functions
     *
     * return LeverageInfo                Struct containing ActionInfo and other data
     */
    function _getAndValidateLeveragedInfo(uint256 _slippageTolerance, uint256 _maxTradeSize, string memory _exchangeName) internal view returns(LeverageInfo memory) {
        // Assume if maxTradeSize is 0, then the exchange is not enabled. This is enforced by addEnabledExchange and updateEnabledExchange
        require(_maxTradeSize > 0, "Must be valid exchange");

        ActionInfo memory actionInfo = _createActionInfo();

        require(actionInfo.setTotalSupply > 0, "SetToken must have > 0 supply");
        require(actionInfo.collateralBalance > 0, "Collateral balance must be > 0");
        require(actionInfo.borrowBalance > 0, "Borrow balance must exist");

        // Get current leverage ratio
        uint256 currentLeverageRatio = _calculateCurrentLeverageRatio(
            actionInfo.collateralValue,
            actionInfo.borrowValue
        );

        return LeverageInfo({
            action: actionInfo,
            currentLeverageRatio: currentLeverageRatio,
            slippageTolerance: _slippageTolerance,
            twapMaxTradeSize: _maxTradeSize,
            exchangeName: _exchangeName
        });
    }

    /**
     * Create the action info struct to be used in internal functions
     *
     * return ActionInfo                Struct containing data used by internal lever and delever functions
     */
    function _createActionInfo() internal view returns(ActionInfo memory) {
        ActionInfo memory rebalanceInfo;

        // Calculate prices from chainlink. Chainlink returns prices with 8 decimal places, but we need 36 - underlyingDecimals decimal places.
        // This is so that when the underlying amount is multiplied by the received price, the collateral valuation is normalized to 36 decimals. 
        // To perform this adjustment, we multiply by 10^(36 - 8 - underlyingDecimals)
        int256 rawCollateralPrice = strategy.collateralPriceOracle.latestAnswer();
        rebalanceInfo.collateralPrice = rawCollateralPrice.toUint256().mul(10 ** strategy.collateralDecimalAdjustment);
        int256 rawBorrowPrice = strategy.borrowPriceOracle.latestAnswer();
        rebalanceInfo.borrowPrice = rawBorrowPrice.toUint256().mul(10 ** strategy.borrowDecimalAdjustment);

        rebalanceInfo.collateralBalance = strategy.targetCollateralAToken.balanceOf(address(strategy.setToken));
        rebalanceInfo.borrowBalance = strategy.targetBorrowDebtToken.balanceOf(address(strategy.setToken));
        rebalanceInfo.collateralValue = rebalanceInfo.collateralPrice.preciseMul(rebalanceInfo.collateralBalance);
        rebalanceInfo.borrowValue = rebalanceInfo.borrowPrice.preciseMul(rebalanceInfo.borrowBalance);
        rebalanceInfo.setTotalSupply = strategy.setToken.totalSupply();

        return rebalanceInfo;
    }

    /**
     * Validate non-exchange settings in constructor and setters when updating.
     */
    function _validateNonExchangeSettings(
        MethodologySettings memory _methodology,
        ExecutionSettings memory _execution,
        IncentiveSettings memory _incentive
    )
        internal
        pure
    {
        require (
            _methodology.minLeverageRatio <= _methodology.targetLeverageRatio && _methodology.minLeverageRatio > 0,
            "Must be valid min leverage"
        );
        require (
            _methodology.maxLeverageRatio >= _methodology.targetLeverageRatio,
            "Must be valid max leverage"
        );
        require (
            _methodology.recenteringSpeed <= PreciseUnitMath.preciseUnit() && _methodology.recenteringSpeed > 0,
            "Must be valid recentering speed"
        );
        require (
            _execution.unutilizedLeveragePercentage <= PreciseUnitMath.preciseUnit(),
            "Unutilized leverage must be <100%"
        );
        require (
            _execution.slippageTolerance <= PreciseUnitMath.preciseUnit(),
            "Slippage tolerance must be <100%"
        );
        require (
            _incentive.incentivizedSlippageTolerance <= PreciseUnitMath.preciseUnit(),
            "Incentivized slippage tolerance must be <100%"
        );
        require (
            _incentive.incentivizedLeverageRatio >= _methodology.maxLeverageRatio,
            "Incentivized leverage ratio must be > max leverage ratio"
        );
        require (
            _methodology.rebalanceInterval >= _execution.twapCooldownPeriod,
            "Rebalance interval must be greater than TWAP cooldown period"
        );
        require (
            _execution.twapCooldownPeriod >= _incentive.incentivizedTwapCooldownPeriod,
            "TWAP cooldown must be greater than incentivized TWAP cooldown"
        );
    }

    /**
     * Validate an ExchangeSettings struct when adding or updating an exchange. Does not validate that twapMaxTradeSize < incentivizedMaxTradeSize since
     * it may be useful to disable exchanges for ripcord by setting incentivizedMaxTradeSize to 0.
     */
     function _validateExchangeSettings(ExchangeSettings memory _settings) internal pure {
         require(_settings.twapMaxTradeSize != 0, "Max TWAP trade size must not be 0");
     }

    /**
     * Validate that current leverage is below incentivized leverage ratio and cooldown / rebalance period has elapsed or outsize max/min bounds. Used
     * in rebalance() and iterateRebalance() functions
     */
    function _validateNormalRebalance(LeverageInfo memory _leverageInfo, uint256 _coolDown, uint256 _lastTradeTimestamp) internal view {
        require(_leverageInfo.currentLeverageRatio < incentive.incentivizedLeverageRatio, "Must be below incentivized leverage ratio");
        require(
            block.timestamp.sub(_lastTradeTimestamp) > _coolDown
            || _leverageInfo.currentLeverageRatio > methodology.maxLeverageRatio
            || _leverageInfo.currentLeverageRatio < methodology.minLeverageRatio,
            "Cooldown not elapsed or not valid leverage ratio"
        );
    }

    /**
     * Validate that current leverage is above incentivized leverage ratio and incentivized cooldown period has elapsed in ripcord()
     */
    function _validateRipcord(LeverageInfo memory _leverageInfo, uint256 _lastTradeTimestamp) internal view {
        require(_leverageInfo.currentLeverageRatio >= incentive.incentivizedLeverageRatio, "Must be above incentivized leverage ratio");
        // If currently in the midst of a TWAP rebalance, ensure that the cooldown period has elapsed
        require(_lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp, "TWAP cooldown must have elapsed");
    }

    /**
     * Validate TWAP in the iterateRebalance() function
     */
    function _validateTWAP() internal view {
        require(twapLeverageRatio > 0, "Not in TWAP state");
    }

    /**
     * Validate not TWAP in the rebalance() function
     */
    function _validateNonTWAP() internal view {
        require(twapLeverageRatio == 0, "Must call iterate");
    }

    /**
     * Check if price has moved advantageously while in the midst of the TWAP rebalance. This means the current leverage ratio has moved over/under
     * the stored TWAP leverage ratio on lever/delever so there is no need to execute a rebalance. Used in iterateRebalance()
     */
    function _isAdvantageousTWAP(uint256 _currentLeverageRatio) internal view returns (bool) {
        return (
            (twapLeverageRatio < methodology.targetLeverageRatio && _currentLeverageRatio >= twapLeverageRatio)
            || (twapLeverageRatio > methodology.targetLeverageRatio && _currentLeverageRatio <= twapLeverageRatio)
        );
    }

    /**
     * Calculate the current leverage ratio given a valuation of the collateral and borrow asset, which is calculated as collateral USD valuation / SetToken USD valuation
     *
     * return uint256            Current leverage ratio
     */
    function _calculateCurrentLeverageRatio(
        uint256 _collateralValue,
        uint256 _borrowValue
    )
        internal
        pure
        returns(uint256)
    {
        return _collateralValue.preciseDiv(_collateralValue.sub(_borrowValue));
    }

    /**
     * Calculate the new leverage ratio. The methodology reduces the size of each rebalance by weighting
     * the current leverage ratio against the target leverage ratio by the recentering speed percentage. The lower the recentering speed, the slower
     * the leverage token will move towards the target leverage each rebalance.
     *
     * return uint256          New leverage ratio
     */
    function _calculateNewLeverageRatio(uint256 _currentLeverageRatio) internal view returns(uint256) {
        // CLRt+1 = max(MINLR, min(MAXLR, CLRt * (1 - RS) + TLR * RS))
        // a: TLR * RS
        // b: (1- RS) * CLRt
        // c: (1- RS) * CLRt + TLR * RS
        // d: min(MAXLR, CLRt * (1 - RS) + TLR * RS)
        uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed);
        uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio);
        uint256 c = a.add(b);
        uint256 d = Math.min(c, methodology.maxLeverageRatio);
        return Math.max(methodology.minLeverageRatio, d);
    }

    /**
     * Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units.
     *
     * return uint256          Chunked rebalance notional in collateral units
     * return uint256          Total rebalance notional in collateral units
     */
    function _calculateChunkRebalanceNotional(
        LeverageInfo memory _leverageInfo,
        uint256 _newLeverageRatio,
        bool _isLever
    )
        internal
        view
        returns (uint256, uint256)
    {
        // Calculate absolute value of difference between new and current leverage ratio
        uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio);

        uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance);

        uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever);

        uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize);

        return (chunkRebalanceNotional, totalRebalanceNotional);
    }

    /**
     * Calculate the max borrow / repay amount allowed in base units for lever / delever. This is due to overcollateralization requirements on
     * assets deposited in lending protocols for borrowing.
     *
     * For lever, max borrow is calculated as:
     * (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals
     *
     * For delever, max repay is calculated as:
     * Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD
     *
     * Net borrow limit for levering is calculated as:
     * The collateral value in USD * Aave collateral factor * (1 - unutilized leverage %)
     *
     * Net repay limit for delevering is calculated as:
     * The collateral value in USD * Aave liquiditon threshold * (1 - unutilized leverage %)
     *
     * return uint256          Max borrow notional denominated in collateral asset
     */
    function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) {
        
        // Retrieve collateral factor and liquidation threshold for the collateral asset in precise units (1e16 = 1%)
        ( , uint256 maxLtvRaw, uint256 liquidationThresholdRaw, , , , , , ,) = strategy.aaveProtocolDataProvider.getReserveConfigurationData(address(strategy.collateralAsset));

        // Normalize LTV and liquidation threshold to precise units. LTV is measured in 4 decimals in Aave which is why we must multiply by 1e14
        // for example ETH has an LTV value of 8000 which represents 80%
        if (_isLever) {
            uint256 netBorrowLimit = _actionInfo.collateralValue
                .preciseMul(maxLtvRaw.mul(10 ** 14))
                .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));

            return netBorrowLimit
                .sub(_actionInfo.borrowValue)
                .preciseDiv(_actionInfo.collateralPrice);
        } else {
            uint256 netRepayLimit = _actionInfo.collateralValue
                .preciseMul(liquidationThresholdRaw.mul(10 ** 14))
                .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));

            return _actionInfo.collateralBalance
                .preciseMul(netRepayLimit.sub(_actionInfo.borrowValue))
                .preciseDiv(netRepayLimit);
        }
    }

    /**
     * Derive the borrow units for lever. The units are calculated by the collateral units multiplied by collateral / borrow asset price.
     * Output is measured to borrow unit decimals.
     *
     * return uint256           Position units to borrow
     */
    function _calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internal pure returns (uint256) {
        return _collateralRebalanceUnits.preciseMul(_actionInfo.collateralPrice).preciseDiv(_actionInfo.borrowPrice);
    }

    /**
     * Calculate the min receive units in collateral units for lever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance
     * Output is measured in collateral asset decimals.
     *
     * return uint256           Min position units to receive after lever trade
     */
    function _calculateMinCollateralReceiveUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance) internal pure returns (uint256) {
        return _collateralRebalanceUnits.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));
    }

    /**
     * Derive the min repay units from collateral units for delever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance
     * and pair price (collateral oracle price / borrow oracle price). Output is measured in borrow unit decimals.
     *
     * return uint256           Min position units to repay in borrow asset
     */
    function _calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internal pure returns (uint256) {
        return _collateralRebalanceUnits
            .preciseMul(_actionInfo.collateralPrice)
            .preciseDiv(_actionInfo.borrowPrice)
            .preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));
    }

    /**
     * Update last trade timestamp and if chunk rebalance size is less than total rebalance notional, store new leverage ratio to kick off TWAP. Used in
     * the engage() and rebalance() functions
     */
    function _updateRebalanceState(
        uint256 _chunkRebalanceNotional,
        uint256 _totalRebalanceNotional,
        uint256 _newLeverageRatio,
        string memory _exchangeName
    )
        internal
    {

        _updateLastTradeTimestamp(_exchangeName);

        if (_chunkRebalanceNotional < _totalRebalanceNotional) {
            twapLeverageRatio = _newLeverageRatio;
        }
    }

    /**
     * Update last trade timestamp and if chunk rebalance size is equal to the total rebalance notional, end TWAP by clearing state. This function is used
     * in iterateRebalance()
     */
    function _updateIterateState(uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional, string memory _exchangeName) internal {

        _updateLastTradeTimestamp(_exchangeName);

        // If the chunk size is equal to the total notional meaning that rebalances are not chunked, then clear TWAP state.
        if (_chunkRebalanceNotional == _totalRebalanceNotional) {
            delete twapLeverageRatio;
        }
    }

    /**
     * Update last trade timestamp and if currently in a TWAP, delete the TWAP state. Used in the ripcord() function.
     */
    function _updateRipcordState(string memory _exchangeName) internal {

        _updateLastTradeTimestamp(_exchangeName);

        // If TWAP leverage ratio is stored, then clear state. This may happen if we are currently in a TWAP rebalance, and the leverage ratio moves above the
        // incentivized threshold for ripcord.
        if (twapLeverageRatio > 0) {
            delete twapLeverageRatio;
        }
    }

    /**
     * Update globalLastTradeTimestamp and exchangeLastTradeTimestamp values. This function updates both the exchange-specific and global timestamp so that the
     * epoch rebalance can use the global timestamp (since the global timestamp is always  equal to the most recently used exchange timestamp). This allows for
     * multiple rebalances to occur simultaneously since only the exchange-specific timestamp is checked for non-epoch rebalances.
     */
     function _updateLastTradeTimestamp(string memory _exchangeName) internal {
        globalLastTradeTimestamp = block.timestamp;
        exchangeSettings[_exchangeName].exchangeLastTradeTimestamp = block.timestamp;
     }

    /**
     * Transfer ETH reward to caller of the ripcord function. If the ETH balance on this contract is less than required
     * incentive quantity, then transfer contract balance instead to prevent reverts.
     *
     * return uint256           Amount of ETH transferred to caller
     */
    function _transferEtherRewardToCaller(uint256 _etherReward) internal returns(uint256) {
        uint256 etherToTransfer = _etherReward < address(this).balance ? _etherReward : address(this).balance;

        msg.sender.transfer(etherToTransfer);

        return etherToTransfer;
    }

    /**
     * Internal function returning the ShouldRebalance enum used in shouldRebalance and shouldRebalanceWithBounds external getter functions
     *
     * return ShouldRebalance         Enum detailing whether to rebalance, iterateRebalance, ripcord or no action
     */
    function _shouldRebalance(
        uint256 _currentLeverageRatio,
        uint256 _minLeverageRatio,
        uint256 _maxLeverageRatio
    )
        internal
        view
        returns(string[] memory, ShouldRebalance[] memory)
    {

        ShouldRebalance[] memory shouldRebalanceEnums = new ShouldRebalance[](enabledExchanges.length);

        for (uint256 i = 0; i < enabledExchanges.length; i++) {
            // If none of the below conditions are satisfied, then should not rebalance
            shouldRebalanceEnums[i] = ShouldRebalance.NONE;

            // If above ripcord threshold, then check if incentivized cooldown period has elapsed
            if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) {
                if (exchangeSettings[enabledExchanges[i]].exchangeLastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) {
                    shouldRebalanceEnums[i] = ShouldRebalance.RIPCORD;
                }
            } else {
                // If TWAP, then check if the cooldown period has elapsed
                if (twapLeverageRatio > 0) {
                    if (exchangeSettings[enabledExchanges[i]].exchangeLastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) {
                        shouldRebalanceEnums[i] = ShouldRebalance.ITERATE_REBALANCE;
                    }
                } else {
                    // If not TWAP, then check if the rebalance interval has elapsed OR current leverage is above max leverage OR current leverage is below
                    // min leverage
                    if (
                        block.timestamp.sub(globalLastTradeTimestamp) > methodology.rebalanceInterval
                        || _currentLeverageRatio > _maxLeverageRatio
                        || _currentLeverageRatio < _minLeverageRatio
                    ) {
                        shouldRebalanceEnums[i] = ShouldRebalance.REBALANCE;
                    }
                }
            }
        }

        return (enabledExchanges, shouldRebalanceEnums);
    }
}

File 2 of 16 : Address.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.2 <0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

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

File 3 of 16 : IERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

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

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

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

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

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

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

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

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

File 4 of 16 : Math.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

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

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

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

File 5 of 16 : SafeCast.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;


/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128) {
        require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
        return int128(value);
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64) {
        require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
        return int64(value);
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32) {
        require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
        return int32(value);
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16) {
        require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
        return int16(value);
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8) {
        require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
        return int8(value);
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        require(value < 2**255, "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 6 of 16 : SafeMath.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        uint256 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

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

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) return (true, 0);
        uint256 c = a * b;
        if (c / a != b) return (false, 0);
        return (true, c);
    }

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

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

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }

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

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) return 0;
        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");
        return c;
    }

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

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

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a % b;
    }
}

File 7 of 16 : BaseExtension.sol
/*
    Copyright 2021 Set Labs Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    SPDX-License-Identifier: Apache License, Version 2.0
*/

pragma solidity 0.6.10;

import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
import { IBaseManager } from "../interfaces/IBaseManager.sol";

/**
 * @title BaseExtension
 * @author Set Protocol
 *
 * Abstract class that houses common extension-related state and functions.
 */
abstract contract BaseExtension {
    using AddressArrayUtils for address[];

    /* ============ Events ============ */

    event CallerStatusUpdated(address indexed _caller, bool _status);
    event AnyoneCallableUpdated(bool indexed _status);

    /* ============ Modifiers ============ */

    /**
     * Throws if the sender is not the SetToken operator
     */
    modifier onlyOperator() {
        require(msg.sender == manager.operator(), "Must be operator");
        _;
    }

    /**
     * Throws if the sender is not the SetToken methodologist
     */
    modifier onlyMethodologist() {
        require(msg.sender == manager.methodologist(), "Must be methodologist");
        _;
    }

    /**
     * Throws if caller is a contract, can be used to stop flash loan and sandwich attacks
     */
    modifier onlyEOA() {
        require(msg.sender == tx.origin, "Caller must be EOA Address");
        _;
    }

    /**
     * Throws if not allowed caller
     */
    modifier onlyAllowedCaller(address _caller) {
        require(isAllowedCaller(_caller), "Address not permitted to call");
        _;
    }

    /* ============ State Variables ============ */

    // Instance of manager contract
    IBaseManager public manager;

    // Boolean indicating if anyone can call function
    bool public anyoneCallable;

    // Mapping of addresses allowed to call function
    mapping(address => bool) public callAllowList;

    /* ============ Constructor ============ */

    constructor(IBaseManager _manager) public { manager = _manager; }

    /* ============ External Functions ============ */

    /**
     * OPERATOR ONLY: Toggle ability for passed addresses to call only allowed caller functions
     *
     * @param _callers           Array of caller addresses to toggle status
     * @param _statuses          Array of statuses for each caller
     */
    function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator {
        require(_callers.length == _statuses.length, "Array length mismatch");
        require(_callers.length > 0, "Array length must be > 0");
        require(!_callers.hasDuplicate(), "Cannot duplicate callers");

        for (uint256 i = 0; i < _callers.length; i++) {
            address caller = _callers[i];
            bool status = _statuses[i];
            callAllowList[caller] = status;
            emit CallerStatusUpdated(caller, status);
        }
    }

    /**
     * OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist
     *
     * @param _status           Boolean indicating whether to allow anyone call
     */
    function updateAnyoneCallable(bool _status) external onlyOperator {
        anyoneCallable = _status;
        emit AnyoneCallableUpdated(_status);
    }

    /* ============ Internal Functions ============ */

    /**
     * Invoke manager to transfer tokens from manager to other contract.
     *
     * @param _token           Token being transferred from manager contract
     * @param _amount          Amount of token being transferred
     */
    function invokeManagerTransfer(address _token, address _destination, uint256 _amount) internal {
        manager.transferTokens(_token, _destination, _amount);
    }

    /**
     * Invoke call from manager
     *
     * @param _module           Module to interact with
     * @param _encoded          Encoded byte data
     */
    function invokeManager(address _module, bytes memory _encoded) internal {
        manager.interactManager(_module, _encoded);
    }

    /**
     * Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved.
     *
     * return bool              Boolean indicating if allowed caller
     */
    function isAllowedCaller(address _caller) internal view virtual returns (bool) {
        return anyoneCallable || callAllowList[_caller];
    }
}

File 8 of 16 : IBaseManager.sol
/*
    Copyright 2021 Set Labs Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    SPDX-License-Identifier: Apache License, Version 2.0
*/

pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";

import { ISetToken } from "./ISetToken.sol";

interface IBaseManager {
    function setToken() external returns(ISetToken);

    function methodologist() external returns(address);

    function operator() external returns(address);

    function interactManager(address _module, bytes calldata _encoded) external;

    function transferTokens(address _token, address _destination, uint256 _amount) external;
}

File 9 of 16 : IChainlinkAggregatorV3.sol
// SPDX-License-Identifier: Apache License, Version 2.0
pragma solidity 0.6.10;

interface IChainlinkAggregatorV3 {
    function latestAnswer() external view returns (int256);
}

File 10 of 16 : ILeverageModule.sol
// SPDX-License-Identifier: Apache License, Version 2.0
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";

import { ISetToken } from "./ISetToken.sol";

interface ILeverageModule {
    function sync(
        ISetToken _setToken
    ) external;

    function lever(
        ISetToken _setToken,
        address _borrowAsset,
        address _collateralAsset,
        uint256 _borrowQuantity,
        uint256 _minReceiveQuantity,
        string memory _tradeAdapterName,
        bytes memory _tradeData
    ) external;

    function delever(
        ISetToken _setToken,
        address _collateralAsset,
        address _repayAsset,
        uint256 _redeemQuantity,
        uint256 _minRepayQuantity,
        string memory _tradeAdapterName,
        bytes memory _tradeData
    ) external;

    function gulp(
        ISetToken _setToken,
        address _collateralAsset,
        uint256 _minNotionalReceiveQuantity,
        string memory _tradeAdapterName,
        bytes memory _tradeData
    ) external;
}

File 11 of 16 : IProtocolDataProvider.sol
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;

interface IProtocolDataProvider {
  struct TokenData {
    string symbol;
    address tokenAddress;
  }

  function ADDRESSES_PROVIDER() external view returns (address);
  function getAllReservesTokens() external view returns (TokenData[] memory);
  function getAllATokens() external view returns (TokenData[] memory);
  function getReserveConfigurationData(address asset) external view returns (uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen);
  function getReserveData(address asset) external view returns (uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp);
  function getUserReserveData(address asset, address user) external view returns (uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled);
  function getReserveTokensAddresses(address asset) external view returns (address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress);
}

File 12 of 16 : ISetToken.sol
// SPDX-License-Identifier: Apache License, Version 2.0
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @title ISetToken
 * @author Set Protocol
 *
 * Interface for operating with SetTokens.
 */
interface ISetToken is IERC20 {

    /* ============ Enums ============ */

    enum ModuleState {
        NONE,
        PENDING,
        INITIALIZED
    }

    /* ============ Structs ============ */
    /**
     * The base definition of a SetToken Position
     *
     * @param component           Address of token in the Position
     * @param module              If not in default state, the address of associated module
     * @param unit                Each unit is the # of components per 10^18 of a SetToken
     * @param positionState       Position ENUM. Default is 0; External is 1
     * @param data                Arbitrary data
     */
    struct Position {
        address component;
        address module;
        int256 unit;
        uint8 positionState;
        bytes data;
    }

    /**
     * A struct that stores a component's cash position details and external positions
     * This data structure allows O(1) access to a component's cash position units and
     * virtual units.
     *
     * @param virtualUnit               Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
     *                                  updating all units at once via the position multiplier. Virtual units are achieved
     *                                  by dividing a "real" value by the "positionMultiplier"
     * @param componentIndex
     * @param externalPositionModules   List of external modules attached to each external position. Each module
     *                                  maps to an external position
     * @param externalPositions         Mapping of module => ExternalPosition struct for a given component
     */
    struct ComponentPosition {
      int256 virtualUnit;
      address[] externalPositionModules;
      mapping(address => ExternalPosition) externalPositions;
    }

    /**
     * A struct that stores a component's external position details including virtual unit and any
     * auxiliary data.
     *
     * @param virtualUnit       Virtual value of a component's EXTERNAL position.
     * @param data              Arbitrary data
     */
    struct ExternalPosition {
      int256 virtualUnit;
      bytes data;
    }


    /* ============ Functions ============ */

    function addComponent(address _component) external;
    function removeComponent(address _component) external;
    function editDefaultPositionUnit(address _component, int256 _realUnit) external;
    function addExternalPositionModule(address _component, address _positionModule) external;
    function removeExternalPositionModule(address _component, address _positionModule) external;
    function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
    function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;

    function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);

    function editPositionMultiplier(int256 _newMultiplier) external;

    function mint(address _account, uint256 _quantity) external;
    function burn(address _account, uint256 _quantity) external;

    function lock() external;
    function unlock() external;

    function addModule(address _module) external;
    function removeModule(address _module) external;
    function initializeModule() external;

    function setManager(address _manager) external;

    function manager() external view returns (address);
    function moduleStates(address _module) external view returns (ModuleState);
    function getModules() external view returns (address[] memory);

    function getDefaultPositionRealUnit(address _component) external view returns(int256);
    function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
    function getComponents() external view returns(address[] memory);
    function getExternalPositionModules(address _component) external view returns(address[] memory);
    function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
    function isExternalPositionModule(address _component, address _module) external view returns(bool);
    function isComponent(address _component) external view returns(bool);

    function positionMultiplier() external view returns (int256);
    function getPositions() external view returns (Position[] memory);
    function getTotalComponentRealUnits(address _component) external view returns(int256);

    function isInitializedModule(address _module) external view returns(bool);
    function isPendingModule(address _module) external view returns(bool);
    function isLocked() external view returns (bool);
}

File 13 of 16 : PreciseUnitMath.sol
/*
    Copyright 2020 Set Labs Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    SPDX-License-Identifier: Apache License, Version 2.0
*/

pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;

import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";


/**
 * @title PreciseUnitMath
 * @author Set Protocol
 *
 * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
 * dYdX's BaseMath library.
 *
 * CHANGELOG:
 * - 9/21/20: Added safePower function
 */
library PreciseUnitMath {
    using SafeMath for uint256;
    using SignedSafeMath for int256;

    // The number One in precise units.
    uint256 constant internal PRECISE_UNIT = 10 ** 18;
    int256 constant internal PRECISE_UNIT_INT = 10 ** 18;

    // Max unsigned integer value
    uint256 constant internal MAX_UINT_256 = type(uint256).max;
    // Max and min signed integer value
    int256 constant internal MAX_INT_256 = type(int256).max;
    int256 constant internal MIN_INT_256 = type(int256).min;

    /**
     * @dev Getter function since constants can't be read directly from libraries.
     */
    function preciseUnit() internal pure returns (uint256) {
        return PRECISE_UNIT;
    }

    /**
     * @dev Getter function since constants can't be read directly from libraries.
     */
    function preciseUnitInt() internal pure returns (int256) {
        return PRECISE_UNIT_INT;
    }

    /**
     * @dev Getter function since constants can't be read directly from libraries.
     */
    function maxUint256() internal pure returns (uint256) {
        return MAX_UINT_256;
    }

    /**
     * @dev Getter function since constants can't be read directly from libraries.
     */
    function maxInt256() internal pure returns (int256) {
        return MAX_INT_256;
    }

    /**
     * @dev Getter function since constants can't be read directly from libraries.
     */
    function minInt256() internal pure returns (int256) {
        return MIN_INT_256;
    }

    /**
     * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
     * of a number with 18 decimals precision.
     */
    function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mul(b).div(PRECISE_UNIT);
    }

    /**
     * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
     * significand of a number with 18 decimals precision.
     */
    function preciseMul(int256 a, int256 b) internal pure returns (int256) {
        return a.mul(b).div(PRECISE_UNIT_INT);
    }

    /**
     * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
     * of a number with 18 decimals precision.
     */
    function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0 || b == 0) {
            return 0;
        }
        return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
    }

    /**
     * @dev Divides value a by value b (result is rounded down).
     */
    function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mul(PRECISE_UNIT).div(b);
    }


    /**
     * @dev Divides value a by value b (result is rounded towards 0).
     */
    function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
        return a.mul(PRECISE_UNIT_INT).div(b);
    }

    /**
     * @dev Divides value a by value b (result is rounded up or away from 0).
     */
    function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b != 0, "Cant divide by 0");

        return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
    }

    /**
     * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
     */
    function divDown(int256 a, int256 b) internal pure returns (int256) {
        require(b != 0, "Cant divide by 0");
        require(a != MIN_INT_256 || b != -1, "Invalid input");

        int256 result = a.div(b);
        if (a ^ b < 0 && a % b != 0) {
            result -= 1;
        }

        return result;
    }

    /**
     * @dev Multiplies value a by value b where rounding is towards the lesser number. 
     * (positive values are rounded towards zero and negative values are rounded away from 0). 
     */
    function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
        return divDown(a.mul(b), PRECISE_UNIT_INT);
    }

    /**
     * @dev Divides value a by value b where rounding is towards the lesser number. 
     * (positive values are rounded towards zero and negative values are rounded away from 0). 
     */
    function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
        return divDown(a.mul(PRECISE_UNIT_INT), b);
    }

    /**
    * @dev Performs the power on a specified value, reverts on overflow.
    */
    function safePower(
        uint256 a,
        uint256 pow
    )
        internal
        pure
        returns (uint256)
    {
        require(a > 0, "Value must be positive");

        uint256 result = 1;
        for (uint256 i = 0; i < pow; i++){
            uint256 previousResult = result;

            // Using safemath multiplication prevents overflows
            result = previousResult.mul(a);
        }

        return result;
    }
}

File 14 of 16 : StringArrayUtils.sol
/*
    Copyright 2021 Set Labs Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    SPDX-License-Identifier: Apache License, Version 2.0
*/

pragma solidity 0.6.10;

/**
 * @title StringArrayUtils
 * @author Set Protocol
 *
 * Utility functions to handle String Arrays
 */
library StringArrayUtils {

    /**
     * Finds the index of the first occurrence of the given element.
     * @param A The input string to search
     * @param a The value to find
     * @return Returns (index and isIn) for the first occurrence starting from index 0
     */
    function indexOf(string[] memory A, string memory a) internal pure returns (uint256, bool) {
        uint256 length = A.length;
        for (uint256 i = 0; i < length; i++) {
            if (keccak256(bytes(A[i])) == keccak256(bytes(a))) {
                return (i, true);
            }
        }
        return (uint256(-1), false);
    }

    /**
     * @param A The input array to search
     * @param a The string to remove
     */
    function removeStorage(string[] storage A, string memory a)
        internal
    {
        (uint256 index, bool isIn) = indexOf(A, a);
        if (!isIn) {
            revert("String not in array.");
        } else {
            uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
            if (index != lastIndex) { A[index] = A[lastIndex]; }
            A.pop();
        }
    }
}

File 15 of 16 : AddressArrayUtils.sol
/*
    Copyright 2020 Set Labs Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    SPDX-License-Identifier: Apache License, Version 2.0
*/

pragma solidity 0.6.10;

/**
 * @title AddressArrayUtils
 * @author Set Protocol
 *
 * Utility functions to handle Address Arrays
 *
 * CHANGELOG:
 * - 4/27/21: Added validatePairsWithArray methods
 */
library AddressArrayUtils {

    /**
     * Finds the index of the first occurrence of the given element.
     * @param A The input array to search
     * @param a The value to find
     * @return Returns (index and isIn) for the first occurrence starting from index 0
     */
    function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
        uint256 length = A.length;
        for (uint256 i = 0; i < length; i++) {
            if (A[i] == a) {
                return (i, true);
            }
        }
        return (uint256(-1), false);
    }

    /**
    * Returns true if the value is present in the list. Uses indexOf internally.
    * @param A The input array to search
    * @param a The value to find
    * @return Returns isIn for the first occurrence starting from index 0
    */
    function contains(address[] memory A, address a) internal pure returns (bool) {
        (, bool isIn) = indexOf(A, a);
        return isIn;
    }

    /**
    * Returns true if there are 2 elements that are the same in an array
    * @param A The input array to search
    * @return Returns boolean for the first occurrence of a duplicate
    */
    function hasDuplicate(address[] memory A) internal pure returns(bool) {
        require(A.length > 0, "A is empty");

        for (uint256 i = 0; i < A.length - 1; i++) {
            address current = A[i];
            for (uint256 j = i + 1; j < A.length; j++) {
                if (current == A[j]) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @param A The input array to search
     * @param a The address to remove
     * @return Returns the array with the object removed.
     */
    function remove(address[] memory A, address a)
        internal
        pure
        returns (address[] memory)
    {
        (uint256 index, bool isIn) = indexOf(A, a);
        if (!isIn) {
            revert("Address not in array.");
        } else {
            (address[] memory _A,) = pop(A, index);
            return _A;
        }
    }

    /**
     * @param A The input array to search
     * @param a The address to remove
     */
    function removeStorage(address[] storage A, address a)
        internal
    {
        (uint256 index, bool isIn) = indexOf(A, a);
        if (!isIn) {
            revert("Address not in array.");
        } else {
            uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
            if (index != lastIndex) { A[index] = A[lastIndex]; }
            A.pop();
        }
    }

    /**
    * Removes specified index from array
    * @param A The input array to search
    * @param index The index to remove
    * @return Returns the new array and the removed entry
    */
    function pop(address[] memory A, uint256 index)
        internal
        pure
        returns (address[] memory, address)
    {
        uint256 length = A.length;
        require(index < A.length, "Index must be < A length");
        address[] memory newAddresses = new address[](length - 1);
        for (uint256 i = 0; i < index; i++) {
            newAddresses[i] = A[i];
        }
        for (uint256 j = index + 1; j < length; j++) {
            newAddresses[j - 1] = A[j];
        }
        return (newAddresses, A[index]);
    }

    /**
     * Returns the combination of the two arrays
     * @param A The first array
     * @param B The second array
     * @return Returns A extended by B
     */
    function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
        uint256 aLength = A.length;
        uint256 bLength = B.length;
        address[] memory newAddresses = new address[](aLength + bLength);
        for (uint256 i = 0; i < aLength; i++) {
            newAddresses[i] = A[i];
        }
        for (uint256 j = 0; j < bLength; j++) {
            newAddresses[aLength + j] = B[j];
        }
        return newAddresses;
    }

    /**
     * Validate that address and uint array lengths match. Validate address array is not empty
     * and contains no duplicate elements.
     *
     * @param A         Array of addresses
     * @param B         Array of uint
     */
    function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
        require(A.length == B.length, "Array length mismatch");
        _validateLengthAndUniqueness(A);
    }

    /**
     * Validate that address and bool array lengths match. Validate address array is not empty
     * and contains no duplicate elements.
     *
     * @param A         Array of addresses
     * @param B         Array of bool
     */
    function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
        require(A.length == B.length, "Array length mismatch");
        _validateLengthAndUniqueness(A);
    }

    /**
     * Validate that address and string array lengths match. Validate address array is not empty
     * and contains no duplicate elements.
     *
     * @param A         Array of addresses
     * @param B         Array of strings
     */
    function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
        require(A.length == B.length, "Array length mismatch");
        _validateLengthAndUniqueness(A);
    }

    /**
     * Validate that address array lengths match, and calling address array are not empty
     * and contain no duplicate elements.
     *
     * @param A         Array of addresses
     * @param B         Array of addresses
     */
    function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
        require(A.length == B.length, "Array length mismatch");
        _validateLengthAndUniqueness(A);
    }

    /**
     * Validate that address and bytes array lengths match. Validate address array is not empty
     * and contains no duplicate elements.
     *
     * @param A         Array of addresses
     * @param B         Array of bytes
     */
    function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
        require(A.length == B.length, "Array length mismatch");
        _validateLengthAndUniqueness(A);
    }

    /**
     * Validate address array is not empty and contains no duplicate elements.
     *
     * @param A          Array of addresses
     */
    function _validateLengthAndUniqueness(address[] memory A) internal pure {
        require(A.length > 0, "Array length must be > 0");
        require(!hasDuplicate(A), "Cannot duplicate addresses");
    }
}

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

pragma solidity >=0.6.0 <0.8.0;

/**
 * @title SignedSafeMath
 * @dev Signed math operations with safety checks that revert on error.
 */
library SignedSafeMath {
    int256 constant private _INT256_MIN = -2**255;

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

        require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");

        int256 c = a * b;
        require(c / a == b, "SignedSafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two signed integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(int256 a, int256 b) internal pure returns (int256) {
        require(b != 0, "SignedSafeMath: division by zero");
        require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");

        int256 c = a / b;

        return c;
    }

    /**
     * @dev Returns the subtraction of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a - b;
        require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");

        return c;
    }

    /**
     * @dev Returns the addition of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a + b;
        require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");

        return c;
    }
}

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

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract IBaseManager","name":"_manager","type":"address"},{"components":[{"internalType":"contract ISetToken","name":"setToken","type":"address"},{"internalType":"contract ILeverageModule","name":"leverageModule","type":"address"},{"internalType":"contract IProtocolDataProvider","name":"aaveProtocolDataProvider","type":"address"},{"internalType":"contract IChainlinkAggregatorV3","name":"collateralPriceOracle","type":"address"},{"internalType":"contract IChainlinkAggregatorV3","name":"borrowPriceOracle","type":"address"},{"internalType":"contract IERC20","name":"targetCollateralAToken","type":"address"},{"internalType":"contract IERC20","name":"targetBorrowDebtToken","type":"address"},{"internalType":"address","name":"collateralAsset","type":"address"},{"internalType":"address","name":"borrowAsset","type":"address"},{"internalType":"uint256","name":"collateralDecimalAdjustment","type":"uint256"},{"internalType":"uint256","name":"borrowDecimalAdjustment","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.ContractSettings","name":"_strategy","type":"tuple"},{"components":[{"internalType":"uint256","name":"targetLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"minLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"maxLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"recenteringSpeed","type":"uint256"},{"internalType":"uint256","name":"rebalanceInterval","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.MethodologySettings","name":"_methodology","type":"tuple"},{"components":[{"internalType":"uint256","name":"unutilizedLeveragePercentage","type":"uint256"},{"internalType":"uint256","name":"slippageTolerance","type":"uint256"},{"internalType":"uint256","name":"twapCooldownPeriod","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.ExecutionSettings","name":"_execution","type":"tuple"},{"components":[{"internalType":"uint256","name":"etherReward","type":"uint256"},{"internalType":"uint256","name":"incentivizedLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"incentivizedSlippageTolerance","type":"uint256"},{"internalType":"uint256","name":"incentivizedTwapCooldownPeriod","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.IncentiveSettings","name":"_incentive","type":"tuple"},{"internalType":"string[]","name":"_exchangeNames","type":"string[]"},{"components":[{"internalType":"uint256","name":"twapMaxTradeSize","type":"uint256"},{"internalType":"uint256","name":"exchangeLastTradeTimestamp","type":"uint256"},{"internalType":"uint256","name":"incentivizedTwapMaxTradeSize","type":"uint256"},{"internalType":"bytes","name":"leverExchangeData","type":"bytes"},{"internalType":"bytes","name":"deleverExchangeData","type":"bytes"}],"internalType":"struct AaveLeverageStrategyExtension.ExchangeSettings[]","name":"_exchangeSettings","type":"tuple[]"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bool","name":"_status","type":"bool"}],"name":"AnyoneCallableUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_caller","type":"address"},{"indexed":false,"internalType":"bool","name":"_status","type":"bool"}],"name":"CallerStatusUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_currentLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_chunkRebalanceNotional","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_totalRebalanceNotional","type":"uint256"}],"name":"Disengaged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_currentLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_chunkRebalanceNotional","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_totalRebalanceNotional","type":"uint256"}],"name":"Engaged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"_exchangeName","type":"string"},{"indexed":false,"internalType":"uint256","name":"twapMaxTradeSize","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"exchangeLastTradeTimestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"incentivizedTwapMaxTradeSize","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"leverExchangeData","type":"bytes"},{"indexed":false,"internalType":"bytes","name":"deleverExchangeData","type":"bytes"}],"name":"ExchangeAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"_exchangeName","type":"string"}],"name":"ExchangeRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"_exchangeName","type":"string"},{"indexed":false,"internalType":"uint256","name":"twapMaxTradeSize","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"exchangeLastTradeTimestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"incentivizedTwapMaxTradeSize","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"leverExchangeData","type":"bytes"},{"indexed":false,"internalType":"bytes","name":"deleverExchangeData","type":"bytes"}],"name":"ExchangeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_unutilizedLeveragePercentage","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_twapCooldownPeriod","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_slippageTolerance","type":"uint256"}],"name":"ExecutionSettingsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_etherReward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_incentivizedLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_incentivizedSlippageTolerance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_incentivizedTwapCooldownPeriod","type":"uint256"}],"name":"IncentiveSettingsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_targetLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_minLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_maxLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_recenteringSpeed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_rebalanceInterval","type":"uint256"}],"name":"MethodologySettingsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_currentLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_chunkRebalanceNotional","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_totalRebalanceNotional","type":"uint256"}],"name":"RebalanceIterated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_currentLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_chunkRebalanceNotional","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_totalRebalanceNotional","type":"uint256"}],"name":"Rebalanced","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_currentLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newLeverageRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_rebalanceNotional","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_etherIncentive","type":"uint256"}],"name":"RipcordCalled","type":"event"},{"inputs":[{"internalType":"string","name":"_exchangeName","type":"string"},{"components":[{"internalType":"uint256","name":"twapMaxTradeSize","type":"uint256"},{"internalType":"uint256","name":"exchangeLastTradeTimestamp","type":"uint256"},{"internalType":"uint256","name":"incentivizedTwapMaxTradeSize","type":"uint256"},{"internalType":"bytes","name":"leverExchangeData","type":"bytes"},{"internalType":"bytes","name":"deleverExchangeData","type":"bytes"}],"internalType":"struct AaveLeverageStrategyExtension.ExchangeSettings","name":"_exchangeSettings","type":"tuple"}],"name":"addEnabledExchange","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"anyoneCallable","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"callAllowList","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_exchangeName","type":"string"}],"name":"disengage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"enabledExchanges","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_exchangeName","type":"string"}],"name":"engage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string[]","name":"_exchangeNames","type":"string[]"}],"name":"getChunkRebalanceNotional","outputs":[{"internalType":"uint256[]","name":"sizes","type":"uint256[]"},{"internalType":"address","name":"sellAsset","type":"address"},{"internalType":"address","name":"buyAsset","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentEtherIncentive","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentLeverageRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getEnabledExchanges","outputs":[{"internalType":"string[]","name":"","type":"string[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_exchangeName","type":"string"}],"name":"getExchangeSettings","outputs":[{"components":[{"internalType":"uint256","name":"twapMaxTradeSize","type":"uint256"},{"internalType":"uint256","name":"exchangeLastTradeTimestamp","type":"uint256"},{"internalType":"uint256","name":"incentivizedTwapMaxTradeSize","type":"uint256"},{"internalType":"bytes","name":"leverExchangeData","type":"bytes"},{"internalType":"bytes","name":"deleverExchangeData","type":"bytes"}],"internalType":"struct AaveLeverageStrategyExtension.ExchangeSettings","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getExecution","outputs":[{"components":[{"internalType":"uint256","name":"unutilizedLeveragePercentage","type":"uint256"},{"internalType":"uint256","name":"slippageTolerance","type":"uint256"},{"internalType":"uint256","name":"twapCooldownPeriod","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.ExecutionSettings","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getIncentive","outputs":[{"components":[{"internalType":"uint256","name":"etherReward","type":"uint256"},{"internalType":"uint256","name":"incentivizedLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"incentivizedSlippageTolerance","type":"uint256"},{"internalType":"uint256","name":"incentivizedTwapCooldownPeriod","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.IncentiveSettings","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getMethodology","outputs":[{"components":[{"internalType":"uint256","name":"targetLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"minLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"maxLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"recenteringSpeed","type":"uint256"},{"internalType":"uint256","name":"rebalanceInterval","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.MethodologySettings","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getStrategy","outputs":[{"components":[{"internalType":"contract ISetToken","name":"setToken","type":"address"},{"internalType":"contract ILeverageModule","name":"leverageModule","type":"address"},{"internalType":"contract IProtocolDataProvider","name":"aaveProtocolDataProvider","type":"address"},{"internalType":"contract IChainlinkAggregatorV3","name":"collateralPriceOracle","type":"address"},{"internalType":"contract IChainlinkAggregatorV3","name":"borrowPriceOracle","type":"address"},{"internalType":"contract IERC20","name":"targetCollateralAToken","type":"address"},{"internalType":"contract IERC20","name":"targetBorrowDebtToken","type":"address"},{"internalType":"address","name":"collateralAsset","type":"address"},{"internalType":"address","name":"borrowAsset","type":"address"},{"internalType":"uint256","name":"collateralDecimalAdjustment","type":"uint256"},{"internalType":"uint256","name":"borrowDecimalAdjustment","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.ContractSettings","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"globalLastTradeTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_exchangeName","type":"string"}],"name":"iterateRebalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"contract IBaseManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_exchangeName","type":"string"}],"name":"rebalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_exchangeName","type":"string"}],"name":"removeEnabledExchange","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_exchangeName","type":"string"}],"name":"ripcord","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"unutilizedLeveragePercentage","type":"uint256"},{"internalType":"uint256","name":"slippageTolerance","type":"uint256"},{"internalType":"uint256","name":"twapCooldownPeriod","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.ExecutionSettings","name":"_newExecutionSettings","type":"tuple"}],"name":"setExecutionSettings","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"etherReward","type":"uint256"},{"internalType":"uint256","name":"incentivizedLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"incentivizedSlippageTolerance","type":"uint256"},{"internalType":"uint256","name":"incentivizedTwapCooldownPeriod","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.IncentiveSettings","name":"_newIncentiveSettings","type":"tuple"}],"name":"setIncentiveSettings","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"targetLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"minLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"maxLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"recenteringSpeed","type":"uint256"},{"internalType":"uint256","name":"rebalanceInterval","type":"uint256"}],"internalType":"struct AaveLeverageStrategyExtension.MethodologySettings","name":"_newMethodologySettings","type":"tuple"}],"name":"setMethodologySettings","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"shouldRebalance","outputs":[{"internalType":"string[]","name":"","type":"string[]"},{"internalType":"enum AaveLeverageStrategyExtension.ShouldRebalance[]","name":"","type":"uint8[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_customMinLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"_customMaxLeverageRatio","type":"uint256"}],"name":"shouldRebalanceWithBounds","outputs":[{"internalType":"string[]","name":"","type":"string[]"},{"internalType":"enum AaveLeverageStrategyExtension.ShouldRebalance[]","name":"","type":"uint8[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"twapLeverageRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_status","type":"bool"}],"name":"updateAnyoneCallable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_callers","type":"address[]"},{"internalType":"bool[]","name":"_statuses","type":"bool[]"}],"name":"updateCallerStatus","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_exchangeName","type":"string"},{"components":[{"internalType":"uint256","name":"twapMaxTradeSize","type":"uint256"},{"internalType":"uint256","name":"exchangeLastTradeTimestamp","type":"uint256"},{"internalType":"uint256","name":"incentivizedTwapMaxTradeSize","type":"uint256"},{"internalType":"bytes","name":"leverExchangeData","type":"bytes"},{"internalType":"bytes","name":"deleverExchangeData","type":"bytes"}],"internalType":"struct AaveLeverageStrategyExtension.ExchangeSettings","name":"_exchangeSettings","type":"tuple"}],"name":"updateEnabledExchange","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"withdrawEtherBalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

60806040523480156200001157600080fd5b5060405162005d6338038062005d638339810160408190526200003491620008a0565b600080546001600160a01b03199081166001600160a01b038a811691909117835588516002805484169183169190911790556020808a01516003805485169184169190911790556040808b01516004805486169185169190911790556060808c01516005805487169186169190911790556080808d015160068054881691871691909117905560a08d015160078054881691871691909117905560c08d015160088054881691871691909117905560e08d01516009805488169187169190911790556101008d0151600a80549097169516949094179094556101208b0151600b556101408b0151600c558951600d5589820151600e5589810151600f5589840151601055918901516011558751601255878101516013558782015160145586516016558601516017558501516018558401516019555b82518110156200028d57620001998282815181106200018557fe5b60200260200101516200032a60201b60201c565b818181518110620001a657fe5b60200260200101516015848381518110620001bd57fe5b6020026020010151604051620001d4919062000a51565b908152602001604051809103902060008201518160000155602082015181600101556040820151816002015560608201518160030190805190602001906200021e92919062000545565b50608082015180516200023c91600484019160209091019062000545565b50905050601a8382815181106200024f57fe5b6020908102919091018101518254600181018455600093845292829020815162000283949190910192919091019062000545565b506001016200016a565b506040805160a081018252600d548152600e54602080830191909152600f548284015260105460608084019190915260115460808085019190915284518083018652601254815260135481850152601454818701528551918201865260165482526017549382019390935260185494810194909452601954908401526200031d926001600160e01b036200035716565b5050505050505062000dbf565b8051620003545760405162461bcd60e51b81526004016200034b9062000c33565b60405180910390fd5b50565b825160208401511180159062000371575060008360200151115b620003905760405162461bcd60e51b81526004016200034b9062000cab565b825160408401511015620003b85760405162461bcd60e51b81526004016200034b9062000a6f565b620003cd6200053860201b620023ac1760201c565b836060015111158015620003e5575060008360600151115b620004045760405162461bcd60e51b81526004016200034b9062000c74565b620004196200053860201b620023ac1760201c565b825111156200043c5760405162461bcd60e51b81526004016200034b9062000b95565b620004516200053860201b620023ac1760201c565b82602001511115620004775760405162461bcd60e51b81526004016200034b9062000aa6565b6200048c6200053860201b620023ac1760201c565b81604001511115620004b25760405162461bcd60e51b81526004016200034b9062000ce2565b826040015181602001511015620004dd5760405162461bcd60e51b81526004016200034b9062000bd6565b816040015183608001511015620005085760405162461bcd60e51b81526004016200034b9062000adb565b806060015182604001511015620005335760405162461bcd60e51b81526004016200034b9062000b38565b505050565b670de0b6b3a76400005b90565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200058857805160ff1916838001178555620005b8565b82800160010185558215620005b8579182015b82811115620005b85782518255916020019190600101906200059b565b50620005c6929150620005ca565b5090565b6200054291905b80821115620005c65760008155600101620005d1565b8051620005f48162000da9565b92915050565b600082601f8301126200060b578081fd5b8151620006226200061c8262000d56565b62000d2f565b818152915060208083019084810160005b8481101562000660576200064d888484518a01016200075a565b8452928201929082019060010162000633565b505050505092915050565b600082601f8301126200067c578081fd5b81516200068d6200061c8262000d56565b818152915060208083019084810160005b8481101562000660578151870160a080601f19838c03011215620006c157600080fd5b620006cc8162000d2f565b8583015181526040808401518783015260608085015182840152608091508185015160018060401b03808211156200070357600080fd5b620007138f8b848a01016200075a565b83860152858701519250808311156200072b57600080fd5b50506200073d8d89838801016200075a565b91830191909152508652505092820192908201906001016200069e565b600082601f8301126200076b578081fd5b81516001600160401b0381111562000781578182fd5b62000796601f8201601f191660200162000d2f565b9150808252836020828501011115620007ae57600080fd5b620007c181602084016020860162000d76565b5092915050565b600060608284031215620007da578081fd5b620007e6606062000d2f565b905081518152602082015160208201526040820151604082015292915050565b60006080828403121562000818578081fd5b62000824608062000d2f565b90508151815260208201516020820152604082015160408201526060820151606082015292915050565b600060a0828403121562000860578081fd5b6200086c60a062000d2f565b9050815181526020820151602082015260408201516040820152606082015160608201526080820151608082015292915050565b6000806000806000806000878903610340811215620008bd578384fd5b8851620008ca8162000da9565b9750610160601f198201811315620008e0578485fd5b620008eb8162000d2f565b9150620008fc8b60208c01620005e7565b82526200090d8b60408c01620005e7565b6020830152620009218b60608c01620005e7565b6040830152620009358b60808c01620005e7565b6060830152620009498b60a08c01620005e7565b60808301526200095d8b60c08c01620005e7565b60a0830152620009718b60e08c01620005e7565b60c0830152610100620009878c828d01620005e7565b60e08401526101206200099d8d828e01620005e7565b918401919091526101408b81015191840191909152908a0151908201529550620009cc896101808a016200084e565b9450620009de896102208a01620007c8565b9350620009f0896102808a0162000806565b6103008901519093506001600160401b038082111562000a0e578384fd5b62000a1c8b838c01620005fa565b93506103208a015191508082111562000a33578283fd5b5062000a428a828b016200066b565b91505092959891949750929550565b6000825162000a6581846020870162000d76565b9190910192915050565b6020808252601a908201527f4d7573742062652076616c6964206d6178206c65766572616765000000000000604082015260600190565b6020808252818101527f536c69707061676520746f6c6572616e6365206d757374206265203c31303025604082015260600190565b6020808252603c908201527f526562616c616e636520696e74657276616c206d75737420626520677265617460408201527f6572207468616e205457415020636f6f6c646f776e20706572696f6400000000606082015260800190565b6020808252603d908201527f5457415020636f6f6c646f776e206d757374206265206772656174657220746860408201527f616e20696e63656e746976697a6564205457415020636f6f6c646f776e000000606082015260800190565b60208082526021908201527f556e7574696c697a6564206c65766572616765206d757374206265203c3130306040820152602560f81b606082015260800190565b60208082526038908201527f496e63656e746976697a6564206c6576657261676520726174696f206d75737460408201527f206265203e206d6178206c6576657261676520726174696f0000000000000000606082015260800190565b60208082526021908201527f4d617820545741502074726164652073697a65206d757374206e6f74206265206040820152600360fc1b606082015260800190565b6020808252601f908201527f4d7573742062652076616c696420726563656e746572696e6720737065656400604082015260600190565b6020808252601a908201527f4d7573742062652076616c6964206d696e206c65766572616765000000000000604082015260600190565b6020808252602d908201527f496e63656e746976697a656420736c69707061676520746f6c6572616e63652060408201526c6d757374206265203c3130302560981b606082015260800190565b6040518181016001600160401b038111828210171562000d4e57600080fd5b604052919050565b60006001600160401b0382111562000d6c578081fd5b5060209081020190565b60005b8381101562000d9357818101518382015260200162000d79565b8381111562000da3576000848401525b50505050565b6001600160a01b03811681146200035457600080fd5b614f948062000dcf6000396000f3fe6080604052600436106101dc5760003560e01c80637e80c93e11610102578063cb7f579611610095578063dde5aa6911610064578063dde5aa691461056c578063e81409d31461058e578063f8bdbda8146105ae578063fdfb7091146105ce576101e3565b8063cb7f5796146104dd578063d330fd7f1461050a578063d3d72afc1461052a578063da3904801461054a576101e3565b8063aea6cc80116100d1578063aea6cc8014610471578063b8e0eeb714610491578063c1c7ff0c146104b3578063c31443bb146104c8576101e3565b80637e80c93e146103df57806389861cf91461040e578063aa31e5d11461043c578063ae2c1d5f1461045c576101e3565b80632ede58131161017a5780635a860bab116101495780635a860bab1461035d57806363f8cb201461037d5780636ad5e3e11461039f5780636db66d29146103bf576101e3565b80632ede5813146102db57806341212e9e146102fb578063481c6a751461031b57806357ff1bc81461033d576101e3565b80631997789a116101b65780631997789a1461025757806324223322146102845780632d158e7d146102a45780632ec0090a146102c6576101e3565b806304d7f3e7146101e857806307da060314610213578063095f027314610235576101e3565b366101e357005b600080fd5b3480156101f457600080fd5b506101fd6105e3565b60405161020a9190614dfe565b60405180910390f35b34801561021f57600080fd5b50610228610621565b60405161020a9190614c87565b34801561024157600080fd5b50610255610250366004613d4a565b6106ae565b005b34801561026357600080fd5b50610277610272366004613d4a565b6107c3565b60405161020a9190614d52565b34801561029057600080fd5b5061025561029f366004613d4a565b610950565b3480156102b057600080fd5b506102b9610ade565b60405161020a9190614374565b3480156102d257600080fd5b50610255610aee565b3480156102e757600080fd5b506102556102f6366004613e8d565b610bf4565b34801561030757600080fd5b50610255610316366004613d4a565b610da1565b34801561032757600080fd5b50610330610eb0565b60405161020a91906141af565b34801561034957600080fd5b50610255610358366004613d7d565b610ebf565b34801561036957600080fd5b50610255610378366004613d16565b6110da565b34801561038957600080fd5b506103926111d8565b60405161020a9190614db2565b3480156103ab57600080fd5b506102556103ba366004613d4a565b611205565b3480156103cb57600080fd5b506102556103da366004613d4a565b611321565b3480156103eb57600080fd5b506103ff6103fa366004613cd6565b61148a565b60405161020a93929190614316565b34801561041a57600080fd5b5061042e610429366004613f3d565b6116f5565b60405161020a9291906142b6565b34801561044857600080fd5b50610255610457366004613ed4565b61174f565b34801561046857600080fd5b5061042e611911565b34801561047d57600080fd5b506102b961048c366004613c35565b61193e565b34801561049d57600080fd5b506104a6611953565b60405161020a9190614e38565b3480156104bf57600080fd5b506104a6611993565b3480156104d457600080fd5b506104a6611999565b3480156104e957600080fd5b506104fd6104f8366004613f25565b6119c5565b60405161020a919061437f565b34801561051657600080fd5b50610255610525366004613e50565b611a6b565b34801561053657600080fd5b50610255610545366004613d7d565b611c16565b34801561055657600080fd5b5061055f611e8f565b60405161020a91906142a3565b34801561057857600080fd5b50610581611f67565b60405161020a9190614dd3565b34801561059a57600080fd5b506102556105a9366004613c6d565b611f9c565b3480156105ba57600080fd5b506102556105c9366004613d4a565b6121ac565b3480156105da57600080fd5b506104a66123a6565b6105eb6138c8565b506040805160a081018252600d548152600e546020820152600f5491810191909152601054606082015260115460808201525b90565b6106296138f7565b5060408051610160810182526002546001600160a01b039081168252600354811660208301526004548116928201929092526005548216606082015260065482166080820152600754821660a0820152600854821660c0820152600954821660e0820152600a54909116610100820152600b54610120820152600c5461014082015290565b3332146106d65760405162461bcd60e51b81526004016106cd9061453b565b60405180910390fd5b6106de613953565b61070f6016600201546015846040516106f79190614123565b908152602001604051809103902060020154846123b8565b905061073c816015846040516107259190614123565b90815260200160405180910390206001015461249a565b600061074f82600d6002015460006124f7565b50905061075c828261259d565b61076583612675565b600061077560166000015461268e565b90507f3ef50471c967ac74a1fec015a5fb439eefe1994f80029752c082a26c3133c9328360200151600d6002015484846040516107b59493929190614e57565b60405180910390a150505050565b6107cb613988565b6015826040516107db9190614123565b90815260200160405180910390206040518060a0016040529081600082015481526020016001820154815260200160028201548152602001600382018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108ab5780601f10610880576101008083540402835291602001916108ab565b820191906000526020600020905b81548152906001019060200180831161088e57829003601f168201915b505050918352505060048201805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815293820193929183018282801561093f5780601f106109145761010080835404028352916020019161093f565b820191906000526020600020905b81548152906001019060200180831161092257829003601f168201915b50505050508152505090505b919050565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561099f57600080fd5b505af11580156109b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109d79190613c51565b6001600160a01b0316336001600160a01b031614610a075760405162461bcd60e51b81526004016106cd906144ab565b601581604051610a179190614123565b90815260405190819003602001902054610a435760405162461bcd60e51b81526004016106cd90614c35565b601581604051610a539190614123565b90815260405190819003602001902060008082556001820181905560028201819055610a8260038301826139b7565b610a906004830160006139b7565b50610aa49050601a8263ffffffff6126d716565b7fd6acd22a732277ebc5ff0aa733e7c08652f8a2921d88558372cce63e40cfdaae81604051610ad3919061437f565b60405180910390a150565b600054600160a01b900460ff1681565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610b3d57600080fd5b505af1158015610b51573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b759190613c51565b6001600160a01b0316336001600160a01b031614610ba55760405162461bcd60e51b81526004016106cd906144ab565b601b5415610bc55760405162461bcd60e51b81526004016106cd906147d2565b60405133904780156108fc02916000818181858888f19350505050158015610bf1573d6000803e3d6000fd5b50565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610c4357600080fd5b505af1158015610c57573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c7b9190613c51565b6001600160a01b0316336001600160a01b031614610cab5760405162461bcd60e51b81526004016106cd906144ab565b601b5415610ccb5760405162461bcd60e51b81526004016106cd906147d2565b80516016819055602080830151601781905560408085015160188190556060808701516019819055835160a081018552600d548152600e5481880152600f548186015260105481840152601154608080830191909152855180850187526012548152601354818a015260145481880152865191820187529881529687019590955292850191909152830152610d6192909161285e565b6016546017546018546019546040517f26bc8aa9f7ec6c447f7831dbe144ee8e1c6ca04e62959e63e5b8002b0b4a5ce194610ad394909390929091614e57565b333214610dc05760405162461bcd60e51b81526004016106cd9061453b565b33610dca816129ee565b610de65760405162461bcd60e51b81526004016106cd9061493f565b610dee613953565b610e1d601260010154601585604051610e079190614123565b90815260405190819003602001902054856123b8565b9050610e3181600d60040154601c54612a25565b610e39612a98565b6000610e488260200151612aba565b9050600080610e578484612b3b565b91509150610e6782828589612b93565b7f6f55209924dba11af5ddabda4999b20d0ce3aa1847c56b67240ed1fc3590c1348460200151848484604051610ea09493929190614e57565b60405180910390a1505050505050565b6000546001600160a01b031681565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610f0e57600080fd5b505af1158015610f22573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f469190613c51565b6001600160a01b0316336001600160a01b031614610f765760405162461bcd60e51b81526004016106cd906144ab565b601582604051610f869190614123565b90815260405190819003602001902054610fb25760405162461bcd60e51b81526004016106cd90614c35565b610fbb81612bac565b8051604051601590610fce908590614123565b9081526020016040518091039020600001819055508060400151601583604051610ff89190614123565b90815260200160405180910390206002018190555080606001516015836040516110229190614123565b908152602001604051809103902060030190805190602001906110469291906139fb565b50806080015160158360405161105c9190614123565b908152602001604051809103902060040190805190602001906110809291906139fb565b507f53fdf113d6ccd58f1d643ab8402360c17a9d114d055d36c8766e84dfec76a93482826000015183602001518460400151856060015186608001516040516110ce96959493929190614392565b60405180910390a15050565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561112957600080fd5b505af115801561113d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111619190613c51565b6001600160a01b0316336001600160a01b0316146111915760405162461bcd60e51b81526004016106cd906144ab565b6000805460ff60a01b1916600160a01b83151590810291909117825560405190917f92f8cd47e301bde05ff0abd73cc198632f3ac64fa443a1afc3e47745b3ea1acb91a250565b6111e0613a75565b5060408051606081018252601254815260135460208201526014549181019190915290565b3332146112245760405162461bcd60e51b81526004016106cd9061453b565b3361122e816129ee565b61124a5760405162461bcd60e51b81526004016106cd9061493f565b611252613953565b61126b601260010154601585604051610e079190614123565b905061129e816012600201546015866040516112879190614123565b908152602001604051809103902060010154612a25565b6112a6612bca565b6000806112b68360200151612bec565b6112cc576112c683601b54612b3b565b90925090505b6112d7828287612c23565b7fbba909c59ebdb6de1c7e9f168dae0e8934434ce708dda9f312d6f3a1d1a502598360200151601b5484846040516113129493929190614e57565b60405180910390a15050505050565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561137057600080fd5b505af1158015611384573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113a89190613c51565b6001600160a01b0316336001600160a01b0316146113d85760405162461bcd60e51b81526004016106cd906144ab565b6113e0613953565b61140f6012600101546015846040516113f99190614123565b90815260405190819003602001902054846123b8565b9050600061141b6123ac565b905060008061142c848460006124f7565b915091508181111561144757611442848361259d565b611451565b6114518482612c3e565b7fe7945163803ad02726587e34ca2c4a76ec8dbc6d0b3ddb72d7f93d794e59075984602001518484846040516113129493929190614e57565b606060008060008061149a611999565b6017549091506000908211156114b75750600f54915060016114d5565b601b54156114c957601b5492506114d5565b6114d282612aba565b92505b6114dd613a96565b6114e5612d2a565b90508284118867ffffffffffffffff8111801561150157600080fd5b5060405190808252806020026020018201604052801561152b578160200160208202803683370190505b50975060005b8981101561169e57611541613953565b6040518060a001604052808581526020018781526020018661156557601354611569565b6018545b8152602001866115b65760158e8e8681811061158157fe5b90506020028101906115939190614e95565b6040516115a1929190614113565b908152604051908190036020019020546115f7565b60158e8e868181106115c457fe5b90506020028101906115d69190614e95565b6040516115e4929190614113565b9081526020016040518091039020600201545b81526020018d8d8581811061160857fe5b905060200281019061161a9190614e95565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250929350915061166190508289866124f7565b5090508361166f578061167d565b61167d81836000015161304a565b8b848151811061168957fe5b60209081029190910101525050600101611531565b50806116b5576009546001600160a01b03166116c2565b600a546001600160a01b03165b9650806116da57600a546001600160a01b03166116e7565b6009546001600160a01b03165b955050505050509250925092565b606080600d60010154841115801561170f5750600f548310155b61172b5760405162461bcd60e51b81526004016106cd906143db565b6000611735611999565b9050611742818686613072565b92509250505b9250929050565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561179e57600080fd5b505af11580156117b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117d69190613c51565b6001600160a01b0316336001600160a01b0316146118065760405162461bcd60e51b81526004016106cd906144ab565b601b54156118265760405162461bcd60e51b81526004016106cd906147d2565b8051600d819055602080830151600e819055604080850151600f81905560608087015160108190556080808901516011819055855160a0810187529889528888019690965287850193909352868201528582019390935281518084018352601254815260135481860152601454818401528251918201835260165482526017549482019490945260185491810191909152601954918101919091526118cc92919061285e565b600d54600e54600f546010546011546040517f69b7cb6b3922c6a0381263018e3350f753caa251b7426259cc918065dc1c45bd95610ad3959094909390929091614e72565b606080600061191e611999565b905061193581600d60010154600d60020154613072565b92509250509091565b60016020526000908152604090205460ff1681565b60008061195e611999565b6017549091508110611985576016544711611979574761197d565b6016545b91505061061e565b600091505061061e565b5090565b601c5481565b60006119a3613a96565b6119ab612d2a565b90506119bf81604001518260600151613316565b91505090565b601a81815481106119d257fe5b600091825260209182902001805460408051601f6002600019610100600187161502019094169390930492830185900485028101850190915281815293509091830182828015611a635780601f10611a3857610100808354040283529160200191611a63565b820191906000526020600020905b815481529060010190602001808311611a4657829003601f168201915b505050505081565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b158015611aba57600080fd5b505af1158015611ace573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611af29190613c51565b6001600160a01b0316336001600160a01b031614611b225760405162461bcd60e51b81526004016106cd906144ab565b601b5415611b425760405162461bcd60e51b81526004016106cd906147d2565b8051601281905560208083015160138190556040808501516014819055815160a081018352600d548152600e5481860152600f5481840152601054606080830191909152601154608080840191909152845180830186529788528787019590955286840192909252825193840183526016548452601754948401949094526018549183019190915260195490820152611bdb929061285e565b6012546014546013546040517fb69986d7b36a79e7024b5654aa4006fbaeb1c553f3a0a8c79990b702fffd5cc693610ad39390929091614e41565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b158015611c6557600080fd5b505af1158015611c79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c9d9190613c51565b6001600160a01b0316336001600160a01b031614611ccd5760405162461bcd60e51b81526004016106cd906144ab565b601582604051611cdd9190614123565b9081526040519081900360200190205415611d0a5760405162461bcd60e51b81526004016106cd906149ee565b611d1381612bac565b8051604051601590611d26908590614123565b9081526020016040518091039020600001819055508060400151601583604051611d509190614123565b9081526020016040518091039020600201819055508060600151601583604051611d7a9190614123565b90815260200160405180910390206003019080519060200190611d9e9291906139fb565b508060800151601583604051611db49190614123565b90815260200160405180910390206004019080519060200190611dd89291906139fb565b506000601583604051611deb9190614123565b90815260405160209181900382019020600190810192909255601a805492830181556000528351611e41927f057c384a7d1c54f3a1b2e5e67b2617b8224fdfd1ea7234eea573a6ff665ff63e01918501906139fb565b507fd2df566766a30e4280d446b04d14012600df99b449ec4c4afe9201ff36047e5382826000015183602001518460400151856060015186608001516040516110ce96959493929190614392565b6060601a805480602002602001604051908101604052809291908181526020016000905b82821015611f5e5760008481526020908190208301805460408051601f6002600019610100600187161502019094169390930492830185900485028101850190915281815292830182828015611f4a5780601f10611f1f57610100808354040283529160200191611f4a565b820191906000526020600020905b815481529060010190602001808311611f2d57829003601f168201915b505050505081526020019060010190611eb3565b50505050905090565b611f6f613ad3565b50604080516080810182526016548152601754602082015260185491810191909152601954606082015290565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b158015611feb57600080fd5b505af1158015611fff573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120239190613c51565b6001600160a01b0316336001600160a01b0316146120535760405162461bcd60e51b81526004016106cd906144ab565b8281146120725760405162461bcd60e51b81526004016106cd906144d5565b8261208f5760405162461bcd60e51b81526004016106cd90614a25565b6120cb84848080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525061333892505050565b156120e85760405162461bcd60e51b81526004016106cd906148e0565b60005b838110156121a557600085858381811061210157fe5b90506020020160208101906121169190613c35565b9050600084848481811061212657fe5b905060200201602081019061213b9190613d16565b6001600160a01b03831660008181526001602052604090819020805460ff191684151517905551919250907fbbf89f81f443eef9b97bfd2b7e260c0f575050d4094a0027dcf5d3623d9ef3ad90612193908490614374565b60405180910390a250506001016120eb565b5050505050565b6000809054906101000a90046001600160a01b03166001600160a01b031663570ca7356040518163ffffffff1660e01b8152600401602060405180830381600087803b1580156121fb57600080fd5b505af115801561220f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122339190613c51565b6001600160a01b0316336001600160a01b0316146122635760405162461bcd60e51b81526004016106cd906144ab565b61226b613a96565b612273612d2a565b905060008160c00151116122995760405162461bcd60e51b81526004016106cd90614b13565b80516122b75760405162461bcd60e51b81526004016106cd90614adc565b6020810151156122d95760405162461bcd60e51b81526004016106cd90614917565b6122e1613953565b6040518060a001604052808381526020016122fa6123ac565b8152602001601260010154815260200160158560405161231a9190614123565b908152602001604051809103902060000154815260200184815250905060008061234b83600d6000015460016124f7565b9150915061235983836133e7565b61236a8282600d6000015488612b93565b6020830151600d546040517fac3b8ab89a07bbb8dd4670bcfe29ef7d4eccea237222f49f997884d89947d53d9261131292909186908690614e57565b601b5481565b670de0b6b3a764000090565b6123c0613953565b600083116123e05760405162461bcd60e51b81526004016106cd90614b4a565b6123e8613a96565b6123f0612d2a565b905060008160c00151116124165760405162461bcd60e51b81526004016106cd90614b13565b80516124345760405162461bcd60e51b81526004016106cd90614adc565b60008160200151116124585760405162461bcd60e51b81526004016106cd906149b7565b600061246c82604001518360600151613316565b6040805160a08101825293845260208401919091528201959095526060810193909352506080820152919050565b601754602083015110156124c05760405162461bcd60e51b81526004016106cd90614a5c565b60195442906124d690839063ffffffff6134d716565b106124f35760405162461bcd60e51b81526004016106cd90614b7a565b5050565b60008060008361251b576020860151612516908663ffffffff6134fc16565b612531565b602086015161253190869063ffffffff6134fc16565b8651516020880151919250600091612561919061255590859063ffffffff61352416565b9063ffffffff61354e16565b9050600061257388600001518761356c565b9050600061258e61258483856136d2565b8a606001516136d2565b99929850919650505050505050565b815160c001516000906125b790839063ffffffff61352416565b905060006125ce82856040015186600001516136e8565b600254600954600a5460808801516040519495506060946001600160a01b039485169493841693909216918791879160159061260b908390614123565b9081526020016040518091039020600401604051602401612632979695949392919061421d565b60408051601f198184030181529190526020810180516001600160e01b03166313f74a0f60e21b1790526003549091506121a5906001600160a01b031682613720565b61267e81613780565b601b5415610bf1576000601b5550565b60008047831061269e57476126a0565b825b604051909150339082156108fc029083906000818181858888f193505050501580156126d0573d6000803e3d6000fd5b5092915050565b6000806127b384805480602002602001604051908101604052809291908181526020016000905b828210156127a95760008481526020908190208301805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156127955780601f1061276a57610100808354040283529160200191612795565b820191906000526020600020905b81548152906001019060200180831161277857829003601f168201915b5050505050815260200190600101906126fe565b50505050846137ad565b91509150806127d45760405162461bcd60e51b81526004016106cd90614871565b83546000190182811461282e578481815481106127ed57fe5b9060005260206000200185848154811061280357fe5b90600052602060002001908054600181600116156101000203166002900461282c929190613afb565b505b8480548061283857fe5b60019003818190600052602060002001600061285491906139b7565b9055505b50505050565b8251602084015111801590612877575060008360200151115b6128935760405162461bcd60e51b81526004016106cd90614bb1565b8251604084015110156128b85760405162461bcd60e51b81526004016106cd90614504565b6128c06123ac565b8360600151111580156128d7575060008360600151115b6128f35760405162461bcd60e51b81526004016106cd90614aa5565b6128fb6123ac565b8251111561291b5760405162461bcd60e51b81526004016106cd90614731565b6129236123ac565b826020015111156129465760405162461bcd60e51b81526004016106cd90614572565b61294e6123ac565b816040015111156129715760405162461bcd60e51b81526004016106cd90614be8565b8260400151816020015110156129995760405162461bcd60e51b81526004016106cd90614814565b8160400151836080015110156129c15760405162461bcd60e51b81526004016106cd906145de565b8060600151826040015110156129e95760405162461bcd60e51b81526004016106cd9061469d565b505050565b60008054600160a01b900460ff1680612a1f57506001600160a01b03821660009081526001602052604090205460ff165b92915050565b601754602084015110612a4a5760405162461bcd60e51b81526004016106cd90614412565b81612a5b428363ffffffff6134fc16565b1180612a6c5750600f546020840151115b80612a7c5750600e546020840151105b6129e95760405162461bcd60e51b81526004016106cd9061445b565b601b5415612ab85760405162461bcd60e51b81526004016106cd90614772565b565b601054600d546000918291612ad49163ffffffff61354e16565b90506000612af984612555600d60030154612aed6123ac565b9063ffffffff6134fc16565b90506000612b0d838363ffffffff6134d716565b90506000612b2082600d600201546136d2565b9050612b31600d600101548261380c565b9695505050505050565b6000806000808560200151851015612b6d57612b59868660006124f7565b9092509050612b68868361259d565b612b88565b612b79868660016124f7565b9092509050612b8886836133e7565b909590945092505050565b612b9c81613780565b828410156128585750601b555050565b8051610bf15760405162461bcd60e51b81526004016106cd90614976565b6000601b5411612ab85760405162461bcd60e51b81526004016106cd9061463b565b6000600d60000154601b54108015612c065750601b548210155b80612a1f5750600d54601b54118015612a1f575050601b54101590565b612c2c81613780565b818314156129e9576000601b55505050565b6000612c85836000015160c00151612c79612c6c601260010154612c606123ac565b9063ffffffff6134d716565b859063ffffffff61354e16565b9063ffffffff61352416565b600254600954600a5460808701516040519495506060946001600160a01b03948516949384169390921691869190601590612cc1908390614123565b9081526020016040518091039020600401604051602401612ce7969594939291906141c3565b60408051601f198184030181529190526020810180516001600160e01b031663d4fd27eb60e01b179052600354909150612858906001600160a01b031682613720565b612d32613a96565b612d3a613a96565b600554604080516350d25bcd60e01b815290516000926001600160a01b0316916350d25bcd916004808301926020929190829003018186803b158015612d7f57600080fd5b505afa158015612d93573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612db79190613d32565b9050612dda600260090154600a0a612dce8361381c565b9063ffffffff61383e16565b6080830152600654604080516350d25bcd60e01b815290516000926001600160a01b0316916350d25bcd916004828101926020929190829003018186803b158015612e2457600080fd5b505afa158015612e38573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e5c9190613d32565b9050612e736002600a0154600a0a612dce8361381c565b60a08401526007546002546040516370a0823160e01b81526001600160a01b03928316926370a0823192612eac929116906004016141af565b60206040518083038186803b158015612ec457600080fd5b505afa158015612ed8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612efc9190613d32565b83526008546002546040516370a0823160e01b81526001600160a01b03928316926370a0823192612f32929116906004016141af565b60206040518083038186803b158015612f4a57600080fd5b505afa158015612f5e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f829190613d32565b602084015282516080840151612f9d9163ffffffff61354e16565b6040840152602083015160a0840151612fbb9163ffffffff61354e16565b6060840152600254604080516318160ddd60e01b815290516001600160a01b03909216916318160ddd91600480820192602092909190829003018186803b15801561300557600080fd5b505afa158015613019573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061303d9190613d32565b60c0840152509091505090565b600061306b8260a00151612c7984608001518661354e90919063ffffffff16565b9392505050565b6060806060601a8054905067ffffffffffffffff8111801561309357600080fd5b506040519080825280602002602001820160405280156130bd578160200160208202803683370190505b50905060005b601a548110156132335760008282815181106130db57fe5b602002602001019060038111156130ee57fe5b908160038111156130fb57fe5b905250601754871061319357426131566016600301546015601a858154811061312057fe5b90600052602060002001604051613137919061413f565b908152604051908190036020019020600101549063ffffffff6134d716565b101561318e57600382828151811061316a57fe5b6020026020010190600381111561317d57fe5b9081600381111561318a57fe5b9052505b61322b565b601b54156131c857426131b46012600201546015601a858154811061312057fe5b101561318e57600282828151811061316a57fe5b601154601c546131df90429063ffffffff6134fc16565b11806131ea57508487115b806131f457508587105b1561322b57600182828151811061320757fe5b6020026020010190600381111561321a57fe5b9081600381111561322757fe5b9052505b6001016130c3565b50601a8181805480602002602001604051908101604052809291908181526020016000905b828210156133035760008481526020908190208301805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156132ef5780601f106132c4576101008083540402835291602001916132ef565b820191906000526020600020905b8154815290600101906020018083116132d257829003601f168201915b505050505081526020019060010190613258565b5050505091509250925050935093915050565b600061306b61332b848463ffffffff6134fc16565b849063ffffffff61352416565b60008082511161335a5760405162461bcd60e51b81526004016106cd90614c63565b60005b60018351038110156133de57600083828151811061337757fe5b6020026020010151905060008260010190505b84518110156133d45784818151811061339f57fe5b60200260200101516001600160a01b0316826001600160a01b031614156133cc576001935050505061094b565b60010161338a565b505060010161335d565b50600092915050565b815160c0015160009061340190839063ffffffff61352416565b9050600061341382856000015161304a565b90506000613425838660400151613878565b600254600a5460095460808901516040519495506060946001600160a01b0394851694938416939092169187918791601590613462908390614123565b9081526020016040518091039020600301604051602401613489979695949392919061421d565b60408051601f198184030181529190526020810180516001600160e01b0316600162114b6960e21b03191790526003549091506134cf906001600160a01b031682613720565b505050505050565b60008282018381101561306b5760405162461bcd60e51b81526004016106cd906145a7565b60008282111561351e5760405162461bcd60e51b81526004016106cd90614666565b50900390565b600061306b8261354285670de0b6b3a764000063ffffffff61383e16565b9063ffffffff61389616565b600061306b670de0b6b3a7640000613542858563ffffffff61383e16565b60048054600954604051633e15014160e01b8152600093849384936001600160a01b0391821693633e150141936135a79390921691016141af565b6101406040518083038186803b1580156135c057600080fd5b505afa1580156135d4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135f89190613f5e565b505050505050509250925050831561367557600061364a613620601260000154612aed6123ac565b61255561363986655af3107a400063ffffffff61383e16565b60408a01519063ffffffff61354e16565b905061366b8660800151612c798860600151846134fc90919063ffffffff16565b9350505050612a1f565b60006136a461368b601260000154612aed6123ac565b61255561363985655af3107a400063ffffffff61383e16565b905061366b81612c796136c48960600151856134fc90919063ffffffff16565b89519063ffffffff61354e16565b60008183106136e1578161306b565b5090919050565b60006137186136f984612aed6123ac565b6125558460a00151612c7986608001518961354e90919063ffffffff16565b949350505050565b600054604051634cf4f63b60e01b81526001600160a01b0390911690634cf4f63b90613752908590859060040161427f565b600060405180830381600087803b15801561376c57600080fd5b505af11580156134cf573d6000803e3d6000fd5b42601c819055604051601590613797908490614123565b9081526040519081900360200190206001015550565b81516000908190815b818110156137fc5784805190602001208682815181106137d257fe5b60200260200101518051906020012014156137f4579250600191506117489050565b6001016137b6565b5060001995600095509350505050565b6000818310156136e1578161306b565b60008082121561198f5760405162461bcd60e51b81526004016106cd9061479d565b60008261384d57506000612a1f565b8282028284828161385a57fe5b041461306b5760405162461bcd60e51b81526004016106cd9061489f565b600061306b61388983612aed6123ac565b849063ffffffff61354e16565b60008082116138b75760405162461bcd60e51b81526004016106cd906146fa565b8183816138c057fe5b049392505050565b6040518060a0016040528060008152602001600081526020016000815260200160008152602001600081525090565b6040805161016081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810182905261014081019190915290565b6040518060a00160405280613966613a96565b8152602001600081526020016000815260200160008152602001606081525090565b6040518060a0016040528060008152602001600081526020016000815260200160608152602001606081525090565b50805460018160011615610100020316600290046000825580601f106139dd5750610bf1565b601f016020900490600052602060002090810190610bf19190613b70565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10613a3c57805160ff1916838001178555613a69565b82800160010185558215613a69579182015b82811115613a69578251825591602001919060010190613a4e565b5061198f929150613b70565b60405180606001604052806000815260200160008152602001600081525090565b6040518060e00160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6040518060800160405280600081526020016000815260200160008152602001600081525090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10613b345780548555613a69565b82800160010185558215613a6957600052602060002091601f016020900482015b82811115613a69578254825591600101919060010190613b55565b61061e91905b8082111561198f5760008155600101613b76565b60008083601f840112613b9b578182fd5b50813567ffffffffffffffff811115613bb2578182fd5b602083019150836020808302850101111561174857600080fd5b600082601f830112613bdc578081fd5b813567ffffffffffffffff811115613bf2578182fd5b613c05601f8201601f1916602001614edc565b9150808252836020828501011115613c1c57600080fd5b8060208401602084013760009082016020015292915050565b600060208284031215613c46578081fd5b813561306b81614f3b565b600060208284031215613c62578081fd5b815161306b81614f3b565b60008060008060408587031215613c82578283fd5b843567ffffffffffffffff80821115613c99578485fd5b613ca588838901613b8a565b90965094506020870135915080821115613cbd578384fd5b50613cca87828801613b8a565b95989497509550505050565b60008060208385031215613ce8578182fd5b823567ffffffffffffffff811115613cfe578283fd5b613d0a85828601613b8a565b90969095509350505050565b600060208284031215613d27578081fd5b813561306b81614f50565b600060208284031215613d43578081fd5b5051919050565b600060208284031215613d5b578081fd5b813567ffffffffffffffff811115613d71578182fd5b61371884828501613bcc565b60008060408385031215613d8f578182fd5b823567ffffffffffffffff80821115613da6578384fd5b613db286838701613bcc565b93506020850135915080821115613dc7578283fd5b81850160a08188031215613dd9578384fd5b613de360a0614edc565b9250803583526020810135602084015260408101356040840152606081013582811115613e0e578485fd5b613e1a88828401613bcc565b606085015250608081013582811115613e31578485fd5b613e3d88828401613bcc565b6080850152505050809150509250929050565b600060608284031215613e61578081fd5b613e6b6060614edc565b8235815260208301356020820152604083013560408201528091505092915050565b600060808284031215613e9e578081fd5b613ea86080614edc565b823581526020830135602082015260408301356040820152606083013560608201528091505092915050565b600060a08284031215613ee5578081fd5b613eef60a0614edc565b82358152602083013560208201526040830135604082015260608301356060820152608083013560808201528091505092915050565b600060208284031215613f36578081fd5b5035919050565b60008060408385031215613f4f578182fd5b50508035926020909101359150565b6000806000806000806000806000806101408b8d031215613f7d578788fd5b8a51995060208b0151985060408b0151975060608b0151965060808b0151955060a08b0151613fab81614f50565b60c08c0151909550613fbc81614f50565b60e08c0151909450613fcd81614f50565b6101008c0151909350613fdf81614f50565b6101208c0151909250613ff181614f50565b809150509295989b9194979a5092959850565b6001600160a01b03169052565b6000815180845260208085018081965082840281019150828601855b85811015614057578284038952614045848351614064565b9885019893509084019060010161402d565b5091979650505050505050565b6000815180845261407c816020860160208601614f0f565b601f01601f19169290920160200192915050565b600081546001808216600081146140ae57600181146140cc5761410a565b60028304607f16865260ff198316602087015260408601935061410a565b600283048087526140dc86614f03565b60005b828110156141005781546020828b01015284820191506020810190506140df565b8801602001955050505b50505092915050565b6000828483379101908152919050565b60008251614135818460208701614f0f565b9190910192915050565b600080835460018082166000811461415e5760018114614175576141a4565b60ff198316865260028304607f16860193506141a4565b600283048786526020808720875b8381101561419c5781548a820152908501908201614183565b505050860193505b509195945050505050565b6001600160a01b0391909116815260200190565b6001600160a01b0387811682528681166020830152851660408201526060810184905260c0608082018190526000906141fe90830185614064565b82810360a08401526142108185614090565b9998505050505050505050565b6001600160a01b038881168252878116602083015286166040820152606081018590526080810184905260e060a0820181905260009061425f90830185614064565b82810360c08401526142718185614090565b9a9950505050505050505050565b6001600160a01b038316815260406020820181905260009061371890830184614064565b60006020825261306b6020830184614011565b6000604082526142c96040830185614011565b828103602084810191909152845180835285820192820190845b81811015614309578451600481106142f757fe5b835293830193918301916001016142e3565b5090979650505050505050565b606080825284519082018190526000906020906080840190828801845b8281101561434f57815184529284019290840190600101614333565b5050506001600160a01b03958616918401919091529290931660409091015292915050565b901515815260200190565b60006020825261306b6020830184614064565b600060c082526143a560c0830189614064565b87602084015286604084015285606084015282810360808401526143c98186614064565b83810360a08501526142718186614064565b6020808252601b908201527f437573746f6d20626f756e6473206d7573742062652076616c69640000000000604082015260600190565b60208082526029908201527f4d7573742062652062656c6f7720696e63656e746976697a6564206c6576657260408201526861676520726174696f60b81b606082015260800190565b60208082526030908201527f436f6f6c646f776e206e6f7420656c6170736564206f72206e6f742076616c6960408201526f64206c6576657261676520726174696f60801b606082015260800190565b60208082526010908201526f26bab9ba1031329037b832b930ba37b960811b604082015260600190565b602080825260159082015274082e4e4c2f240d8cadccee8d040dad2e6dac2e8c6d605b1b604082015260600190565b6020808252601a908201527f4d7573742062652076616c6964206d6178206c65766572616765000000000000604082015260600190565b6020808252601a908201527f43616c6c6572206d75737420626520454f412041646472657373000000000000604082015260600190565b6020808252818101527f536c69707061676520746f6c6572616e6365206d757374206265203c31303025604082015260600190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252603c908201527f526562616c616e636520696e74657276616c206d75737420626520677265617460408201527f6572207468616e205457415020636f6f6c646f776e20706572696f6400000000606082015260800190565b6020808252601190820152704e6f7420696e205457415020737461746560781b604082015260600190565b6020808252601e908201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604082015260600190565b6020808252603d908201527f5457415020636f6f6c646f776e206d757374206265206772656174657220746860408201527f616e20696e63656e746976697a6564205457415020636f6f6c646f776e000000606082015260800190565b6020808252601a908201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604082015260600190565b60208082526021908201527f556e7574696c697a6564206c65766572616765206d757374206265203c3130306040820152602560f81b606082015260800190565b6020808252601190820152704d7573742063616c6c206974657261746560781b604082015260600190565b6020808252818101527f53616665436173743a2076616c7565206d75737420626520706f736974697665604082015260600190565b60208082526022908201527f526562616c616e63652069732063757272656e746c7920696e2070726f677265604082015261737360f01b606082015260800190565b60208082526038908201527f496e63656e746976697a6564206c6576657261676520726174696f206d75737460408201527f206265203e206d6178206c6576657261676520726174696f0000000000000000606082015260800190565b60208082526014908201527329ba3934b733903737ba1034b71030b93930bc9760611b604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b60208082526018908201527f43616e6e6f74206475706c69636174652063616c6c6572730000000000000000604082015260600190565b6020808252600e908201526d044656274206d75737420626520360941b604082015260600190565b6020808252601d908201527f41646472657373206e6f74207065726d697474656420746f2063616c6c000000604082015260600190565b60208082526021908201527f4d617820545741502074726164652073697a65206d757374206e6f74206265206040820152600360fc1b606082015260800190565b60208082526019908201527f426f72726f772062616c616e6365206d75737420657869737400000000000000604082015260600190565b60208082526018908201527f45786368616e676520616c726561647920656e61626c65640000000000000000604082015260600190565b60208082526018908201527f4172726179206c656e677468206d757374206265203e20300000000000000000604082015260600190565b60208082526029908201527f4d7573742062652061626f766520696e63656e746976697a6564206c6576657260408201526861676520726174696f60b81b606082015260800190565b6020808252601f908201527f4d7573742062652076616c696420726563656e746572696e6720737065656400604082015260600190565b6020808252601e908201527f436f6c6c61746572616c2062616c616e6365206d757374206265203e20300000604082015260600190565b6020808252601d908201527f536574546f6b656e206d7573742068617665203e203020737570706c79000000604082015260600190565b6020808252601690820152754d7573742062652076616c69642065786368616e676560501b604082015260600190565b6020808252601f908201527f5457415020636f6f6c646f776e206d757374206861766520656c617073656400604082015260600190565b6020808252601a908201527f4d7573742062652076616c6964206d696e206c65766572616765000000000000604082015260600190565b6020808252602d908201527f496e63656e746976697a656420736c69707061676520746f6c6572616e63652060408201526c6d757374206265203c3130302560981b606082015260800190565b602080825260149082015273115e18da185b99d9481b9bdd08195b98589b195960621b604082015260600190565b6020808252600a90820152694120697320656d70747960b01b604082015260600190565b600061016082019050614c9b828451614004565b6020830151614cad6020840182614004565b506040830151614cc06040840182614004565b506060830151614cd36060840182614004565b506080830151614ce66080840182614004565b5060a0830151614cf960a0840182614004565b5060c0830151614d0c60c0840182614004565b5060e0830151614d1f60e0840182614004565b5061010080840151614d3382850182614004565b5050610120838101519083015261014092830151929091019190915290565b600060208252825160208301526020830151604083015260408301516060830152606083015160a06080840152614d8c60c0840182614064565b6080850151848203601f190160a08601529150614da98183614064565b95945050505050565b81518152602080830151908201526040918201519181019190915260600190565b8151815260208083015190820152604080830151908201526060918201519181019190915260800190565b600060a082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015292915050565b90815260200190565b9283526020830191909152604082015260600190565b93845260208401929092526040830152606082015260800190565b948552602085019390935260408401919091526060830152608082015260a00190565b6000808335601e19843603018112614eab578283fd5b8084018035925067ffffffffffffffff831115614ec6578384fd5b6020019250503681900382131561174857600080fd5b60405181810167ffffffffffffffff81118282101715614efb57600080fd5b604052919050565b60009081526020902090565b60005b83811015614f2a578181015183820152602001614f12565b838111156128585750506000910152565b6001600160a01b0381168114610bf157600080fd5b8015158114610bf157600080fdfea26469706673582212200b18b1fe68126c665d421340bbe1362466ec51c29d5c0e628a0ca862557ec36664736f6c634300060a003300000000000000000000000028d1b4f13ba91d0e8510ef291838b9046a8645fc000000000000000000000000bef26aa15c6e24b73478917d0e4188a2370c735c000000000000000000000000e31c6a62d0cfad81b07b367b483fd9af8185a5300000000000000000000000007551b5d2763519d4e37e8b81929d336de671d46d000000000000000000000000f9680d99d6c9589e2a93a78a04a279e509205945000000000000000000000000fe4a8cc5b5b2366c1b58bea3858e81843581b2f700000000000000000000000028424507fefb6f7f8e9d3860f56504e4e5f5f390000000000000000000000000248960a9d75edfa3de94f7193eae3161eb349a120000000000000000000000007ceb23fd6bc0add59e62ac25578270cff1b9f6190000000000000000000000002791bca1f2de4661ed88a30c99a7a9449aa84174000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000001bc16d674ec8000000000000000000000000000000000000000000000000000017979cfe362a00000000000000000000000000000000000000000000000000001feb3dd0676600000000000000000000000000000000000000000000000000000058d15e176280000000000000000000000000000000000000000000000000000000000000003840000000000000000000000000000000000000000000000000002386f26fc1000000000000000000000000000000000000000000000000000000470de4df820000000000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022b1c8c1227a000000000000000000000000000000000000000000000000000000b1a2bc2ec50000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000003400000000000000000000000000000000000000000000000000000000000000420000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000001a414d4d53706c697474657245786368616e676541646170746572000000000000000000000000000000000000000000000000000000000000000000000000001853757368697377617045786368616e6765416461707465720000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000002b5e3af16b1880000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000821ab0d441498000000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002b5e3af16b1880000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000821ab0d441498000000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading
Loading
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.