ETH Price: $3,106.59 (+0.43%)
Gas: 3 Gwei

Transaction Decoder

Block:
16535691 at Feb-01-2023 06:15:23 PM +UTC
Transaction Fee:
0.0014884084492776 ETH $4.62
Gas Used:
70,176 Gas / 21.209650725 Gwei

Account State Difference:

  Address   Before After State Difference Code
(beaverbuild)
78.934424684570031136 Eth78.934494860570031136 Eth0.000070176
0xB5c46131...43945891e
4.149016625062209656 Eth
Nonce: 1926
4.147528216612932056 Eth
Nonce: 1927
0.0014884084492776

Execution Trace

FraxlendPair.repayAsset( _shares=31765679651849340912759, _borrower=0xB5c46131B4d8d13e4c0E476B9A2Ea5b43945891e ) => ( _amountToRepay=3963877391197344453575983046348115674221700746820753546331534351508065746944 )
  • VariableInterestRate.getNewRate( _deltaTime=1524, _utilization=87841, _oldFullUtilizationInterest=7318720626 ) => ( _newRatePerSec=1747125560, _newFullUtilizationInterest=7321036081 )
  • FRAXStablecoin.transferFrom( sender=0xB5c46131B4d8d13e4c0E476B9A2Ea5b43945891e, recipient=0x21E354Da5D929A4da55428F6bfd71eD9Ffd5001F, amount=31952442809585840987233 )
    File 1 of 3: FraxlendPair
    // SPDX-License-Identifier: ISC
    pragma solidity ^0.8.17;
    // ====================================================================
    // |     ______                   _______                             |
    // |    / _____________ __  __   / ____(_____  ____ _____  ________   |
    // |   / /_  / ___/ __ `| |/_/  / /_  / / __ \\/ __ `/ __ \\/ ___/ _ \\  |
    // |  / __/ / /  / /_/ _>  <   / __/ / / / / / /_/ / / / / /__/  __/  |
    // | /_/   /_/   \\__,_/_/|_|  /_/   /_/_/ /_/\\__,_/_/ /_/\\___/\\___/   |
    // |                                                                  |
    // ====================================================================
    // ========================== FraxlendPair ============================
    // ====================================================================
    // Frax Finance: https://github.com/FraxFinance
    // Primary Author
    // Drake Evans: https://github.com/DrakeEvans
    // Reviewers
    // Dennis: https://github.com/denett
    // Sam Kazemian: https://github.com/samkazemian
    // Travis Moore: https://github.com/FortisFortuna
    // Jack Corddry: https://github.com/corddry
    // Rich Gee: https://github.com/zer0blockchain
    // ====================================================================
    import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
    import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
    import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
    import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
    import "./FraxlendPairConstants.sol";
    import "./FraxlendPairCore.sol";
    import "./libraries/VaultAccount.sol";
    import "./libraries/SafeERC20.sol";
    import "./interfaces/IERC4626.sol";
    import "./interfaces/IFraxlendWhitelist.sol";
    import "./interfaces/IRateCalculator.sol";
    import "./interfaces/ISwapper.sol";
    contract FraxlendPair is IERC20Metadata, FraxlendPairCore {
        using VaultAccountingLibrary for VaultAccount;
        using SafeERC20 for IERC20;
        constructor(bytes memory _configData, bytes memory _immutables, bytes memory _customConfigData)
            FraxlendPairCore(_configData, _immutables, _customConfigData)
            ERC20("", "")
            Ownable()
            Pausable()
        {}
        // ============================================================================================
        // ERC20 Metadata
        // ============================================================================================
        function name() public view override(ERC20, IERC20Metadata) returns (string memory) {
            return nameOfContract;
        }
        function symbol() public view override(ERC20, IERC20Metadata) returns (string memory) {
            return symbolOfContract;
        }
        function decimals() public view override(ERC20, IERC20Metadata) returns (uint8) {
            return decimalsOfContract;
        }
        // totalSupply for fToken ERC20 compatibility
        function totalSupply() public view override(ERC20, IERC20) returns (uint256) {
            return totalAsset.shares;
        }
        // ============================================================================================
        // Functions: Helpers
        // ============================================================================================
        function asset() external view returns (address) {
            return address(assetContract);
        }
        function getConstants()
            external
            pure
            returns (
                uint256 _LTV_PRECISION,
                uint256 _LIQ_PRECISION,
                uint256 _UTIL_PREC,
                uint256 _FEE_PRECISION,
                uint256 _EXCHANGE_PRECISION,
                uint64 _DEFAULT_INT,
                uint16 _DEFAULT_PROTOCOL_FEE,
                uint256 _MAX_PROTOCOL_FEE
            )
        {
            _LTV_PRECISION = LTV_PRECISION;
            _LIQ_PRECISION = LIQ_PRECISION;
            _UTIL_PREC = UTIL_PREC;
            _FEE_PRECISION = FEE_PRECISION;
            _EXCHANGE_PRECISION = EXCHANGE_PRECISION;
            _DEFAULT_INT = DEFAULT_INT;
            _DEFAULT_PROTOCOL_FEE = DEFAULT_PROTOCOL_FEE;
            _MAX_PROTOCOL_FEE = MAX_PROTOCOL_FEE;
        }
        /// @notice The ```getImmutableAddressBool``` function gets all the address and bool configs
        /// @return _assetContract Address of asset
        /// @return _collateralContract Address of collateral
        /// @return _oracleMultiply Address of oracle numerator
        /// @return _oracleDivide Address of oracle denominator
        /// @return _rateContract Address of rate contract
        /// @return _DEPLOYER_CONTRACT Address of deployer contract
        /// @return _COMPTROLLER_ADDRESS Address of comptroller
        /// @return _FRAXLEND_WHITELIST Address of whitelist
        /// @return _borrowerWhitelistActive Boolean is borrower whitelist active
        /// @return _lenderWhitelistActive Boolean is lender whitelist active
        function getImmutableAddressBool()
            external
            view
            returns (
                address _assetContract,
                address _collateralContract,
                address _oracleMultiply,
                address _oracleDivide,
                address _rateContract,
                address _DEPLOYER_CONTRACT,
                address _COMPTROLLER_ADDRESS,
                address _FRAXLEND_WHITELIST,
                bool _borrowerWhitelistActive,
                bool _lenderWhitelistActive
            )
        {
            _assetContract = address(assetContract);
            _collateralContract = address(collateralContract);
            _oracleMultiply = oracleMultiply;
            _oracleDivide = oracleDivide;
            _rateContract = address(rateContract);
            _DEPLOYER_CONTRACT = DEPLOYER_ADDRESS;
            _COMPTROLLER_ADDRESS = COMPTROLLER_ADDRESS;
            _FRAXLEND_WHITELIST = FRAXLEND_WHITELIST_ADDRESS;
            _borrowerWhitelistActive = borrowerWhitelistActive;
            _lenderWhitelistActive = lenderWhitelistActive;
        }
        /// @notice The ```getImmutableUint256``` function gets all uint256 config values
        /// @return _oracleNormalization Oracle normalization factor
        /// @return _maxLTV Maximum LTV
        /// @return _cleanLiquidationFee Clean Liquidation Fee
        /// @return _maturityDate Maturity Date
        /// @return _penaltyRate Penalty Rate
        function getImmutableUint256()
            external
            view
            returns (
                uint256 _oracleNormalization,
                uint256 _maxLTV,
                uint256 _cleanLiquidationFee,
                uint256 _maturityDate,
                uint256 _penaltyRate
            )
        {
            _oracleNormalization = oracleNormalization;
            _maxLTV = maxLTV;
            _cleanLiquidationFee = cleanLiquidationFee;
            _maturityDate = maturityDate;
            _penaltyRate = penaltyRate;
        }
        /// @notice The ```getUserSnapshot``` function gets user level accounting data
        /// @param _address The user address
        /// @return _userAssetShares The user fToken balance
        /// @return _userBorrowShares The user borrow shares
        /// @return _userCollateralBalance The user collateral balance
        function getUserSnapshot(address _address)
            external
            view
            returns (uint256 _userAssetShares, uint256 _userBorrowShares, uint256 _userCollateralBalance)
        {
            _userAssetShares = balanceOf(_address);
            _userBorrowShares = userBorrowShares[_address];
            _userCollateralBalance = userCollateralBalance[_address];
        }
        /// @notice The ```getPairAccounting``` function gets all pair level accounting numbers
        /// @return _totalAssetAmount Total assets deposited and interest accrued, total claims
        /// @return _totalAssetShares Total fTokens
        /// @return _totalBorrowAmount Total borrows
        /// @return _totalBorrowShares Total borrow shares
        /// @return _totalCollateral Total collateral
        function getPairAccounting()
            external
            view
            returns (
                uint128 _totalAssetAmount,
                uint128 _totalAssetShares,
                uint128 _totalBorrowAmount,
                uint128 _totalBorrowShares,
                uint256 _totalCollateral
            )
        {
            VaultAccount memory _totalAsset = totalAsset;
            _totalAssetAmount = _totalAsset.amount;
            _totalAssetShares = _totalAsset.shares;
            VaultAccount memory _totalBorrow = totalBorrow;
            _totalBorrowAmount = _totalBorrow.amount;
            _totalBorrowShares = _totalBorrow.shares;
            _totalCollateral = totalCollateral;
        }
        /// @notice The ```toBorrowShares``` function converts a given amount of borrow debt into the number of shares
        /// @param _amount Amount of borrow
        /// @param _roundUp Whether to roundup during division
        function toBorrowShares(uint256 _amount, bool _roundUp) external view returns (uint256) {
            return totalBorrow.toShares(_amount, _roundUp);
        }
        /// @notice The ```toBorrowAmount``` function converts a given amount of borrow debt into the number of shares
        /// @param _shares Shares of borrow
        /// @param _roundUp Whether to roundup during division
        /// @return The amount of asset
        function toBorrowAmount(uint256 _shares, bool _roundUp) external view returns (uint256) {
            return totalBorrow.toAmount(_shares, _roundUp);
        }
        /// @notice The ```toAssetAmount``` function converts a given number of shares to an asset amount
        /// @param _shares Shares of asset (fToken)
        /// @param _roundUp Whether to round up after division
        /// @return The amount of asset
        function toAssetAmount(uint256 _shares, bool _roundUp) external view returns (uint256) {
            return totalAsset.toAmount(_shares, _roundUp);
        }
        /// @notice The ```toAssetShares``` function converts a given asset amount to a number of asset shares (fTokens)
        /// @param _amount The amount of asset
        /// @param _roundUp Whether to round up after division
        /// @return The number of shares (fTokens)
        function toAssetShares(uint256 _amount, bool _roundUp) external view returns (uint256) {
            return totalAsset.toShares(_amount, _roundUp);
        }
        // ============================================================================================
        // Functions: Configuration
        // ============================================================================================
        event SetMaxOracleDelay(uint256 _oldDelay, uint256 _newDelay);
        function setMaxOracleDelay(uint256 _newDelay) external {
            if (msg.sender != TIME_LOCK_ADDRESS) revert OnlyTimeLock();
            emit SetMaxOracleDelay(maxOracleDelay, _newDelay);
            maxOracleDelay = _newDelay;
        }
        /// @notice The ```SetTimeLock``` event fires when the TIME_LOCK_ADDRESS is set
        /// @param _oldAddress The original address
        /// @param _newAddress The new address
        event SetTimeLock(address _oldAddress, address _newAddress);
        /// @notice The ```setTimeLock``` function sets the TIME_LOCK address
        /// @param _newAddress the new time lock address
        function setTimeLock(address _newAddress) external {
            if (msg.sender != TIME_LOCK_ADDRESS) revert OnlyTimeLock();
            emit SetTimeLock(TIME_LOCK_ADDRESS, _newAddress);
            TIME_LOCK_ADDRESS = _newAddress;
        }
        /// @notice The ```ChangeFee``` event first when the fee is changed
        /// @param _newFee The new fee
        event ChangeFee(uint32 _newFee);
        /// @notice The ```changeFee``` function changes the protocol fee, max 50%
        /// @param _newFee The new fee
        function changeFee(uint32 _newFee) external whenNotPaused {
            if (msg.sender != TIME_LOCK_ADDRESS) revert OnlyTimeLock();
            if (_newFee > MAX_PROTOCOL_FEE) {
                revert BadProtocolFee();
            }
            _addInterest();
            currentRateInfo.feeToProtocolRate = _newFee;
            emit ChangeFee(_newFee);
        }
        /// @notice The ```WithdrawFees``` event fires when the fees are withdrawn
        /// @param _shares Number of _shares (fTokens) redeemed
        /// @param _recipient To whom the assets were sent
        /// @param _amountToTransfer The amount of fees redeemed
        event WithdrawFees(uint128 _shares, address _recipient, uint256 _amountToTransfer);
        /// @notice The ```withdrawFees``` function withdraws fees accumulated
        /// @param _shares Number of fTokens to redeem
        /// @param _recipient Address to send the assets
        /// @return _amountToTransfer Amount of assets sent to recipient
        function withdrawFees(uint128 _shares, address _recipient) external onlyOwner returns (uint256 _amountToTransfer) {
            // Grab some data from state to save gas
            VaultAccount memory _totalAsset = totalAsset;
            VaultAccount memory _totalBorrow = totalBorrow;
            // Take all available if 0 value passed
            if (_shares == 0) _shares = uint128(balanceOf(address(this)));
            // We must calculate this before we subtract from _totalAsset or invoke _burn
            _amountToTransfer = _totalAsset.toAmount(_shares, true);
            // Check for sufficient withdraw liquidity
            uint256 _assetsAvailable = _totalAssetAvailable(_totalAsset, _totalBorrow);
            if (_assetsAvailable < _amountToTransfer) {
                revert InsufficientAssetsInContract(_assetsAvailable, _amountToTransfer);
            }
            // Effects: bookkeeping
            _totalAsset.amount -= uint128(_amountToTransfer);
            _totalAsset.shares -= _shares;
            // Effects: write to states
            // NOTE: will revert if _shares > balanceOf(address(this))
            _burn(address(this), _shares);
            totalAsset = _totalAsset;
            // Interactions
            assetContract.safeTransfer(_recipient, _amountToTransfer);
            emit WithdrawFees(_shares, _recipient, _amountToTransfer);
        }
        /// @notice The ```SetSwapper``` event fires whenever a swapper is black or whitelisted
        /// @param _swapper The swapper address
        /// @param _approval The approval
        event SetSwapper(address _swapper, bool _approval);
        /// @notice The ```setSwapper``` function is called to black or whitelist a given swapper address
        /// @dev
        /// @param _swapper The swapper address
        /// @param _approval The approval
        function setSwapper(address _swapper, bool _approval) external onlyOwner {
            swappers[_swapper] = _approval;
            emit SetSwapper(_swapper, _approval);
        }
        /// @notice The ```SetApprovedLender``` event fires when a lender is black or whitelisted
        /// @param _address The address
        /// @param _approval The approval
        event SetApprovedLender(address indexed _address, bool _approval);
        /// @notice The ```setApprovedLenders``` function sets a given set of addresses to the whitelist
        /// @dev Cannot black list self
        /// @param _lenders The addresses who's status will be set
        /// @param _approval The approval status
        function setApprovedLenders(address[] calldata _lenders, bool _approval) external approvedLender(msg.sender) {
            for (uint256 i = 0; i < _lenders.length; i++) {
                // Do not set when _approval == false and _lender == msg.sender
                if (_approval || _lenders[i] != msg.sender) {
                    approvedLenders[_lenders[i]] = _approval;
                    emit SetApprovedLender(_lenders[i], _approval);
                }
            }
        }
        /// @notice The ```SetApprovedBorrower``` event fires when a borrower is black or whitelisted
        /// @param _address The address
        /// @param _approval The approval
        event SetApprovedBorrower(address indexed _address, bool _approval);
        /// @notice The ```setApprovedBorrowers``` function sets a given array of addresses to the whitelist
        /// @dev Cannot black list self
        /// @param _borrowers The addresses who's status will be set
        /// @param _approval The approval status
        function setApprovedBorrowers(address[] calldata _borrowers, bool _approval) external approvedBorrower {
            for (uint256 i = 0; i < _borrowers.length; i++) {
                // Do not set when _approval == false and _borrower == msg.sender
                if (_approval || _borrowers[i] != msg.sender) {
                    approvedBorrowers[_borrowers[i]] = _approval;
                    emit SetApprovedBorrower(_borrowers[i], _approval);
                }
            }
        }
        function pause() external {
            if (
                msg.sender != CIRCUIT_BREAKER_ADDRESS &&
                msg.sender != COMPTROLLER_ADDRESS &&
                msg.sender != owner() &&
                msg.sender != DEPLOYER_ADDRESS
            ) {
                revert ProtocolOrOwnerOnly();
            }
            _addInterest(); // accrue any interest prior to pausing as it won't accrue during pause
            _pause();
        }
        function unpause() external {
            if (msg.sender != COMPTROLLER_ADDRESS && msg.sender != owner()) {
                revert ProtocolOrOwnerOnly();
            }
            // Resets the lastTimestamp which has the effect of no interest accruing over the pause period
            _addInterest();
            _unpause();
        }
    }
    // SPDX-License-Identifier: ISC
    pragma solidity ^0.8.17;
    // ====================================================================
    // |     ______                   _______                             |
    // |    / _____________ __  __   / ____(_____  ____ _____  ________   |
    // |   / /_  / ___/ __ `| |/_/  / /_  / / __ \\/ __ `/ __ \\/ ___/ _ \\  |
    // |  / __/ / /  / /_/ _>  <   / __/ / / / / / /_/ / / / / /__/  __/  |
    // | /_/   /_/   \\__,_/_/|_|  /_/   /_/_/ /_/\\__,_/_/ /_/\\___/\\___/   |
    // |                                                                  |
    // ====================================================================
    // ===================== FraxlendPairConstants ========================
    // ====================================================================
    // Frax Finance: https://github.com/FraxFinance
    // Primary Author
    // Drake Evans: https://github.com/DrakeEvans
    // Reviewers
    // Dennis: https://github.com/denett
    // Sam Kazemian: https://github.com/samkazemian
    // Travis Moore: https://github.com/FortisFortuna
    // Jack Corddry: https://github.com/corddry
    // Rich Gee: https://github.com/zer0blockchain
    // ====================================================================
    abstract contract FraxlendPairConstants {
        // ============================================================================================
        // Constants
        // ============================================================================================
        // Precision settings
        uint256 internal constant LTV_PRECISION = 1e5; // 5 decimals
        uint256 internal constant LIQ_PRECISION = 1e5;
        uint256 internal constant UTIL_PREC = 1e5;
        uint256 internal constant FEE_PRECISION = 1e5;
        uint256 internal constant EXCHANGE_PRECISION = 1e18;
        // Default Interest Rate (if borrows = 0)
        uint64 internal constant DEFAULT_INT = 158_247_046; // 0.5% annual yield 1e18 precision
        // Protocol Fee
        uint16 internal constant DEFAULT_PROTOCOL_FEE = 0; // 1e5 precision
        uint256 internal constant MAX_PROTOCOL_FEE = 5e4; // 50% 1e5 precision
        error Insolvent(uint256 _borrow, uint256 _collateral, uint256 _exchangeRate);
        error BorrowerSolvent();
        error OnlyApprovedBorrowers();
        error OnlyApprovedLenders();
        error PastMaturity();
        error ProtocolOrOwnerOnly();
        error OracleLTEZero(address _oracle);
        error InsufficientAssetsInContract(uint256 _assets, uint256 _request);
        error NotOnWhitelist(address _address);
        error SlippageTooHigh(uint256 _minOut, uint256 _actual);
        error BadSwapper();
        error InvalidPath(address _expected, address _actual);
        error BadProtocolFee();
        error BorrowerWhitelistRequired();
        error OnlyTimeLock();
        error PriceTooLarge();
        error PastDeadline(uint256 _blockTimestamp, uint256 _deadline);
        error OracleStale(address _oracle);
    }
    // SPDX-License-Identifier: ISC
    pragma solidity ^0.8.17;
    // ====================================================================
    // |     ______                   _______                             |
    // |    / _____________ __  __   / ____(_____  ____ _____  ________   |
    // |   / /_  / ___/ __ `| |/_/  / /_  / / __ \\/ __ `/ __ \\/ ___/ _ \\  |
    // |  / __/ / /  / /_/ _>  <   / __/ / / / / / /_/ / / / / /__/  __/  |
    // | /_/   /_/   \\__,_/_/|_|  /_/   /_/_/ /_/\\__,_/_/ /_/\\___/\\___/   |
    // |                                                                  |
    // ====================================================================
    // ========================= FraxlendPairCore =========================
    // ====================================================================
    // Frax Finance: https://github.com/FraxFinance
    // Primary Author
    // Drake Evans: https://github.com/DrakeEvans
    // Reviewers
    // Dennis: https://github.com/denett
    // Sam Kazemian: https://github.com/samkazemian
    // Travis Moore: https://github.com/FortisFortuna
    // Jack Corddry: https://github.com/corddry
    // Rich Gee: https://github.com/zer0blockchain
    // ====================================================================
    import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
    import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
    import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
    import "@openzeppelin/contracts/security/Pausable.sol";
    import "@openzeppelin/contracts/access/Ownable.sol";
    import "@openzeppelin/contracts/utils/math/SafeCast.sol";
    import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
    import "./FraxlendPairConstants.sol";
    import "./libraries/VaultAccount.sol";
    import "./libraries/SafeERC20.sol";
    import "./interfaces/IERC4626.sol";
    import "./interfaces/IFraxlendWhitelist.sol";
    import "./interfaces/IRateCalculatorV2.sol";
    import "./interfaces/ISwapper.sol";
    /// @title FraxlendPairCore
    /// @author Drake Evans (Frax Finance) https://github.com/drakeevans
    /// @notice  An abstract contract which contains the core logic and storage for the FraxlendPair
    abstract contract FraxlendPairCore is FraxlendPairConstants, ERC20, Ownable, Pausable, ReentrancyGuard {
        using VaultAccountingLibrary for VaultAccount;
        using SafeERC20 for IERC20;
        using SafeCast for uint256;
        function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
            _major = 2;
            _minor = 0;
            _patch = 0;
        }
        // ============================================================================================
        // Settings set by constructor() & initialize()
        // ============================================================================================
        // Asset and collateral contracts
        IERC20 internal immutable assetContract;
        IERC20 public immutable collateralContract;
        // Oracle wrapper contract and oracleData
        address public immutable oracleMultiply;
        address public immutable oracleDivide;
        uint256 public immutable oracleNormalization;
        uint256 public maxOracleDelay;
        // LTV Settings
        uint256 public immutable maxLTV;
        // Liquidation Fee
        uint256 public immutable cleanLiquidationFee;
        uint256 public immutable dirtyLiquidationFee;
        // Interest Rate Calculator Contract
        IRateCalculatorV2 public immutable rateContract; // For complex rate calculations
        // Swapper
        mapping(address => bool) public swappers; // approved swapper addresses
        // Deployer
        address public immutable DEPLOYER_ADDRESS;
        // Admin contracts
        address public immutable CIRCUIT_BREAKER_ADDRESS;
        address public immutable COMPTROLLER_ADDRESS;
        address public TIME_LOCK_ADDRESS;
        // Dependencies
        address public immutable FRAXLEND_WHITELIST_ADDRESS;
        // ERC20 Metadata
        string internal nameOfContract;
        string internal symbolOfContract;
        uint8 internal immutable decimalsOfContract;
        // Maturity Date & Penalty Interest Rate (per Sec)
        uint256 public immutable maturityDate;
        uint256 public immutable penaltyRate;
        // ============================================================================================
        // Storage
        // ============================================================================================
        /// @notice Stores information about the current interest rate
        /// @dev struct is packed to reduce SLOADs. feeToProtocolRate is 1e5 precision, ratePerSec is 1e18 precision
        CurrentRateInfo public currentRateInfo;
        struct CurrentRateInfo {
            uint32 lastBlock;
            uint32 feeToProtocolRate; // Fee amount 1e5 precision
            uint64 lastTimestamp;
            uint64 ratePerSec;
            uint64 fullUtilizationRate;
        }
        /// @notice Stores information about the current exchange rate. Collateral:Asset ratio
        /// @dev Struct packed to save SLOADs. Amount of Collateral Token to buy 1e18 Asset Token
        ExchangeRateInfo public exchangeRateInfo;
        struct ExchangeRateInfo {
            uint32 lastTimestamp;
            uint224 exchangeRate; // collateral:asset ratio. i.e. how much collateral to buy 1e18 asset
        }
        // Contract Level Accounting
        VaultAccount public totalAsset; // amount = total amount of assets, shares = total shares outstanding
        VaultAccount public totalBorrow; // amount = total borrow amount with interest accrued, shares = total shares outstanding
        uint256 public totalCollateral; // total amount of collateral in contract
        // User Level Accounting
        /// @notice Stores the balance of collateral for each user
        mapping(address => uint256) public userCollateralBalance; // amount of collateral each user is backed
        /// @notice Stores the balance of borrow shares for each user
        mapping(address => uint256) public userBorrowShares; // represents the shares held by individuals
        // NOTE: user shares of assets are represented as ERC-20 tokens and accessible via balanceOf()
        // Internal Whitelists
        bool public immutable borrowerWhitelistActive;
        mapping(address => bool) public approvedBorrowers;
        bool public immutable lenderWhitelistActive;
        mapping(address => bool) public approvedLenders;
        // ============================================================================================
        // Initialize
        // ============================================================================================
        /// @notice The ```constructor``` function is called on deployment
        /// @param _configData abi.encode(address _asset, address _collateral, address _oracleMultiply, address _oracleDivide, uint256 _oracleNormalization, address _rateContract)
        constructor(bytes memory _configData, bytes memory _immutables, bytes memory _customConfigData) {
            // Handle Immutables Configuration
            {
                (
                    address _circuitBreaker,
                    address _comptrollerAddress,
                    address _timeLockAddress,
                    address _fraxlendWhitelistAddress
                ) = abi.decode(_immutables, (address, address, address, address));
                // Deployer contract
                DEPLOYER_ADDRESS = msg.sender;
                CIRCUIT_BREAKER_ADDRESS = _circuitBreaker;
                COMPTROLLER_ADDRESS = _comptrollerAddress;
                TIME_LOCK_ADDRESS = _timeLockAddress;
                FRAXLEND_WHITELIST_ADDRESS = _fraxlendWhitelistAddress;
            }
            {
                (
                    address _asset,
                    address _collateral,
                    address _oracleMultiply,
                    address _oracleDivide,
                    uint256 _oracleNormalization,
                    address _rateContract,
                    uint64 _fullUtilizationRate
                ) = abi.decode(_configData, (address, address, address, address, uint256, address, uint64));
                // Pair Settings
                assetContract = IERC20(_asset);
                collateralContract = IERC20(_collateral);
                currentRateInfo.feeToProtocolRate = DEFAULT_PROTOCOL_FEE;
                currentRateInfo.fullUtilizationRate = _fullUtilizationRate;
                // Oracle Settings
                {
                    IFraxlendWhitelist _fraxlendWhitelist = IFraxlendWhitelist(FRAXLEND_WHITELIST_ADDRESS);
                    // Check that oracles are on the whitelist
                    if (_oracleMultiply != address(0) && !_fraxlendWhitelist.oracleContractWhitelist(_oracleMultiply)) {
                        revert NotOnWhitelist(_oracleMultiply);
                    }
                    if (_oracleDivide != address(0) && !_fraxlendWhitelist.oracleContractWhitelist(_oracleDivide)) {
                        revert NotOnWhitelist(_oracleDivide);
                    }
                    // Write oracleData to storage
                    oracleMultiply = _oracleMultiply;
                    oracleDivide = _oracleDivide;
                    oracleNormalization = _oracleNormalization;
                    // Rate Settings
                    if (!_fraxlendWhitelist.rateContractWhitelist(_rateContract)) {
                        revert NotOnWhitelist(_rateContract);
                    }
                }
                rateContract = IRateCalculatorV2(_rateContract);
            }
            {
                (
                    string memory _nameOfContract,
                    string memory _symbolOfContract,
                    uint8 _decimalsOfContract,
                    uint256 _maxLTV,
                    uint256 _liquidationFee,
                    uint256 _maturityDate,
                    uint256 _penaltyRate,
                    address[] memory _approvedBorrowers,
                    address[] memory _approvedLenders,
                    uint256 _maxOracleDelay
                ) = abi.decode(
                        _customConfigData,
                        (string, string, uint8, uint256, uint256, uint256, uint256, address[], address[], uint256)
                    );
                // ERC20 Metadata
                nameOfContract = _nameOfContract;
                symbolOfContract = _symbolOfContract;
                decimalsOfContract = _decimalsOfContract;
                //Liquiation Fee Settings
                cleanLiquidationFee = _liquidationFee;
                dirtyLiquidationFee = (_liquidationFee * 90000) / LIQ_PRECISION; // 90% of clean fee
                // Oracle freshness setting
                maxOracleDelay = _maxOracleDelay;
                // Grab these in preparation for checks
                bool _isBorrowerWhitelistActive = _approvedBorrowers.length > 0;
                bool _isLenderWhitelistActive = _approvedLenders.length > 0;
                // If loan under-collateralized then enforce borrower whitelist, set maxLTV
                if (_maxLTV >= LTV_PRECISION && !_isBorrowerWhitelistActive) revert BorrowerWhitelistRequired();
                maxLTV = _maxLTV;
                // Maturity Date & Penalty Interest Rate (per Sec)
                maturityDate = _maturityDate;
                penaltyRate = _penaltyRate;
                // Set approved borrowers whitelist
                borrowerWhitelistActive = _isBorrowerWhitelistActive;
                // Set approved lenders whitelist active
                lenderWhitelistActive = _isLenderWhitelistActive;
                // Set approved borrowers
                for (uint256 i = 0; i < _approvedBorrowers.length; ++i) {
                    approvedBorrowers[_approvedBorrowers[i]] = true;
                }
                // Set approved lenders
                for (uint256 i = 0; i < _approvedLenders.length; ++i) {
                    approvedLenders[_approvedLenders[i]] = true;
                }
                // Instantiate Interest
                _addInterest();
                // Instantiate Exchange Rate
                _updateExchangeRate();
            }
        }
        // ============================================================================================
        // Internal Helpers
        // ============================================================================================
        /// @notice The ```_totalAssetAvailable``` function returns the total balance of Asset Tokens in the contract
        /// @param _totalAsset VaultAccount struct which stores total amount and shares for assets
        /// @param _totalBorrow VaultAccount struct which stores total amount and shares for borrows
        /// @return The balance of Asset Tokens held by contract
        function _totalAssetAvailable(VaultAccount memory _totalAsset, VaultAccount memory _totalBorrow)
            internal
            pure
            returns (uint256)
        {
            return _totalAsset.amount - _totalBorrow.amount;
        }
        /// @notice The ```_isSolvent``` function determines if a given borrower is solvent given an exchange rate
        /// @param _borrower The borrower address to check
        /// @param _exchangeRate The exchange rate, i.e. the amount of collateral to buy 1e18 asset
        /// @return Whether borrower is solvent
        function _isSolvent(address _borrower, uint256 _exchangeRate) internal view returns (bool) {
            if (maxLTV == 0) return true;
            uint256 _borrowerAmount = totalBorrow.toAmount(userBorrowShares[_borrower], true);
            if (_borrowerAmount == 0) return true;
            uint256 _collateralAmount = userCollateralBalance[_borrower];
            if (_collateralAmount == 0) return false;
            uint256 _ltv = (((_borrowerAmount * _exchangeRate) / EXCHANGE_PRECISION) * LTV_PRECISION) / _collateralAmount;
            return _ltv <= maxLTV;
        }
        /// @notice The ```_isPastMaturity``` function determines if the current block timestamp is past the maturityDate date
        /// @return Whether or not the debt is past maturity
        function _isPastMaturity() internal view returns (bool) {
            return maturityDate != 0 && block.timestamp > maturityDate;
        }
        // ============================================================================================
        // Modifiers
        // ============================================================================================
        /// @notice Checks for solvency AFTER executing contract code
        /// @param _borrower The borrower whose solvency we will check
        modifier isSolvent(address _borrower) {
            _;
            if (!_isSolvent(_borrower, exchangeRateInfo.exchangeRate)) {
                revert Insolvent(
                    totalBorrow.toAmount(userBorrowShares[_borrower], true),
                    userCollateralBalance[_borrower],
                    exchangeRateInfo.exchangeRate
                );
            }
        }
        /// @notice Checks if msg.sender is an approved Borrower
        modifier approvedBorrower() {
            if (borrowerWhitelistActive && !approvedBorrowers[msg.sender]) {
                revert OnlyApprovedBorrowers();
            }
            _;
        }
        /// @notice Checks if msg.sender and _receiver are both an approved Lender
        /// @param _receiver An additional receiver address to check
        modifier approvedLender(address _receiver) {
            if (lenderWhitelistActive && (!approvedLenders[msg.sender] || !approvedLenders[_receiver])) {
                revert OnlyApprovedLenders();
            }
            _;
        }
        /// @notice Ensure function is not called when passed maturity
        modifier isNotPastMaturity() {
            if (_isPastMaturity()) {
                revert PastMaturity();
            }
            _;
        }
        // ============================================================================================
        // Functions: Interest Accumulation and Adjustment
        // ============================================================================================
        /// @notice The ```AddInterest``` event is emitted when interest is accrued by borrowers
        /// @param _interestEarned The total interest accrued by all borrowers
        /// @param _rate The interest rate used to calculate accrued interest
        /// @param _deltaTime The time elapsed since last interest accrual
        /// @param _feesAmount The amount of fees paid to protocol
        /// @param _feesShare The amount of shares distributed to protocol
        event AddInterest(
            uint256 _interestEarned,
            uint256 _rate,
            uint256 _deltaTime,
            uint256 _feesAmount,
            uint256 _feesShare
        );
        /// @notice The ```UpdateRate``` event is emitted when the interest rate is updated
        /// @param _ratePerSec The old interest rate (per second)
        /// @param _deltaTime The time elapsed since last update
        /// @param _utilizationRate The utilization of assets in the Pair
        /// @param _newRatePerSec The new interest rate (per second)
        event UpdateRate(uint256 _ratePerSec, uint256 _deltaTime, uint256 _utilizationRate, uint256 _newRatePerSec);
        /// @notice The ```addInterest``` function is a public implementation of _addInterest and allows 3rd parties to trigger interest accrual
        /// @return _interestEarned The amount of interest accrued by all borrowers
        function addInterest()
            external
            nonReentrant
            returns (uint256 _interestEarned, uint256 _feesAmount, uint256 _feesShare, uint64 _newRate)
        {
            return _addInterest();
        }
        /// @notice The ```_addInterest``` function is invoked prior to every external function and is used to accrue interest and update interest rate
        /// @dev Can only called once per block
        /// @return _interestEarned The amount of interest accrued by all borrowers
        function _addInterest()
            internal
            returns (uint256 _interestEarned, uint256 _feesAmount, uint256 _feesShare, uint64 _newRate)
        {
            // Add interest only once per block
            CurrentRateInfo memory _currentRateInfo = currentRateInfo;
            if (_currentRateInfo.lastTimestamp == block.timestamp) {
                _newRate = _currentRateInfo.ratePerSec;
                return (_interestEarned, _feesAmount, _feesShare, _newRate);
            }
            // Pull some data from storage to save gas
            VaultAccount memory _totalAsset = totalAsset;
            VaultAccount memory _totalBorrow = totalBorrow;
            // If there are no borrows or contract is paused, no interest accrues and we reset interest rate
            if (_totalBorrow.shares == 0 || paused()) {
                if (!paused()) {
                    _currentRateInfo.ratePerSec = DEFAULT_INT;
                }
                _currentRateInfo.lastTimestamp = uint64(block.timestamp);
                _currentRateInfo.lastBlock = uint32(block.number);
                // Effects: write to storage
                currentRateInfo = _currentRateInfo;
            } else {
                // We know totalBorrow.shares > 0
                uint256 _deltaTime = block.timestamp - _currentRateInfo.lastTimestamp;
                // NOTE: Violates Checks-Effects-Interactions pattern
                // Be sure to mark external version NONREENTRANT (even though rateContract is trusted)
                // Calc new rate
                uint256 _utilizationRate = (UTIL_PREC * _totalBorrow.amount) / _totalAsset.amount;
                if (_isPastMaturity()) {
                    _newRate = uint64(penaltyRate);
                } else {
                    (_newRate, _currentRateInfo.fullUtilizationRate) = IRateCalculatorV2(rateContract).getNewRate(
                        _deltaTime,
                        _utilizationRate,
                        _currentRateInfo.fullUtilizationRate
                    );
                }
                // Event must be here to use non-mutated values
                emit UpdateRate(_currentRateInfo.ratePerSec, _deltaTime, _utilizationRate, _newRate);
                // Effects: bookkeeping
                _currentRateInfo.ratePerSec = _newRate;
                _currentRateInfo.lastTimestamp = uint64(block.timestamp);
                _currentRateInfo.lastBlock = uint32(block.number);
                // Calculate interest accrued
                _interestEarned = (_deltaTime * _totalBorrow.amount * _currentRateInfo.ratePerSec) / 1e18;
                // Accumulate interest and fees, only if no overflow upon casting
                if (
                    _interestEarned + _totalBorrow.amount <= type(uint128).max &&
                    _interestEarned + _totalAsset.amount <= type(uint128).max
                ) {
                    _totalBorrow.amount += uint128(_interestEarned);
                    _totalAsset.amount += uint128(_interestEarned);
                    if (_currentRateInfo.feeToProtocolRate > 0) {
                        _feesAmount = (_interestEarned * _currentRateInfo.feeToProtocolRate) / FEE_PRECISION;
                        _feesShare = (_feesAmount * _totalAsset.shares) / (_totalAsset.amount - _feesAmount);
                        // Effects: Give new shares to this contract, effectively diluting lenders an amount equal to the fees
                        // We can safely cast because _feesShare < _feesAmount < interestEarned which is always less than uint128
                        _totalAsset.shares += uint128(_feesShare);
                        // Effects: write to storage
                        _mint(address(this), _feesShare);
                    }
                    emit AddInterest(_interestEarned, _currentRateInfo.ratePerSec, _deltaTime, _feesAmount, _feesShare);
                }
                // Effects: write to storage
                totalAsset = _totalAsset;
                currentRateInfo = _currentRateInfo;
                totalBorrow = _totalBorrow;
            }
        }
        // ============================================================================================
        // Functions: ExchangeRate
        // ============================================================================================
        /// @notice The ```UpdateExchangeRate``` event is emitted when the Collateral:Asset exchange rate is updated
        /// @param _rate The new rate given as the amount of Collateral Token to buy 1e18 Asset Token
        event UpdateExchangeRate(uint256 _rate);
        /// @notice The ```updateExchangeRate``` function is the external implementation of _updateExchangeRate.
        /// @dev This function is invoked at most once per block as these queries can be expensive
        /// @return _exchangeRate The new exchange rate
        function updateExchangeRate() external nonReentrant returns (uint256 _exchangeRate) {
            _exchangeRate = _updateExchangeRate();
        }
        /// @notice The ```_updateExchangeRate``` function retrieves the latest exchange rate. i.e how much collateral to buy 1e18 asset.
        /// @dev This function is invoked at most once per block as these queries can be expensive
        /// @return _exchangeRate The new exchange rate
        function _updateExchangeRate() internal returns (uint256 _exchangeRate) {
            ExchangeRateInfo memory _exchangeRateInfo = exchangeRateInfo;
            if (_exchangeRateInfo.lastTimestamp == block.timestamp) {
                return _exchangeRate = _exchangeRateInfo.exchangeRate;
            }
            uint256 _price = uint256(1e36);
            uint256 _maxOracleDelay = maxOracleDelay;
            if (oracleMultiply != address(0)) {
                (, int256 _answer, , uint256 _updatedAt, ) = AggregatorV3Interface(oracleMultiply).latestRoundData();
                if (_answer <= 0) {
                    revert OracleLTEZero(oracleMultiply);
                }
                if (block.timestamp - _updatedAt > _maxOracleDelay) {
                    revert OracleStale(oracleMultiply);
                }
                _price = _price * uint256(_answer);
            }
            if (oracleDivide != address(0)) {
                (, int256 _answer, , uint256 _updatedAt, ) = AggregatorV3Interface(oracleDivide).latestRoundData();
                if (_answer <= 0) {
                    revert OracleLTEZero(oracleDivide);
                }
                if (block.timestamp - _updatedAt > _maxOracleDelay) {
                    revert OracleStale(oracleDivide);
                }
                _price = _price / uint256(_answer);
            }
            _exchangeRate = _price / oracleNormalization;
            // write to storage, if no overflow
            if (_exchangeRate > type(uint224).max) revert PriceTooLarge();
            _exchangeRateInfo.exchangeRate = uint224(_exchangeRate);
            _exchangeRateInfo.lastTimestamp = uint32(block.timestamp);
            exchangeRateInfo = _exchangeRateInfo;
            emit UpdateExchangeRate(_exchangeRate);
        }
        // ============================================================================================
        // Functions: Lending
        // ============================================================================================
        /// @notice The ```Deposit``` event fires when a user deposits assets to the pair
        /// @param caller the msg.sender
        /// @param owner the account the fTokens are sent to
        /// @param assets the amount of assets deposited
        /// @param shares the number of fTokens minted
        event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
        /// @notice The ```_deposit``` function is the internal implementation for lending assets
        /// @dev Caller must invoke ```ERC20.approve``` on the Asset Token contract prior to calling function
        /// @param _totalAsset An in memory VaultAccount struct representing the total amounts and shares for the Asset Token
        /// @param _amount The amount of Asset Token to be transferred
        /// @param _shares The amount of Asset Shares (fTokens) to be minted
        /// @param _receiver The address to receive the Asset Shares (fTokens)
        function _deposit(VaultAccount memory _totalAsset, uint128 _amount, uint128 _shares, address _receiver) internal {
            // Effects: bookkeeping
            _totalAsset.amount += _amount;
            _totalAsset.shares += _shares;
            // Effects: write back to storage
            _mint(_receiver, _shares);
            totalAsset = _totalAsset;
            // Interactions
            assetContract.safeTransferFrom(msg.sender, address(this), _amount);
            emit Deposit(msg.sender, _receiver, _amount, _shares);
        }
        /// @notice The ```deposit``` function allows a user to Lend Assets by specifying the amount of Asset Tokens to lend
        /// @dev Caller must invoke ```ERC20.approve``` on the Asset Token contract prior to calling function
        /// @param _amount The amount of Asset Token to transfer to Pair
        /// @param _receiver The address to receive the Asset Shares (fTokens)
        /// @return _sharesReceived The number of fTokens received for the deposit
        function deposit(uint256 _amount, address _receiver)
            external
            nonReentrant
            isNotPastMaturity
            whenNotPaused
            approvedLender(_receiver)
            returns (uint256 _sharesReceived)
        {
            _addInterest();
            VaultAccount memory _totalAsset = totalAsset;
            _sharesReceived = _totalAsset.toShares(_amount, false);
            _deposit(_totalAsset, _amount.toUint128(), _sharesReceived.toUint128(), _receiver);
        }
        /// @notice The ```Withdraw``` event fires when a user redeems their fTokens for the underlying asset
        /// @param caller the msg.sender
        /// @param receiver The address to which the underlying asset will be transferred to
        /// @param owner The owner of the fTokens
        /// @param assets The assets transferred
        /// @param shares The number of fTokens burned
        event Withdraw(
            address indexed caller,
            address indexed receiver,
            address indexed owner,
            uint256 assets,
            uint256 shares
        );
        /// @notice The ```_redeem``` function is an internal implementation which allows a Lender to pull their Asset Tokens out of the Pair
        /// @dev Caller must invoke ```ERC20.approve``` on the Asset Token contract prior to calling function
        /// @param _totalAsset An in-memory VaultAccount struct which holds the total amount of Asset Tokens and the total number of Asset Shares (fTokens)
        /// @param _amountToReturn The number of Asset Tokens to return
        /// @param _shares The number of Asset Shares (fTokens) to burn
        /// @param _receiver The address to which the Asset Tokens will be transferred
        /// @param _owner The owner of the Asset Shares (fTokens)
        function _redeem(
            VaultAccount memory _totalAsset,
            uint128 _amountToReturn,
            uint128 _shares,
            address _receiver,
            address _owner
        ) internal {
            if (msg.sender != _owner) {
                uint256 allowed = allowance(_owner, msg.sender);
                // NOTE: This will revert on underflow ensuring that allowance > shares
                if (allowed != type(uint256).max) _approve(_owner, msg.sender, allowed - _shares);
            }
            // Check for sufficient withdraw liquidity
            uint256 _assetsAvailable = _totalAssetAvailable(_totalAsset, totalBorrow);
            if (_assetsAvailable < _amountToReturn) {
                revert InsufficientAssetsInContract(_assetsAvailable, _amountToReturn);
            }
            // Effects: bookkeeping
            _totalAsset.amount -= _amountToReturn;
            _totalAsset.shares -= _shares;
            // Effects: write to storage
            totalAsset = _totalAsset;
            _burn(_owner, _shares);
            // Interactions
            assetContract.safeTransfer(_receiver, _amountToReturn);
            emit Withdraw(msg.sender, _receiver, _owner, _amountToReturn, _shares);
        }
        /// @notice The ```redeem``` function allows the caller to redeem their Asset Shares for Asset Tokens
        /// @param _shares The number of Asset Shares (fTokens) to burn for Asset Tokens
        /// @param _receiver The address to which the Asset Tokens will be transferred
        /// @param _owner The owner of the Asset Shares (fTokens)
        /// @return _amountToReturn The amount of Asset Tokens to be transferred
        function redeem(uint256 _shares, address _receiver, address _owner)
            external
            nonReentrant
            returns (uint256 _amountToReturn)
        {
            _addInterest();
            VaultAccount memory _totalAsset = totalAsset;
            _amountToReturn = _totalAsset.toAmount(_shares, false);
            _redeem(_totalAsset, _amountToReturn.toUint128(), _shares.toUint128(), _receiver, _owner);
        }
        // ============================================================================================
        // Functions: Borrowing
        // ============================================================================================
        /// @notice The ```BorrowAsset``` event is emitted when a borrower increases their position
        /// @param _borrower The borrower whose account was debited
        /// @param _receiver The address to which the Asset Tokens were transferred
        /// @param _borrowAmount The amount of Asset Tokens transferred
        /// @param _sharesAdded The number of Borrow Shares the borrower was debited
        event BorrowAsset(
            address indexed _borrower,
            address indexed _receiver,
            uint256 _borrowAmount,
            uint256 _sharesAdded
        );
        /// @notice The ```_borrowAsset``` function is the internal implementation for borrowing assets
        /// @param _borrowAmount The amount of the Asset Token to borrow
        /// @param _receiver The address to receive the Asset Tokens
        /// @return _sharesAdded The amount of borrow shares the msg.sender will be debited
        function _borrowAsset(uint128 _borrowAmount, address _receiver) internal returns (uint256 _sharesAdded) {
            VaultAccount memory _totalBorrow = totalBorrow;
            // Check available capital
            uint256 _assetsAvailable = _totalAssetAvailable(totalAsset, _totalBorrow);
            if (_assetsAvailable < _borrowAmount) {
                revert InsufficientAssetsInContract(_assetsAvailable, _borrowAmount);
            }
            // Effects: Bookkeeping to add shares & amounts to total Borrow accounting
            _sharesAdded = _totalBorrow.toShares(_borrowAmount, true);
            _totalBorrow.amount += _borrowAmount;
            _totalBorrow.shares += uint128(_sharesAdded);
            // NOTE: we can safely cast here because shares are always less than amount and _borrowAmount is uint128
            // Effects: write back to storage
            totalBorrow = _totalBorrow;
            userBorrowShares[msg.sender] += _sharesAdded;
            // Interactions
            if (_receiver != address(this)) {
                assetContract.safeTransfer(_receiver, _borrowAmount);
            }
            emit BorrowAsset(msg.sender, _receiver, _borrowAmount, _sharesAdded);
        }
        /// @notice The ```borrowAsset``` function allows a user to open/increase a borrow position
        /// @dev Borrower must call ```ERC20.approve``` on the Collateral Token contract if applicable
        /// @param _borrowAmount The amount of Asset Token to borrow
        /// @param _collateralAmount The amount of Collateral Token to transfer to Pair
        /// @param _receiver The address which will receive the Asset Tokens
        /// @return _shares The number of borrow Shares the msg.sender will be debited
        function borrowAsset(uint256 _borrowAmount, uint256 _collateralAmount, address _receiver)
            external
            isNotPastMaturity
            whenNotPaused
            nonReentrant
            isSolvent(msg.sender)
            approvedBorrower
            returns (uint256 _shares)
        {
            _addInterest();
            _updateExchangeRate();
            if (_collateralAmount > 0) {
                _addCollateral(msg.sender, _collateralAmount, msg.sender);
            }
            _shares = _borrowAsset(_borrowAmount.toUint128(), _receiver);
        }
        event AddCollateral(address indexed _sender, address indexed _borrower, uint256 _collateralAmount);
        /// @notice The ```_addCollateral``` function is an internal implementation for adding collateral to a borrowers position
        /// @param _sender The source of funds for the new collateral
        /// @param _collateralAmount The amount of Collateral Token to be transferred
        /// @param _borrower The borrower account for which the collateral should be credited
        function _addCollateral(address _sender, uint256 _collateralAmount, address _borrower) internal {
            // Effects: write to state
            userCollateralBalance[_borrower] += _collateralAmount;
            totalCollateral += _collateralAmount;
            // Interactions
            if (_sender != address(this)) {
                collateralContract.safeTransferFrom(_sender, address(this), _collateralAmount);
            }
            emit AddCollateral(_sender, _borrower, _collateralAmount);
        }
        /// @notice The ```addCollateral``` function allows the caller to add Collateral Token to a borrowers position
        /// @dev msg.sender must call ERC20.approve() on the Collateral Token contract prior to invocation
        /// @param _collateralAmount The amount of Collateral Token to be added to borrower's position
        /// @param _borrower The account to be credited
        function addCollateral(uint256 _collateralAmount, address _borrower) external nonReentrant isNotPastMaturity {
            _addInterest();
            _addCollateral(msg.sender, _collateralAmount, _borrower);
        }
        /// @notice The ```RemoveCollateral``` event is emitted when collateral is removed from a borrower's position
        /// @param _sender The account from which funds are transferred
        /// @param _collateralAmount The amount of Collateral Token to be transferred
        /// @param _receiver The address to which Collateral Tokens will be transferred
        event RemoveCollateral(
            address indexed _sender,
            uint256 _collateralAmount,
            address indexed _receiver,
            address indexed _borrower
        );
        /// @notice The ```_removeCollateral``` function is the internal implementation for removing collateral from a borrower's position
        /// @param _collateralAmount The amount of Collateral Token to remove from the borrower's position
        /// @param _receiver The address to receive the Collateral Token transferred
        /// @param _borrower The borrower whose account will be debited the Collateral amount
        function _removeCollateral(uint256 _collateralAmount, address _receiver, address _borrower) internal {
            // Effects: write to state
            // Following line will revert on underflow if _collateralAmount > userCollateralBalance
            userCollateralBalance[_borrower] -= _collateralAmount;
            // Following line will revert on underflow if totalCollateral < _collateralAmount
            totalCollateral -= _collateralAmount;
            // Interactions
            if (_receiver != address(this)) {
                collateralContract.safeTransfer(_receiver, _collateralAmount);
            }
            emit RemoveCollateral(msg.sender, _collateralAmount, _receiver, _borrower);
        }
        /// @notice The ```removeCollateral``` function is used to remove collateral from msg.sender's borrow position
        /// @dev msg.sender must be solvent after invocation or transaction will revert
        /// @param _collateralAmount The amount of Collateral Token to transfer
        /// @param _receiver The address to receive the transferred funds
        function removeCollateral(uint256 _collateralAmount, address _receiver)
            external
            nonReentrant
            isSolvent(msg.sender)
        {
            _addInterest();
            // Note: exchange rate is irrelevant when borrower has no debt shares
            if (userBorrowShares[msg.sender] > 0) {
                _updateExchangeRate();
            }
            _removeCollateral(_collateralAmount, _receiver, msg.sender);
        }
        /// @notice The ```RepayAsset``` event is emitted whenever a debt position is repaid
        /// @param _payer The address paying for the repayment
        /// @param _borrower The borrower whose account will be credited
        /// @param _amountToRepay The amount of Asset token to be transferred
        /// @param _shares The amount of Borrow Shares which will be debited from the borrower after repayment
        event RepayAsset(address indexed _payer, address indexed _borrower, uint256 _amountToRepay, uint256 _shares);
        /// @notice The ```_repayAsset``` function is the internal implementation for repaying a borrow position
        /// @dev The payer must have called ERC20.approve() on the Asset Token contract prior to invocation
        /// @param _totalBorrow An in memory copy of the totalBorrow VaultAccount struct
        /// @param _amountToRepay The amount of Asset Token to transfer
        /// @param _shares The number of Borrow Shares the sender is repaying
        /// @param _payer The address from which funds will be transferred
        /// @param _borrower The borrower account which will be credited
        function _repayAsset(
            VaultAccount memory _totalBorrow,
            uint128 _amountToRepay,
            uint128 _shares,
            address _payer,
            address _borrower
        ) internal {
            // Effects: Bookkeeping
            _totalBorrow.amount -= _amountToRepay;
            _totalBorrow.shares -= _shares;
            // Effects: write to state
            userBorrowShares[_borrower] -= _shares;
            totalBorrow = _totalBorrow;
            // Interactions
            if (_payer != address(this)) {
                assetContract.safeTransferFrom(_payer, address(this), _amountToRepay);
            }
            emit RepayAsset(_payer, _borrower, _amountToRepay, _shares);
        }
        /// @notice The ```repayAsset``` function allows the caller to pay down the debt for a given borrower.
        /// @dev Caller must first invoke ```ERC20.approve()``` for the Asset Token contract
        /// @param _shares The number of Borrow Shares which will be repaid by the call
        /// @param _borrower The account for which the debt will be reduced
        /// @return _amountToRepay The amount of Asset Tokens which were transferred in order to repay the Borrow Shares
        function repayAsset(uint256 _shares, address _borrower) external nonReentrant returns (uint256 _amountToRepay) {
            _addInterest();
            VaultAccount memory _totalBorrow = totalBorrow;
            _amountToRepay = _totalBorrow.toAmount(_shares, true);
            _repayAsset(_totalBorrow, _amountToRepay.toUint128(), _shares.toUint128(), msg.sender, _borrower);
        }
        // ============================================================================================
        // Functions: Liquidations
        // ============================================================================================
        /// @notice The ```Liquidate``` event is emitted when a liquidation occurs
        /// @param _borrower The borrower account for which the liquidation occurred
        /// @param _collateralForLiquidator The amount of Collateral Token transferred to the liquidator
        /// @param _sharesToLiquidate The number of Borrow Shares the liquidator repaid on behalf of the borrower
        /// @param _sharesToAdjust The number of Borrow Shares that were adjusted on liabilities and assets (a writeoff)
        event Liquidate(
            address indexed _borrower,
            uint256 _collateralForLiquidator,
            uint256 _sharesToLiquidate,
            uint256 _amountLiquidatorToRepay,
            uint256 _sharesToAdjust,
            uint256 _amountToAdjust
        );
        /// @notice The ```liquidate``` function allows a third party to repay a borrower's debt if they have become insolvent
        /// @dev Caller must invoke ```ERC20.approve``` on the Asset Token contract prior to calling ```Liquidate()```
        /// @param _sharesToLiquidate The number of Borrow Shares repaid by the liquidator
        /// @param _deadline The timestamp after which tx will revert
        /// @param _borrower The account for which the repayment is credited and from whom collateral will be taken
        /// @return _collateralForLiquidator The amount of Collateral Token transferred to the liquidator
        function liquidate(uint128 _sharesToLiquidate, uint256 _deadline, address _borrower)
            external
            whenNotPaused
            nonReentrant
            approvedLender(msg.sender)
            returns (uint256 _collateralForLiquidator)
        {
            if (block.timestamp > _deadline) revert PastDeadline(block.timestamp, _deadline);
            _addInterest();
            uint256 _exchangeRate = _updateExchangeRate();
            if (_isSolvent(_borrower, _exchangeRate)) {
                revert BorrowerSolvent();
            }
            // Read from state
            VaultAccount memory _totalBorrow = totalBorrow;
            uint256 _userCollateralBalance = userCollateralBalance[_borrower];
            uint128 _borrowerShares = userBorrowShares[_borrower].toUint128();
            // Prevent stack-too-deep
            int256 _leftoverCollateral;
            {
                // Checks & Calculations
                // Determine the liquidation amount in collateral units (i.e. how much debt is liquidator going to repay)
                uint256 _liquidationAmountInCollateralUnits = ((_totalBorrow.toAmount(_sharesToLiquidate, false) *
                    _exchangeRate) / EXCHANGE_PRECISION);
                // We first optimistically calculate the amount of collateral to give the liquidator based on the higher clean liquidation fee
                // This fee only applies if the liquidator does a full liquidation
                uint256 _optimisticCollateralForLiquidator = (_liquidationAmountInCollateralUnits *
                    (LIQ_PRECISION + cleanLiquidationFee)) / LIQ_PRECISION;
                // Because interest accrues every block, _liquidationAmountInCollateralUnits from a few lines up is an ever increasing value
                // This means that leftoverCollateral can occasionally go negative by a few hundred wei (cleanLiqFee premium covers this for liquidator)
                _leftoverCollateral = (_userCollateralBalance.toInt256() - _optimisticCollateralForLiquidator.toInt256());
                // If cleanLiquidation fee results in no leftover collateral, give liquidator all the collateral
                // This will only be true when there liquidator is cleaning out the position
                _collateralForLiquidator = _leftoverCollateral <= 0
                    ? _userCollateralBalance
                    : (_liquidationAmountInCollateralUnits * (LIQ_PRECISION + dirtyLiquidationFee)) / LIQ_PRECISION;
            }
            // Calculated here for use during repayment, grouped with other calcs before effects start
            uint128 _amountLiquidatorToRepay = (_totalBorrow.toAmount(_sharesToLiquidate, true)).toUint128();
            // Determine if and how much debt to adjust
            uint128 _sharesToAdjust;
            {
                uint128 _amountToAdjust;
                if (_leftoverCollateral <= 0) {
                    // Determine if we need to adjust any shares
                    _sharesToAdjust = _borrowerShares - _sharesToLiquidate;
                    if (_sharesToAdjust > 0) {
                        // Write off bad debt
                        _amountToAdjust = (_totalBorrow.toAmount(_sharesToAdjust, false)).toUint128();
                        // Note: Ensure this memory struct will be passed to _repayAsset for write to state
                        _totalBorrow.amount -= _amountToAdjust;
                        // Effects: write to state
                        totalAsset.amount -= _amountToAdjust;
                    }
                }
                emit Liquidate(
                    _borrower,
                    _collateralForLiquidator,
                    _sharesToLiquidate,
                    _amountLiquidatorToRepay,
                    _sharesToAdjust,
                    _amountToAdjust
                );
            }
            // Effects & Interactions
            // NOTE: reverts if _shares > userBorrowShares
            _repayAsset(
                _totalBorrow,
                _amountLiquidatorToRepay,
                _sharesToLiquidate + _sharesToAdjust,
                msg.sender,
                _borrower
            ); // liquidator repays shares on behalf of borrower
            // NOTE: reverts if _collateralForLiquidator > userCollateralBalance
            // Collateral is removed on behalf of borrower and sent to liquidator
            // NOTE: reverts if _collateralForLiquidator > userCollateralBalance
            _removeCollateral(_collateralForLiquidator, msg.sender, _borrower);
        }
        // ============================================================================================
        // Functions: Leverage
        // ============================================================================================
        /// @notice The ```LeveragedPosition``` event is emitted when a borrower takes out a new leveraged position
        /// @param _borrower The account for which the debt is debited
        /// @param _swapperAddress The address of the swapper which conforms the FraxSwap interface
        /// @param _borrowAmount The amount of Asset Token to be borrowed to be borrowed
        /// @param _borrowShares The number of Borrow Shares the borrower is credited
        /// @param _initialCollateralAmount The amount of initial Collateral Tokens supplied by the borrower
        /// @param _amountCollateralOut The amount of Collateral Token which was received for the Asset Tokens
        event LeveragedPosition(
            address indexed _borrower,
            address _swapperAddress,
            uint256 _borrowAmount,
            uint256 _borrowShares,
            uint256 _initialCollateralAmount,
            uint256 _amountCollateralOut
        );
        /// @notice The ```leveragedPosition``` function allows a user to enter a leveraged borrow position with minimal upfront Collateral
        /// @dev Caller must invoke ```ERC20.approve()``` on the Collateral Token contract prior to calling function
        /// @param _swapperAddress The address of the whitelisted swapper to use to swap borrowed Asset Tokens for Collateral Tokens
        /// @param _borrowAmount The amount of Asset Tokens borrowed
        /// @param _initialCollateralAmount The initial amount of Collateral Tokens supplied by the borrower
        /// @param _amountCollateralOutMin The minimum amount of Collateral Tokens to be received in exchange for the borrowed Asset Tokens
        /// @param _path An array containing the addresses of ERC20 tokens to swap.  Adheres to UniV2 style path params.
        /// @return _totalCollateralBalance The total amount of Collateral Tokens added to a users account (initial + swap)
        function leveragedPosition(
            address _swapperAddress,
            uint256 _borrowAmount,
            uint256 _initialCollateralAmount,
            uint256 _amountCollateralOutMin,
            address[] memory _path
        )
            external
            isNotPastMaturity
            nonReentrant
            whenNotPaused
            approvedBorrower
            isSolvent(msg.sender)
            returns (uint256 _totalCollateralBalance)
        {
            _addInterest();
            _updateExchangeRate();
            IERC20 _assetContract = assetContract;
            IERC20 _collateralContract = collateralContract;
            if (!swappers[_swapperAddress]) {
                revert BadSwapper();
            }
            if (_path[0] != address(_assetContract)) {
                revert InvalidPath(address(_assetContract), _path[0]);
            }
            if (_path[_path.length - 1] != address(_collateralContract)) {
                revert InvalidPath(address(_collateralContract), _path[_path.length - 1]);
            }
            // Add initial collateral
            if (_initialCollateralAmount > 0) {
                _addCollateral(msg.sender, _initialCollateralAmount, msg.sender);
            }
            // Debit borrowers account
            // setting recipient to address(this) means no transfer will happen
            uint256 _borrowShares = _borrowAsset(_borrowAmount.toUint128(), address(this));
            // Interactions
            _assetContract.approve(_swapperAddress, _borrowAmount);
            // Even though swappers are trusted, we verify the balance before and after swap
            uint256 _initialCollateralBalance = _collateralContract.balanceOf(address(this));
            ISwapper(_swapperAddress).swapExactTokensForTokens(
                _borrowAmount,
                _amountCollateralOutMin,
                _path,
                address(this),
                block.timestamp
            );
            uint256 _finalCollateralBalance = _collateralContract.balanceOf(address(this));
            // Note: VIOLATES CHECKS-EFFECTS-INTERACTION pattern, make sure function is NONREENTRANT
            // Effects: bookkeeping & write to state
            uint256 _amountCollateralOut = _finalCollateralBalance - _initialCollateralBalance;
            if (_amountCollateralOut < _amountCollateralOutMin) {
                revert SlippageTooHigh(_amountCollateralOutMin, _amountCollateralOut);
            }
            // address(this) as _sender means no transfer occurs as the pair has already received the collateral during swap
            _addCollateral(address(this), _amountCollateralOut, msg.sender);
            _totalCollateralBalance = _initialCollateralAmount + _amountCollateralOut;
            emit LeveragedPosition(
                msg.sender,
                _swapperAddress,
                _borrowAmount,
                _borrowShares,
                _initialCollateralAmount,
                _amountCollateralOut
            );
        }
        /// @notice The ```RepayAssetWithCollateral``` event is emitted whenever ```repayAssetWithCollateral()``` is invoked
        /// @param _borrower The borrower account for which the repayment is taking place
        /// @param _swapperAddress The address of the whitelisted swapper to use for token swaps
        /// @param _collateralToSwap The amount of Collateral Token to swap and use for repayment
        /// @param _amountAssetOut The amount of Asset Token which was repaid
        /// @param _sharesRepaid The number of Borrow Shares which were repaid
        event RepayAssetWithCollateral(
            address indexed _borrower,
            address _swapperAddress,
            uint256 _collateralToSwap,
            uint256 _amountAssetOut,
            uint256 _sharesRepaid
        );
        /// @notice The ```repayAssetWithCollateral``` function allows a borrower to repay their debt using existing collateral in contract
        /// @param _swapperAddress The address of the whitelisted swapper to use for token swaps
        /// @param _collateralToSwap The amount of Collateral Tokens to swap for Asset Tokens
        /// @param _amountAssetOutMin The minimum amount of Asset Tokens to receive during the swap
        /// @param _path An array containing the addresses of ERC20 tokens to swap.  Adheres to UniV2 style path params.
        /// @return _amountAssetOut The amount of Asset Tokens received for the Collateral Tokens, the amount the borrowers account was credited
        function repayAssetWithCollateral(
            address _swapperAddress,
            uint256 _collateralToSwap,
            uint256 _amountAssetOutMin,
            address[] calldata _path
        ) external nonReentrant isSolvent(msg.sender) returns (uint256 _amountAssetOut) {
            _addInterest();
            _updateExchangeRate();
            IERC20 _assetContract = assetContract;
            IERC20 _collateralContract = collateralContract;
            if (!swappers[_swapperAddress]) {
                revert BadSwapper();
            }
            if (_path[0] != address(_collateralContract)) {
                revert InvalidPath(address(_collateralContract), _path[0]);
            }
            if (_path[_path.length - 1] != address(_assetContract)) {
                revert InvalidPath(address(_assetContract), _path[_path.length - 1]);
            }
            // Effects: bookkeeping & write to state
            // Debit users collateral balance in preparation for swap, setting _recipient to address(this) means no transfer occurs
            _removeCollateral(_collateralToSwap, address(this), msg.sender);
            // Interactions
            _collateralContract.approve(_swapperAddress, _collateralToSwap);
            // Even though swappers are trusted, we verify the balance before and after swap
            uint256 _initialAssetBalance = _assetContract.balanceOf(address(this));
            ISwapper(_swapperAddress).swapExactTokensForTokens(
                _collateralToSwap,
                _amountAssetOutMin,
                _path,
                address(this),
                block.timestamp
            );
            uint256 _finalAssetBalance = _assetContract.balanceOf(address(this));
            // Note: VIOLATES CHECKS-EFFECTS-INTERACTION pattern, make sure function is NONREENTRANT
            // Effects: bookkeeping
            _amountAssetOut = _finalAssetBalance - _initialAssetBalance;
            if (_amountAssetOut < _amountAssetOutMin) {
                revert SlippageTooHigh(_amountAssetOutMin, _amountAssetOut);
            }
            VaultAccount memory _totalBorrow = totalBorrow;
            uint256 _sharesToRepay = _totalBorrow.toShares(_amountAssetOut, false);
            // Effects: write to state
            // Note: setting _payer to address(this) means no actual transfer will occur.  Contract already has funds
            _repayAsset(_totalBorrow, _amountAssetOut.toUint128(), _sharesToRepay.toUint128(), address(this), msg.sender);
            emit RepayAssetWithCollateral(msg.sender, _swapperAddress, _collateralToSwap, _amountAssetOut, _sharesToRepay);
        }
    }
    // SPDX-License-Identifier: ISC
    pragma solidity ^0.8.17;
    struct VaultAccount {
        uint128 amount; // Total amount, analogous to market cap
        uint128 shares; // Total shares, analogous to shares outstanding
    }
    /// @title VaultAccount Library
    /// @author Drake Evans (Frax Finance) github.com/drakeevans, modified from work by @Boring_Crypto github.com/boring_crypto
    /// @notice Provides a library for use with the VaultAccount struct, provides convenient math implementations
    /// @dev Uses uint128 to save on storage
    library VaultAccountingLibrary {
        /// @notice Calculates the shares value in relationship to `amount` and `total`
        /// @dev Given an amount, return the appropriate number of shares
        function toShares(
            VaultAccount memory total,
            uint256 amount,
            bool roundUp
        ) internal pure returns (uint256 shares) {
            if (total.amount == 0) {
                shares = amount;
            } else {
                shares = (amount * total.shares) / total.amount;
                if (roundUp && (shares * total.amount) / total.shares < amount) {
                    shares = shares + 1;
                }
            }
        }
        /// @notice Calculates the amount value in relationship to `shares` and `total`
        /// @dev Given a number of shares, returns the appropriate amount
        function toAmount(
            VaultAccount memory total,
            uint256 shares,
            bool roundUp
        ) internal pure returns (uint256 amount) {
            if (total.shares == 0) {
                amount = shares;
            } else {
                amount = (shares * total.amount) / total.shares;
                if (roundUp && (amount * total.shares) / total.amount < shares) {
                    amount = amount + 1;
                }
            }
        }
    }
    // SPDX-License-Identifier: ISC
    pragma solidity ^0.8.17;
    import "@openzeppelin/contracts/interfaces/IERC20.sol";
    import { SafeERC20 as OZSafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
    // solhint-disable avoid-low-level-calls
    // solhint-disable max-line-length
    /// @title SafeERC20 provides helper functions for safe transfers as well as safe metadata access
    /// @author Library originally written by @Boring_Crypto github.com/boring_crypto, modified by Drake Evans (Frax Finance) github.com/drakeevans
    /// @dev original: https://github.com/boringcrypto/BoringSolidity/blob/fed25c5d43cb7ce20764cd0b838e21a02ea162e9/contracts/libraries/BoringERC20.sol
    library SafeERC20 {
        bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
        bytes4 private constant SIG_NAME = 0x06fdde03; // name()
        bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
        function returnDataToString(bytes memory data) internal pure returns (string memory) {
            if (data.length >= 64) {
                return abi.decode(data, (string));
            } else if (data.length == 32) {
                uint8 i = 0;
                while (i < 32 && data[i] != 0) {
                    i++;
                }
                bytes memory bytesArray = new bytes(i);
                for (i = 0; i < 32 && data[i] != 0; i++) {
                    bytesArray[i] = data[i];
                }
                return string(bytesArray);
            } else {
                return "???";
            }
        }
        /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string.
        /// @param token The address of the ERC-20 token contract.
        /// @return (string) Token symbol.
        function safeSymbol(IERC20 token) internal view returns (string memory) {
            (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
            return success ? returnDataToString(data) : "???";
        }
        /// @notice Provides a safe ERC20.name version which returns '???' as fallback string.
        /// @param token The address of the ERC-20 token contract.
        /// @return (string) Token name.
        function safeName(IERC20 token) internal view returns (string memory) {
            (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
            return success ? returnDataToString(data) : "???";
        }
        /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
        /// @param token The address of the ERC-20 token contract.
        /// @return (uint8) Token decimals.
        function safeDecimals(IERC20 token) internal view returns (uint8) {
            (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS));
            return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
        }
        function safeTransfer(
            IERC20 token,
            address to,
            uint256 value
        ) internal {
            OZSafeERC20.safeTransfer(token, to, value);
        }
        function safeTransferFrom(
            IERC20 token,
            address from,
            address to,
            uint256 value
        ) internal {
            OZSafeERC20.safeTransferFrom(token, from, to, value);
        }
    }
    // SPDX-License-Identifier: ISC
    pragma solidity >=0.8.17;
    interface IFraxlendWhitelist {
        function fraxlendDeployerWhitelist(address) external view returns (bool);
        function oracleContractWhitelist(address) external view returns (bool);
        function owner() external view returns (address);
        function rateContractWhitelist(address) external view returns (bool);
        function renounceOwnership() external;
        function setFraxlendDeployerWhitelist(address[] calldata _addresses, bool _bool) external;
        function setOracleContractWhitelist(address[] calldata _addresses, bool _bool) external;
        function setRateContractWhitelist(address[] calldata _addresses, bool _bool) external;
        function transferOwnership(address newOwner) external;
    }
    // SPDX-License-Identifier: ISC
    pragma solidity >=0.8.17;
    import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
    import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
    interface IERC4626 is IERC20, IERC20Metadata {
        event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
        event Withdraw(
            address indexed caller,
            address indexed receiver,
            address indexed owner,
            uint256 assets,
            uint256 shares
        );
        function asset() external view returns (address);
        function convertToAssets(uint256 shares) external view returns (uint256);
        function convertToShares(uint256 assets) external view returns (uint256);
        function maxDeposit(address) external view returns (uint256);
        function maxMint(address) external view returns (uint256);
        function maxRedeem(address owner) external view returns (uint256);
        function maxWithdraw(address owner) external view returns (uint256);
        function previewDeposit(uint256 assets) external view returns (uint256);
        function previewMint(uint256 shares) external view returns (uint256);
        function previewRedeem(uint256 shares) external view returns (uint256);
        function previewWithdraw(uint256 assets) external view returns (uint256);
        function totalAssets() external view returns (uint256);
        function mint(uint256 shares, address receiver) external returns (uint256 assets);
        function deposit(uint256 assets, address receiver) external returns (uint256 shares);
        function redeem(
            uint256 shares,
            address receiver,
            address owner
        ) external returns (uint256 assets);
        function withdraw(
            uint256 assets,
            address receiver,
            address owner
        ) external returns (uint256 shares);
    }
    // SPDX-License-Identifier: ISC
    pragma solidity >=0.8.17;
    interface IRateCalculator {
        function name() external pure returns (string memory);
        function requireValidInitData(bytes calldata _initData) external pure;
        function getConstants() external pure returns (bytes memory _calldata);
        function getNewRate(bytes calldata _data, bytes calldata _initData) external pure returns (uint64 _newRatePerSec);
    }
    // SPDX-License-Identifier: MIT
    pragma solidity >=0.8.17;
    interface ISwapper {
        function swapExactTokensForTokens(
            uint256 amountIn,
            uint256 amountOutMin,
            address[] calldata path,
            address to,
            uint256 deadline
        ) external returns (uint256[] memory amounts);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Interface of the ERC20 standard as defined in the EIP.
     */
    interface IERC20 {
        /**
         * @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);
        /**
         * @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 `to`.
         *
         * Returns a boolean value indicating whether the operation succeeded.
         *
         * Emits a {Transfer} event.
         */
        function transfer(address to, 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 `from` to `to` 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 from,
            address to,
            uint256 amount
        ) external returns (bool);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
    pragma solidity ^0.8.0;
    import "../IERC20.sol";
    /**
     * @dev Interface for the optional metadata functions from the ERC20 standard.
     *
     * _Available since v4.1._
     */
    interface IERC20Metadata is IERC20 {
        /**
         * @dev Returns the name of the token.
         */
        function name() external view returns (string memory);
        /**
         * @dev Returns the symbol of the token.
         */
        function symbol() external view returns (string memory);
        /**
         * @dev Returns the decimals places of the token.
         */
        function decimals() external view returns (uint8);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Contract module that helps prevent reentrant calls to a function.
     *
     * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
     * available, which can be applied to functions to make sure there are no nested
     * (reentrant) calls to them.
     *
     * Note that because there is a single `nonReentrant` guard, functions marked as
     * `nonReentrant` may not call one another. This can be worked around by making
     * those functions `private`, and then adding `external` `nonReentrant` entry
     * points to them.
     *
     * TIP: If you would like to learn more about reentrancy and alternative ways
     * to protect against it, check out our blog post
     * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
     */
    abstract contract ReentrancyGuard {
        // Booleans are more expensive than uint256 or any type that takes up a full
        // word because each write operation emits an extra SLOAD to first read the
        // slot's contents, replace the bits taken up by the boolean, and then write
        // back. This is the compiler's defense against contract upgrades and
        // pointer aliasing, and it cannot be disabled.
        // The values being non-zero value makes deployment a bit more expensive,
        // but in exchange the refund on every call to nonReentrant will be lower in
        // amount. Since refunds are capped to a percentage of the total
        // transaction's gas, it is best to keep them low in cases like this one, to
        // increase the likelihood of the full refund coming into effect.
        uint256 private constant _NOT_ENTERED = 1;
        uint256 private constant _ENTERED = 2;
        uint256 private _status;
        constructor() {
            _status = _NOT_ENTERED;
        }
        /**
         * @dev Prevents a contract from calling itself, directly or indirectly.
         * Calling a `nonReentrant` function from another `nonReentrant`
         * function is not supported. It is possible to prevent this from happening
         * by making the `nonReentrant` function external, and making it call a
         * `private` function that does the actual work.
         */
        modifier nonReentrant() {
            // On the first call to nonReentrant, _notEntered will be true
            require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
            // Any calls to nonReentrant after this point will fail
            _status = _ENTERED;
            _;
            // By storing the original value once again, a refund is triggered (see
            // https://eips.ethereum.org/EIPS/eip-2200)
            _status = _NOT_ENTERED;
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    interface AggregatorV3Interface {
      function decimals() external view returns (uint8);
      function description() external view returns (string memory);
      function version() external view returns (uint256);
      function getRoundData(uint80 _roundId)
        external
        view
        returns (
          uint80 roundId,
          int256 answer,
          uint256 startedAt,
          uint256 updatedAt,
          uint80 answeredInRound
        );
      function latestRoundData()
        external
        view
        returns (
          uint80 roundId,
          int256 answer,
          uint256 startedAt,
          uint256 updatedAt,
          uint80 answeredInRound
        );
    }
    // SPDX-License-Identifier: ISC
    pragma solidity ^0.8.17;
    interface IRateCalculatorV2 {
        function name() external view returns (string memory);
        function version() external view returns (uint256, uint256, uint256);
        function getNewRate(uint256 _deltaTime, uint256 _utilization, uint64 _maxInterest)
            external
            view
            returns (uint64 _newRatePerSec, uint64 _newMaxInterest);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
    pragma solidity ^0.8.0;
    import "../utils/Context.sol";
    /**
     * @dev Contract module which allows children to implement an emergency stop
     * mechanism that can be triggered by an authorized account.
     *
     * This module is used through inheritance. It will make available the
     * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
     * the functions of your contract. Note that they will not be pausable by
     * simply including this module, only once the modifiers are put in place.
     */
    abstract contract Pausable is Context {
        /**
         * @dev Emitted when the pause is triggered by `account`.
         */
        event Paused(address account);
        /**
         * @dev Emitted when the pause is lifted by `account`.
         */
        event Unpaused(address account);
        bool private _paused;
        /**
         * @dev Initializes the contract in unpaused state.
         */
        constructor() {
            _paused = false;
        }
        /**
         * @dev Modifier to make a function callable only when the contract is not paused.
         *
         * Requirements:
         *
         * - The contract must not be paused.
         */
        modifier whenNotPaused() {
            _requireNotPaused();
            _;
        }
        /**
         * @dev Modifier to make a function callable only when the contract is paused.
         *
         * Requirements:
         *
         * - The contract must be paused.
         */
        modifier whenPaused() {
            _requirePaused();
            _;
        }
        /**
         * @dev Returns true if the contract is paused, and false otherwise.
         */
        function paused() public view virtual returns (bool) {
            return _paused;
        }
        /**
         * @dev Throws if the contract is paused.
         */
        function _requireNotPaused() internal view virtual {
            require(!paused(), "Pausable: paused");
        }
        /**
         * @dev Throws if the contract is not paused.
         */
        function _requirePaused() internal view virtual {
            require(paused(), "Pausable: not paused");
        }
        /**
         * @dev Triggers stopped state.
         *
         * Requirements:
         *
         * - The contract must not be paused.
         */
        function _pause() internal virtual whenNotPaused {
            _paused = true;
            emit Paused(_msgSender());
        }
        /**
         * @dev Returns to normal state.
         *
         * Requirements:
         *
         * - The contract must be paused.
         */
        function _unpause() internal virtual whenPaused {
            _paused = false;
            emit Unpaused(_msgSender());
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)
    pragma solidity ^0.8.0;
    import "./IERC20.sol";
    import "./extensions/IERC20Metadata.sol";
    import "../../utils/Context.sol";
    /**
     * @dev Implementation of the {IERC20} interface.
     *
     * This implementation is agnostic to the way tokens are created. This means
     * that a supply mechanism has to be added in a derived contract using {_mint}.
     * For a generic mechanism see {ERC20PresetMinterPauser}.
     *
     * TIP: For a detailed writeup see our guide
     * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
     * to implement supply mechanisms].
     *
     * We have followed general OpenZeppelin Contracts guidelines: functions revert
     * instead returning `false` on failure. This behavior is nonetheless
     * conventional and does not conflict with the expectations of ERC20
     * applications.
     *
     * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
     * This allows applications to reconstruct the allowance for all accounts just
     * by listening to said events. Other implementations of the EIP may not emit
     * these events, as it isn't required by the specification.
     *
     * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
     * functions have been added to mitigate the well-known issues around setting
     * allowances. See {IERC20-approve}.
     */
    contract ERC20 is Context, IERC20, IERC20Metadata {
        mapping(address => uint256) private _balances;
        mapping(address => mapping(address => uint256)) private _allowances;
        uint256 private _totalSupply;
        string private _name;
        string private _symbol;
        /**
         * @dev Sets the values for {name} and {symbol}.
         *
         * The default value of {decimals} is 18. To select a different value for
         * {decimals} you should overload it.
         *
         * All two of these values are immutable: they can only be set once during
         * construction.
         */
        constructor(string memory name_, string memory symbol_) {
            _name = name_;
            _symbol = symbol_;
        }
        /**
         * @dev Returns the name of the token.
         */
        function name() public view virtual override returns (string memory) {
            return _name;
        }
        /**
         * @dev Returns the symbol of the token, usually a shorter version of the
         * name.
         */
        function symbol() public view virtual override returns (string memory) {
            return _symbol;
        }
        /**
         * @dev Returns the number of decimals used to get its user representation.
         * For example, if `decimals` equals `2`, a balance of `505` tokens should
         * be displayed to a user as `5.05` (`505 / 10 ** 2`).
         *
         * Tokens usually opt for a value of 18, imitating the relationship between
         * Ether and Wei. This is the value {ERC20} uses, unless this function is
         * overridden;
         *
         * NOTE: This information is only used for _display_ purposes: it in
         * no way affects any of the arithmetic of the contract, including
         * {IERC20-balanceOf} and {IERC20-transfer}.
         */
        function decimals() public view virtual override returns (uint8) {
            return 18;
        }
        /**
         * @dev See {IERC20-totalSupply}.
         */
        function totalSupply() public view virtual override returns (uint256) {
            return _totalSupply;
        }
        /**
         * @dev See {IERC20-balanceOf}.
         */
        function balanceOf(address account) public view virtual override returns (uint256) {
            return _balances[account];
        }
        /**
         * @dev See {IERC20-transfer}.
         *
         * Requirements:
         *
         * - `to` cannot be the zero address.
         * - the caller must have a balance of at least `amount`.
         */
        function transfer(address to, uint256 amount) public virtual override returns (bool) {
            address owner = _msgSender();
            _transfer(owner, to, amount);
            return true;
        }
        /**
         * @dev See {IERC20-allowance}.
         */
        function allowance(address owner, address spender) public view virtual override returns (uint256) {
            return _allowances[owner][spender];
        }
        /**
         * @dev See {IERC20-approve}.
         *
         * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
         * `transferFrom`. This is semantically equivalent to an infinite approval.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         */
        function approve(address spender, uint256 amount) public virtual override returns (bool) {
            address owner = _msgSender();
            _approve(owner, spender, amount);
            return true;
        }
        /**
         * @dev See {IERC20-transferFrom}.
         *
         * Emits an {Approval} event indicating the updated allowance. This is not
         * required by the EIP. See the note at the beginning of {ERC20}.
         *
         * NOTE: Does not update the allowance if the current allowance
         * is the maximum `uint256`.
         *
         * Requirements:
         *
         * - `from` and `to` cannot be the zero address.
         * - `from` must have a balance of at least `amount`.
         * - the caller must have allowance for ``from``'s tokens of at least
         * `amount`.
         */
        function transferFrom(
            address from,
            address to,
            uint256 amount
        ) public virtual override returns (bool) {
            address spender = _msgSender();
            _spendAllowance(from, spender, amount);
            _transfer(from, to, amount);
            return true;
        }
        /**
         * @dev Atomically increases the allowance granted to `spender` by the caller.
         *
         * This is an alternative to {approve} that can be used as a mitigation for
         * problems described in {IERC20-approve}.
         *
         * Emits an {Approval} event indicating the updated allowance.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         */
        function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
            address owner = _msgSender();
            _approve(owner, spender, allowance(owner, spender) + addedValue);
            return true;
        }
        /**
         * @dev Atomically decreases the allowance granted to `spender` by the caller.
         *
         * This is an alternative to {approve} that can be used as a mitigation for
         * problems described in {IERC20-approve}.
         *
         * Emits an {Approval} event indicating the updated allowance.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         * - `spender` must have allowance for the caller of at least
         * `subtractedValue`.
         */
        function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
            address owner = _msgSender();
            uint256 currentAllowance = allowance(owner, spender);
            require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
            unchecked {
                _approve(owner, spender, currentAllowance - subtractedValue);
            }
            return true;
        }
        /**
         * @dev Moves `amount` of tokens from `from` to `to`.
         *
         * This internal function is equivalent to {transfer}, and can be used to
         * e.g. implement automatic token fees, slashing mechanisms, etc.
         *
         * Emits a {Transfer} event.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `from` must have a balance of at least `amount`.
         */
        function _transfer(
            address from,
            address to,
            uint256 amount
        ) internal virtual {
            require(from != address(0), "ERC20: transfer from the zero address");
            require(to != address(0), "ERC20: transfer to the zero address");
            _beforeTokenTransfer(from, to, amount);
            uint256 fromBalance = _balances[from];
            require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
            unchecked {
                _balances[from] = fromBalance - amount;
            }
            _balances[to] += amount;
            emit Transfer(from, to, amount);
            _afterTokenTransfer(from, to, amount);
        }
        /** @dev Creates `amount` tokens and assigns them to `account`, increasing
         * the total supply.
         *
         * Emits a {Transfer} event with `from` set to the zero address.
         *
         * Requirements:
         *
         * - `account` cannot be the zero address.
         */
        function _mint(address account, uint256 amount) internal virtual {
            require(account != address(0), "ERC20: mint to the zero address");
            _beforeTokenTransfer(address(0), account, amount);
            _totalSupply += amount;
            _balances[account] += amount;
            emit Transfer(address(0), account, amount);
            _afterTokenTransfer(address(0), account, amount);
        }
        /**
         * @dev Destroys `amount` tokens from `account`, reducing the
         * total supply.
         *
         * Emits a {Transfer} event with `to` set to the zero address.
         *
         * Requirements:
         *
         * - `account` cannot be the zero address.
         * - `account` must have at least `amount` tokens.
         */
        function _burn(address account, uint256 amount) internal virtual {
            require(account != address(0), "ERC20: burn from the zero address");
            _beforeTokenTransfer(account, address(0), amount);
            uint256 accountBalance = _balances[account];
            require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
            unchecked {
                _balances[account] = accountBalance - amount;
            }
            _totalSupply -= amount;
            emit Transfer(account, address(0), amount);
            _afterTokenTransfer(account, address(0), amount);
        }
        /**
         * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
         *
         * This internal function is equivalent to `approve`, and can be used to
         * e.g. set automatic allowances for certain subsystems, etc.
         *
         * Emits an {Approval} event.
         *
         * Requirements:
         *
         * - `owner` cannot be the zero address.
         * - `spender` cannot be the zero address.
         */
        function _approve(
            address owner,
            address spender,
            uint256 amount
        ) internal virtual {
            require(owner != address(0), "ERC20: approve from the zero address");
            require(spender != address(0), "ERC20: approve to the zero address");
            _allowances[owner][spender] = amount;
            emit Approval(owner, spender, amount);
        }
        /**
         * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
         *
         * Does not update the allowance amount in case of infinite allowance.
         * Revert if not enough allowance is available.
         *
         * Might emit an {Approval} event.
         */
        function _spendAllowance(
            address owner,
            address spender,
            uint256 amount
        ) internal virtual {
            uint256 currentAllowance = allowance(owner, spender);
            if (currentAllowance != type(uint256).max) {
                require(currentAllowance >= amount, "ERC20: insufficient allowance");
                unchecked {
                    _approve(owner, spender, currentAllowance - amount);
                }
            }
        }
        /**
         * @dev Hook that is called before any transfer of tokens. This includes
         * minting and burning.
         *
         * Calling conditions:
         *
         * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
         * will be transferred to `to`.
         * - when `from` is zero, `amount` tokens will be minted for `to`.
         * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
         * - `from` and `to` are never both zero.
         *
         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
         */
        function _beforeTokenTransfer(
            address from,
            address to,
            uint256 amount
        ) internal virtual {}
        /**
         * @dev Hook that is called after any transfer of tokens. This includes
         * minting and burning.
         *
         * Calling conditions:
         *
         * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
         * has been transferred to `to`.
         * - when `from` is zero, `amount` tokens have been minted for `to`.
         * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
         * - `from` and `to` are never both zero.
         *
         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
         */
        function _afterTokenTransfer(
            address from,
            address to,
            uint256 amount
        ) internal virtual {}
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
    pragma solidity ^0.8.0;
    import "../utils/Context.sol";
    /**
     * @dev Contract module which provides a basic access control mechanism, where
     * there is an account (an owner) that can be granted exclusive access to
     * specific functions.
     *
     * By default, the owner account will be the one that deploys the contract. This
     * can later be changed with {transferOwnership}.
     *
     * This module is used through inheritance. It will make available the modifier
     * `onlyOwner`, which can be applied to your functions to restrict their use to
     * the owner.
     */
    abstract contract Ownable is Context {
        address private _owner;
        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
        /**
         * @dev Initializes the contract setting the deployer as the initial owner.
         */
        constructor() {
            _transferOwnership(_msgSender());
        }
        /**
         * @dev Throws if called by any account other than the owner.
         */
        modifier onlyOwner() {
            _checkOwner();
            _;
        }
        /**
         * @dev Returns the address of the current owner.
         */
        function owner() public view virtual returns (address) {
            return _owner;
        }
        /**
         * @dev Throws if the sender is not the owner.
         */
        function _checkOwner() internal view virtual {
            require(owner() == _msgSender(), "Ownable: caller is not the owner");
        }
        /**
         * @dev Leaves the contract without owner. It will not be possible to call
         * `onlyOwner` functions anymore. Can only be called by the current owner.
         *
         * NOTE: Renouncing ownership will leave the contract without an owner,
         * thereby removing any functionality that is only available to the owner.
         */
        function renounceOwnership() public virtual onlyOwner {
            _transferOwnership(address(0));
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`).
         * Can only be called by the current owner.
         */
        function transferOwnership(address newOwner) public virtual onlyOwner {
            require(newOwner != address(0), "Ownable: new owner is the zero address");
            _transferOwnership(newOwner);
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`).
         * Internal function without access restriction.
         */
        function _transferOwnership(address newOwner) internal virtual {
            address oldOwner = _owner;
            _owner = newOwner;
            emit OwnershipTransferred(oldOwner, newOwner);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)
    pragma solidity ^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 uint248 from uint256, reverting on
         * overflow (when the input is greater than largest uint248).
         *
         * Counterpart to Solidity's `uint248` operator.
         *
         * Requirements:
         *
         * - input must fit into 248 bits
         *
         * _Available since v4.7._
         */
        function toUint248(uint256 value) internal pure returns (uint248) {
            require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
            return uint248(value);
        }
        /**
         * @dev Returns the downcasted uint240 from uint256, reverting on
         * overflow (when the input is greater than largest uint240).
         *
         * Counterpart to Solidity's `uint240` operator.
         *
         * Requirements:
         *
         * - input must fit into 240 bits
         *
         * _Available since v4.7._
         */
        function toUint240(uint256 value) internal pure returns (uint240) {
            require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
            return uint240(value);
        }
        /**
         * @dev Returns the downcasted uint232 from uint256, reverting on
         * overflow (when the input is greater than largest uint232).
         *
         * Counterpart to Solidity's `uint232` operator.
         *
         * Requirements:
         *
         * - input must fit into 232 bits
         *
         * _Available since v4.7._
         */
        function toUint232(uint256 value) internal pure returns (uint232) {
            require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
            return uint232(value);
        }
        /**
         * @dev Returns the downcasted uint224 from uint256, reverting on
         * overflow (when the input is greater than largest uint224).
         *
         * Counterpart to Solidity's `uint224` operator.
         *
         * Requirements:
         *
         * - input must fit into 224 bits
         *
         * _Available since v4.2._
         */
        function toUint224(uint256 value) internal pure returns (uint224) {
            require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
            return uint224(value);
        }
        /**
         * @dev Returns the downcasted uint216 from uint256, reverting on
         * overflow (when the input is greater than largest uint216).
         *
         * Counterpart to Solidity's `uint216` operator.
         *
         * Requirements:
         *
         * - input must fit into 216 bits
         *
         * _Available since v4.7._
         */
        function toUint216(uint256 value) internal pure returns (uint216) {
            require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
            return uint216(value);
        }
        /**
         * @dev Returns the downcasted uint208 from uint256, reverting on
         * overflow (when the input is greater than largest uint208).
         *
         * Counterpart to Solidity's `uint208` operator.
         *
         * Requirements:
         *
         * - input must fit into 208 bits
         *
         * _Available since v4.7._
         */
        function toUint208(uint256 value) internal pure returns (uint208) {
            require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
            return uint208(value);
        }
        /**
         * @dev Returns the downcasted uint200 from uint256, reverting on
         * overflow (when the input is greater than largest uint200).
         *
         * Counterpart to Solidity's `uint200` operator.
         *
         * Requirements:
         *
         * - input must fit into 200 bits
         *
         * _Available since v4.7._
         */
        function toUint200(uint256 value) internal pure returns (uint200) {
            require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
            return uint200(value);
        }
        /**
         * @dev Returns the downcasted uint192 from uint256, reverting on
         * overflow (when the input is greater than largest uint192).
         *
         * Counterpart to Solidity's `uint192` operator.
         *
         * Requirements:
         *
         * - input must fit into 192 bits
         *
         * _Available since v4.7._
         */
        function toUint192(uint256 value) internal pure returns (uint192) {
            require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
            return uint192(value);
        }
        /**
         * @dev Returns the downcasted uint184 from uint256, reverting on
         * overflow (when the input is greater than largest uint184).
         *
         * Counterpart to Solidity's `uint184` operator.
         *
         * Requirements:
         *
         * - input must fit into 184 bits
         *
         * _Available since v4.7._
         */
        function toUint184(uint256 value) internal pure returns (uint184) {
            require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
            return uint184(value);
        }
        /**
         * @dev Returns the downcasted uint176 from uint256, reverting on
         * overflow (when the input is greater than largest uint176).
         *
         * Counterpart to Solidity's `uint176` operator.
         *
         * Requirements:
         *
         * - input must fit into 176 bits
         *
         * _Available since v4.7._
         */
        function toUint176(uint256 value) internal pure returns (uint176) {
            require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
            return uint176(value);
        }
        /**
         * @dev Returns the downcasted uint168 from uint256, reverting on
         * overflow (when the input is greater than largest uint168).
         *
         * Counterpart to Solidity's `uint168` operator.
         *
         * Requirements:
         *
         * - input must fit into 168 bits
         *
         * _Available since v4.7._
         */
        function toUint168(uint256 value) internal pure returns (uint168) {
            require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
            return uint168(value);
        }
        /**
         * @dev Returns the downcasted uint160 from uint256, reverting on
         * overflow (when the input is greater than largest uint160).
         *
         * Counterpart to Solidity's `uint160` operator.
         *
         * Requirements:
         *
         * - input must fit into 160 bits
         *
         * _Available since v4.7._
         */
        function toUint160(uint256 value) internal pure returns (uint160) {
            require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
            return uint160(value);
        }
        /**
         * @dev Returns the downcasted uint152 from uint256, reverting on
         * overflow (when the input is greater than largest uint152).
         *
         * Counterpart to Solidity's `uint152` operator.
         *
         * Requirements:
         *
         * - input must fit into 152 bits
         *
         * _Available since v4.7._
         */
        function toUint152(uint256 value) internal pure returns (uint152) {
            require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
            return uint152(value);
        }
        /**
         * @dev Returns the downcasted uint144 from uint256, reverting on
         * overflow (when the input is greater than largest uint144).
         *
         * Counterpart to Solidity's `uint144` operator.
         *
         * Requirements:
         *
         * - input must fit into 144 bits
         *
         * _Available since v4.7._
         */
        function toUint144(uint256 value) internal pure returns (uint144) {
            require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
            return uint144(value);
        }
        /**
         * @dev Returns the downcasted uint136 from uint256, reverting on
         * overflow (when the input is greater than largest uint136).
         *
         * Counterpart to Solidity's `uint136` operator.
         *
         * Requirements:
         *
         * - input must fit into 136 bits
         *
         * _Available since v4.7._
         */
        function toUint136(uint256 value) internal pure returns (uint136) {
            require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
            return uint136(value);
        }
        /**
         * @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
         *
         * _Available since v2.5._
         */
        function toUint128(uint256 value) internal pure returns (uint128) {
            require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
            return uint128(value);
        }
        /**
         * @dev Returns the downcasted uint120 from uint256, reverting on
         * overflow (when the input is greater than largest uint120).
         *
         * Counterpart to Solidity's `uint120` operator.
         *
         * Requirements:
         *
         * - input must fit into 120 bits
         *
         * _Available since v4.7._
         */
        function toUint120(uint256 value) internal pure returns (uint120) {
            require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
            return uint120(value);
        }
        /**
         * @dev Returns the downcasted uint112 from uint256, reverting on
         * overflow (when the input is greater than largest uint112).
         *
         * Counterpart to Solidity's `uint112` operator.
         *
         * Requirements:
         *
         * - input must fit into 112 bits
         *
         * _Available since v4.7._
         */
        function toUint112(uint256 value) internal pure returns (uint112) {
            require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
            return uint112(value);
        }
        /**
         * @dev Returns the downcasted uint104 from uint256, reverting on
         * overflow (when the input is greater than largest uint104).
         *
         * Counterpart to Solidity's `uint104` operator.
         *
         * Requirements:
         *
         * - input must fit into 104 bits
         *
         * _Available since v4.7._
         */
        function toUint104(uint256 value) internal pure returns (uint104) {
            require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
            return uint104(value);
        }
        /**
         * @dev Returns the downcasted uint96 from uint256, reverting on
         * overflow (when the input is greater than largest uint96).
         *
         * Counterpart to Solidity's `uint96` operator.
         *
         * Requirements:
         *
         * - input must fit into 96 bits
         *
         * _Available since v4.2._
         */
        function toUint96(uint256 value) internal pure returns (uint96) {
            require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
            return uint96(value);
        }
        /**
         * @dev Returns the downcasted uint88 from uint256, reverting on
         * overflow (when the input is greater than largest uint88).
         *
         * Counterpart to Solidity's `uint88` operator.
         *
         * Requirements:
         *
         * - input must fit into 88 bits
         *
         * _Available since v4.7._
         */
        function toUint88(uint256 value) internal pure returns (uint88) {
            require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
            return uint88(value);
        }
        /**
         * @dev Returns the downcasted uint80 from uint256, reverting on
         * overflow (when the input is greater than largest uint80).
         *
         * Counterpart to Solidity's `uint80` operator.
         *
         * Requirements:
         *
         * - input must fit into 80 bits
         *
         * _Available since v4.7._
         */
        function toUint80(uint256 value) internal pure returns (uint80) {
            require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
            return uint80(value);
        }
        /**
         * @dev Returns the downcasted uint72 from uint256, reverting on
         * overflow (when the input is greater than largest uint72).
         *
         * Counterpart to Solidity's `uint72` operator.
         *
         * Requirements:
         *
         * - input must fit into 72 bits
         *
         * _Available since v4.7._
         */
        function toUint72(uint256 value) internal pure returns (uint72) {
            require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
            return uint72(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
         *
         * _Available since v2.5._
         */
        function toUint64(uint256 value) internal pure returns (uint64) {
            require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
            return uint64(value);
        }
        /**
         * @dev Returns the downcasted uint56 from uint256, reverting on
         * overflow (when the input is greater than largest uint56).
         *
         * Counterpart to Solidity's `uint56` operator.
         *
         * Requirements:
         *
         * - input must fit into 56 bits
         *
         * _Available since v4.7._
         */
        function toUint56(uint256 value) internal pure returns (uint56) {
            require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
            return uint56(value);
        }
        /**
         * @dev Returns the downcasted uint48 from uint256, reverting on
         * overflow (when the input is greater than largest uint48).
         *
         * Counterpart to Solidity's `uint48` operator.
         *
         * Requirements:
         *
         * - input must fit into 48 bits
         *
         * _Available since v4.7._
         */
        function toUint48(uint256 value) internal pure returns (uint48) {
            require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
            return uint48(value);
        }
        /**
         * @dev Returns the downcasted uint40 from uint256, reverting on
         * overflow (when the input is greater than largest uint40).
         *
         * Counterpart to Solidity's `uint40` operator.
         *
         * Requirements:
         *
         * - input must fit into 40 bits
         *
         * _Available since v4.7._
         */
        function toUint40(uint256 value) internal pure returns (uint40) {
            require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
            return uint40(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
         *
         * _Available since v2.5._
         */
        function toUint32(uint256 value) internal pure returns (uint32) {
            require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
            return uint32(value);
        }
        /**
         * @dev Returns the downcasted uint24 from uint256, reverting on
         * overflow (when the input is greater than largest uint24).
         *
         * Counterpart to Solidity's `uint24` operator.
         *
         * Requirements:
         *
         * - input must fit into 24 bits
         *
         * _Available since v4.7._
         */
        function toUint24(uint256 value) internal pure returns (uint24) {
            require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
            return uint24(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
         *
         * _Available since v2.5._
         */
        function toUint16(uint256 value) internal pure returns (uint16) {
            require(value <= type(uint16).max, "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
         *
         * _Available since v2.5._
         */
        function toUint8(uint256 value) internal pure returns (uint8) {
            require(value <= type(uint8).max, "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.
         *
         * _Available since v3.0._
         */
        function toUint256(int256 value) internal pure returns (uint256) {
            require(value >= 0, "SafeCast: value must be positive");
            return uint256(value);
        }
        /**
         * @dev Returns the downcasted int248 from int256, reverting on
         * overflow (when the input is less than smallest int248 or
         * greater than largest int248).
         *
         * Counterpart to Solidity's `int248` operator.
         *
         * Requirements:
         *
         * - input must fit into 248 bits
         *
         * _Available since v4.7._
         */
        function toInt248(int256 value) internal pure returns (int248) {
            require(value >= type(int248).min && value <= type(int248).max, "SafeCast: value doesn't fit in 248 bits");
            return int248(value);
        }
        /**
         * @dev Returns the downcasted int240 from int256, reverting on
         * overflow (when the input is less than smallest int240 or
         * greater than largest int240).
         *
         * Counterpart to Solidity's `int240` operator.
         *
         * Requirements:
         *
         * - input must fit into 240 bits
         *
         * _Available since v4.7._
         */
        function toInt240(int256 value) internal pure returns (int240) {
            require(value >= type(int240).min && value <= type(int240).max, "SafeCast: value doesn't fit in 240 bits");
            return int240(value);
        }
        /**
         * @dev Returns the downcasted int232 from int256, reverting on
         * overflow (when the input is less than smallest int232 or
         * greater than largest int232).
         *
         * Counterpart to Solidity's `int232` operator.
         *
         * Requirements:
         *
         * - input must fit into 232 bits
         *
         * _Available since v4.7._
         */
        function toInt232(int256 value) internal pure returns (int232) {
            require(value >= type(int232).min && value <= type(int232).max, "SafeCast: value doesn't fit in 232 bits");
            return int232(value);
        }
        /**
         * @dev Returns the downcasted int224 from int256, reverting on
         * overflow (when the input is less than smallest int224 or
         * greater than largest int224).
         *
         * Counterpart to Solidity's `int224` operator.
         *
         * Requirements:
         *
         * - input must fit into 224 bits
         *
         * _Available since v4.7._
         */
        function toInt224(int256 value) internal pure returns (int224) {
            require(value >= type(int224).min && value <= type(int224).max, "SafeCast: value doesn't fit in 224 bits");
            return int224(value);
        }
        /**
         * @dev Returns the downcasted int216 from int256, reverting on
         * overflow (when the input is less than smallest int216 or
         * greater than largest int216).
         *
         * Counterpart to Solidity's `int216` operator.
         *
         * Requirements:
         *
         * - input must fit into 216 bits
         *
         * _Available since v4.7._
         */
        function toInt216(int256 value) internal pure returns (int216) {
            require(value >= type(int216).min && value <= type(int216).max, "SafeCast: value doesn't fit in 216 bits");
            return int216(value);
        }
        /**
         * @dev Returns the downcasted int208 from int256, reverting on
         * overflow (when the input is less than smallest int208 or
         * greater than largest int208).
         *
         * Counterpart to Solidity's `int208` operator.
         *
         * Requirements:
         *
         * - input must fit into 208 bits
         *
         * _Available since v4.7._
         */
        function toInt208(int256 value) internal pure returns (int208) {
            require(value >= type(int208).min && value <= type(int208).max, "SafeCast: value doesn't fit in 208 bits");
            return int208(value);
        }
        /**
         * @dev Returns the downcasted int200 from int256, reverting on
         * overflow (when the input is less than smallest int200 or
         * greater than largest int200).
         *
         * Counterpart to Solidity's `int200` operator.
         *
         * Requirements:
         *
         * - input must fit into 200 bits
         *
         * _Available since v4.7._
         */
        function toInt200(int256 value) internal pure returns (int200) {
            require(value >= type(int200).min && value <= type(int200).max, "SafeCast: value doesn't fit in 200 bits");
            return int200(value);
        }
        /**
         * @dev Returns the downcasted int192 from int256, reverting on
         * overflow (when the input is less than smallest int192 or
         * greater than largest int192).
         *
         * Counterpart to Solidity's `int192` operator.
         *
         * Requirements:
         *
         * - input must fit into 192 bits
         *
         * _Available since v4.7._
         */
        function toInt192(int256 value) internal pure returns (int192) {
            require(value >= type(int192).min && value <= type(int192).max, "SafeCast: value doesn't fit in 192 bits");
            return int192(value);
        }
        /**
         * @dev Returns the downcasted int184 from int256, reverting on
         * overflow (when the input is less than smallest int184 or
         * greater than largest int184).
         *
         * Counterpart to Solidity's `int184` operator.
         *
         * Requirements:
         *
         * - input must fit into 184 bits
         *
         * _Available since v4.7._
         */
        function toInt184(int256 value) internal pure returns (int184) {
            require(value >= type(int184).min && value <= type(int184).max, "SafeCast: value doesn't fit in 184 bits");
            return int184(value);
        }
        /**
         * @dev Returns the downcasted int176 from int256, reverting on
         * overflow (when the input is less than smallest int176 or
         * greater than largest int176).
         *
         * Counterpart to Solidity's `int176` operator.
         *
         * Requirements:
         *
         * - input must fit into 176 bits
         *
         * _Available since v4.7._
         */
        function toInt176(int256 value) internal pure returns (int176) {
            require(value >= type(int176).min && value <= type(int176).max, "SafeCast: value doesn't fit in 176 bits");
            return int176(value);
        }
        /**
         * @dev Returns the downcasted int168 from int256, reverting on
         * overflow (when the input is less than smallest int168 or
         * greater than largest int168).
         *
         * Counterpart to Solidity's `int168` operator.
         *
         * Requirements:
         *
         * - input must fit into 168 bits
         *
         * _Available since v4.7._
         */
        function toInt168(int256 value) internal pure returns (int168) {
            require(value >= type(int168).min && value <= type(int168).max, "SafeCast: value doesn't fit in 168 bits");
            return int168(value);
        }
        /**
         * @dev Returns the downcasted int160 from int256, reverting on
         * overflow (when the input is less than smallest int160 or
         * greater than largest int160).
         *
         * Counterpart to Solidity's `int160` operator.
         *
         * Requirements:
         *
         * - input must fit into 160 bits
         *
         * _Available since v4.7._
         */
        function toInt160(int256 value) internal pure returns (int160) {
            require(value >= type(int160).min && value <= type(int160).max, "SafeCast: value doesn't fit in 160 bits");
            return int160(value);
        }
        /**
         * @dev Returns the downcasted int152 from int256, reverting on
         * overflow (when the input is less than smallest int152 or
         * greater than largest int152).
         *
         * Counterpart to Solidity's `int152` operator.
         *
         * Requirements:
         *
         * - input must fit into 152 bits
         *
         * _Available since v4.7._
         */
        function toInt152(int256 value) internal pure returns (int152) {
            require(value >= type(int152).min && value <= type(int152).max, "SafeCast: value doesn't fit in 152 bits");
            return int152(value);
        }
        /**
         * @dev Returns the downcasted int144 from int256, reverting on
         * overflow (when the input is less than smallest int144 or
         * greater than largest int144).
         *
         * Counterpart to Solidity's `int144` operator.
         *
         * Requirements:
         *
         * - input must fit into 144 bits
         *
         * _Available since v4.7._
         */
        function toInt144(int256 value) internal pure returns (int144) {
            require(value >= type(int144).min && value <= type(int144).max, "SafeCast: value doesn't fit in 144 bits");
            return int144(value);
        }
        /**
         * @dev Returns the downcasted int136 from int256, reverting on
         * overflow (when the input is less than smallest int136 or
         * greater than largest int136).
         *
         * Counterpart to Solidity's `int136` operator.
         *
         * Requirements:
         *
         * - input must fit into 136 bits
         *
         * _Available since v4.7._
         */
        function toInt136(int256 value) internal pure returns (int136) {
            require(value >= type(int136).min && value <= type(int136).max, "SafeCast: value doesn't fit in 136 bits");
            return int136(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 >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
            return int128(value);
        }
        /**
         * @dev Returns the downcasted int120 from int256, reverting on
         * overflow (when the input is less than smallest int120 or
         * greater than largest int120).
         *
         * Counterpart to Solidity's `int120` operator.
         *
         * Requirements:
         *
         * - input must fit into 120 bits
         *
         * _Available since v4.7._
         */
        function toInt120(int256 value) internal pure returns (int120) {
            require(value >= type(int120).min && value <= type(int120).max, "SafeCast: value doesn't fit in 120 bits");
            return int120(value);
        }
        /**
         * @dev Returns the downcasted int112 from int256, reverting on
         * overflow (when the input is less than smallest int112 or
         * greater than largest int112).
         *
         * Counterpart to Solidity's `int112` operator.
         *
         * Requirements:
         *
         * - input must fit into 112 bits
         *
         * _Available since v4.7._
         */
        function toInt112(int256 value) internal pure returns (int112) {
            require(value >= type(int112).min && value <= type(int112).max, "SafeCast: value doesn't fit in 112 bits");
            return int112(value);
        }
        /**
         * @dev Returns the downcasted int104 from int256, reverting on
         * overflow (when the input is less than smallest int104 or
         * greater than largest int104).
         *
         * Counterpart to Solidity's `int104` operator.
         *
         * Requirements:
         *
         * - input must fit into 104 bits
         *
         * _Available since v4.7._
         */
        function toInt104(int256 value) internal pure returns (int104) {
            require(value >= type(int104).min && value <= type(int104).max, "SafeCast: value doesn't fit in 104 bits");
            return int104(value);
        }
        /**
         * @dev Returns the downcasted int96 from int256, reverting on
         * overflow (when the input is less than smallest int96 or
         * greater than largest int96).
         *
         * Counterpart to Solidity's `int96` operator.
         *
         * Requirements:
         *
         * - input must fit into 96 bits
         *
         * _Available since v4.7._
         */
        function toInt96(int256 value) internal pure returns (int96) {
            require(value >= type(int96).min && value <= type(int96).max, "SafeCast: value doesn't fit in 96 bits");
            return int96(value);
        }
        /**
         * @dev Returns the downcasted int88 from int256, reverting on
         * overflow (when the input is less than smallest int88 or
         * greater than largest int88).
         *
         * Counterpart to Solidity's `int88` operator.
         *
         * Requirements:
         *
         * - input must fit into 88 bits
         *
         * _Available since v4.7._
         */
        function toInt88(int256 value) internal pure returns (int88) {
            require(value >= type(int88).min && value <= type(int88).max, "SafeCast: value doesn't fit in 88 bits");
            return int88(value);
        }
        /**
         * @dev Returns the downcasted int80 from int256, reverting on
         * overflow (when the input is less than smallest int80 or
         * greater than largest int80).
         *
         * Counterpart to Solidity's `int80` operator.
         *
         * Requirements:
         *
         * - input must fit into 80 bits
         *
         * _Available since v4.7._
         */
        function toInt80(int256 value) internal pure returns (int80) {
            require(value >= type(int80).min && value <= type(int80).max, "SafeCast: value doesn't fit in 80 bits");
            return int80(value);
        }
        /**
         * @dev Returns the downcasted int72 from int256, reverting on
         * overflow (when the input is less than smallest int72 or
         * greater than largest int72).
         *
         * Counterpart to Solidity's `int72` operator.
         *
         * Requirements:
         *
         * - input must fit into 72 bits
         *
         * _Available since v4.7._
         */
        function toInt72(int256 value) internal pure returns (int72) {
            require(value >= type(int72).min && value <= type(int72).max, "SafeCast: value doesn't fit in 72 bits");
            return int72(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 >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
            return int64(value);
        }
        /**
         * @dev Returns the downcasted int56 from int256, reverting on
         * overflow (when the input is less than smallest int56 or
         * greater than largest int56).
         *
         * Counterpart to Solidity's `int56` operator.
         *
         * Requirements:
         *
         * - input must fit into 56 bits
         *
         * _Available since v4.7._
         */
        function toInt56(int256 value) internal pure returns (int56) {
            require(value >= type(int56).min && value <= type(int56).max, "SafeCast: value doesn't fit in 56 bits");
            return int56(value);
        }
        /**
         * @dev Returns the downcasted int48 from int256, reverting on
         * overflow (when the input is less than smallest int48 or
         * greater than largest int48).
         *
         * Counterpart to Solidity's `int48` operator.
         *
         * Requirements:
         *
         * - input must fit into 48 bits
         *
         * _Available since v4.7._
         */
        function toInt48(int256 value) internal pure returns (int48) {
            require(value >= type(int48).min && value <= type(int48).max, "SafeCast: value doesn't fit in 48 bits");
            return int48(value);
        }
        /**
         * @dev Returns the downcasted int40 from int256, reverting on
         * overflow (when the input is less than smallest int40 or
         * greater than largest int40).
         *
         * Counterpart to Solidity's `int40` operator.
         *
         * Requirements:
         *
         * - input must fit into 40 bits
         *
         * _Available since v4.7._
         */
        function toInt40(int256 value) internal pure returns (int40) {
            require(value >= type(int40).min && value <= type(int40).max, "SafeCast: value doesn't fit in 40 bits");
            return int40(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 >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
            return int32(value);
        }
        /**
         * @dev Returns the downcasted int24 from int256, reverting on
         * overflow (when the input is less than smallest int24 or
         * greater than largest int24).
         *
         * Counterpart to Solidity's `int24` operator.
         *
         * Requirements:
         *
         * - input must fit into 24 bits
         *
         * _Available since v4.7._
         */
        function toInt24(int256 value) internal pure returns (int24) {
            require(value >= type(int24).min && value <= type(int24).max, "SafeCast: value doesn't fit in 24 bits");
            return int24(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 >= type(int16).min && value <= type(int16).max, "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 >= type(int8).min && value <= type(int8).max, "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.
         *
         * _Available since v3.0._
         */
        function toInt256(uint256 value) internal pure returns (int256) {
            // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
            require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
            return int256(value);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)
    pragma solidity ^0.8.0;
    import "../token/ERC20/IERC20.sol";
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)
    pragma solidity ^0.8.0;
    import "../IERC20.sol";
    import "../extensions/draft-IERC20Permit.sol";
    import "../../../utils/Address.sol";
    /**
     * @title SafeERC20
     * @dev Wrappers around ERC20 operations that throw on failure (when the token
     * contract returns false). Tokens that return no value (and instead revert or
     * throw on failure) are also supported, non-reverting calls are assumed to be
     * successful.
     * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
     * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
     */
    library SafeERC20 {
        using Address for address;
        function safeTransfer(
            IERC20 token,
            address to,
            uint256 value
        ) internal {
            _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
        }
        function safeTransferFrom(
            IERC20 token,
            address from,
            address to,
            uint256 value
        ) internal {
            _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
        }
        /**
         * @dev Deprecated. This function has issues similar to the ones found in
         * {IERC20-approve}, and its usage is discouraged.
         *
         * Whenever possible, use {safeIncreaseAllowance} and
         * {safeDecreaseAllowance} instead.
         */
        function safeApprove(
            IERC20 token,
            address spender,
            uint256 value
        ) internal {
            // safeApprove should only be called when setting an initial allowance,
            // or when resetting it to zero. To increase and decrease it, use
            // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
            require(
                (value == 0) || (token.allowance(address(this), spender) == 0),
                "SafeERC20: approve from non-zero to non-zero allowance"
            );
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
        }
        function safeIncreaseAllowance(
            IERC20 token,
            address spender,
            uint256 value
        ) internal {
            uint256 newAllowance = token.allowance(address(this), spender) + value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
        function safeDecreaseAllowance(
            IERC20 token,
            address spender,
            uint256 value
        ) internal {
            unchecked {
                uint256 oldAllowance = token.allowance(address(this), spender);
                require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                uint256 newAllowance = oldAllowance - value;
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
            }
        }
        function safePermit(
            IERC20Permit token,
            address owner,
            address spender,
            uint256 value,
            uint256 deadline,
            uint8 v,
            bytes32 r,
            bytes32 s
        ) internal {
            uint256 nonceBefore = token.nonces(owner);
            token.permit(owner, spender, value, deadline, v, r, s);
            uint256 nonceAfter = token.nonces(owner);
            require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
        }
        /**
         * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
         * on the return value: the return value is optional (but if data is returned, it must not be false).
         * @param token The token targeted by the call.
         * @param data The call data (encoded using abi.encode or one of its variants).
         */
        function _callOptionalReturn(IERC20 token, bytes memory data) private {
            // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
            // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
            // the target address contains contract code and also asserts for success in the low-level call.
            bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
            if (returndata.length > 0) {
                // Return data is optional
                require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
     * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
     *
     * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
     * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
     * need to send a transaction, and thus is not required to hold Ether at all.
     */
    interface IERC20Permit {
        /**
         * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
         * given ``owner``'s signed approval.
         *
         * IMPORTANT: The same issues {IERC20-approve} has related to transaction
         * ordering also apply here.
         *
         * Emits an {Approval} event.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         * - `deadline` must be a timestamp in the future.
         * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
         * over the EIP712-formatted function arguments.
         * - the signature must use ``owner``'s current nonce (see {nonces}).
         *
         * For more information on the signature format, see the
         * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
         * section].
         */
        function permit(
            address owner,
            address spender,
            uint256 value,
            uint256 deadline,
            uint8 v,
            bytes32 r,
            bytes32 s
        ) external;
        /**
         * @dev Returns the current nonce for `owner`. This value must be
         * included whenever a signature is generated for {permit}.
         *
         * Every successful call to {permit} increases ``owner``'s nonce by one. This
         * prevents a signature from being used multiple times.
         */
        function nonces(address owner) external view returns (uint256);
        /**
         * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
         */
        // solhint-disable-next-line func-name-mixedcase
        function DOMAIN_SEPARATOR() external view returns (bytes32);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
    pragma solidity ^0.8.1;
    /**
     * @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
         * ====
         *
         * [IMPORTANT]
         * ====
         * You shouldn't rely on `isContract` to protect against flash loan attacks!
         *
         * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
         * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
         * constructor.
         * ====
         */
        function isContract(address account) internal view returns (bool) {
            // This method relies on extcodesize/address.code.length, which returns 0
            // for contracts in construction, since the code is only stored at the end
            // of the constructor execution.
            return account.code.length > 0;
        }
        /**
         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
         * `recipient`, forwarding all available gas and reverting on errors.
         *
         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
         * of certain opcodes, possibly making contracts go over the 2300 gas limit
         * imposed by `transfer`, making them unable to receive funds via
         * `transfer`. {sendValue} removes this limitation.
         *
         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
         *
         * IMPORTANT: because control is transferred to `recipient`, care must be
         * taken to not create reentrancy vulnerabilities. Consider using
         * {ReentrancyGuard} or the
         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
         */
        function sendValue(address payable recipient, uint256 amount) internal {
            require(address(this).balance >= amount, "Address: insufficient balance");
            (bool success, ) = recipient.call{value: amount}("");
            require(success, "Address: unable to send value, recipient may have reverted");
        }
        /**
         * @dev Performs a Solidity function call using a low level `call`. A
         * plain `call` is an unsafe replacement for a function call: use this
         * function instead.
         *
         * If `target` reverts with a revert reason, it is bubbled up by this
         * function (like regular Solidity function calls).
         *
         * Returns the raw returned data. To convert to the expected return value,
         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
         *
         * Requirements:
         *
         * - `target` must be a contract.
         * - calling `target` with `data` must not revert.
         *
         * _Available since v3.1._
         */
        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
            return functionCall(target, data, "Address: low-level call failed");
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
         * `errorMessage` as a fallback revert reason when `target` reverts.
         *
         * _Available since v3.1._
         */
        function functionCall(
            address target,
            bytes memory data,
            string memory errorMessage
        ) internal returns (bytes memory) {
            return functionCallWithValue(target, data, 0, errorMessage);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but also transferring `value` wei to `target`.
         *
         * Requirements:
         *
         * - the calling contract must have an ETH balance of at least `value`.
         * - the called Solidity function must be `payable`.
         *
         * _Available since v3.1._
         */
        function functionCallWithValue(
            address target,
            bytes memory data,
            uint256 value
        ) internal returns (bytes memory) {
            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
        }
        /**
         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
         * with `errorMessage` as a fallback revert reason when `target` reverts.
         *
         * _Available since v3.1._
         */
        function functionCallWithValue(
            address target,
            bytes memory data,
            uint256 value,
            string memory errorMessage
        ) internal returns (bytes memory) {
            require(address(this).balance >= value, "Address: insufficient balance for call");
            require(isContract(target), "Address: call to non-contract");
            (bool success, bytes memory returndata) = target.call{value: value}(data);
            return verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a static call.
         *
         * _Available since v3.3._
         */
        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
            return functionStaticCall(target, data, "Address: low-level static call failed");
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
         * but performing a static call.
         *
         * _Available since v3.3._
         */
        function functionStaticCall(
            address target,
            bytes memory data,
            string memory errorMessage
        ) internal view returns (bytes memory) {
            require(isContract(target), "Address: static call to non-contract");
            (bool success, bytes memory returndata) = target.staticcall(data);
            return verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev 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");
            (bool success, bytes memory returndata) = target.delegatecall(data);
            return verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
         * revert reason using the provided one.
         *
         * _Available since v4.3._
         */
        function verifyCallResult(
            bool success,
            bytes memory returndata,
            string memory errorMessage
        ) internal pure returns (bytes memory) {
            if (success) {
                return returndata;
            } else {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
                    /// @solidity memory-safe-assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Provides information about the current execution context, including the
     * sender of the transaction and its data. While these are generally available
     * via msg.sender and msg.data, they should not be accessed in such a direct
     * manner, since when dealing with meta-transactions the account sending and
     * paying for execution may not be the actual sender (as far as an application
     * is concerned).
     *
     * This contract is only required for intermediate, library-like contracts.
     */
    abstract contract Context {
        function _msgSender() internal view virtual returns (address) {
            return msg.sender;
        }
        function _msgData() internal view virtual returns (bytes calldata) {
            return msg.data;
        }
    }
    

    File 2 of 3: VariableInterestRate
    // SPDX-License-Identifier: ISC
    pragma solidity ^0.8.17;
    // ====================================================================
    // |     ______                   _______                             |
    // |    / _____________ __  __   / ____(_____  ____ _____  ________   |
    // |   / /_  / ___/ __ `| |/_/  / /_  / / __ \\/ __ `/ __ \\/ ___/ _ \\  |
    // |  / __/ / /  / /_/ _>  <   / __/ / / / / / /_/ / / / / /__/  __/  |
    // | /_/   /_/   \\__,_/_/|_|  /_/   /_/_/ /_/\\__,_/_/ /_/\\___/\\___/   |
    // |                                                                  |
    // ====================================================================
    // ====================== VariableInterestRate ========================
    // ====================================================================
    // Frax Finance: https://github.com/FraxFinance
    // Primary Author
    // Drake Evans: https://github.com/DrakeEvans
    // Reviewers
    // Dennis: https://github.com/denett
    // ====================================================================
    import "@openzeppelin/contracts/utils/Strings.sol";
    import "./interfaces/IRateCalculatorV2.sol";
    /// @title A formula for calculating interest rates as a function of utilization and time
    /// @author Drake Evans github.com/drakeevans
    /// @notice A Contract for calculating interest rates as a function of utilization and time
    contract VariableInterestRate is IRateCalculatorV2 {
        using Strings for uint256;
        // Name Suffix
        string public suffix;
        // Utilization Settings
        /// @notice The minimimum utilization wherein no adjustment to full utilization and vertex rates occurs
        uint256 public immutable MIN_TARGET_UTIL;
        /// @notice The maximum utilization wherein no adjustment to full utilization and vertex rates occurs
        uint256 public immutable MAX_TARGET_UTIL;
        /// @notice The utilization at which the slope increases
        uint256 public immutable VERTEX_UTILIZATION;
        /// @notice precision of utilization calculations
        uint256 public constant UTIL_PREC = 1e5; // 5 decimals
        // Interest Rate Settings (all rates are per second), 365.24 days per year
        /// @notice The minimum interest rate (per second) when utilization is 100%
        uint256 public immutable MIN_FULL_UTIL_RATE; // 18 decimals
        /// @notice The maximum interest rate (per second) when utilization is 100%
        uint256 public immutable MAX_FULL_UTIL_RATE; // 18 decimals
        /// @notice The interest rate (per second) when utilization is 0%
        uint256 public immutable ZERO_UTIL_RATE; // 18 decimals
        /// @notice The interest rate half life in seconds, determines rate of adjustments to rate curve
        uint256 public immutable RATE_HALF_LIFE; // 1 decimals
        /// @notice The percent of the delta between max and min
        uint256 public immutable VERTEX_RATE_PERCENT; // 18 decimals
        /// @notice The precision of interest rate calculations
        uint256 public constant RATE_PREC = 1e18; // 18 decimals
        /// @notice The ```constructor``` function
        /// @param _vertexUtilization The utilization at which the slope increases
        /// @param _vertexRatePercentOfDelta The percent of the delta between max and min, defines vertex rate
        /// @param _minUtil The minimimum utilization wherein no adjustment to full utilization and vertex rates occurs
        /// @param _maxUtil The maximum utilization wherein no adjustment to full utilization and vertex rates occurs
        /// @param _zeroUtilizationRate The interest rate (per second) when utilization is 0%
        /// @param _minFullUtilizationRate The minimum interest rate at 100% utilization
        /// @param _maxFullUtilizationRate The maximum interest rate at 100% utilization
        /// @param _rateHalfLife The half life parameter for interest rate adjustments
        constructor(
            string memory _suffix,
            uint256 _vertexUtilization,
            uint256 _vertexRatePercentOfDelta,
            uint256 _minUtil,
            uint256 _maxUtil,
            uint256 _zeroUtilizationRate,
            uint256 _minFullUtilizationRate,
            uint256 _maxFullUtilizationRate,
            uint256 _rateHalfLife
        ) {
            suffix = _suffix;
            MIN_TARGET_UTIL = _minUtil;
            MAX_TARGET_UTIL = _maxUtil;
            VERTEX_UTILIZATION = _vertexUtilization;
            ZERO_UTIL_RATE = _zeroUtilizationRate;
            MIN_FULL_UTIL_RATE = _minFullUtilizationRate;
            MAX_FULL_UTIL_RATE = _maxFullUtilizationRate;
            RATE_HALF_LIFE = _rateHalfLife;
            VERTEX_RATE_PERCENT = _vertexRatePercentOfDelta;
        }
        /// @notice The ```name``` function returns the name of the rate contract
        /// @return memory name of contract
        function name() external view returns (string memory) {
            return
                string(
                    abi.encodePacked(
                        "Variable Rate V2 ",
                        suffix
                    )
                );
        }
        /// @notice The ```version``` function returns the semantic version of the rate contract
        /// @dev Follows semantic versioning
        /// @return _major Major version
        /// @return _minor Minor version
        /// @return _patch Patch version
        function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
            _major = 2;
            _minor = 0;
            _patch = 0;
        }
        /// @notice The ```getFullUtilizationInterest``` function calculate the new maximum interest rate, i.e. rate when utilization is 100%
        /// @dev Given in interest per second
        /// @param _deltaTime The elapsed time since last update given in seconds
        /// @param _utilization The utilization %, given with 5 decimals of precision
        /// @param _fullUtilizationInterest The interest value when utilization is 100%, given with 18 decimals of precision
        /// @return _newFullUtilizationInterest The new maximum interest rate
        function getFullUtilizationInterest(uint256 _deltaTime, uint256 _utilization, uint64 _fullUtilizationInterest)
            internal
            view
            returns (uint64 _newFullUtilizationInterest)
        {
            if (_utilization < MIN_TARGET_UTIL) {
                // 18 decimals
                uint256 _deltaUtilization = ((MIN_TARGET_UTIL - _utilization) * 1e18) / MIN_TARGET_UTIL;
                // 36 decimals
                uint256 _decayGrowth = (RATE_HALF_LIFE * 1e36) + (_deltaUtilization * _deltaUtilization * _deltaTime);
                // 18 decimals
                _newFullUtilizationInterest = uint64((_fullUtilizationInterest * (RATE_HALF_LIFE * 1e36)) / _decayGrowth);
            } else if (_utilization > MAX_TARGET_UTIL) {
                // 18 decimals
                uint256 _deltaUtilization = ((_utilization - MAX_TARGET_UTIL) * 1e18) / (UTIL_PREC - MAX_TARGET_UTIL);
                // 36 decimals
                uint256 _decayGrowth = (RATE_HALF_LIFE * 1e36) + (_deltaUtilization * _deltaUtilization * _deltaTime);
                // 18 decimals
                _newFullUtilizationInterest = uint64((_fullUtilizationInterest * _decayGrowth) / (RATE_HALF_LIFE * 1e36));
            } else {
                _newFullUtilizationInterest = _fullUtilizationInterest;
            }
            if (_newFullUtilizationInterest > MAX_FULL_UTIL_RATE) {
                _newFullUtilizationInterest = uint64(MAX_FULL_UTIL_RATE);
            } else if (_newFullUtilizationInterest < MIN_FULL_UTIL_RATE) {
                _newFullUtilizationInterest = uint64(MIN_FULL_UTIL_RATE);
            }
        }
        /// @notice The ```getNewRate``` function calculates interest rates using two linear functions f(utilization)
        /// @param _deltaTime The elapsed time since last update, given in seconds
        /// @param _utilization The utilization %, given with 5 decimals of precision
        /// @param _oldFullUtilizationInterest The interest value when utilization is 100%, given with 18 decimals of precision
        /// @return _newRatePerSec The new interest rate, 18 decimals of precision
        /// @return _newFullUtilizationInterest The new max interest rate, 18 decimals of precision
        function getNewRate(uint256 _deltaTime, uint256 _utilization, uint64 _oldFullUtilizationInterest)
            external
            view
            returns (uint64 _newRatePerSec, uint64 _newFullUtilizationInterest)
        {
            _newFullUtilizationInterest = getFullUtilizationInterest(_deltaTime, _utilization, _oldFullUtilizationInterest);
            // _vertexInterest is calculated as the percentage of the detla between min and max interest
            uint256 _vertexInterest = (((_newFullUtilizationInterest - ZERO_UTIL_RATE) * VERTEX_RATE_PERCENT) / RATE_PREC) +
                ZERO_UTIL_RATE;
            if (_utilization < VERTEX_UTILIZATION) {
                // For readability, the following formula is equivalent to:
                // uint256 _slope = ((_vertexInterest - ZERO_UTIL_RATE) * UTIL_PREC) / VERTEX_UTILIZATION;
                // _newRatePerSec = uint64(ZERO_UTIL_RATE + ((_utilization * _slope) / UTIL_PREC));
                // 18 decimals
                _newRatePerSec = uint64(
                    ZERO_UTIL_RATE + (_utilization * (_vertexInterest - ZERO_UTIL_RATE)) / VERTEX_UTILIZATION
                );
            } else {
                // For readability, the following formula is equivalent to:
                // uint256 _slope = (((_newFullUtilizationInterest - _vertexInterest) * UTIL_PREC) / (UTIL_PREC - VERTEX_UTILIZATION));
                // _newRatePerSec = uint64(_vertexInterest + (((_utilization - VERTEX_UTILIZATION) * _slope) / UTIL_PREC));
                // 18 decimals
                _newRatePerSec = uint64(
                    _vertexInterest +
                        ((_utilization - VERTEX_UTILIZATION) * (_newFullUtilizationInterest - _vertexInterest)) /
                        (UTIL_PREC - VERTEX_UTILIZATION)
                );
            }
        }
    }
    // SPDX-License-Identifier: ISC
    pragma solidity ^0.8.17;
    interface IRateCalculatorV2 {
        function name() external view returns (string memory);
        function version() external view returns (uint256, uint256, uint256);
        function getNewRate(uint256 _deltaTime, uint256 _utilization, uint64 _maxInterest)
            external
            view
            returns (uint64 _newRatePerSec, uint64 _newMaxInterest);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev String operations.
     */
    library Strings {
        bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
        uint8 private constant _ADDRESS_LENGTH = 20;
        /**
         * @dev Converts a `uint256` to its ASCII `string` decimal representation.
         */
        function toString(uint256 value) internal pure returns (string memory) {
            // Inspired by OraclizeAPI's implementation - MIT licence
            // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
            if (value == 0) {
                return "0";
            }
            uint256 temp = value;
            uint256 digits;
            while (temp != 0) {
                digits++;
                temp /= 10;
            }
            bytes memory buffer = new bytes(digits);
            while (value != 0) {
                digits -= 1;
                buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                value /= 10;
            }
            return string(buffer);
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
         */
        function toHexString(uint256 value) internal pure returns (string memory) {
            if (value == 0) {
                return "0x00";
            }
            uint256 temp = value;
            uint256 length = 0;
            while (temp != 0) {
                length++;
                temp >>= 8;
            }
            return toHexString(value, length);
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
         */
        function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
            bytes memory buffer = new bytes(2 * length + 2);
            buffer[0] = "0";
            buffer[1] = "x";
            for (uint256 i = 2 * length + 1; i > 1; --i) {
                buffer[i] = _HEX_SYMBOLS[value & 0xf];
                value >>= 4;
            }
            require(value == 0, "Strings: hex length insufficient");
            return string(buffer);
        }
        /**
         * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
         */
        function toHexString(address addr) internal pure returns (string memory) {
            return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
        }
    }
    

    File 3 of 3: FRAXStablecoin
    {"AccessControl.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.6.0;\n\nimport \"./EnumerableSet.sol\";\nimport \"./Address.sol\";\nimport \"./Context.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role\u0027s admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context {\n    using EnumerableSet for EnumerableSet.AddressSet;\n    using Address for address;\n\n    struct RoleData {\n        EnumerableSet.AddressSet members;\n        bytes32 adminRole;\n    }\n\n    mapping (bytes32 =\u003e RoleData) private _roles;\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) \u003c\u003c 96);\n\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``\u0027s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted signaling this.\n     *\n     * _Available since v3.1._\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call, an admin role\n     * bearer except when using {_setupRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view returns (bool) {\n        return _roles[role].members.contains(account);\n    }\n\n    /**\n     * @dev Returns the number of accounts that have `role`. Can be used\n     * together with {getRoleMember} to enumerate all bearers of a role.\n     */\n    function getRoleMemberCount(bytes32 role) public view returns (uint256) {\n        return _roles[role].members.length();\n    }\n\n    /**\n     * @dev Returns one of the accounts that have `role`. `index` must be a\n     * value between 0 and {getRoleMemberCount}, non-inclusive.\n     *\n     * Role bearers are not sorted in any particular way, and their ordering may\n     * change at any point.\n     *\n     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n     * you perform all queries on the same block. See the following\n     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n     * for more information.\n     */\n    function getRoleMember(bytes32 role, uint256 index) public view returns (address) {\n        return _roles[role].members.at(index);\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role\u0027s admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) public view returns (bytes32) {\n        return _roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``\u0027s admin role.\n     */\n    function grantRole(bytes32 role, address account) public virtual {\n        require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to grant\");\n\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``\u0027s admin role.\n     */\n    function revokeRole(bytes32 role, address account) public virtual {\n        require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to revoke\");\n\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function\u0027s\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     */\n    function renounceRole(bytes32 role, address account) public virtual {\n        require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event. Note that unlike {grantRole}, this function doesn\u0027t perform any\n     * checks on the calling account.\n     *\n     * [WARNING]\n     * ====\n     * This function should only be called from the constructor when setting\n     * up the initial roles for the system.\n     *\n     * Using this function in any other way is effectively circumventing the admin\n     * system imposed by {AccessControl}.\n     * ====\n     */\n    function _setupRole(bytes32 role, address account) internal virtual {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``\u0027s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);\n        _roles[role].adminRole = adminRole;\n    }\n\n    function _grantRole(bytes32 role, address account) private {\n        if (_roles[role].members.add(account)) {\n            emit RoleGranted(role, account, _msgSender());\n        }\n    }\n\n    function _revokeRole(bytes32 role, address account) private {\n        if (_roles[role].members.remove(account)) {\n            emit RoleRevoked(role, account, _msgSender());\n        }\n    }\n}\n"},"Address.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies in extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly { size := extcodesize(account) }\n        return size \u003e 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity\u0027s `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance \u003e= amount, \"Address: insufficient balance\");\n\n        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n        (bool success, ) = recipient.call{ value: amount }(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain`call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n      return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n        return _functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n        require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n        return _functionCallWithValue(target, data, value, errorMessage);\n    }\n\n    function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {\n        require(isContract(target), \"Address: call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length \u003e 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n\n                // solhint-disable-next-line no-inline-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}"},"AggregatorV3Interface.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity \u003e=0.6.0;\n\ninterface AggregatorV3Interface {\n\n  function decimals() external view returns (uint8);\n  function description() external view returns (string memory);\n  function version() external view returns (uint256);\n\n  // getRoundData and latestRoundData should both raise \"No data present\"\n  // if they do not have data to report, instead of returning unset values\n  // which could be misinterpreted as actual reported values.\n  function getRoundData(uint80 _roundId)\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n  function latestRoundData()\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n\n}"},"Babylonian.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// computes square roots using the babylonian method\n// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method\nlibrary Babylonian {\n    function sqrt(uint y) internal pure returns (uint z) {\n        if (y \u003e 3) {\n            z = y;\n            uint x = y / 2 + 1;\n            while (x \u003c z) {\n                z = x;\n                x = (y / x + x) / 2;\n            }\n        } else if (y != 0) {\n            z = 1;\n        }\n        // else z = 0\n    }\n}"},"BlockMiner.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n// file: BlockMinder.sol\n\n// used to \"waste\" blocks for truffle tests\ncontract BlockMiner {\n    uint256 public blocksMined;\n\n    constructor () public {\n        blocksMined = 0;\n    }\n\n    function mine() public {\n       blocksMined += 1;\n    }\n\n    function blockTime() external view returns (uint256) {\n       return block.timestamp;\n    }\n}"},"ChainlinkETHUSDPriceConsumer.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./AggregatorV3Interface.sol\";\n\ncontract ChainlinkETHUSDPriceConsumer {\n\n    AggregatorV3Interface internal priceFeed;\n\n\n    constructor() public {\n        priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);\n    }\n\n    /**\n     * Returns the latest price\n     */\n    function getLatestPrice() public view returns (int) {\n        (\n            , \n            int price,\n            ,\n            ,\n            \n        ) = priceFeed.latestRoundData();\n        return price;\n    }\n\n    function getDecimals() public view returns (uint8) {\n        return priceFeed.decimals();\n    }\n}"},"ChainlinkETHUSDPriceConsumerTest.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./AggregatorV3Interface.sol\";\n\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// VERY IMPORTANT: UNCOMMENT THIS LATER\n// import \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol\";\n\ncontract ChainlinkETHUSDPriceConsumerTest {\n\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // VERY IMPORTANT: UNCOMMENT THIS LATER\n    // AggregatorV3Interface internal priceFeed;\n\n    /**\n     * Network: Kovan\n     * Aggregator: ETH/USD\n     * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331\n     */\n    /**\n     * Network: Mainnet\n     * Aggregator: ETH/USD\n     * Address: 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419\n     */\n\n     \n    constructor() public {\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);\n    }\n\n    /**\n     * Returns the latest price\n     */\n    function getLatestPrice() public pure returns (int) {\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // (\n        //     uint80 roundID, \n        //     int price,\n        //     uint startedAt,\n        //     uint timeStamp,\n        //     uint80 answeredInRound\n        // ) = priceFeed.latestRoundData();\n        // // If the round is not complete yet, timestamp is 0\n        // require(timeStamp \u003e 0, \"Round not complete\");\n\n        // This will return something like 32063000000\n        // Divide this by getDecimals to get the \"true\" price\n        // You can can multiply the \"true\" price by 1e6 to get the frax ecosystem \u0027price\u0027\n        // return price;\n\n        return 59000000000;\n    }\n\n    function getDecimals() public pure returns (uint8) {\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // VERY IMPORTANT: UNCOMMENT THIS LATER\n        // return priceFeed.decimals();\n        return 8;\n    }\n}"},"Context.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\ncontract Context {\n    // Empty internal constructor, to prevent people from mistakenly deploying\n    // an instance of this contract, which should be used via inheritance.\n    constructor () internal { }\n\n    function _msgSender() internal view virtual returns (address payable) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes memory) {\n        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n        return msg.data;\n    }\n}"},"EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.6.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`\n * (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping (bytes32 =\u003e uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value\u0027s index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) { // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as \u0027swap and pop\u0027).\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n            // so rarely, we still do the swap anyway to avoid the gas cost of adding an \u0027if\u0027 statement.\n\n            bytes32 lastvalue = set._values[lastIndex];\n\n            // Move the last value to the index where the value to delete is\n            set._values[toDeleteIndex] = lastvalue;\n            // Update the index for the moved value\n            set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n   /**\n    * @dev Returns the value stored at position `index` in the set. O(1).\n    *\n    * Note that there are no guarantees on the ordering of values inside the\n    * array, and it may change when more values are added or removed.\n    *\n    * Requirements:\n    *\n    * - `index` must be strictly less than {length}.\n    */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        require(set._values.length \u003e index, \"EnumerableSet: index out of bounds\");\n        return set._values[index];\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(value)));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(value)));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(value)));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n   /**\n    * @dev Returns the value stored at position `index` in the set. O(1).\n    *\n    * Note that there are no guarantees on the ordering of values inside the\n    * array, and it may change when more values are added or removed.\n    *\n    * Requirements:\n    *\n    * - `index` must be strictly less than {length}.\n    */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint256(_at(set._inner, index)));\n    }\n\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n   /**\n    * @dev Returns the value stored at position `index` in the set. O(1).\n    *\n    * Note that there are no guarantees on the ordering of values inside the\n    * array, and it may change when more values are added or removed.\n    *\n    * Requirements:\n    *\n    * - `index` must be strictly less than {length}.\n    */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n}\n"},"ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./Context.sol\";\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20Mintable}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn\u0027t required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\n \ncontract ERC20 is Context, IERC20 {\n    using SafeMath for uint256;\n\n    mapping (address =\u003e uint256) private _balances;\n\n    mapping (address =\u003e mapping (address =\u003e uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n    uint8 private _decimals;\n    \n    /**\n     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n     * a default value of 18.\n     *\n     * To select a different value for {decimals}, use {_setupDecimals}.\n     *\n     * All three of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor (string memory name, string memory symbol) public {\n        _name = name;\n        _symbol = symbol;\n        _decimals = 18;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n     * called.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view returns (uint8) {\n        return _decimals;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `recipient` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.approve(address spender, uint256 amount)\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        _approve(_msgSender(), spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20};\n     *\n     * Requirements:\n     * - `sender` and `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     * - the caller must have allowance for `sender`\u0027s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n        return true;\n    }\n\n    /**\n     * @dev Moves tokens `amount` from `sender` to `recipient`.\n     *\n     * This is internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `sender` cannot be the zero address.\n     * - `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     */\n    function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n        require(sender != address(0), \"ERC20: transfer from the zero address\");\n        require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(sender, recipient, amount);\n\n        _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n        _balances[recipient] = _balances[recipient].add(amount);\n        emit Transfer(sender, recipient, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `to` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply = _totalSupply.add(amount);\n        _balances[account] = _balances[account].add(amount);\n        emit Transfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 amount) public virtual {\n        _burn(_msgSender(), amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, deducting from the caller\u0027s\n     * allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for `accounts`\u0027s tokens of at least\n     * `amount`.\n     */\n    function burnFrom(address account, uint256 amount) public virtual {\n        uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, \"ERC20: burn amount exceeds allowance\");\n\n        _approve(account, _msgSender(), decreasedAllowance);\n        _burn(account, amount);\n    }\n\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n        _totalSupply = _totalSupply.sub(amount);\n        emit Transfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n     *\n     * This is internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`.`amount` is then deducted\n     * from the caller\u0027s allowance.\n     *\n     * See {_burn} and {_approve}.\n     */\n    function _burnFrom(address account, uint256 amount) internal virtual {\n        _burn(account, amount);\n        _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, \"ERC20: burn amount exceeds allowance\"));\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of `from`\u0027s tokens\n     * will be to transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of `from`\u0027s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}\n"},"ERC20Custom.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./Context.sol\";\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n// Due to compiling issues, _name, _symbol, and _decimals were removed\n\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20Mintable}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn\u0027t required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20Custom is Context, IERC20 {\n    using SafeMath for uint256;\n\n    mapping (address =\u003e uint256) internal _balances;\n\n    mapping (address =\u003e mapping (address =\u003e uint256)) internal _allowances;\n\n    uint256 private _totalSupply;\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `recipient` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.approve(address spender, uint256 amount)\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        _approve(_msgSender(), spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20};\n     *\n     * Requirements:\n     * - `sender` and `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     * - the caller must have allowance for `sender`\u0027s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n        return true;\n    }\n\n    /**\n     * @dev Moves tokens `amount` from `sender` to `recipient`.\n     *\n     * This is internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `sender` cannot be the zero address.\n     * - `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     */\n    function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n        require(sender != address(0), \"ERC20: transfer from the zero address\");\n        require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(sender, recipient, amount);\n\n        _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n        _balances[recipient] = _balances[recipient].add(amount);\n        emit Transfer(sender, recipient, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `to` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply = _totalSupply.add(amount);\n        _balances[account] = _balances[account].add(amount);\n        emit Transfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 amount) public virtual {\n        _burn(_msgSender(), amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, deducting from the caller\u0027s\n     * allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for `accounts`\u0027s tokens of at least\n     * `amount`.\n     */\n    function burnFrom(address account, uint256 amount) public virtual {\n        uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, \"ERC20: burn amount exceeds allowance\");\n\n        _approve(account, _msgSender(), decreasedAllowance);\n        _burn(account, amount);\n    }\n\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n        _totalSupply = _totalSupply.sub(amount);\n        emit Transfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n     *\n     * This is internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`.`amount` is then deducted\n     * from the caller\u0027s allowance.\n     *\n     * See {_burn} and {_approve}.\n     */\n    function _burnFrom(address account, uint256 amount) internal virtual {\n        _burn(account, amount);\n        _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, \"ERC20: burn amount exceeds allowance\"));\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of `from`\u0027s tokens\n     * will be to transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of `from`\u0027s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}"},"FakeCollateral.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./Context.sol\";\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n// Due to compiling issues, _name, _symbol, and _decimals were removed\n\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20Mintable}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn\u0027t required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract FakeCollateral is Context, IERC20 {\n    using SafeMath for uint256;\n    string public symbol;\n    uint8 public decimals;\n    address public creator_address;\n    uint256 public genesis_supply;\n    uint256 private _totalSupply;\n\n    mapping (address =\u003e uint256) private _balances;\n    mapping (address =\u003e mapping (address =\u003e uint256)) private _allowances;\n    mapping (address =\u003e bool) used;\n\n    constructor(\n        address _creator_address,\n        uint256 _genesis_supply,\n        string memory _symbol,\n        uint8 _decimals\n    ) public {\n        genesis_supply = _genesis_supply;\n        creator_address = _creator_address;\n        symbol = _symbol;\n        decimals = _decimals;\n        _mint(creator_address, genesis_supply);\n    }\n\n    function faucet() public {\n    \tif (used[msg.sender] == false) {\n    \t\tused[msg.sender] = true;\n    \t\t_mint(msg.sender, 1000 * (10 ** uint256(decimals)));\n    \t}\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `recipient` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.approve(address spender, uint256 amount)\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        _approve(_msgSender(), spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20};\n     *\n     * Requirements:\n     * - `sender` and `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     * - the caller must have allowance for `sender`\u0027s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n        return true;\n    }\n\n    /**\n     * @dev Moves tokens `amount` from `sender` to `recipient`.\n     *\n     * This is internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `sender` cannot be the zero address.\n     * - `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     */\n    function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n        require(sender != address(0), \"ERC20: transfer from the zero address\");\n        require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(sender, recipient, amount);\n\n        _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n        _balances[recipient] = _balances[recipient].add(amount);\n        emit Transfer(sender, recipient, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `to` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply = _totalSupply.add(amount);\n        _balances[account] = _balances[account].add(amount);\n        emit Transfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 amount) public virtual {\n        _burn(_msgSender(), amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, deducting from the caller\u0027s\n     * allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for `accounts`\u0027s tokens of at least\n     * `amount`.\n     */\n    function burnFrom(address account, uint256 amount) public virtual {\n        uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, \"ERC20: burn amount exceeds allowance\");\n\n        _approve(account, _msgSender(), decreasedAllowance);\n        _burn(account, amount);\n    }\n\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n        _totalSupply = _totalSupply.sub(amount);\n        emit Transfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n     *\n     * This is internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`.`amount` is then deducted\n     * from the caller\u0027s allowance.\n     *\n     * See {_burn} and {_approve}.\n     */\n    function _burnFrom(address account, uint256 amount) internal virtual {\n        _burn(account, amount);\n        _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, \"ERC20: burn amount exceeds allowance\"));\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of `from`\u0027s tokens\n     * will be to transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of `from`\u0027s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}\n"},"FakeCollateral_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FakeCollateral.sol\";\n\ncontract FakeCollateral_USDC is FakeCollateral {\n    constructor(\n        address _creator_address,\n        uint256 _genesis_supply,\n        string memory _symbol,\n        uint8 _decimals\n    ) \n    FakeCollateral(_creator_address, _genesis_supply, _symbol, _decimals)\n    public {}\n}"},"FakeCollateral_USDT.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FakeCollateral.sol\";\n\ncontract FakeCollateral_USDT is FakeCollateral {\n    constructor(\n        address _creator_address,\n        uint256 _genesis_supply,\n        string memory _symbol,\n        uint8 _decimals\n    ) \n    FakeCollateral(_creator_address, _genesis_supply, _symbol, _decimals)\n    public {}\n}"},"FakeCollateral_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FakeCollateral.sol\";\n\ncontract FakeCollateral_WETH is FakeCollateral {\n    constructor(\n        address _creator_address,\n        uint256 _genesis_supply,\n        string memory _symbol,\n        uint8 _decimals\n    ) \n    FakeCollateral(_creator_address, _genesis_supply, _symbol, _decimals)\n    public {}\n}"},"FixedPoint.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./Babylonian.sol\u0027;\n\n// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))\nlibrary FixedPoint {\n    // range: [0, 2**112 - 1]\n    // resolution: 1 / 2**112\n    struct uq112x112 {\n        uint224 _x;\n    }\n\n    // range: [0, 2**144 - 1]\n    // resolution: 1 / 2**112\n    struct uq144x112 {\n        uint _x;\n    }\n\n    uint8 private constant RESOLUTION = 112;\n    uint private constant Q112 = uint(1) \u003c\u003c RESOLUTION;\n    uint private constant Q224 = Q112 \u003c\u003c RESOLUTION;\n\n    // encode a uint112 as a UQ112x112\n    function encode(uint112 x) internal pure returns (uq112x112 memory) {\n        return uq112x112(uint224(x) \u003c\u003c RESOLUTION);\n    }\n\n    // encodes a uint144 as a UQ144x112\n    function encode144(uint144 x) internal pure returns (uq144x112 memory) {\n        return uq144x112(uint256(x) \u003c\u003c RESOLUTION);\n    }\n\n    // divide a UQ112x112 by a uint112, returning a UQ112x112\n    function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {\n        require(x != 0, \u0027FixedPoint: DIV_BY_ZERO\u0027);\n        return uq112x112(self._x / uint224(x));\n    }\n\n    // multiply a UQ112x112 by a uint, returning a UQ144x112\n    // reverts on overflow\n    function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {\n        uint z;\n        require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), \"FixedPoint: MULTIPLICATION_OVERFLOW\");\n        return uq144x112(z);\n    }\n\n    // returns a UQ112x112 which represents the ratio of the numerator to the denominator\n    // equivalent to encode(numerator).div(denominator)\n    function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {\n        require(denominator \u003e 0, \"FixedPoint: DIV_BY_ZERO\");\n        return uq112x112((uint224(numerator) \u003c\u003c RESOLUTION) / denominator);\n    }\n\n    // decode a UQ112x112 into a uint112 by truncating after the radix point\n    function decode(uq112x112 memory self) internal pure returns (uint112) {\n        return uint112(self._x \u003e\u003e RESOLUTION);\n    }\n\n    // decode a UQ144x112 into a uint144 by truncating after the radix point\n    function decode144(uq144x112 memory self) internal pure returns (uint144) {\n        return uint144(self._x \u003e\u003e RESOLUTION);\n    }\n\n    // take the reciprocal of a UQ112x112\n    function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {\n        require(self._x != 0, \u0027FixedPoint: ZERO_RECIPROCAL\u0027);\n        return uq112x112(uint224(Q224 / self._x));\n    }\n\n    // square root of a UQ112x112\n    function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {\n        return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) \u003c\u003c 56));\n    }\n}"},"Frax.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./Context.sol\";\nimport \"./IERC20.sol\";\nimport \"./ERC20Custom.sol\";\nimport \"./ERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./FXS.sol\";\nimport \"./FraxPool.sol\";\nimport \"./UniswapPairOracle.sol\";\nimport \"./ChainlinkETHUSDPriceConsumer.sol\";\nimport \"./AccessControl.sol\";\n\ncontract FRAXStablecoin is ERC20Custom, AccessControl {\n    using SafeMath for uint256;\n\n    /* ========== STATE VARIABLES ========== */\n    enum PriceChoice { FRAX, FXS }\n    ChainlinkETHUSDPriceConsumer private eth_usd_pricer;\n    uint8 private eth_usd_pricer_decimals;\n    UniswapPairOracle private fraxEthOracle;\n    UniswapPairOracle private fxsEthOracle;\n    string public symbol;\n    string public name;\n    uint8 public constant decimals = 18;\n    address public owner_address;\n    address public creator_address;\n    address public timelock_address; // Governance timelock address\n    address public controller_address; // Controller contract to dynamically adjust system parameters automatically\n    address public fxs_address;\n    address public frax_eth_oracle_address;\n    address public fxs_eth_oracle_address;\n    address public weth_address;\n    address public eth_usd_consumer_address;\n    uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity\n\n    // The addresses in this array are added by the oracle and these contracts are able to mint frax\n    address[] public frax_pools_array;\n\n    // Mapping is also used for faster verification\n    mapping(address =\u003e bool) public frax_pools; \n\n    // Constants for various precisions\n    uint256 private constant PRICE_PRECISION = 1e6;\n    \n    uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102\n    uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee\n    uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee\n    uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio()\n    uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again\n    uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1\n    uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio\n\n    address public DEFAULT_ADMIN_ADDRESS;\n    bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256(\"COLLATERAL_RATIO_PAUSER\");\n    bool public collateral_ratio_paused = false;\n\n    /* ========== MODIFIERS ========== */\n\n    modifier onlyCollateralRatioPauser() {\n        require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender));\n        _;\n    }\n\n    modifier onlyPools() {\n       require(frax_pools[msg.sender] == true, \"Only frax pools can call this function\");\n        _;\n    } \n    \n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == owner_address || msg.sender == timelock_address || msg.sender == controller_address, \"You are not the owner, controller, or the governance timelock\");\n        _;\n    }\n\n    modifier onlyByOwnerGovernanceOrPool() {\n        require(\n            msg.sender == owner_address \n            || msg.sender == timelock_address \n            || frax_pools[msg.sender] == true, \n            \"You are not the owner, the governance timelock, or a pool\");\n        _;\n    }\n\n    /* ========== CONSTRUCTOR ========== */\n\n    constructor(\n        string memory _name,\n        string memory _symbol,\n        address _creator_address,\n        address _timelock_address\n    ) public {\n        name = _name;\n        symbol = _symbol;\n        creator_address = _creator_address;\n        timelock_address = _timelock_address;\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        DEFAULT_ADMIN_ADDRESS = _msgSender();\n        owner_address = _creator_address;\n        _mint(creator_address, genesis_supply);\n        grantRole(COLLATERAL_RATIO_PAUSER, creator_address);\n        grantRole(COLLATERAL_RATIO_PAUSER, timelock_address);\n        frax_step = 2500; // 6 decimals of precision, equal to 0.25%\n        global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision)\n        refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis\n        price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis\n        price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis\n    }\n\n    /* ========== VIEWS ========== */\n\n    // Choice = \u0027FRAX\u0027 or \u0027FXS\u0027 for now\n    function oracle_price(PriceChoice choice) internal view returns (uint256) {\n        // Get the ETH / USD price first, and cut it down to 1e6 precision\n        uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);\n        uint256 price_vs_eth;\n\n        if (choice == PriceChoice.FRAX) {\n            price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH\n        }\n        else if (choice == PriceChoice.FXS) {\n            price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH\n        }\n        else revert(\"INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)\");\n\n        // Will be in 1e6 format\n        return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth);\n    }\n\n    // Returns X FRAX = 1 USD\n    function frax_price() public view returns (uint256) {\n        return oracle_price(PriceChoice.FRAX);\n    }\n\n    // Returns X FXS = 1 USD\n    function fxs_price()  public view returns (uint256) {\n        return oracle_price(PriceChoice.FXS);\n    }\n\n    function eth_usd_price() public view returns (uint256) {\n        return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);\n    }\n\n    // This is needed to avoid costly repeat calls to different getter functions\n    // It is cheaper gas-wise to just dump everything and only use some of the info\n    function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {\n        return (\n            oracle_price(PriceChoice.FRAX), // frax_price()\n            oracle_price(PriceChoice.FXS), // fxs_price()\n            totalSupply(), // totalSupply()\n            global_collateral_ratio, // global_collateral_ratio()\n            globalCollateralValue(), // globalCollateralValue\n            minting_fee, // minting_fee()\n            redemption_fee, // redemption_fee()\n            uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price\n        );\n    }\n\n    // Iterate through all frax pools and calculate all value of collateral in all pools globally \n    function globalCollateralValue() public view returns (uint256) {\n        uint256 total_collateral_value_d18 = 0; \n\n        for (uint i = 0; i \u003c frax_pools_array.length; i++){ \n            // Exclude null addresses\n            if (frax_pools_array[i] != address(0)){\n                total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance());\n            }\n\n        }\n        return total_collateral_value_d18;\n    }\n\n    /* ========== PUBLIC FUNCTIONS ========== */\n    \n    // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion.\n    uint256 public last_call_time; // Last time the refreshCollateralRatio function was called\n    function refreshCollateralRatio() public {\n        require(collateral_ratio_paused == false, \"Collateral Ratio has been paused\");\n        uint256 frax_price_cur = frax_price();\n        require(block.timestamp - last_call_time \u003e= refresh_cooldown, \"Must wait for the refresh cooldown since last refresh\");\n\n        // Step increments are 0.25% (upon genesis, changable by setFraxStep()) \n        \n        if (frax_price_cur \u003e price_target.add(price_band)) { //decrease collateral ratio\n            if(global_collateral_ratio \u003c= frax_step){ //if within a step of 0, go to 0\n                global_collateral_ratio = 0;\n            } else {\n                global_collateral_ratio = global_collateral_ratio.sub(frax_step);\n            }\n        } else if (frax_price_cur \u003c price_target.sub(price_band)) { //increase collateral ratio\n            if(global_collateral_ratio.add(frax_step) \u003e= 1000000){\n                global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000\n            } else {\n                global_collateral_ratio = global_collateral_ratio.add(frax_step);\n            }\n        }\n\n        last_call_time = block.timestamp; // Set the time of the last expansion\n    }\n\n    /* ========== RESTRICTED FUNCTIONS ========== */\n\n    // Used by pools when user redeems\n    function pool_burn_from(address b_address, uint256 b_amount) public onlyPools {\n        super._burnFrom(b_address, b_amount);\n        emit FRAXBurned(b_address, msg.sender, b_amount);\n    }\n\n    // This function is what other frax pools will call to mint new FRAX \n    function pool_mint(address m_address, uint256 m_amount) public onlyPools {\n        super._mint(m_address, m_amount);\n        emit FRAXMinted(msg.sender, m_address, m_amount);\n    }\n\n    // Adds collateral addresses supported, such as tether and busd, must be ERC20 \n    function addPool(address pool_address) public onlyByOwnerOrGovernance {\n        require(frax_pools[pool_address] == false, \"address already exists\");\n        frax_pools[pool_address] = true; \n        frax_pools_array.push(pool_address);\n    }\n\n    // Remove a pool \n    function removePool(address pool_address) public onlyByOwnerOrGovernance {\n        require(frax_pools[pool_address] == true, \"address doesn\u0027t exist already\");\n        \n        // Delete from the mapping\n        delete frax_pools[pool_address];\n\n        // \u0027Delete\u0027 from the array by setting the address to 0x0\n        for (uint i = 0; i \u003c frax_pools_array.length; i++){ \n            if (frax_pools_array[i] == pool_address) {\n                frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same\n                break;\n            }\n        }\n    }\n\n    function setOwner(address _owner_address) external onlyByOwnerOrGovernance {\n        owner_address = _owner_address;\n    }\n\n    function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance {\n        redemption_fee = red_fee;\n    }\n\n    function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance {\n        minting_fee = min_fee;\n    }  \n\n    function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance {\n        frax_step = _new_step;\n    }  \n\n    function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance {\n        price_target = _new_price_target;\n    }\n\n    function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance {\n    \trefresh_cooldown = _new_cooldown;\n    }\n\n    function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance {\n        fxs_address = _fxs_address;\n    }\n\n    function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance {\n        eth_usd_consumer_address = _eth_usd_consumer_address;\n        eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address);\n        eth_usd_pricer_decimals = eth_usd_pricer.getDecimals();\n    }\n\n    function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {\n        timelock_address = new_timelock;\n    }\n\n    function setController(address _controller_address) external onlyByOwnerOrGovernance {\n        controller_address = _controller_address;\n    }\n\n    function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance {\n        price_band = _price_band;\n    }\n\n    // Sets the FRAX_ETH Uniswap oracle address \n    function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {\n        frax_eth_oracle_address = _frax_oracle_addr;\n        fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); \n        weth_address = _weth_address;\n    }\n\n    // Sets the FXS_ETH Uniswap oracle address \n    function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance {\n        fxs_eth_oracle_address = _fxs_oracle_addr;\n        fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr);\n        weth_address = _weth_address;\n    }\n\n    function toggleCollateralRatio() public onlyCollateralRatioPauser {\n        collateral_ratio_paused = !collateral_ratio_paused;\n    }\n\n    /* ========== EVENTS ========== */\n\n    // Track FRAX burned\n    event FRAXBurned(address indexed from, address indexed to, uint256 amount);\n\n    // Track FRAX minted\n    event FRAXMinted(address indexed from, address indexed to, uint256 amount);\n}\n"},"FraxPool.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./SafeMath.sol\";\nimport \"./FXS.sol\";\nimport \"./Frax.sol\";\nimport \"./ERC20.sol\";\n// import \u0027../../Uniswap/TransferHelper.sol\u0027;\nimport \"./UniswapPairOracle.sol\";\nimport \"./AccessControl.sol\";\n// import \"../../Utils/StringHelpers.sol\";\nimport \"./FraxPoolLibrary.sol\";\n\n/*\n   Same as FraxPool.sol, but has some gas optimizations\n*/\n\n\ncontract FraxPool is AccessControl {\n    using SafeMath for uint256;\n\n    /* ========== STATE VARIABLES ========== */\n\n    ERC20 private collateral_token;\n    address private collateral_address;\n    address private owner_address;\n    // address private oracle_address;\n    address private frax_contract_address;\n    address private fxs_contract_address;\n    address private timelock_address; // Timelock address for the governance contract\n    FRAXShares private FXS;\n    FRAXStablecoin private FRAX;\n    // UniswapPairOracle private oracle;\n    UniswapPairOracle private collatEthOracle;\n    address private collat_eth_oracle_address;\n    address private weth_address;\n\n    uint256 private minting_fee;\n    uint256 private redemption_fee;\n\n    mapping (address =\u003e uint256) public redeemFXSBalances;\n    mapping (address =\u003e uint256) public redeemCollateralBalances;\n    uint256 public unclaimedPoolCollateral;\n    uint256 public unclaimedPoolFXS;\n    mapping (address =\u003e uint256) public lastRedeemed;\n\n    // Constants for various precisions\n    uint256 private constant PRICE_PRECISION = 1e6;\n    uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;\n    uint256 private constant COLLATERAL_RATIO_MAX = 1e6;\n\n    // Number of decimals needed to get to 18\n    uint256 private missing_decimals;\n    \n    // Pool_ceiling is the total units of collateral that a pool contract can hold\n    uint256 public pool_ceiling = 0;\n\n    // Stores price of the collateral, if price is paused\n    uint256 public pausedPrice = 0;\n\n    // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis\n    uint256 public bonus_rate = 7500;\n\n    // Number of blocks to wait before being able to collectRedemption()\n    uint256 public redemption_delay = 1;\n\n    // AccessControl Roles\n    bytes32 private constant MINT_PAUSER = keccak256(\"MINT_PAUSER\");\n    bytes32 private constant REDEEM_PAUSER = keccak256(\"REDEEM_PAUSER\");\n    bytes32 private constant BUYBACK_PAUSER = keccak256(\"BUYBACK_PAUSER\");\n    bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256(\"RECOLLATERALIZE_PAUSER\");\n    bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256(\"COLLATERAL_PRICE_PAUSER\");\n    \n    // AccessControl state variables\n    bool private mintPaused = false;\n    bool private redeemPaused = false;\n    bool private recollateralizePaused = false;\n    bool private buyBackPaused = false;\n    bool private collateralPricePaused = false;\n\n    /* ========== MODIFIERS ========== */\n\n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == timelock_address || msg.sender == owner_address, \"You are not the owner or the governance timelock\");\n        _;\n    }\n\n    modifier notRedeemPaused() {\n        require(redeemPaused == false, \"Redeeming is paused\");\n        _;\n    }\n\n    modifier notMintPaused() {\n        require(mintPaused == false, \"Minting is paused\");\n        _;\n    }\n \n    /* ========== CONSTRUCTOR ========== */\n    \n    constructor(\n        address _frax_contract_address,\n        address _fxs_contract_address,\n        address _collateral_address,\n        address _creator_address,\n        address _timelock_address,\n        uint256 _pool_ceiling\n    ) public {\n        FRAX = FRAXStablecoin(_frax_contract_address);\n        FXS = FRAXShares(_fxs_contract_address);\n        frax_contract_address = _frax_contract_address;\n        fxs_contract_address = _fxs_contract_address;\n        collateral_address = _collateral_address;\n        timelock_address = _timelock_address;\n        owner_address = _creator_address;\n        collateral_token = ERC20(_collateral_address);\n        pool_ceiling = _pool_ceiling;\n        missing_decimals = uint(18).sub(collateral_token.decimals());\n\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        grantRole(MINT_PAUSER, timelock_address);\n        grantRole(REDEEM_PAUSER, timelock_address);\n        grantRole(RECOLLATERALIZE_PAUSER, timelock_address);\n        grantRole(BUYBACK_PAUSER, timelock_address);\n        grantRole(COLLATERAL_PRICE_PAUSER, timelock_address);\n    }\n\n    /* ========== VIEWS ========== */\n\n    // Returns dollar value of collateral held in this Frax pool\n    function collatDollarBalance() public view returns (uint256) {\n        uint256 eth_usd_price = FRAX.eth_usd_price();\n        uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals)));\n\n        uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price);\n        return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6);    \n    }\n\n    // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio\n    function availableExcessCollatDV() public view returns (uint256) {\n        uint256 total_supply = FRAX.totalSupply();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n        uint256 global_collat_value = FRAX.globalCollateralValue();\n\n        if (global_collateral_ratio \u003e COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR \u003e 1\n        uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio\n        if (global_collat_value \u003e required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18);\n        else return 0;\n    }\n\n    /* ========== PUBLIC FUNCTIONS ========== */\n    \n    // Returns the price of the pool collateral in USD\n    function getCollateralPrice() public view returns (uint256) {\n        if(collateralPricePaused == true){\n            return pausedPrice;\n        } else {\n            uint256 eth_usd_price = FRAX.eth_usd_price();\n            return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals)));\n        }\n    }\n\n    function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance {\n        collat_eth_oracle_address = _collateral_weth_oracle_address;\n        collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address);\n        weth_address = _weth_address;\n    }\n\n    // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency \n    function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused {\n        uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n\n        require(global_collateral_ratio \u003e= COLLATERAL_RATIO_MAX, \"Collateral ratio must be \u003e= 1\");\n        require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) \u003c= pool_ceiling, \"[Pool\u0027s Closed]: Ceiling reached\");\n        \n        (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX(\n            getCollateralPrice(),\n            minting_fee,\n            collateral_amount_d18\n        ); //1 FRAX for each $1 worth of collateral\n\n        require(FRAX_out_min \u003c= frax_amount_d18, \"Slippage limit reached\");\n        collateral_token.transferFrom(msg.sender, address(this), collateral_amount);\n        FRAX.pool_mint(msg.sender, frax_amount_d18);\n    }\n\n    // 0% collateral-backed\n    function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused {\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n        require(global_collateral_ratio == 0, \"Collateral ratio must be 0\");\n        \n        (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX(\n            minting_fee, \n            fxs_price, // X FXS / 1 USD\n            fxs_amount_d18\n        );\n\n        require(FRAX_out_min \u003c= frax_amount_d18, \"Slippage limit reached\");\n        FXS.pool_burn_from(msg.sender, fxs_amount_d18);\n        FRAX.pool_mint(msg.sender, frax_amount_d18);\n    }\n\n    // Will fail if fully collateralized or fully algorithmic\n    // \u003e 0% and \u003c 100% collateral-backed\n    function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused {\n        uint256 frax_price = FRAX.frax_price();\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n\n        require(global_collateral_ratio \u003c COLLATERAL_RATIO_MAX \u0026\u0026 global_collateral_ratio \u003e 0, \"Collateral ratio needs to be between .000001 and .999999\");\n        require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) \u003c= pool_ceiling, \"Pool ceiling reached, no more FRAX can be minted with this collateral\");\n\n        uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);\n        FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params(\n            minting_fee, \n            fxs_price,\n            frax_price,\n            getCollateralPrice(),\n            fxs_amount,\n            collateral_amount_d18,\n            (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)),\n            pool_ceiling,\n            global_collateral_ratio\n        );\n\n        (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params);\n\n        require(FRAX_out_min \u003c= mint_amount, \"Slippage limit reached\");\n        require(fxs_needed \u003c= fxs_amount, \"Not enough FXS inputted\");\n        FXS.pool_burn_from(msg.sender, fxs_needed);\n        collateral_token.transferFrom(msg.sender, address(this), collateral_amount);\n        FRAX.pool_mint(msg.sender, mint_amount);\n    }\n\n    // Redeem collateral. 100% collateral-backed\n    function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused {\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n        require(global_collateral_ratio == COLLATERAL_RATIO_MAX, \"Collateral ratio must be == 1\");\n\n        // Need to adjust for decimals of collateral\n        uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals);\n        (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX(\n            getCollateralPrice(),\n            FRAX_amount_precision,\n            redemption_fee\n        );\n\n        require(collateral_needed \u003c= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), \"Not enough collateral in pool\");\n\n        redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed);\n        unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed);\n        lastRedeemed[msg.sender] = block.number;\n\n        require(COLLATERAL_out_min \u003c= collateral_needed, \"Slippage limit reached\");\n        \n        // Move all external functions to the end\n        FRAX.pool_burn_from(msg.sender, FRAX_amount);\n    }\n\n    // Will fail if fully collateralized or algorithmic\n    // Redeem FRAX for collateral and FXS. \u003e 0% and \u003c 100% collateral-backed\n    function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused {\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n\n        require(global_collateral_ratio \u003c COLLATERAL_RATIO_MAX \u0026\u0026 global_collateral_ratio \u003e 0, \"Collateral ratio needs to be between .000001 and .999999\");\n        uint256 col_price_usd = getCollateralPrice();\n\n        uint256 FRAX_amount_post_fee = FRAX_amount.sub((FRAX_amount.mul(redemption_fee)).div(PRICE_PRECISION));\n        uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION));\n        uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);\n\n        // Need to adjust for decimals of collateral\n        uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals);\n        uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION);\n        uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd);\n\n        redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount);\n        unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount);\n\n        redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);\n        unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);\n\n        lastRedeemed[msg.sender] = block.number;\n\n        require(collateral_amount \u003c= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), \"Not enough collateral in pool\");\n        require(COLLATERAL_out_min \u003c= collateral_amount, \"Slippage limit reached [collateral]\");\n        require(FXS_out_min \u003c= fxs_amount, \"Slippage limit reached [FXS]\");\n        \n        // Move all external functions to the end\n        FRAX.pool_burn_from(msg.sender, FRAX_amount);\n        FXS.pool_mint(address(this), fxs_amount);\n    }\n\n    // Redeem FRAX for FXS. 0% collateral-backed\n    function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused {\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n\n        require(global_collateral_ratio == 0, \"Collateral ratio must be 0\"); \n        uint256 fxs_dollar_value_d18 = FRAX_amount;\n        fxs_dollar_value_d18 = fxs_dollar_value_d18.sub((fxs_dollar_value_d18.mul(redemption_fee)).div(PRICE_PRECISION)); //apply redemption fee\n\n        uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price);\n        \n        redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount);\n        unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount);\n        \n        lastRedeemed[msg.sender] = block.number;\n        \n        require(FXS_out_min \u003c= fxs_amount, \"Slippage limit reached\");\n        // Move all external functions to the end\n        FRAX.pool_burn_from(msg.sender, FRAX_amount);\n        FXS.pool_mint(address(this), fxs_amount);\n    }\n\n    // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool\n    // contract to the user. Redemption is split into two functions to prevent flash loans from being able\n    // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.\n    function collectRedemption() external {\n        require((lastRedeemed[msg.sender].add(redemption_delay)) \u003c= block.number, \"Must wait for redemption_delay blocks before collecting redemption\");\n        bool sendFXS = false;\n        bool sendCollateral = false;\n        uint FXSAmount;\n        uint CollateralAmount;\n\n        // Use Checks-Effects-Interactions pattern\n        if(redeemFXSBalances[msg.sender] \u003e 0){\n            FXSAmount = redeemFXSBalances[msg.sender];\n            redeemFXSBalances[msg.sender] = 0;\n            unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount);\n\n            sendFXS = true;\n        }\n        \n        if(redeemCollateralBalances[msg.sender] \u003e 0){\n            CollateralAmount = redeemCollateralBalances[msg.sender];\n            redeemCollateralBalances[msg.sender] = 0;\n            unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount);\n\n            sendCollateral = true;\n        }\n\n        if(sendFXS == true){\n            FXS.transfer(msg.sender, FXSAmount);\n        }\n        if(sendCollateral == true){\n            collateral_token.transfer(msg.sender, CollateralAmount);\n        }\n    }\n\n\n    // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target\n    // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral\n    // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate\n    // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity\n    function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external {\n        require(recollateralizePaused == false, \"Recollateralize is paused\");\n        uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);\n        uint256 fxs_price = FRAX.fxs_price();\n        uint256 frax_total_supply = FRAX.totalSupply();\n        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\n        uint256 global_collat_value = FRAX.globalCollateralValue();\n        \n        (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner(\n            collateral_amount_d18,\n            getCollateralPrice(),\n            global_collat_value,\n            frax_total_supply,\n            global_collateral_ratio\n        ); \n\n        uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals);\n\n        uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate)).div(fxs_price);\n\n        require(FXS_out_min \u003c= fxs_paid_back, \"Slippage limit reached\");\n        collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision);\n        FXS.pool_mint(msg.sender, fxs_paid_back);\n        \n    }\n\n    // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool\n    // This can also happen if the collateral ratio \u003e 1\n    function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external {\n        require(buyBackPaused == false, \"Buyback is paused\");\n        uint256 fxs_price = FRAX.fxs_price();\n        \n        FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params(\n            availableExcessCollatDV(),\n            fxs_price,\n            getCollateralPrice(),\n            FXS_amount\n        );\n\n        (uint256 collateral_equivalent_d18) = FraxPoolLibrary.calcBuyBackFXS(input_params);\n        uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals);\n\n        require(COLLATERAL_out_min \u003c= collateral_precision, \"Slippage limit reached\");\n        // Give the sender their desired collateral and burn the FXS\n        FXS.pool_burn_from(msg.sender, FXS_amount);\n        collateral_token.transfer(msg.sender, collateral_precision);\n    }\n\n    /* ========== RESTRICTED FUNCTIONS ========== */\n\n    function toggleMinting() external {\n        require(hasRole(MINT_PAUSER, msg.sender));\n        mintPaused = !mintPaused;\n    }\n    \n    function toggleRedeeming() external {\n        require(hasRole(REDEEM_PAUSER, msg.sender));\n        redeemPaused = !redeemPaused;\n    }\n\n    function toggleRecollateralize() external {\n        require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender));\n        recollateralizePaused = !recollateralizePaused;\n    }\n    \n    function toggleBuyBack() external {\n        require(hasRole(BUYBACK_PAUSER, msg.sender));\n        buyBackPaused = !buyBackPaused;\n    }\n\n    function toggleCollateralPrice() external {\n        require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender));\n        // If pausing, set paused price; else if unpausing, clear pausedPrice\n        if(collateralPricePaused == false){\n            pausedPrice = getCollateralPrice();\n        } else {\n            pausedPrice = 0;\n        }\n        collateralPricePaused = !collateralPricePaused;\n    }\n\n    // Combined into one function due to 24KiB contract memory limit\n    function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay) external onlyByOwnerOrGovernance {\n        pool_ceiling = new_ceiling;\n        bonus_rate = new_bonus_rate;\n        redemption_delay = new_redemption_delay;\n        minting_fee = FRAX.minting_fee();\n        redemption_fee = FRAX.redemption_fee();\n    }\n\n    function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {\n        timelock_address = new_timelock;\n    }\n\n    function setOwner(address _owner_address) external onlyByOwnerOrGovernance {\n        owner_address = _owner_address;\n    }\n\n    /* ========== EVENTS ========== */\n\n}"},"FraxPoolLibrary.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.6.0;\npragma experimental ABIEncoderV2;\n\nimport \"./SafeMath.sol\";\n\n\n\nlibrary FraxPoolLibrary {\n    using SafeMath for uint256;\n\n    // Constants for various precisions\n    uint256 private constant PRICE_PRECISION = 1e6;\n\n    // ================ Structs ================\n    // Needed to lower stack size\n    struct MintFF_Params {\n        uint256 mint_fee; \n        uint256 fxs_price_usd; \n        uint256 frax_price_usd; \n        uint256 col_price_usd;\n        uint256 fxs_amount;\n        uint256 collateral_amount;\n        uint256 collateral_token_balance;\n        uint256 pool_ceiling;\n        uint256 col_ratio;\n    }\n\n    struct BuybackFXS_Params {\n        uint256 excess_collateral_dollar_value_d18;\n        uint256 fxs_price_usd;\n        uint256 col_price_usd;\n        uint256 FXS_amount;\n    }\n\n    // ================ Functions ================\n\n    function calcMint1t1FRAX(uint256 col_price, uint256 mint_fee, uint256 collateral_amount_d18) public pure returns (uint256) {\n        uint256 col_price_usd = col_price;\n        uint256 c_dollar_value_d18 = (collateral_amount_d18.mul(col_price_usd)).div(1e6);\n        return c_dollar_value_d18.sub((c_dollar_value_d18.mul(mint_fee)).div(1e6));\n    }\n\n    function calcMintAlgorithmicFRAX(uint256 mint_fee, uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) {\n        uint256 fxs_dollar_value_d18 = fxs_amount_d18.mul(fxs_price_usd).div(1e6);\n        return fxs_dollar_value_d18.sub((fxs_dollar_value_d18.mul(mint_fee)).div(1e6));\n    }\n\n    // Must be internal because of the struct\n    function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) {\n        // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error\n        // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount \n        uint256 fxs_dollar_value_d18;\n        uint256 c_dollar_value_d18;\n        \n        // Scoping for stack concerns\n        {    \n            // USD amounts of the collateral and the FXS\n            fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6);\n            c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6);\n\n        }\n        uint calculated_fxs_dollar_value_d18 = \n                    (c_dollar_value_d18.mul(1e6).div(params.col_ratio))\n                    .sub(c_dollar_value_d18);\n\n        uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd);\n\n        return (\n            (c_dollar_value_d18.add(calculated_fxs_dollar_value_d18)).sub(((c_dollar_value_d18.add(calculated_fxs_dollar_value_d18)).mul(params.mint_fee)).div(1e6)),\n            calculated_fxs_needed\n        );\n    }\n\n    function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount, uint256 redemption_fee) public pure returns (uint256) {\n        uint256 collateral_needed_d18 = FRAX_amount.mul(1e6).div(col_price_usd);\n        return collateral_needed_d18.sub((collateral_needed_d18.mul(redemption_fee)).div(1e6));\n    }\n\n    // Must be internal because of the struct\n    function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) {\n        // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral\n        require(params.excess_collateral_dollar_value_d18 \u003e 0, \"No excess collateral to buy back!\");\n\n        // Make sure not to take more than is available\n        uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6);\n        require(fxs_dollar_value_d18 \u003c= params.excess_collateral_dollar_value_d18, \"You are trying to buy back more than the excess!\");\n\n        // Get the equivalent amount of collateral based on the market value of FXS provided \n        uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd);\n        //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6));\n\n        return (\n            collateral_equivalent_d18\n        );\n\n    }\n\n\n    // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization)\n    function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) {\n        uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6\n        // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize\n        uint256 recollateralization_left = target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow\n        return(recollateralization_left);\n    }\n\n    function calcRecollateralizeFRAXInner(\n        uint256 collateral_amount, \n        uint256 col_price,\n        uint256 global_collat_value,\n        uint256 frax_total_supply,\n        uint256 global_collateral_ratio\n    ) public pure returns (uint256, uint256) {\n        uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6);\n        uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6\n        uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6);\n\n        uint256 amount_to_recollat;\n        if(collat_value_attempted \u003c= recollat_possible){\n            amount_to_recollat = collat_value_attempted;\n        } else {\n            amount_to_recollat = recollat_possible;\n        }\n\n        return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat);\n\n    }\n\n}"},"FXS.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./Context.sol\";\nimport \"./ERC20Custom.sol\";\nimport \"./IERC20.sol\";\nimport \"./Frax.sol\";\nimport \"./SafeMath.sol\";\nimport \"./AccessControl.sol\";\n\ncontract FRAXShares is ERC20Custom, AccessControl {\n    using SafeMath for uint256;\n\n    /* ========== STATE VARIABLES ========== */\n\n    string public symbol;\n    string public name;\n    uint8 public constant decimals = 18;\n    address public FRAXStablecoinAdd;\n    \n    uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis\n    uint256 public FXS_DAO_min; // Minimum FXS required to join DAO groups \n\n    address public owner_address;\n    address public oracle_address;\n    address public timelock_address; // Governance timelock address\n    FRAXStablecoin private FRAX;\n\n    bool public trackingVotes = true; // Tracking votes (only change if need to disable votes)\n\n    // A checkpoint for marking number of votes from a given block\n    struct Checkpoint {\n        uint32 fromBlock;\n        uint96 votes;\n    }\n\n    // A record of votes checkpoints for each account, by index\n    mapping (address =\u003e mapping (uint32 =\u003e Checkpoint)) public checkpoints;\n\n    // The number of checkpoints for each account\n    mapping (address =\u003e uint32) public numCheckpoints;\n\n    /* ========== MODIFIERS ========== */\n\n    modifier onlyPools() {\n       require(FRAX.frax_pools(msg.sender) == true, \"Only frax pools can mint new FRAX\");\n        _;\n    } \n    \n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == owner_address || msg.sender == timelock_address, \"You are not an owner or the governance timelock\");\n        _;\n    }\n\n    /* ========== CONSTRUCTOR ========== */\n\n    constructor(\n        string memory _name,\n        string memory _symbol, \n        address _oracle_address,\n        address _owner_address,\n        address _timelock_address\n    ) public {\n        name = _name;\n        symbol = _symbol;\n        owner_address = _owner_address;\n        oracle_address = _oracle_address;\n        timelock_address = _timelock_address;\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        _mint(owner_address, genesis_supply);\n\n        // Do a checkpoint for the owner\n        _writeCheckpoint(owner_address, 0, 0, uint96(genesis_supply));\n    }\n\n    /* ========== RESTRICTED FUNCTIONS ========== */\n\n    function setOracle(address new_oracle) external onlyByOwnerOrGovernance {\n        oracle_address = new_oracle;\n    }\n\n    function setTimelock(address new_timelock) external onlyByOwnerOrGovernance {\n        timelock_address = new_timelock;\n    }\n    \n    function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance {\n        FRAX = FRAXStablecoin(frax_contract_address);\n    }\n    \n    function setFXSMinDAO(uint256 min_FXS) external onlyByOwnerOrGovernance {\n        FXS_DAO_min = min_FXS;\n    }\n\n    function setOwner(address _owner_address) external onlyByOwnerOrGovernance {\n        owner_address = _owner_address;\n    }\n\n    function mint(address to, uint256 amount) public onlyPools {\n        _mint(to, amount);\n    }\n    \n    // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) \n    function pool_mint(address m_address, uint256 m_amount) external onlyPools {        \n        if(trackingVotes){\n            uint32 srcRepNum = numCheckpoints[address(this)];\n            uint96 srcRepOld = srcRepNum \u003e 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;\n            uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), \"pool_mint new votes overflows\");\n            _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes\n            trackVotes(address(this), m_address, uint96(m_amount));\n        }\n\n        super._mint(m_address, m_amount);\n        emit FXSMinted(address(this), m_address, m_amount);\n    }\n\n    // This function is what other frax pools will call to burn FXS \n    function pool_burn_from(address b_address, uint256 b_amount) external onlyPools {\n        if(trackingVotes){\n            trackVotes(b_address, address(this), uint96(b_amount));\n            uint32 srcRepNum = numCheckpoints[address(this)];\n            uint96 srcRepOld = srcRepNum \u003e 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;\n            uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), \"pool_burn_from new votes underflows\");\n            _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes\n        }\n\n        super._burnFrom(b_address, b_amount);\n        emit FXSBurned(b_address, address(this), b_amount);\n    }\n\n    function toggleVotes() external onlyByOwnerOrGovernance {\n        trackingVotes = !trackingVotes;\n    }\n\n    /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */\n\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        if(trackingVotes){\n            // Transfer votes\n            trackVotes(_msgSender(), recipient, uint96(amount));\n        }\n\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        if(trackingVotes){\n            // Transfer votes\n            trackVotes(sender, recipient, uint96(amount));\n        }\n\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n\n        return true;\n    }\n\n    /* ========== PUBLIC FUNCTIONS ========== */\n\n    /**\n     * @notice Gets the current votes balance for `account`\n     * @param account The address to get votes balance\n     * @return The number of current votes for `account`\n     */\n    function getCurrentVotes(address account) external view returns (uint96) {\n        uint32 nCheckpoints = numCheckpoints[account];\n        return nCheckpoints \u003e 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;\n    }\n\n    /**\n     * @notice Determine the prior number of votes for an account as of a block number\n     * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.\n     * @param account The address of the account to check\n     * @param blockNumber The block number to get the vote balance at\n     * @return The number of votes the account had as of the given block\n     */\n    function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {\n        require(blockNumber \u003c block.number, \"FXS::getPriorVotes: not yet determined\");\n\n        uint32 nCheckpoints = numCheckpoints[account];\n        if (nCheckpoints == 0) {\n            return 0;\n        }\n\n        // First check most recent balance\n        if (checkpoints[account][nCheckpoints - 1].fromBlock \u003c= blockNumber) {\n            return checkpoints[account][nCheckpoints - 1].votes;\n        }\n\n        // Next check implicit zero balance\n        if (checkpoints[account][0].fromBlock \u003e blockNumber) {\n            return 0;\n        }\n\n        uint32 lower = 0;\n        uint32 upper = nCheckpoints - 1;\n        while (upper \u003e lower) {\n            uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\n            Checkpoint memory cp = checkpoints[account][center];\n            if (cp.fromBlock == blockNumber) {\n                return cp.votes;\n            } else if (cp.fromBlock \u003c blockNumber) {\n                lower = center;\n            } else {\n                upper = center - 1;\n            }\n        }\n        return checkpoints[account][lower].votes;\n    }\n\n    /* ========== INTERNAL FUNCTIONS ========== */\n\n    // From compound\u0027s _moveDelegates\n    // Keep track of votes. \"Delegates\" is a misnomer here\n    function trackVotes(address srcRep, address dstRep, uint96 amount) internal {\n        if (srcRep != dstRep \u0026\u0026 amount \u003e 0) {\n            if (srcRep != address(0)) {\n                uint32 srcRepNum = numCheckpoints[srcRep];\n                uint96 srcRepOld = srcRepNum \u003e 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;\n                uint96 srcRepNew = sub96(srcRepOld, amount, \"FXS::_moveVotes: vote amount underflows\");\n                _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);\n            }\n\n            if (dstRep != address(0)) {\n                uint32 dstRepNum = numCheckpoints[dstRep];\n                uint96 dstRepOld = dstRepNum \u003e 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;\n                uint96 dstRepNew = add96(dstRepOld, amount, \"FXS::_moveVotes: vote amount overflows\");\n                _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);\n            }\n        }\n    }\n\n    function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {\n      uint32 blockNumber = safe32(block.number, \"FXS::_writeCheckpoint: block number exceeds 32 bits\");\n\n      if (nCheckpoints \u003e 0 \u0026\u0026 checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {\n          checkpoints[voter][nCheckpoints - 1].votes = newVotes;\n      } else {\n          checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);\n          numCheckpoints[voter] = nCheckpoints + 1;\n      }\n\n      emit VoterVotesChanged(voter, oldVotes, newVotes);\n    }\n\n    function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {\n        require(n \u003c 2**32, errorMessage);\n        return uint32(n);\n    }\n\n    function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {\n        require(n \u003c 2**96, errorMessage);\n        return uint96(n);\n    }\n\n    function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {\n        uint96 c = a + b;\n        require(c \u003e= a, errorMessage);\n        return c;\n    }\n\n    function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {\n        require(b \u003c= a, errorMessage);\n        return a - b;\n    }\n\n    function getChainId() internal pure returns (uint) {\n        uint256 chainId;\n        assembly { chainId := chainid() }\n        return chainId;\n    }\n\n    /* ========== EVENTS ========== */\n    \n    /// @notice An event thats emitted when a voters account\u0027s vote balance changes\n    event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance);\n\n    // Track FXS burned\n    event FXSBurned(address indexed from, address indexed to, uint256 amount);\n\n    // Track FXS minted\n    event FXSMinted(address indexed from, address indexed to, uint256 amount);\n\n}\n"},"Governance.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./FXS.sol\";\n\n// From https://compound.finance/docs/governance\n// and https://github.com/compound-finance/compound-protocol/tree/master/contracts/Governance\ncontract GovernorAlpha {\n    /// @notice The name of this contract\n    string public constant name = \"FXS Governor Alpha\";\n\n    /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed\n    function quorumVotes() public pure returns (uint) { return 4000000e18; } // 4,000,000 = 4% of FXS\n\n    /// @notice The number of votes required in order for a voter to become a proposer\n    function proposalThreshold() public pure returns (uint) { return 1000000e18; } // 1,000,000 = 1% of FXS\n\n    /// @notice The maximum number of actions that can be included in a proposal\n    function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions\n\n    /// @notice The delay before voting on a proposal may take place, once proposed\n    // This also helps protect against flash loan attacks because only the vote balance at the proposal start block is considered\n    function votingDelay() public pure returns (uint) { return 1; } // 1 block\n\n    /// @notice The duration of voting on a proposal, in blocks\n    // function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks)\n    uint public votingPeriod = 17280;\n    \n    /// @notice The address of the Timelock\n    TimelockInterface public timelock;\n\n    // The address of the FXS token\n    FRAXShares public fxs;\n\n    /// @notice The address of the Governor Guardian\n    address public guardian;\n\n    /// @notice The total number of proposals\n    uint public proposalCount = 0;\n\n    struct Proposal {\n        // @notice Unique id for looking up a proposal\n        uint id;\n\n        // @notice Creator of the proposal\n        address proposer;\n\n        // @notice The timestamp that the proposal will be available for execution, set once the vote succeeds\n        uint eta;\n\n        // @notice the ordered list of target addresses for calls to be made\n        address[] targets;\n\n        // @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made\n        uint[] values;\n\n        // @notice The ordered list of function signatures to be called\n        string[] signatures;\n\n        // @notice The ordered list of calldata to be passed to each call\n        bytes[] calldatas;\n\n        // @notice The block at which voting begins: holders must delegate their votes prior to this block\n        uint startBlock;\n\n        // @notice The block at which voting ends: votes must be cast prior to this block\n        uint endBlock;\n\n        // @notice Current number of votes in favor of this proposal\n        uint forVotes;\n\n        // @notice Current number of votes in opposition to this proposal\n        uint againstVotes;\n\n        // @notice Flag marking whether the proposal has been canceled\n        bool canceled;\n\n        // @notice Flag marking whether the proposal has been executed\n        bool executed;\n\n        // @notice Title of the proposal (human-readable)\n        string title;\n\n        // @notice Description of the proposall (human-readable)\n        string description;\n\n        // @notice Receipts of ballots for the entire set of voters\n        mapping (address =\u003e Receipt) receipts;\n    }\n\n    /// @notice Ballot receipt record for a voter\n    struct Receipt {\n        // @notice Whether or not a vote has been cast\n        bool hasVoted;\n\n        // @notice Whether or not the voter supports the proposal\n        bool support;\n\n        // @notice The number of votes the voter had, which were cast\n        uint96 votes;\n    }\n\n    /// @notice Possible states that a proposal may be in\n    enum ProposalState {\n        Pending,\n        Active,\n        Canceled,\n        Defeated,\n        Succeeded,\n        Queued,\n        Expired,\n        Executed\n    }\n\n    /// @notice The official record of all proposals ever proposed\n    mapping (uint =\u003e Proposal) public proposals;\n\n    /// @notice The latest proposal for each proposer\n    mapping (address =\u003e uint) public latestProposalIds;\n\n    /// @notice The EIP-712 typehash for the contract\u0027s domain\n    bytes32 public constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\n\n    /// @notice The EIP-712 typehash for the ballot struct used by the contract\n    bytes32 public constant BALLOT_TYPEHASH = keccak256(\"Ballot(uint256 proposalId,bool support)\");\n\n    /// @notice An event emitted when a new proposal is created\n    event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);\n\n    /// @notice An event emitted when a vote has been cast on a proposal\n    event VoteCast(address voter, uint proposalId, bool support, uint votes);\n\n    /// @notice An event emitted when a proposal has been canceled\n    event ProposalCanceled(uint id);\n\n    /// @notice An event emitted when a proposal has been queued in the Timelock\n    event ProposalQueued(uint id, uint eta);\n\n    /// @notice An event emitted when a proposal has been executed in the Timelock\n    event ProposalExecuted(uint id);\n\n    constructor(address timelock_, address fxs_, address guardian_) public {\n        timelock = TimelockInterface(timelock_);\n        fxs = FRAXShares(fxs_);\n        guardian = guardian_;\n    }\n\n    function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory title, string memory description) public returns (uint) {\n        require(fxs.getPriorVotes(msg.sender, sub256(block.number, 1)) \u003e= proposalThreshold(), \"GovernorAlpha::propose: proposer votes below proposal threshold\");\n        require(targets.length == values.length \u0026\u0026 targets.length == signatures.length \u0026\u0026 targets.length == calldatas.length, \"GovernorAlpha::propose: proposal function information arity mismatch\");\n        require(targets.length != 0, \"GovernorAlpha::propose: must provide actions\");\n        require(targets.length \u003c= proposalMaxOperations(), \"GovernorAlpha::propose: too many actions\");\n\n        uint latestProposalId = latestProposalIds[msg.sender];\n        if (latestProposalId != 0) {\n          ProposalState proposersLatestProposalState = state(latestProposalId);\n          require(proposersLatestProposalState != ProposalState.Active, \"GovernorAlpha::propose: one live proposal per proposer, found an already active proposal\");\n          require(proposersLatestProposalState != ProposalState.Pending, \"GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal\");\n        }\n\n        uint startBlock = add256(block.number, votingDelay());\n        uint endBlock = add256(startBlock, votingPeriod);\n\n        proposalCount++;\n        Proposal memory newProposal = Proposal({\n            id: proposalCount,\n            proposer: msg.sender,\n            eta: 0,\n            targets: targets,\n            values: values,\n            signatures: signatures,\n            calldatas: calldatas,\n            startBlock: startBlock,\n            endBlock: endBlock,\n            forVotes: 0,\n            againstVotes: 0,\n            canceled: false,\n            executed: false,\n            title: title,\n            description: description\n        });\n\n        proposals[newProposal.id] = newProposal;\n        latestProposalIds[newProposal.proposer] = newProposal.id;\n\n        emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);\n        return newProposal.id;\n    }\n\n    function queue(uint proposalId) public {\n        require(state(proposalId) == ProposalState.Succeeded, \"GovernorAlpha::queue: proposal can only be queued if it succeeded\");\n        Proposal storage proposal = proposals[proposalId];\n        uint eta = add256(block.timestamp, timelock.delay());\n        for (uint i = 0; i \u003c proposal.targets.length; i++) {\n            _queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);\n        }\n        proposal.eta = eta;\n        emit ProposalQueued(proposalId, eta);\n    }\n\n    function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {\n        require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), \"GovernorAlpha::_queueOrRevert: proposal action already queued at eta\");\n        timelock.queueTransaction(target, value, signature, data, eta);\n    }\n\n    function execute(uint proposalId) public payable {\n        require(state(proposalId) == ProposalState.Queued, \"GovernorAlpha::execute: proposal can only be executed if it is queued\");\n        Proposal storage proposal = proposals[proposalId];\n        proposal.executed = true;\n        for (uint i = 0; i \u003c proposal.targets.length; i++) {\n            timelock.executeTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);\n        }\n        emit ProposalExecuted(proposalId);\n    }\n\n    function cancel(uint proposalId) public {\n        ProposalState state = state(proposalId);\n        require(state != ProposalState.Executed, \"GovernorAlpha::cancel: cannot cancel executed proposal\");\n\n        Proposal storage proposal = proposals[proposalId];\n        require(msg.sender == guardian || fxs.getPriorVotes(proposal.proposer, sub256(block.number, 1)) \u003c proposalThreshold(), \"GovernorAlpha::cancel: proposer at or above threshold\");\n\n        proposal.canceled = true;\n        for (uint i = 0; i \u003c proposal.targets.length; i++) {\n            timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);\n        }\n\n        emit ProposalCanceled(proposalId);\n    }\n\n    function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {\n        Proposal storage p = proposals[proposalId];\n        return (p.targets, p.values, p.signatures, p.calldatas);\n    }\n\n    function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {\n        return proposals[proposalId].receipts[voter];\n    }\n\n    function state(uint proposalId) public view returns (ProposalState) {\n        require(proposalCount \u003e= proposalId \u0026\u0026 proposalId \u003e 0, \"GovernorAlpha::state: invalid proposal id\");\n        Proposal storage proposal = proposals[proposalId];\n        if (proposal.canceled) {\n            return ProposalState.Canceled;\n        } else if (block.number \u003c= proposal.startBlock) {\n            return ProposalState.Pending;\n        } else if (block.number \u003c= proposal.endBlock) {\n            return ProposalState.Active;\n        } else if (proposal.forVotes \u003c= proposal.againstVotes || proposal.forVotes \u003c quorumVotes()) {\n            return ProposalState.Defeated;\n        } else if (proposal.eta == 0) {\n            return ProposalState.Succeeded;\n        } else if (proposal.executed) {\n            return ProposalState.Executed;\n        } else if (block.timestamp \u003e= add256(proposal.eta, timelock.GRACE_PERIOD())) {\n            return ProposalState.Expired;\n        } else {\n            return ProposalState.Queued;\n        }\n    }\n\n    function castVote(uint proposalId, bool support) public {\n        return _castVote(msg.sender, proposalId, support);\n    }\n\n    function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {\n        bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));\n        bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));\n        bytes32 digest = keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n        address signatory = ecrecover(digest, v, r, s);\n        require(signatory != address(0), \"GovernorAlpha::castVoteBySig: invalid signature\");\n        return _castVote(signatory, proposalId, support);\n    }\n\n    function _castVote(address voter, uint proposalId, bool support) internal {\n        require(state(proposalId) == ProposalState.Active, \"GovernorAlpha::_castVote: voting is closed\");\n        Proposal storage proposal = proposals[proposalId];\n        Receipt storage receipt = proposal.receipts[voter];\n        require(receipt.hasVoted == false, \"GovernorAlpha::_castVote: voter already voted\");\n        uint96 votes = fxs.getPriorVotes(voter, proposal.startBlock);\n\n        if (support) {\n            proposal.forVotes = add256(proposal.forVotes, votes);\n        } else {\n            proposal.againstVotes = add256(proposal.againstVotes, votes);\n        }\n\n        receipt.hasVoted = true;\n        receipt.support = support;\n        receipt.votes = votes;\n\n        emit VoteCast(voter, proposalId, support, votes);\n    }\n\n    function __acceptAdmin() public {\n        require(msg.sender == guardian, \"GovernorAlpha::__acceptAdmin: sender must be gov guardian\");\n        timelock.acceptAdmin();\n    }\n\n    function __abdicate() public {\n        require(msg.sender == guardian, \"GovernorAlpha::__abdicate: sender must be gov guardian\");\n        guardian = address(0);\n    }\n\n    function __setVotingPeriod(uint period) public {\n        require(msg.sender == guardian, \"GovernorAlpha::__setVotingPeriod: sender must be gov guardian\");\n        votingPeriod = period;\n    }\n\n    function __setTimelockAddress(address timelock_) public {\n        require(msg.sender == guardian, \"GovernorAlpha::__setTimelockAddress: sender must be gov guardian\");\n        timelock = TimelockInterface(timelock_);\n    }\n\n    function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {\n        require(msg.sender == guardian, \"GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian\");\n        timelock.queueTransaction(address(timelock), 0, \"setPendingAdmin(address)\", abi.encode(newPendingAdmin), eta);\n    }\n\n    function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {\n        require(msg.sender == guardian, \"GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian\");\n        timelock.executeTransaction(address(timelock), 0, \"setPendingAdmin(address)\", abi.encode(newPendingAdmin), eta);\n    }\n\n    function add256(uint256 a, uint256 b) internal pure returns (uint) {\n        uint c = a + b;\n        require(c \u003e= a, \"addition overflow\");\n        return c;\n    }\n\n    function sub256(uint256 a, uint256 b) internal pure returns (uint) {\n        require(b \u003c= a, \"subtraction underflow\");\n        return a - b;\n    }\n\n    function getChainId() internal pure returns (uint) {\n        uint chainId;\n        assembly { chainId := chainid() }\n        return chainId;\n    }\n}\n\ninterface TimelockInterface {\n    function delay() external view returns (uint);\n    function GRACE_PERIOD() external view returns (uint);\n    function acceptAdmin() external;\n    function queuedTransactions(bytes32 hash) external view returns (bool);\n    function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);\n    function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;\n    function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);\n}\n"},"IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./Context.sol\";\nimport \"./SafeMath.sol\";\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP. Does not include\n * the optional functions; to access them see {ERC20Detailed}.\n */\ninterface IERC20 {\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller\u0027s account to `recipient`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller\u0027s tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender\u0027s allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `sender` to `recipient` using the\n     * allowance mechanism. `amount` is then deducted from the caller\u0027s\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n\n"},"IStakingRewards.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n\ninterface IStakingRewards {\n    // Views\n    function lastTimeRewardApplicable() external view returns (uint256);\n\n    function rewardPerToken() external view returns (uint256);\n\n    function earned(address account) external view returns (uint256);\n\n    function getRewardForDuration() external view returns (uint256);\n\n    function totalSupply() external view returns (uint256);\n\n    function balanceOf(address account) external view returns (uint256);\n\n    // Mutative\n\n    function stake(uint256 amount) external;\n\n    function withdraw(uint256 amount) external;\n\n    function getReward() external;\n\n    //function exit() external;\n}\n"},"IUniswapV2Callee.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2Callee {\n    function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;\n}\n"},"IUniswapV2ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2ERC20 {\n    event Approval(address indexed owner, address indexed spender, uint value);\n    event Transfer(address indexed from, address indexed to, uint value);\n\n    function name() external pure returns (string memory);\n    function symbol() external pure returns (string memory);\n    function decimals() external pure returns (uint8);\n    function totalSupply() external view returns (uint);\n    function balanceOf(address owner) external view returns (uint);\n    function allowance(address owner, address spender) external view returns (uint);\n\n    function approve(address spender, uint value) external returns (bool);\n    function transfer(address to, uint value) external returns (bool);\n    function transferFrom(address from, address to, uint value) external returns (bool);\n\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n    function PERMIT_TYPEHASH() external pure returns (bytes32);\n    function nonces(address owner) external view returns (uint);\n\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n}\n"},"IUniswapV2Factory.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2Factory {\n    event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n    function feeTo() external view returns (address);\n    function feeToSetter() external view returns (address);\n\n    function getPair(address tokenA, address tokenB) external view returns (address pair);\n    function allPairs(uint) external view returns (address pair);\n    function allPairsLength() external view returns (uint);\n\n    function createPair(address tokenA, address tokenB) external returns (address pair);\n\n    function setFeeTo(address) external;\n    function setFeeToSetter(address) external;\n}\n"},"IUniswapV2Pair.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2Pair {\n    event Approval(address indexed owner, address indexed spender, uint value);\n    event Transfer(address indexed from, address indexed to, uint value);\n\n    function name() external pure returns (string memory);\n    function symbol() external pure returns (string memory);\n    function decimals() external pure returns (uint8);\n    function totalSupply() external view returns (uint);\n    function balanceOf(address owner) external view returns (uint);\n    function allowance(address owner, address spender) external view returns (uint);\n\n    function approve(address spender, uint value) external returns (bool);\n    function transfer(address to, uint value) external returns (bool);\n    function transferFrom(address from, address to, uint value) external returns (bool);\n\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n    function PERMIT_TYPEHASH() external pure returns (bytes32);\n    function nonces(address owner) external view returns (uint);\n\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n    event Mint(address indexed sender, uint amount0, uint amount1);\n    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n    event Swap(\n        address indexed sender,\n        uint amount0In,\n        uint amount1In,\n        uint amount0Out,\n        uint amount1Out,\n        address indexed to\n    );\n    event Sync(uint112 reserve0, uint112 reserve1);\n\n    function MINIMUM_LIQUIDITY() external pure returns (uint);\n    function factory() external view returns (address);\n    function token0() external view returns (address);\n    function token1() external view returns (address);\n    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n    function price0CumulativeLast() external view returns (uint);\n    function price1CumulativeLast() external view returns (uint);\n    function kLast() external view returns (uint);\n\n    function mint(address to) external returns (uint liquidity);\n    function burn(address to) external returns (uint amount0, uint amount1);\n    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;\n    function skim(address to) external;\n    function sync() external;\n\n    function initialize(address, address) external;\n\n\n\n\n\n\n\n\n\n\n\n\n    \n}\n"},"IUniswapV2Router01.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IUniswapV2Router01 {\n    function factory() external pure returns (address);\n    function WETH() external pure returns (address);\n\n    function addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB, uint liquidity);\n    function addLiquidityETH(\n        address token,\n        uint amountTokenDesired,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n    function removeLiquidity(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETH(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountToken, uint amountETH);\n    function removeLiquidityWithPermit(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETHWithPermit(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountToken, uint amountETH);\n    function swapExactTokensForTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapTokensForExactTokens(\n        uint amountOut,\n        uint amountInMax,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n\n    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);\n    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);\n    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);\n}"},"IUniswapV2Router02.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Router01.sol\u0027;\n\ninterface IUniswapV2Router02 is IUniswapV2Router01 {\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountETH);\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountETH);\n\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external payable;\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n}"},"IWETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ninterface IWETH {\n    function deposit() external payable;\n    function transfer(address to, uint value) external returns (bool);\n    function transferFrom(address src, address dst, uint wad) external returns (bool);\n    function withdraw(uint) external;\n}"},"Math.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a \u003e= b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a \u003c b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow, so we distribute\n        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);\n    }\n\n    // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n    function sqrt(uint y) internal pure returns (uint z) {\n        if (y \u003e 3) {\n            z = y;\n            uint x = y / 2 + 1;\n            while (x \u003c z) {\n                z = x;\n                x = (y / x + x) / 2;\n            }\n        } else if (y != 0) {\n            z = 1;\n        }\n    }\n}"},"MigrationHelper.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ncontract MigrationHelper {\n  address public owner;\n  uint256 public gov_to_timelock_eta;\n\n  modifier restricted() {\n    if (msg.sender == owner) _;\n  }\n\n  constructor(address _owner) public {\n    owner = _owner;\n  }\n\n  function setGovToTimeLockETA(uint256 _eta) public restricted {\n    gov_to_timelock_eta = _eta;\n  }\n}\n"},"Migrations.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\ncontract Migrations {\n  address public owner;\n  uint public last_completed_migration;\n\n  modifier restricted() {\n    if (msg.sender == owner) _;\n  }\n\n  constructor() public {\n    owner = msg.sender;\n  }\n\n  function setCompleted(uint completed) public restricted {\n    last_completed_migration = completed;\n  }\n}\n"},"Owned.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// https://docs.synthetix.io/contracts/Owned\ncontract Owned {\n    address public owner;\n    address public nominatedOwner;\n\n    constructor(address _owner) public {\n        require(_owner != address(0), \"Owner address cannot be 0\");\n        owner = _owner;\n        emit OwnerChanged(address(0), _owner);\n    }\n\n    function nominateNewOwner(address _owner) external onlyOwner {\n        nominatedOwner = _owner;\n        emit OwnerNominated(_owner);\n    }\n\n    function acceptOwnership() external {\n        require(msg.sender == nominatedOwner, \"You must be nominated before you can accept ownership\");\n        emit OwnerChanged(owner, nominatedOwner);\n        owner = nominatedOwner;\n        nominatedOwner = address(0);\n    }\n\n    modifier onlyOwner {\n        require(msg.sender == owner, \"Only the contract owner may perform this action\");\n        _;\n    }\n\n    event OwnerNominated(address newOwner);\n    event OwnerChanged(address oldOwner, address newOwner);\n}"},"Pausable.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// Inheritance\nimport \"./Owned.sol\";\n\n// https://docs.synthetix.io/contracts/Pausable\nabstract contract Pausable is Owned {\n    uint public lastPauseTime;\n    bool public paused;\n\n    constructor() internal {\n        // This contract is abstract, and thus cannot be instantiated directly\n        require(owner != address(0), \"Owner must be set\");\n        // Paused will be false, and lastPauseTime will be 0 upon initialisation\n    }\n\n    /**\n     * @notice Change the paused state of the contract\n     * @dev Only the contract owner may call this.\n     */\n    function setPaused(bool _paused) external onlyOwner {\n        // Ensure we\u0027re actually changing the state before we do anything\n        if (_paused == paused) {\n            return;\n        }\n\n        // Set our paused state.\n        paused = _paused;\n\n        // If applicable, set the last pause time.\n        if (paused) {\n            lastPauseTime = now;\n        }\n\n        // Let everyone know that our pause state has changed.\n        emit PauseChanged(paused);\n    }\n\n    event PauseChanged(bool isPaused);\n\n    modifier notPaused {\n        require(!paused, \"This action cannot be performed while the contract is paused\");\n        _;\n    }\n}"},"Pool_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FraxPool.sol\";\n\ncontract Pool_USDC is FraxPool {\n    address public USDC_address;\n    constructor(\n        address _frax_contract_address,\n        address _fxs_contract_address,\n        address _collateral_address,\n        address _creator_address,\n        address _timelock_address,\n        uint256 _pool_ceiling\n    ) \n    FraxPool(_frax_contract_address, _fxs_contract_address, _collateral_address, _creator_address, _timelock_address, _pool_ceiling)\n    public {\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        USDC_address = _collateral_address;\n    }\n}\n"},"Pool_USDT.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FraxPool.sol\";\n\ncontract Pool_USDT is FraxPool {\n    address public USDT_address;\n    constructor(\n        address _frax_contract_address,\n        address _fxs_contract_address,\n        address _collateral_address,\n        address _creator_address,\n        address _timelock_address,\n        uint256 _pool_ceiling\n    ) \n    FraxPool(_frax_contract_address, _fxs_contract_address, _collateral_address, _creator_address, _timelock_address, _pool_ceiling)\n    public {\n        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());\n        USDT_address = _collateral_address;\n    }\n}\n"},"ReentrancyGuard.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\ncontract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot\u0027s contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler\u0027s defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction\u0027s gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor () internal {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and make it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}"},"RewardsDistributionRecipient.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// Inheritance\nimport \"./Owned.sol\";\n\n\n// https://docs.synthetix.io/contracts/RewardsDistributionRecipient\nabstract contract RewardsDistributionRecipient is Owned {\n    address public rewardsDistribution;\n\n    //function notifyRewardAmount(uint256 reward) external virtual;\n\n    modifier onlyRewardsDistribution() {\n        require(msg.sender == rewardsDistribution, \"Caller is not RewardsDistribution contract\");\n        _;\n    }\n\n    function setRewardsDistribution(address _rewardsDistribution) external onlyOwner {\n        rewardsDistribution = _rewardsDistribution;\n    }\n}\n"},"SafeERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using SafeMath for uint256;\n    using Address for address;\n\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // \u0027safeIncreaseAllowance\u0027 and \u0027safeDecreaseAllowance\u0027\n        // solhint-disable-next-line max-line-length\n        require((value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).add(value);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity\u0027s return data size checking mechanism, since\n        // we\u0027re implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length \u003e 0) { // Return data is optional\n            // solhint-disable-next-line max-line-length\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}"},"SafeMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n/**\n * @dev Wrappers over Solidity\u0027s arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it\u0027s recommended to use it always.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity\u0027s `+` operator.\n     *\n     * Requirements:\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c \u003e= a, \"SafeMath: addition overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity\u0027s `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        return sub(a, b, \"SafeMath: subtraction overflow\");\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity\u0027s `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot overflow.\n     *\n     * _Available since v2.4.0._\n     */\n    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b \u003c= a, errorMessage);\n        uint256 c = a - b;\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity\u0027s `*` operator.\n     *\n     * Requirements:\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        // Gas optimization: this is cheaper than requiring \u0027a\u0027 not being zero, but the\n        // benefit is lost if \u0027b\u0027 is also tested.\n        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n        if (a == 0) {\n            return 0;\n        }\n\n        uint256 c = a * b;\n        require(c / a == b, \"SafeMath: multiplication overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers. Reverts on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        return div(a, b, \"SafeMath: division by zero\");\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     *\n     * _Available since v2.4.0._\n     */\n    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        // Solidity only automatically asserts when dividing by 0\n        require(b \u003e 0, errorMessage);\n        uint256 c = a / b;\n        // assert(a == b * c + a % b); // There is no case in which this doesn\u0027t hold\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts when dividing by zero.\n     *\n     * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        return mod(a, b, \"SafeMath: modulo by zero\");\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts with custom message when dividing by zero.\n     *\n     * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     *\n     * _Available since v2.4.0._\n     */\n    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b != 0, errorMessage);\n        return a % b;\n    }\n}"},"Stake_FRAX_FXS.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./StakingRewards.sol\";\n\ncontract Stake_FRAX_FXS is StakingRewards {\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) \n    StakingRewards(_owner, _rewardsDistribution, _rewardsToken, _stakingToken, _frax_address, _timelock_address, _pool_weight)\n    public {}\n}"},"Stake_FRAX_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./StakingRewards.sol\";\n\ncontract Stake_FRAX_USDC is StakingRewards {\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) \n    StakingRewards(_owner, _rewardsDistribution, _rewardsToken, _stakingToken, _frax_address, _timelock_address, _pool_weight)\n    public {}\n}"},"Stake_FRAX_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./StakingRewards.sol\";\n\ncontract Stake_FRAX_WETH is StakingRewards {\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) \n    StakingRewards(_owner, _rewardsDistribution, _rewardsToken, _stakingToken, _frax_address, _timelock_address, _pool_weight)\n    public {}\n}"},"Stake_FXS_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\nimport \"./StakingRewards.sol\";\n\ncontract Stake_FXS_WETH is StakingRewards {\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) \n    StakingRewards(_owner, _rewardsDistribution, _rewardsToken, _stakingToken, _frax_address, _timelock_address, _pool_weight)\n    public {}\n}"},"StakingRewards.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\npragma experimental ABIEncoderV2;\n\n// Stolen with love from Synthetixio\n// https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol\n\nimport \"./Math.sol\";\nimport \"./SafeMath.sol\";\nimport \"./ERC20.sol\";\nimport \u0027./TransferHelper.sol\u0027;\nimport \"./SafeERC20.sol\";\nimport \"./Frax.sol\";\nimport \"./ReentrancyGuard.sol\";\nimport \"./StringHelpers.sol\";\n\n// Inheritance\nimport \"./IStakingRewards.sol\";\nimport \"./RewardsDistributionRecipient.sol\";\nimport \"./Pausable.sol\";\n\ncontract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, Pausable {\n    using SafeMath for uint256;\n    using SafeERC20 for ERC20;\n\n    /* ========== STATE VARIABLES ========== */\n\n    FRAXStablecoin private FRAX;\n    ERC20 public rewardsToken;\n    ERC20 public stakingToken;\n    uint256 public periodFinish;\n\n    // Constant for various precisions\n    uint256 private constant PRICE_PRECISION = 1e6;\n    uint256 private constant MULTIPLIER_BASE = 1e6;\n\n    // Max reward per second\n    uint256 public rewardRate;\n\n    // uint256 public rewardsDuration = 86400 hours;\n    uint256 public rewardsDuration = 604800; // 7 * 86400  (7 days)\n\n    uint256 public lastUpdateTime;\n    uint256 public rewardPerTokenStored = 0;\n    uint256 private pool_weight; // This staking pool\u0027s percentage of the total FXS being distributed by all pools, 6 decimals of precision\n\n    address public owner_address;\n    address public timelock_address; // Governance timelock address\n\n    uint256 public locked_stake_max_multiplier = 3000000; // 6 decimals of precision. 1x = 1000000\n    uint256 public locked_stake_time_for_max_multiplier = 3 * 365 * 86400; // 3 years\n    uint256 public locked_stake_min_time = 604800; // 7 * 86400  (7 days)\n    string private locked_stake_min_time_str = \"604800\"; // 7 days on genesis\n\n    uint256 public cr_boost_max_multiplier = 3000000; // 6 decimals of precision. 1x = 1000000\n\n    mapping(address =\u003e uint256) public userRewardPerTokenPaid;\n    mapping(address =\u003e uint256) public rewards;\n\n    uint256 private _staking_token_supply = 0;\n    uint256 private _staking_token_boosted_supply = 0;\n    mapping(address =\u003e uint256) private _unlocked_balances;\n    mapping(address =\u003e uint256) private _locked_balances;\n    mapping(address =\u003e uint256) private _boosted_balances;\n\n    mapping(address =\u003e LockedStake[]) private lockedStakes;\n\n    mapping(address =\u003e bool) public greylist;\n\n    bool public unlockedStakes; // Release lock stakes in case of system migration\n\n    struct LockedStake {\n        bytes32 kek_id;\n        uint256 start_timestamp;\n        uint256 amount;\n        uint256 ending_timestamp;\n        uint256 multiplier; // 6 decimals of precision. 1x = 1000000\n    }\n\n    /* ========== CONSTRUCTOR ========== */\n\n    constructor(\n        address _owner,\n        address _rewardsDistribution,\n        address _rewardsToken,\n        address _stakingToken,\n        address _frax_address,\n        address _timelock_address,\n        uint256 _pool_weight\n    ) public Owned(_owner){\n        owner_address = _owner;\n        rewardsToken = ERC20(_rewardsToken);\n        stakingToken = ERC20(_stakingToken);\n        FRAX = FRAXStablecoin(_frax_address);\n        rewardsDistribution = _rewardsDistribution;\n        lastUpdateTime = block.timestamp;\n        timelock_address = _timelock_address;\n        pool_weight = _pool_weight;\n        rewardRate = 380517503805175038; // (uint256(12000000e18)).div(365 * 86400); // Base emission rate of 12M FXS over the first year\n        rewardRate = rewardRate.mul(pool_weight).div(1e6);\n        unlockedStakes = false;\n    }\n\n    /* ========== VIEWS ========== */\n\n    function totalSupply() external override view returns (uint256) {\n        return _staking_token_supply;\n    }\n\n    function totalBoostedSupply() external view returns (uint256) {\n        return _staking_token_boosted_supply;\n    }\n\n    function stakingMultiplier(uint256 secs) public view returns (uint256) {\n        uint256 multiplier = uint(MULTIPLIER_BASE).add(secs.mul(locked_stake_max_multiplier.sub(MULTIPLIER_BASE)).div(locked_stake_time_for_max_multiplier));\n        if (multiplier \u003e locked_stake_max_multiplier) multiplier = locked_stake_max_multiplier;\n        return multiplier;\n    }\n\n    function crBoostMultiplier() public view returns (uint256) {\n        uint256 multiplier = uint(MULTIPLIER_BASE).add((uint(MULTIPLIER_BASE).sub(FRAX.global_collateral_ratio())).mul(cr_boost_max_multiplier.sub(MULTIPLIER_BASE)).div(MULTIPLIER_BASE) );\n        return multiplier;\n    }\n\n    // Total unlocked and locked liquidity tokens\n    function balanceOf(address account) external override view returns (uint256) {\n        return (_unlocked_balances[account]).add(_locked_balances[account]);\n    }\n\n    // Total unlocked liquidity tokens\n    function unlockedBalanceOf(address account) external view returns (uint256) {\n        return _unlocked_balances[account];\n    }\n\n    // Total locked liquidity tokens\n    function lockedBalanceOf(address account) public view returns (uint256) {\n        return _locked_balances[account];\n    }\n\n    // Total \u0027balance\u0027 used for calculating the percent of the pool the account owns\n    // Takes into account the locked stake time multiplier\n    function boostedBalanceOf(address account) external view returns (uint256) {\n        return _boosted_balances[account];\n    }\n\n    function lockedStakesOf(address account) external view returns (LockedStake[] memory) {\n        return lockedStakes[account];\n    }\n\n    function stakingDecimals() external view returns (uint256) {\n        return stakingToken.decimals();\n    }\n\n    function rewardsFor(address account) external view returns (uint256) {\n        // You may have use earned() instead, because of the order in which the contract executes \n        return rewards[account];\n    }\n\n    function lastTimeRewardApplicable() public override view returns (uint256) {\n        return Math.min(block.timestamp, periodFinish);\n    }\n\n    function rewardPerToken() public override view returns (uint256) {\n        if (_staking_token_supply == 0) {\n            return rewardPerTokenStored;\n        }\n        else {\n            return rewardPerTokenStored.add(\n                lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(crBoostMultiplier()).mul(1e18).div(PRICE_PRECISION).div(_staking_token_boosted_supply)\n            );\n        }\n    }\n\n    function earned(address account) public override view returns (uint256) {\n        return _boosted_balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);\n    }\n\n    // function earned(address account) public override view returns (uint256) {\n    //     return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).add(rewards[account]);\n    // }\n\n    function getRewardForDuration() external override view returns (uint256) {\n        return rewardRate.mul(rewardsDuration).mul(crBoostMultiplier()).div(PRICE_PRECISION);\n    }\n\n    /* ========== MUTATIVE FUNCTIONS ========== */\n\n    function stake(uint256 amount) external override nonReentrant notPaused updateReward(msg.sender) {\n        require(amount \u003e 0, \"Cannot stake 0\");\n        require(greylist[msg.sender] == false, \"address has been greylisted\");\n\n        // Pull the tokens from the staker\n        TransferHelper.safeTransferFrom(address(stakingToken), msg.sender, address(this), amount);\n\n        // Staking token supply and boosted supply\n        _staking_token_supply = _staking_token_supply.add(amount);\n        _staking_token_boosted_supply = _staking_token_boosted_supply.add(amount);\n\n        // Staking token balance and boosted balance\n        _unlocked_balances[msg.sender] = _unlocked_balances[msg.sender].add(amount);\n        _boosted_balances[msg.sender] = _boosted_balances[msg.sender].add(amount);\n\n        emit Staked(msg.sender, amount);\n    }\n\n    function stakeLocked(uint256 amount, uint256 secs) external nonReentrant notPaused updateReward(msg.sender) {\n        require(amount \u003e 0, \"Cannot stake 0\");\n        require(secs \u003e 0, \"Cannot wait for a negative number\");\n        require(greylist[msg.sender] == false, \"address has been greylisted\");\n        require(secs \u003e= locked_stake_min_time, StringHelpers.strConcat(\"Minimum stake time not met (\", locked_stake_min_time_str, \")\") );\n\n        uint256 multiplier = stakingMultiplier(secs);\n        uint256 boostedAmount = amount.mul(multiplier).div(PRICE_PRECISION);\n        lockedStakes[msg.sender].push(LockedStake(\n            keccak256(abi.encodePacked(msg.sender, block.timestamp, amount)),\n            block.timestamp,\n            amount,\n            block.timestamp.add(secs),\n            multiplier\n        ));\n\n        // Pull the tokens from the staker\n        TransferHelper.safeTransferFrom(address(stakingToken), msg.sender, address(this), amount);\n\n        // Staking token supply and boosted supply\n        _staking_token_supply = _staking_token_supply.add(amount);\n        _staking_token_boosted_supply = _staking_token_boosted_supply.add(boostedAmount);\n\n        // Staking token balance and boosted balance\n        _locked_balances[msg.sender] = _locked_balances[msg.sender].add(amount);\n        _boosted_balances[msg.sender] = _boosted_balances[msg.sender].add(boostedAmount);\n\n        emit StakeLocked(msg.sender, amount, secs);\n    }\n\n    function withdraw(uint256 amount) public override nonReentrant updateReward(msg.sender) {\n        require(amount \u003e 0, \"Cannot withdraw 0\");\n\n        // Staking token balance and boosted balance\n        _unlocked_balances[msg.sender] = _unlocked_balances[msg.sender].sub(amount);\n        _boosted_balances[msg.sender] = _boosted_balances[msg.sender].sub(amount);\n\n        // Staking token supply and boosted supply\n        _staking_token_supply = _staking_token_supply.sub(amount);\n        _staking_token_boosted_supply = _staking_token_boosted_supply.sub(amount);\n\n        // Give the tokens to the withdrawer\n        stakingToken.safeTransfer(msg.sender, amount);\n        emit Withdrawn(msg.sender, amount);\n    }\n\n    function withdrawLocked(bytes32 kek_id) public nonReentrant updateReward(msg.sender) {\n        LockedStake memory thisStake;\n        thisStake.amount = 0;\n        uint theIndex;\n        for (uint i = 0; i \u003c lockedStakes[msg.sender].length; i++){ \n            if (kek_id == lockedStakes[msg.sender][i].kek_id){\n                thisStake = lockedStakes[msg.sender][i];\n                theIndex = i;\n                break;\n            }\n        }\n        require(thisStake.kek_id == kek_id, \"Stake not found\");\n        require(block.timestamp \u003e= thisStake.ending_timestamp || unlockedStakes == true, \"Stake is still locked!\");\n\n        uint256 theAmount = thisStake.amount;\n        uint256 boostedAmount = theAmount.mul(thisStake.multiplier).div(PRICE_PRECISION);\n        if (theAmount \u003e 0){\n            // Staking token balance and boosted balance\n            _locked_balances[msg.sender] = _locked_balances[msg.sender].sub(theAmount);\n            _boosted_balances[msg.sender] = _boosted_balances[msg.sender].sub(boostedAmount);\n\n            // Staking token supply and boosted supply\n            _staking_token_supply = _staking_token_supply.sub(theAmount);\n            _staking_token_boosted_supply = _staking_token_boosted_supply.sub(boostedAmount);\n\n            // Remove the stake from the array\n            delete lockedStakes[msg.sender][theIndex];\n\n            // Give the tokens to the withdrawer\n            stakingToken.safeTransfer(msg.sender, theAmount);\n\n            emit WithdrawnLocked(msg.sender, theAmount, kek_id);\n        }\n\n    }\n\n    function getReward() public override nonReentrant updateReward(msg.sender) {\n        uint256 reward = rewards[msg.sender];\n        if (reward \u003e 0) {\n            rewards[msg.sender] = 0;\n            rewardsToken.transfer(msg.sender, reward);\n            emit RewardPaid(msg.sender, reward);\n        }\n    }\n/*\n    function exit() external override {\n        withdraw(_balances[msg.sender]);\n\n        // TODO: Add locked stakes too?\n\n        getReward();\n    }\n*/\n    function renewIfApplicable() external {\n        if (block.timestamp \u003e periodFinish) {\n            retroCatchUp();\n        }\n    }\n\n    // If the period expired, renew it\n    function retroCatchUp() internal {\n        // Failsafe check\n        require(block.timestamp \u003e periodFinish, \"Period has not expired yet!\");\n\n        // Ensure the provided reward amount is not more than the balance in the contract.\n        // This keeps the reward rate in the right range, preventing overflows due to\n        // very high values of rewardRate in the earned and rewardsPerToken functions;\n        // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.\n        uint256 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period\n        uint balance = rewardsToken.balanceOf(address(this));\n        require(rewardRate.mul(rewardsDuration).mul(crBoostMultiplier()).mul(num_periods_elapsed + 1).div(PRICE_PRECISION) \u003c= balance, \"Not enough FXS available for rewards!\");\n\n        // uint256 old_lastUpdateTime = lastUpdateTime;\n        // uint256 new_lastUpdateTime = block.timestamp;\n\n        // lastUpdateTime = periodFinish;\n        periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration));\n\n        rewardPerTokenStored = rewardPerToken();\n        lastUpdateTime = lastTimeRewardApplicable();\n\n        emit RewardsPeriodRenewed(address(stakingToken));\n    }\n\n    /* ========== RESTRICTED FUNCTIONS ========== */\n/*\n    // This notifies people that the reward is being changed\n    function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) {\n        // Needed to make compiler happy\n\n        \n        // if (block.timestamp \u003e= periodFinish) {\n        //     rewardRate = reward.mul(crBoostMultiplier()).div(rewardsDuration).div(PRICE_PRECISION);\n        // } else {\n        //     uint256 remaining = periodFinish.sub(block.timestamp);\n        //     uint256 leftover = remaining.mul(rewardRate);\n        //     rewardRate = reward.mul(crBoostMultiplier()).add(leftover).div(rewardsDuration).div(PRICE_PRECISION);\n        // }\n\n        // // Ensure the provided reward amount is not more than the balance in the contract.\n        // // This keeps the reward rate in the right range, preventing overflows due to\n        // // very high values of rewardRate in the earned and rewardsPerToken functions;\n        // // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.\n        // uint balance = rewardsToken.balanceOf(address(this));\n        // require(rewardRate \u003c= balance.div(rewardsDuration), \"Provided reward too high\");\n\n        // lastUpdateTime = block.timestamp;\n        // periodFinish = block.timestamp.add(rewardsDuration);\n        // emit RewardAdded(reward);\n    }\n*/\n    // Added to support recovering LP Rewards from other systems to be distributed to holders\n    function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance {\n        // Admin cannot withdraw the staking token from the contract\n        require(tokenAddress != address(stakingToken));\n        ERC20(tokenAddress).transfer(owner_address, tokenAmount);\n        emit Recovered(tokenAddress, tokenAmount);\n    }\n\n    function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance {\n        require(\n            periodFinish == 0 || block.timestamp \u003e periodFinish,\n            \"Previous rewards period must be complete before changing the duration for the new period\"\n        );\n        rewardsDuration = _rewardsDuration;\n        emit RewardsDurationUpdated(rewardsDuration);\n    }\n\n    function setMultipliers(uint256 _locked_stake_max_multiplier, uint256 _cr_boost_max_multiplier) external onlyByOwnerOrGovernance {\n        require(_locked_stake_max_multiplier \u003e= 1, \"Multiplier must be greater than or equal to 1\");\n        require(_cr_boost_max_multiplier \u003e= 1, \"Max CR Boost must be greater than or equal to 1\");\n\n        locked_stake_max_multiplier = _locked_stake_max_multiplier;\n        cr_boost_max_multiplier = _cr_boost_max_multiplier;\n        \n        emit MaxCRBoostMultiplier(cr_boost_max_multiplier);\n        emit LockedStakeMaxMultiplierUpdated(locked_stake_max_multiplier);\n    }\n\n    function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _locked_stake_time_for_max_multiplier, uint256 _locked_stake_min_time) external onlyByOwnerOrGovernance {\n        require(_locked_stake_time_for_max_multiplier \u003e= 1, \"Multiplier Max Time must be greater than or equal to 1\");\n        require(_locked_stake_min_time \u003e= 1, \"Multiplier Min Time must be greater than or equal to 1\");\n        \n        locked_stake_time_for_max_multiplier = _locked_stake_time_for_max_multiplier;\n\n        locked_stake_min_time = _locked_stake_min_time;\n        locked_stake_min_time_str = StringHelpers.uint2str(_locked_stake_min_time);\n\n        emit LockedStakeTimeForMaxMultiplier(locked_stake_time_for_max_multiplier);\n        emit LockedStakeMinTime(_locked_stake_min_time);\n    }\n\n    function initializeDefault() external onlyByOwnerOrGovernance {\n        lastUpdateTime = block.timestamp;\n        periodFinish = block.timestamp.add(rewardsDuration);\n        emit DefaultInitialization();\n    }\n\n    function greylistAddress(address _address) external onlyByOwnerOrGovernance {\n        greylist[_address] = !(greylist[_address]);\n    }\n\n    function unlockStakes() external onlyByOwnerOrGovernance {\n        unlockedStakes = !unlockedStakes;\n    }\n\n    function setRewardRate(uint256 _new_rate) external onlyByOwnerOrGovernance {\n        rewardRate = _new_rate;\n    }\n\n    function setOwnerAndTimelock(address _new_owner, address _new_timelock) external onlyByOwnerOrGovernance {\n        owner_address = _new_owner;\n        timelock_address = _new_timelock;\n    }\n\n    /* ========== MODIFIERS ========== */\n\n    modifier updateReward(address account) {\n        // Need to retro-adjust some things if the period hasn\u0027t been renewed, then start a new one\n        if (block.timestamp \u003e periodFinish) {\n            retroCatchUp();\n        }\n        else {\n            rewardPerTokenStored = rewardPerToken();\n            lastUpdateTime = lastTimeRewardApplicable();\n        }\n        if (account != address(0)) {\n            rewards[account] = earned(account);\n            userRewardPerTokenPaid[account] = rewardPerTokenStored;\n        }\n        _;\n    }\n\n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == owner_address || msg.sender == timelock_address, \"You are not the owner or the governance timelock\");\n        _;\n    }\n\n    /* ========== EVENTS ========== */\n\n    event RewardAdded(uint256 reward);\n    event Staked(address indexed user, uint256 amount);\n    event StakeLocked(address indexed user, uint256 amount, uint256 secs);\n    event Withdrawn(address indexed user, uint256 amount);\n    event WithdrawnLocked(address indexed user, uint256 amount, bytes32 kek_id);\n    event RewardPaid(address indexed user, uint256 reward);\n    event RewardsDurationUpdated(uint256 newDuration);\n    event Recovered(address token, uint256 amount);\n    event RewardsPeriodRenewed(address token);\n    event DefaultInitialization();\n    event LockedStakeMaxMultiplierUpdated(uint256 multiplier);\n    event LockedStakeTimeForMaxMultiplier(uint256 secs);\n    event LockedStakeMinTime(uint256 secs);\n    event MaxCRBoostMultiplier(uint256 multiplier);\n}\n"},"StringHelpers.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n\nlibrary StringHelpers {\n    function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {\n        bytes memory tmp = bytes(_a);\n        uint160 iaddr = 0;\n        uint160 b1;\n        uint160 b2;\n        for (uint i = 2; i \u003c 2 + 2 * 20; i += 2) {\n            iaddr *= 256;\n            b1 = uint160(uint8(tmp[i]));\n            b2 = uint160(uint8(tmp[i + 1]));\n            if ((b1 \u003e= 97) \u0026\u0026 (b1 \u003c= 102)) {\n                b1 -= 87;\n            } else if ((b1 \u003e= 65) \u0026\u0026 (b1 \u003c= 70)) {\n                b1 -= 55;\n            } else if ((b1 \u003e= 48) \u0026\u0026 (b1 \u003c= 57)) {\n                b1 -= 48;\n            }\n            if ((b2 \u003e= 97) \u0026\u0026 (b2 \u003c= 102)) {\n                b2 -= 87;\n            } else if ((b2 \u003e= 65) \u0026\u0026 (b2 \u003c= 70)) {\n                b2 -= 55;\n            } else if ((b2 \u003e= 48) \u0026\u0026 (b2 \u003c= 57)) {\n                b2 -= 48;\n            }\n            iaddr += (b1 * 16 + b2);\n        }\n        return address(iaddr);\n    }\n\n    function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) {\n        bytes memory a = bytes(_a);\n        bytes memory b = bytes(_b);\n        uint minLength = a.length;\n        if (b.length \u003c minLength) {\n            minLength = b.length;\n        }\n        for (uint i = 0; i \u003c minLength; i ++) {\n            if (a[i] \u003c b[i]) {\n                return -1;\n            } else if (a[i] \u003e b[i]) {\n                return 1;\n            }\n        }\n        if (a.length \u003c b.length) {\n            return -1;\n        } else if (a.length \u003e b.length) {\n            return 1;\n        } else {\n            return 0;\n        }\n    }\n\n    function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) {\n        bytes memory h = bytes(_haystack);\n        bytes memory n = bytes(_needle);\n        if (h.length \u003c 1 || n.length \u003c 1 || (n.length \u003e h.length)) {\n            return -1;\n        } else if (h.length \u003e (2 ** 128 - 1)) {\n            return -1;\n        } else {\n            uint subindex = 0;\n            for (uint i = 0; i \u003c h.length; i++) {\n                if (h[i] == n[0]) {\n                    subindex = 1;\n                    while(subindex \u003c n.length \u0026\u0026 (i + subindex) \u003c h.length \u0026\u0026 h[i + subindex] == n[subindex]) {\n                        subindex++;\n                    }\n                    if (subindex == n.length) {\n                        return int(i);\n                    }\n                }\n            }\n            return -1;\n        }\n    }\n\n    function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {\n        return strConcat(_a, _b, \"\", \"\", \"\");\n    }\n\n    function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {\n        return strConcat(_a, _b, _c, \"\", \"\");\n    }\n\n    function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {\n        return strConcat(_a, _b, _c, _d, \"\");\n    }\n\n    function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {\n        bytes memory _ba = bytes(_a);\n        bytes memory _bb = bytes(_b);\n        bytes memory _bc = bytes(_c);\n        bytes memory _bd = bytes(_d);\n        bytes memory _be = bytes(_e);\n        string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);\n        bytes memory babcde = bytes(abcde);\n        uint k = 0;\n        uint i = 0;\n        for (i = 0; i \u003c _ba.length; i++) {\n            babcde[k++] = _ba[i];\n        }\n        for (i = 0; i \u003c _bb.length; i++) {\n            babcde[k++] = _bb[i];\n        }\n        for (i = 0; i \u003c _bc.length; i++) {\n            babcde[k++] = _bc[i];\n        }\n        for (i = 0; i \u003c _bd.length; i++) {\n            babcde[k++] = _bd[i];\n        }\n        for (i = 0; i \u003c _be.length; i++) {\n            babcde[k++] = _be[i];\n        }\n        return string(babcde);\n    }\n\n    function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {\n        return safeParseInt(_a, 0);\n    }\n\n    function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {\n        bytes memory bresult = bytes(_a);\n        uint mint = 0;\n        bool decimals = false;\n        for (uint i = 0; i \u003c bresult.length; i++) {\n            if ((uint(uint8(bresult[i])) \u003e= 48) \u0026\u0026 (uint(uint8(bresult[i])) \u003c= 57)) {\n                if (decimals) {\n                   if (_b == 0) break;\n                    else _b--;\n                }\n                mint *= 10;\n                mint += uint(uint8(bresult[i])) - 48;\n            } else if (uint(uint8(bresult[i])) == 46) {\n                require(!decimals, \u0027More than one decimal encountered in string!\u0027);\n                decimals = true;\n            } else {\n                revert(\"Non-numeral character encountered in string!\");\n            }\n        }\n        if (_b \u003e 0) {\n            mint *= 10 ** _b;\n        }\n        return mint;\n    }\n\n    function parseInt(string memory _a) internal pure returns (uint _parsedInt) {\n        return parseInt(_a, 0);\n    }\n\n    function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {\n        bytes memory bresult = bytes(_a);\n        uint mint = 0;\n        bool decimals = false;\n        for (uint i = 0; i \u003c bresult.length; i++) {\n            if ((uint(uint8(bresult[i])) \u003e= 48) \u0026\u0026 (uint(uint8(bresult[i])) \u003c= 57)) {\n                if (decimals) {\n                   if (_b == 0) {\n                       break;\n                   } else {\n                       _b--;\n                   }\n                }\n                mint *= 10;\n                mint += uint(uint8(bresult[i])) - 48;\n            } else if (uint(uint8(bresult[i])) == 46) {\n                decimals = true;\n            }\n        }\n        if (_b \u003e 0) {\n            mint *= 10 ** _b;\n        }\n        return mint;\n    }\n\n    function uint2str(uint _i) internal pure returns (string memory _uintAsString) {\n        if (_i == 0) {\n            return \"0\";\n        }\n        uint j = _i;\n        uint len;\n        while (j != 0) {\n            len++;\n            j /= 10;\n        }\n        bytes memory bstr = new bytes(len);\n        uint k = len - 1;\n        while (_i != 0) {\n            bstr[k--] = byte(uint8(48 + _i % 10));\n            _i /= 10;\n        }\n        return string(bstr);\n    }\n}"},"SwapToPrice.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./Babylonian.sol\u0027;\nimport \u0027./SafeMath.sol\u0027;\nimport \u0027./TransferHelper.sol\u0027;\nimport \u0027./IERC20.sol\u0027;\nimport \u0027./IUniswapV2Router01.sol\u0027;\nimport \u0027./UniswapV2Library.sol\u0027;\n\ncontract SwapToPrice {\n    using SafeMath for uint256;\n\n    IUniswapV2Router01 public immutable router;\n    address public immutable factory;\n\n    constructor(address factory_, IUniswapV2Router01 router_) public {\n        factory = factory_;\n        router = router_;\n    }\n\n    // computes the direction and magnitude of the profit-maximizing trade\n    function computeProfitMaximizingTrade(\n        uint256 truePriceTokenA,\n        uint256 truePriceTokenB,\n        uint256 reserveA,\n        uint256 reserveB\n    ) pure public returns (bool aToB, uint256 amountIn) {\n        aToB = reserveA.mul(truePriceTokenB) / reserveB \u003c truePriceTokenA;\n\n        uint256 invariant = reserveA.mul(reserveB);\n\n        uint256 leftSide = Babylonian.sqrt(\n            invariant.mul(aToB ? truePriceTokenA : truePriceTokenB).mul(1000) /\n            uint256(aToB ? truePriceTokenB : truePriceTokenA).mul(997)\n        );\n        uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997;\n\n        // compute the amount that must be sent to move the price to the profit-maximizing price\n        amountIn = leftSide.sub(rightSide);\n    }\n\n    // swaps an amount of either token such that the trade is profit-maximizing, given an external true price\n    // true price is expressed in the ratio of token A to token B\n    // caller must approve this contract to spend whichever token is intended to be swapped\n    function swapToPrice(\n        address tokenA,\n        address tokenB,\n        uint256 truePriceTokenA,\n        uint256 truePriceTokenB,\n        uint256 maxSpendTokenA,\n        uint256 maxSpendTokenB,\n        address to,\n        uint256 deadline\n    ) public {\n        // true price is expressed as a ratio, so both values must be non-zero\n        require(truePriceTokenA != 0 \u0026\u0026 truePriceTokenB != 0, \"ExampleSwapToPrice: ZERO_PRICE\");\n        // caller can specify 0 for either if they wish to swap in only one direction, but not both\n        require(maxSpendTokenA != 0 || maxSpendTokenB != 0, \"ExampleSwapToPrice: ZERO_SPEND\");\n\n        bool aToB;\n        uint256 amountIn;\n        {\n            (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n            (aToB, amountIn) = computeProfitMaximizingTrade(\n                truePriceTokenA, truePriceTokenB,\n                reserveA, reserveB\n            );\n        }\n\n        // spend up to the allowance of the token in\n        uint256 maxSpend = aToB ? maxSpendTokenA : maxSpendTokenB;\n        if (amountIn \u003e maxSpend) {\n            amountIn = maxSpend;\n        }\n\n        address tokenIn = aToB ? tokenA : tokenB;\n        address tokenOut = aToB ? tokenB : tokenA;\n        TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);\n        TransferHelper.safeApprove(tokenIn, address(router), amountIn);\n\n        address[] memory path = new address[](2);\n        path[0] = tokenIn;\n        path[1] = tokenOut;\n\n        router.swapExactTokensForTokens(\n            amountIn,\n            0, // amountOutMin: we can skip computing this number because the math is tested\n            path,\n            to,\n            deadline\n        );\n    }\n}"},"TestSwap.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./FakeCollateral_USDT.sol\";\nimport \"./FakeCollateral_WETH.sol\";\nimport \"./UniswapV2Router02_Modified.sol\";\n\n/* IGNORE THIS CONTRACT, ONLY USED FOR TESTING PURPOSES */\n\ncontract TestSwap {\n\taddress public USDT_address;\n\taddress public WETH_address;\n\tUniswapV2Router02_Modified public router;\n\tFakeCollateral_USDT USDT = FakeCollateral_USDT(USDT);\n\tFakeCollateral_WETH WETH = FakeCollateral_WETH(WETH);\n\n\tconstructor( \n\t\taddress _USDT_address, \n\t\taddress _WETH_address,\n\t\tUniswapV2Router02_Modified _router_address\n\t) public {\n\t\tUSDT_address = _USDT_address;\n\t\tWETH_address = _WETH_address;\n\t\trouter = UniswapV2Router02_Modified(_router_address);\n\t}\n\n\tfunction getPath() public returns (address[] memory) {\n\t\taddress[] memory path = new address[](2);\n\t\tpath[0] = USDT_address;\n\t\tpath[1] = WETH_address;\n\t\treturn path;\n\t}\n\n\tfunction swapUSDTforETH(uint256 amountIn, uint256 amountOutMin) public payable {\n\t\trequire(USDT.transferFrom(msg.sender, address(this), amountIn), \"transferFrom failed.\");\n\t\trequire(USDT.approve(address(router), amountIn), \"approve failed.\");\n\n\t\taddress[] memory path = new address[](2);\n\t\tpath[0] = USDT_address;\n\t\tpath[1] = WETH_address;\n\n\t\trouter.swapExactTokensForETH(amountIn, amountOutMin, path, msg.sender, block.timestamp);\n\t}\n\n}"},"Timelock.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./SafeMath.sol\";\n\ncontract Timelock {\n    using SafeMath for uint;\n\n    event NewAdmin(address indexed newAdmin);\n    event NewPendingAdmin(address indexed newPendingAdmin);\n    event NewDelay(uint indexed newDelay);\n    event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature,  bytes data, uint eta);\n    event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature,  bytes data, uint eta);\n    event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);\n\n    uint public constant GRACE_PERIOD = 14 days;\n    uint public constant MINIMUM_DELAY = 2 days;\n    uint public constant MAXIMUM_DELAY = 30 days;\n\n    address public admin;\n    address public pendingAdmin;\n    uint public delay;\n\n    mapping (bytes32 =\u003e bool) public queuedTransactions;\n\n\n    constructor(address admin_, uint delay_) public {\n        require(delay_ \u003e= MINIMUM_DELAY, \"Timelock::constructor: Delay must exceed minimum delay.\");\n        require(delay_ \u003c= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\");\n\n        admin = admin_;\n        delay = delay_;\n    }\n\n    //function() external payable { }\n\n    function setDelay(uint delay_) public {\n        require(msg.sender == address(this), \"Timelock::setDelay: Call must come from Timelock.\");\n        require(delay_ \u003e= MINIMUM_DELAY, \"Timelock::setDelay: Delay must exceed minimum delay.\");\n        require(delay_ \u003c= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\");\n        delay = delay_;\n\n        emit NewDelay(delay);\n    }\n\n    function acceptAdmin() public {\n        require(msg.sender == pendingAdmin, \"Timelock::acceptAdmin: Call must come from pendingAdmin.\");\n        admin = msg.sender;\n        pendingAdmin = address(0);\n\n        emit NewAdmin(admin);\n    }\n\n    function setPendingAdmin(address pendingAdmin_) public {\n        require(msg.sender == address(this), \"Timelock::setPendingAdmin: Call must come from Timelock.\");\n        pendingAdmin = pendingAdmin_;\n\n        emit NewPendingAdmin(pendingAdmin);\n    }\n\n    function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {\n        require(msg.sender == admin, \"Timelock::queueTransaction: Call must come from admin.\");\n        require(eta \u003e= getBlockTimestamp().add(delay), \"Timelock::queueTransaction: Estimated execution block must satisfy delay.\");\n\n        bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n        queuedTransactions[txHash] = true;\n\n        emit QueueTransaction(txHash, target, value, signature, data, eta);\n        return txHash;\n    }\n\n    function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {\n        require(msg.sender == admin, \"Timelock::cancelTransaction: Call must come from admin.\");\n\n        bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n        queuedTransactions[txHash] = false;\n\n        emit CancelTransaction(txHash, target, value, signature, data, eta);\n    }\n\n    function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {\n        require(msg.sender == admin, \"Timelock::executeTransaction: Call must come from admin.\");\n\n        bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n        require(queuedTransactions[txHash], \"Timelock::executeTransaction: Transaction hasn\u0027t been queued.\");\n        require(getBlockTimestamp() \u003e= eta, \"Timelock::executeTransaction: Transaction hasn\u0027t surpassed time lock.\");\n        require(getBlockTimestamp() \u003c= eta.add(GRACE_PERIOD), \"Timelock::executeTransaction: Transaction is stale.\");\n\n        queuedTransactions[txHash] = false;\n\n        bytes memory callData;\n\n        if (bytes(signature).length == 0) {\n            callData = data;\n        } else {\n            callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\n        }\n\n        // Execute the call\n        (bool success, bytes memory returnData) = target.call{ value: value }(callData);\n        require(success, \"Timelock::executeTransaction: Transaction execution reverted.\");\n\n        emit ExecuteTransaction(txHash, target, value, signature, data, eta);\n\n        return returnData;\n    }\n\n    function getBlockTimestamp() internal view returns (uint) {\n        return block.timestamp;\n    }\n}"},"TokenVesting.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \"./ERC20Custom.sol\";\nimport \"./ERC20.sol\";\nimport \"./SafeMath.sol\";\n\n/**\n * @title TokenVesting\n * @dev A token holder contract that can release its token balance gradually like a\n * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the\n * owner.\n * \n * Modified from OpenZeppelin\u0027s TokenVesting.sol draft\n */\ncontract TokenVesting {\n    // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is\n    // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,\n    // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a\n    // cliff period of a year and a duration of four years, are safe to use.\n    // solhint-disable not-rely-on-time\n\n    using SafeMath for uint256;\n\n    event TokensReleased(uint256 amount);\n    event TokenVestingRevoked();\n\n    // beneficiary of tokens after they are released\n    address private _beneficiary;\n\n    // owner (grantor) of the tokens\n    address private _owner;\n\n    // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.\n    uint256 private _cliff;\n    uint256 private _start;\n    uint256 private _duration;\n\n    address public _FXS_contract_address;\n    ERC20 FXS;\n    address public _timelock_address;\n    bool public _revocable;\n\n    uint256 private _released;\n    bool public _revoked;\n\n    /**\n     * @dev Creates a vesting contract that vests its balance of any ERC20 token to the\n     * beneficiary, gradually in a linear fashion until start + duration. By then all\n     * of the balance will have vested.\n     * @param beneficiary address of the beneficiary to whom vested tokens are transferred\n     * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest\n     * @param start the time (as Unix time) at which point vesting starts\n     * @param duration duration in seconds of the period in which the tokens will vest\n     * @param revocable whether the vesting is revocable or not\n     */\n\n    constructor(\n        address beneficiary,\n        uint256 start,\n        uint256 cliffDuration,\n        uint256 duration,\n        bool revocable\n    ) public {\n        require(beneficiary != address(0), \"TokenVesting: beneficiary is the zero address\");\n        // solhint-disable-next-line max-line-length\n        require(cliffDuration \u003c= duration, \"TokenVesting: cliff is longer than duration\");\n        require(duration \u003e 0, \"TokenVesting: duration is 0\");\n        // solhint-disable-next-line max-line-length\n        require(start.add(duration) \u003e block.timestamp, \"TokenVesting: final time is before current time\");\n\n        _beneficiary = beneficiary;\n        _revocable = revocable;\n        _duration = duration;\n        _cliff = start.add(cliffDuration);\n        _start = start;\n        _owner = msg.sender;\n    }\n\n    function setFXSAddress(address FXS_address) public {\n        require(msg.sender == _owner, \"must be set by the owner\");\n        _FXS_contract_address = FXS_address;\n        FXS = ERC20(FXS_address);\n    }\n\n    function setTimelockAddress(address timelock_address) public {\n        require(msg.sender == _owner, \"must be set by the owner\");\n        _timelock_address = timelock_address;\n    }\n\n    /**\n     * @return the beneficiary of the tokens.\n     */\n    function getBeneficiary() public view returns (address) {\n        return _beneficiary;\n    }\n\n    /**\n     * @return the cliff time of the token vesting.\n     */\n    function getCliff() public view returns (uint256) {\n        return _cliff;\n    }\n\n    /**\n     * @return the start time of the token vesting.\n     */\n    function getStart() public view returns (uint256) {\n        return _start;\n    }\n\n    /**\n     * @return the duration of the token vesting.\n     */\n    function getDuration() public view returns (uint256) {\n        return _duration;\n    }\n\n    /**\n     * @return true if the vesting is revocable.\n     */\n    function getRevocable() public view returns (bool) {\n        return _revocable;\n    }\n\n    /**\n     * @return the amount of the token released.\n     */\n    function getReleased() public view returns (uint256) {\n        return _released;\n    }\n\n    /**\n     * @return true if the token is revoked.\n     */\n    function getRevoked() public view returns (bool) {\n        return _revoked;\n    }\n\n    /**\n     * @notice Transfers vested tokens to beneficiary.\n     */\n    function release() public {\n        require(msg.sender == _beneficiary, \"must be the beneficiary to release tokens\");\n        uint256 unreleased = _releasableAmount();\n\n        require(unreleased \u003e 0, \"TokenVesting: no tokens are due\");\n\n        _released = _released.add(unreleased);\n\n        FXS.transfer(_beneficiary, unreleased);\n\n        emit TokensReleased(unreleased);\n    }\n\n    /**\n     * @notice Allows the owner to revoke the vesting. Tokens already vested\n     * remain in the contract, the rest are returned to the owner.\n     */\n    function revoke() public {\n        require(msg.sender == _timelock_address, \"Must be called by the timelock contract\");\n        require(_revocable, \"TokenVesting: cannot revoke\");\n        require(!_revoked, \"TokenVesting: token already revoked\");\n\n        uint256 balance = FXS.balanceOf(address(this));\n\n        uint256 unreleased = _releasableAmount();\n        uint256 refund = balance.sub(unreleased);\n\n        _revoked = true;\n\n        FXS.transfer(_owner, refund);\n\n        emit TokenVestingRevoked();\n    }\n\n    // Added to support recovering possible airdrops\n    function recoverERC20(address tokenAddress, uint256 tokenAmount) external {\n        require(msg.sender == _beneficiary, \"Must be called by the beneficiary\");\n\n        // Cannot recover the staking token or the rewards token\n        require(tokenAddress != _FXS_contract_address, \"Cannot withdraw the FXS through this function\");\n        ERC20(tokenAddress).transfer(_beneficiary, tokenAmount);\n    }\n\n\n    /**\n     * @dev Calculates the amount that has already vested but hasn\u0027t been released yet.\n     */\n    function _releasableAmount() private view returns (uint256) {\n        return _vestedAmount().sub(_released);\n    }\n\n    /**\n     * @dev Calculates the amount that has already vested.\n     */\n    function _vestedAmount() private view returns (uint256) {\n        uint256 currentBalance = FXS.balanceOf(address(this));\n        uint256 totalBalance = currentBalance.add(_released);\n        if (block.timestamp \u003c _cliff) {\n            return 0;\n        } else if (block.timestamp \u003e= _start.add(_duration) || _revoked) {\n            return totalBalance;\n        } else {\n            return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);\n        }\n    }\n\n    uint256[44] private __gap;\n}\n"},"TransferHelper.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n    function safeApprove(address token, address to, uint value) internal {\n        // bytes4(keccak256(bytes(\u0027approve(address,uint256)\u0027)));\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n        require(success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))), \u0027TransferHelper: APPROVE_FAILED\u0027);\n    }\n\n    function safeTransfer(address token, address to, uint value) internal {\n        // bytes4(keccak256(bytes(\u0027transfer(address,uint256)\u0027)));\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n        require(success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))), \u0027TransferHelper: TRANSFER_FAILED\u0027);\n    }\n\n    function safeTransferFrom(address token, address from, address to, uint value) internal {\n        // bytes4(keccak256(bytes(\u0027transferFrom(address,address,uint256)\u0027)));\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n        require(success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))), \u0027TransferHelper: TRANSFER_FROM_FAILED\u0027);\n    }\n\n    function safeTransferETH(address to, uint value) internal {\n        (bool success,) = to.call{value:value}(new bytes(0));\n        require(success, \u0027TransferHelper: ETH_TRANSFER_FAILED\u0027);\n    }\n}"},"UniswapPairOracle.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./FixedPoint.sol\u0027;\n\nimport \u0027./UniswapV2OracleLibrary.sol\u0027;\nimport \u0027./UniswapV2Library.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle {\n    using FixedPoint for *;\n    \n    address owner_address;\n    address timelock_address;\n\n    uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price)\n\n    IUniswapV2Pair public immutable pair;\n    address public immutable token0;\n    address public immutable token1;\n\n    uint    public price0CumulativeLast;\n    uint    public price1CumulativeLast;\n    uint32  public blockTimestampLast;\n    FixedPoint.uq112x112 public price0Average;\n    FixedPoint.uq112x112 public price1Average;\n\n    modifier onlyByOwnerOrGovernance() {\n        require(msg.sender == owner_address || msg.sender == timelock_address, \"You are not an owner or the governance timelock\");\n        _;\n    }\n\n    constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public {\n        IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));\n        pair = _pair;\n        token0 = _pair.token0();\n        token1 = _pair.token1();\n        price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0)\n        price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1)\n        uint112 reserve0;\n        uint112 reserve1;\n        (reserve0, reserve1, blockTimestampLast) = _pair.getReserves();\n        require(reserve0 != 0 \u0026\u0026 reserve1 != 0, \u0027UniswapPairOracle: NO_RESERVES\u0027); // Ensure that there\u0027s liquidity in the pair\n\n        owner_address = _owner_address;\n        timelock_address = _timelock_address;\n    }\n\n    function setOwner(address _owner_address) external onlyByOwnerOrGovernance {\n        owner_address = _owner_address;\n    }\n\n    function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance {\n        timelock_address = _timelock_address;\n    }\n\n    function setPeriod(uint _period) external onlyByOwnerOrGovernance {\n        PERIOD = _period;\n    }\n\n    function update() external {\n        (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =\n            UniswapV2OracleLibrary.currentCumulativePrices(address(pair));\n        uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired\n\n        // Ensure that at least one full period has passed since the last update\n        require(timeElapsed \u003e= PERIOD, \u0027UniswapPairOracle: PERIOD_NOT_ELAPSED\u0027);\n\n        // Overflow is desired, casting never truncates\n        // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed\n        price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));\n        price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));\n\n        price0CumulativeLast = price0Cumulative;\n        price1CumulativeLast = price1Cumulative;\n        blockTimestampLast = blockTimestamp;\n    }\n\n    // Note this will always return 0 before update has been called successfully for the first time.\n    function consult(address token, uint amountIn) external view returns (uint amountOut) {\n        if (token == token0) {\n            amountOut = price0Average.mul(amountIn).decode144();\n        } else {\n            require(token == token1, \u0027UniswapPairOracle: INVALID_TOKEN\u0027);\n            amountOut = price1Average.mul(amountIn).decode144();\n        }\n    }\n}\n"},"UniswapPairOracle_FRAX_FXS.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FRAX_FXS is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_FRAX_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FRAX_USDC is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}\n"},"UniswapPairOracle_FRAX_USDT.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FRAX_USDT is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address)  \n    public {}\n}\n"},"UniswapPairOracle_FRAX_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FRAX_WETH is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_FXS_USDC.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FXS_USDC is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_FXS_USDT.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FXS_USDT is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_FXS_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_FXS_WETH is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}"},"UniswapPairOracle_USDC_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_USDC_WETH is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}\n"},"UniswapPairOracle_USDT_WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./UniswapPairOracle.sol\u0027;\n\n// Fixed window oracle that recomputes the average price for the entire period once every period\n// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period\ncontract UniswapPairOracle_USDT_WETH is UniswapPairOracle {\n    constructor(address factory, address tokenA, address tokenB, address owner_address, address timelock_address) \n    UniswapPairOracle(factory, tokenA, tokenB, owner_address, timelock_address) \n    public {}\n}\n"},"UniswapV2ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2ERC20.sol\u0027;\nimport \u0027./SafeMath.sol\u0027;\n\ncontract UniswapV2ERC20 is IUniswapV2ERC20 {\n    using SafeMath for uint;\n\n    string public override constant name = \u0027Uniswap V2\u0027;\n    string public override constant symbol = \u0027UNI-V2\u0027;\n    uint8 public override constant decimals = 18;\n    uint  public override totalSupply;\n    mapping(address =\u003e uint) public override balanceOf;\n    mapping(address =\u003e mapping(address =\u003e uint)) public override allowance;\n\n    bytes32 public override DOMAIN_SEPARATOR;\n    // keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n    bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;\n    mapping(address =\u003e uint) public override nonces;\n\n    event Approval(address indexed owner, address indexed spender, uint value);\n    event Transfer(address indexed from, address indexed to, uint value);\n\n    constructor() public {\n        uint chainId;\n        assembly {\n            chainId := chainid()\n        }\n        DOMAIN_SEPARATOR = keccak256(\n            abi.encode(\n                keccak256(\u0027EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\u0027),\n                keccak256(bytes(name)),\n                keccak256(bytes(\u00271\u0027)),\n                chainId,\n                address(this)\n            )\n        );\n    }\n\n    function _mint(address to, uint value) internal {\n        totalSupply = totalSupply.add(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(address(0), to, value);\n    }\n\n    function _burn(address from, uint value) internal {\n        balanceOf[from] = balanceOf[from].sub(value);\n        totalSupply = totalSupply.sub(value);\n        emit Transfer(from, address(0), value);\n    }\n\n    function _approve(address owner, address spender, uint value) private {\n        allowance[owner][spender] = value;\n        emit Approval(owner, spender, value);\n    }\n\n    function _transfer(address from, address to, uint value) private {\n        balanceOf[from] = balanceOf[from].sub(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(from, to, value);\n    }\n\n    function approve(address spender, uint value) external override returns (bool) {\n        _approve(msg.sender, spender, value);\n        return true;\n    }\n\n    function transfer(address to, uint value) external override returns (bool) {\n        _transfer(msg.sender, to, value);\n        return true;\n    }\n\n    function transferFrom(address from, address to, uint value) external override returns (bool) {\n        if (allowance[from][msg.sender] != uint(-1)) {\n            allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);\n        }\n        _transfer(from, to, value);\n        return true;\n    }\n\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {\n        require(deadline \u003e= block.timestamp, \u0027UniswapV2: EXPIRED\u0027);\n        bytes32 digest = keccak256(\n            abi.encodePacked(\n                \u0027\\x19\\x01\u0027,\n                DOMAIN_SEPARATOR,\n                keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n            )\n        );\n        address recoveredAddress = ecrecover(digest, v, r, s);\n        require(recoveredAddress != address(0) \u0026\u0026 recoveredAddress == owner, \u0027UniswapV2: INVALID_SIGNATURE\u0027);\n        _approve(owner, spender, value);\n    }\n}\n"},"UniswapV2Factory.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./UniswapV2Pair.sol\u0027;\n\ncontract UniswapV2Factory is IUniswapV2Factory {\n    address public override feeTo;\n    address public override feeToSetter;\n\n    mapping(address =\u003e mapping(address =\u003e address)) public override getPair;\n    address[] public override allPairs;\n\n    event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n    constructor(address _feeToSetter) public {\n        feeToSetter = _feeToSetter;\n    }\n\n    function allPairsLength() external override view returns (uint) {\n        return allPairs.length;\n    }\n\n    function createPair(address tokenA, address tokenB) external override returns (address pair) {\n        require(tokenA != tokenB, \u0027UniswapV2: IDENTICAL_ADDRESSES\u0027);\n        (address token0, address token1) = tokenA \u003c tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n        require(token0 != address(0), \u0027UniswapV2: ZERO_ADDRESS\u0027);\n        require(getPair[token0][token1] == address(0), \u0027UniswapV2: PAIR_EXISTS\u0027); // single check is sufficient\n        bytes memory bytecode = type(UniswapV2Pair).creationCode;\n        bytes32 salt = keccak256(abi.encodePacked(token0, token1));\n\n        // This creates a new contract\n        assembly {\n            pair := create2(0, add(bytecode, 32), mload(bytecode), salt)\n        }\n        IUniswapV2Pair(pair).initialize(token0, token1);\n        getPair[token0][token1] = pair;\n        getPair[token1][token0] = pair; // populate mapping in the reverse direction\n        allPairs.push(pair);\n        emit PairCreated(token0, token1, pair, allPairs.length);\n    }\n\n    function setFeeTo(address _feeTo) external override {\n        require(msg.sender == feeToSetter, \u0027UniswapV2: FORBIDDEN\u0027);\n        feeTo = _feeTo;\n    }\n\n    function setFeeToSetter(address _feeToSetter) external override {\n        require(msg.sender == feeToSetter, \u0027UniswapV2: FORBIDDEN\u0027);\n        feeToSetter = _feeToSetter;\n    }\n}\n"},"UniswapV2Library.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./IUniswapV2Factory.sol\u0027;\n\nimport \"./SafeMath.sol\";\n\nlibrary UniswapV2Library {\n    using SafeMath for uint;\n\n    // returns sorted token addresses, used to handle return values from pairs sorted in this order\n    function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {\n        require(tokenA != tokenB, \u0027UniswapV2Library: IDENTICAL_ADDRESSES\u0027);\n        (token0, token1) = tokenA \u003c tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n        require(token0 != address(0), \u0027UniswapV2Library: ZERO_ADDRESS\u0027);\n    }\n\n    // Less efficient than the CREATE2 method below\n    function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {\n        (address token0, address token1) = sortTokens(tokenA, tokenB);\n        pair = IUniswapV2Factory(factory).getPair(token0, token1);\n    }\n\n    // calculates the CREATE2 address for a pair without making any external calls\n    function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n        (address token0, address token1) = sortTokens(tokenA, tokenB);\n        pair = address(uint(keccak256(abi.encodePacked(\n                hex\u0027ff\u0027,\n                factory,\n                keccak256(abi.encodePacked(token0, token1)),\n                hex\u002796e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f\u0027 // init code hash\n            )))); // this matches the CREATE2 in UniswapV2Factory.createPair\n    }\n\n    // fetches and sorts the reserves for a pair\n    function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {\n        (address token0,) = sortTokens(tokenA, tokenB);\n        (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();\n        (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n    }\n\n    // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset\n    function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {\n        require(amountA \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_AMOUNT\u0027);\n        require(reserveA \u003e 0 \u0026\u0026 reserveB \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_LIQUIDITY\u0027);\n        amountB = amountA.mul(reserveB) / reserveA;\n    }\n\n    // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {\n        require(amountIn \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT\u0027);\n        require(reserveIn \u003e 0 \u0026\u0026 reserveOut \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_LIQUIDITY\u0027);\n        uint amountInWithFee = amountIn.mul(997);\n        uint numerator = amountInWithFee.mul(reserveOut);\n        uint denominator = reserveIn.mul(1000).add(amountInWithFee);\n        amountOut = numerator / denominator;\n    }\n\n    // given an output amount of an asset and pair reserves, returns a required input amount of the other asset\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {\n        require(amountOut \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        require(reserveIn \u003e 0 \u0026\u0026 reserveOut \u003e 0, \u0027UniswapV2Library: INSUFFICIENT_LIQUIDITY\u0027);\n        uint numerator = reserveIn.mul(amountOut).mul(1000);\n        uint denominator = reserveOut.sub(amountOut).mul(997);\n        amountIn = (numerator / denominator).add(1);\n    }\n\n    // performs chained getAmountOut calculations on any number of pairs\n    function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {\n        require(path.length \u003e= 2, \u0027UniswapV2Library: INVALID_PATH\u0027);\n        amounts = new uint[](path.length);\n        amounts[0] = amountIn;\n        for (uint i; i \u003c path.length - 1; i++) {\n            (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);\n            amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);\n        }\n    }\n\n    // performs chained getAmountIn calculations on any number of pairs\n    function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {\n        require(path.length \u003e= 2, \u0027UniswapV2Library: INVALID_PATH\u0027);\n        amounts = new uint[](path.length);\n        amounts[amounts.length - 1] = amountOut;\n        for (uint i = path.length - 1; i \u003e 0; i--) {\n            (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);\n            amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);\n        }\n    }\n}"},"UniswapV2OracleLibrary.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./FixedPoint.sol\u0027;\n\n// library with helper methods for oracles that are concerned with computing average prices\nlibrary UniswapV2OracleLibrary {\n    using FixedPoint for *;\n\n    // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]\n    function currentBlockTimestamp() internal view returns (uint32) {\n        return uint32(block.timestamp % 2 ** 32);\n    }\n\n    // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.\n    function currentCumulativePrices(\n        address pair\n    ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {\n        blockTimestamp = currentBlockTimestamp();\n        price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();\n        price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();\n\n        // if time has elapsed since the last update on the pair, mock the accumulated price values\n        (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();\n        if (blockTimestampLast != blockTimestamp) {\n            // subtraction overflow is desired\n            uint32 timeElapsed = blockTimestamp - blockTimestampLast;\n            // addition overflow is desired\n            // counterfactual\n            price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;\n            // counterfactual\n            price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;\n        }\n    }\n}"},"UniswapV2Pair.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n\nimport \u0027./IUniswapV2Pair.sol\u0027;\nimport \u0027./UniswapV2ERC20.sol\u0027;\nimport \u0027./Math.sol\u0027;\nimport \u0027./UQ112x112.sol\u0027;\nimport \u0027./IERC20.sol\u0027;\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./IUniswapV2Callee.sol\u0027;\n\ncontract UniswapV2Pair is IUniswapV2Pair {\n    using SafeMath  for uint;\n    using UQ112x112 for uint224;\n\n    string public override constant name = \u0027Uniswap V2\u0027;\n    string public override constant symbol = \u0027UNI-V2\u0027;\n    uint8 public override constant decimals = 18;\n    uint  public override totalSupply;\n    mapping(address =\u003e uint) public override balanceOf;\n    mapping(address =\u003e mapping(address =\u003e uint)) public override allowance;\n\n    uint public override constant MINIMUM_LIQUIDITY = 10**3;\n    bytes4 private constant SELECTOR = bytes4(keccak256(bytes(\u0027transfer(address,uint256)\u0027)));\n    bytes32 public override DOMAIN_SEPARATOR;\n    // keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n    bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;\n    mapping(address =\u003e uint) public override nonces;\n\n\n    \n\n    address public override factory;\n    address public override token0;\n    address public override token1;\n\n    uint112 private reserve0;           // uses single storage slot, accessible via getReserves\n    uint112 private reserve1;           // uses single storage slot, accessible via getReserves\n    uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves\n\n    uint public override price0CumulativeLast;\n    uint public override price1CumulativeLast;\n    uint public override kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event\n\n    uint private unlocked = 1;\n    modifier lock() {\n        require(unlocked == 1, \u0027UniswapV2: LOCKED\u0027);\n        unlocked = 0;\n        _;\n        unlocked = 1;\n    }\n\n    function getReserves() public override view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {\n        _reserve0 = reserve0;\n        _reserve1 = reserve1;\n        _blockTimestampLast = blockTimestampLast;\n    }\n\n    function _safeTransfer(address token, address to, uint value) private {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));\n        require(success \u0026\u0026 (data.length == 0 || abi.decode(data, (bool))), \u0027UniswapV2: TRANSFER_FAILED\u0027);\n    }\n\n    event Mint(address indexed sender, uint amount0, uint amount1);\n    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n    event Swap(\n        address indexed sender,\n        uint amount0In,\n        uint amount1In,\n        uint amount0Out,\n        uint amount1Out,\n        address indexed to\n    );\n    event Sync(uint112 reserve0, uint112 reserve1);\n\n    constructor() public {\n        factory = msg.sender;\n    }\n\n    // called once by the factory at time of deployment\n    function initialize(address _token0, address _token1) external override {\n        require(msg.sender == factory, \u0027UniswapV2: FORBIDDEN\u0027); // sufficient check\n        token0 = _token0;\n        token1 = _token1;\n    }\n\n    // update reserves and, on the first call per block, price accumulators\n    function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {\n        require(balance0 \u003c= uint112(-1) \u0026\u0026 balance1 \u003c= uint112(-1), \u0027UniswapV2: OVERFLOW\u0027);\n        uint32 blockTimestamp = uint32(block.timestamp % 2**32);\n        uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\n        if (timeElapsed \u003e 0 \u0026\u0026 _reserve0 != 0 \u0026\u0026 _reserve1 != 0) {\n            // * never overflows, and + overflow is desired\n            price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;\n            price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;\n        }\n        reserve0 = uint112(balance0);\n        reserve1 = uint112(balance1);\n        blockTimestampLast = blockTimestamp;\n        emit Sync(reserve0, reserve1);\n    }\n\n    // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)\n    function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {\n        address feeTo = IUniswapV2Factory(factory).feeTo();\n        feeOn = feeTo != address(0);\n        uint _kLast = kLast; // gas savings\n        if (feeOn) {\n            if (_kLast != 0) {\n                uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));\n                uint rootKLast = Math.sqrt(_kLast);\n                if (rootK \u003e rootKLast) {\n                    uint numerator = totalSupply.mul(rootK.sub(rootKLast));\n                    uint denominator = rootK.mul(5).add(rootKLast);\n                    uint liquidity = numerator / denominator;\n                    if (liquidity \u003e 0) _mint(feeTo, liquidity);\n                }\n            }\n        } else if (_kLast != 0) {\n            kLast = 0;\n        }\n    }\n\n    // this low-level function should be called from a contract which performs important safety checks\n    function mint(address to) external override lock returns (uint liquidity) {\n        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n        uint balance0 = IERC20(token0).balanceOf(address(this));\n        uint balance1 = IERC20(token1).balanceOf(address(this));\n        uint amount0 = balance0.sub(_reserve0);\n        uint amount1 = balance1.sub(_reserve1);\n        bool feeOn = _mintFee(_reserve0, _reserve1);\n        uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee\n\n        if (_totalSupply == 0) {\n            liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);\n           _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens\n        } else {\n            liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);\n        }\n\n        require(liquidity \u003e 0, \u0027UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED\u0027);\n        _mint(to, liquidity);\n\n        _update(balance0, balance1, _reserve0, _reserve1);\n        if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date\n        emit Mint(msg.sender, amount0, amount1);\n    }\n\n    // this low-level function should be called from a contract which performs important safety checks\n    function burn(address to) external override lock returns (uint amount0, uint amount1) {\n        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n        address _token0 = token0;                                // gas savings\n        address _token1 = token1;                                // gas savings\n        uint balance0 = IERC20(_token0).balanceOf(address(this));\n        uint balance1 = IERC20(_token1).balanceOf(address(this));\n        uint liquidity = balanceOf[address(this)];\n\n        bool feeOn = _mintFee(_reserve0, _reserve1);\n        uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee\n        amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution\n        amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution\n        require(amount0 \u003e 0 \u0026\u0026 amount1 \u003e 0, \u0027UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED\u0027);\n        _burn(address(this), liquidity);\n        _safeTransfer(_token0, to, amount0);\n        _safeTransfer(_token1, to, amount1);\n        balance0 = IERC20(_token0).balanceOf(address(this));\n        balance1 = IERC20(_token1).balanceOf(address(this));\n\n        _update(balance0, balance1, _reserve0, _reserve1);\n        if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date\n        emit Burn(msg.sender, amount0, amount1, to);\n    }\n\n    // this low-level function should be called from a contract which performs important safety checks\n    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external override lock {\n        require(amount0Out \u003e 0 || amount1Out \u003e 0, \u0027UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n        require(amount0Out \u003c _reserve0 \u0026\u0026 amount1Out \u003c _reserve1, \u0027UniswapV2: INSUFFICIENT_LIQUIDITY\u0027);\n\n        uint balance0;\n        uint balance1;\n        { // scope for _token{0,1}, avoids stack too deep errors\n        address _token0 = token0;\n        address _token1 = token1;\n        require(to != _token0 \u0026\u0026 to != _token1, \u0027UniswapV2: INVALID_TO\u0027);\n        if (amount0Out \u003e 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens\n        if (amount1Out \u003e 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens\n        if (data.length \u003e 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);\n        balance0 = IERC20(_token0).balanceOf(address(this));\n        balance1 = IERC20(_token1).balanceOf(address(this));\n        }\n        uint amount0In = balance0 \u003e _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;\n        uint amount1In = balance1 \u003e _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;\n        require(amount0In \u003e 0 || amount1In \u003e 0, \u0027UniswapV2: INSUFFICIENT_INPUT_AMOUNT\u0027);\n        { // scope for reserve{0,1}Adjusted, avoids stack too deep errors\n        uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));\n        uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));\n        require(balance0Adjusted.mul(balance1Adjusted) \u003e= uint(_reserve0).mul(_reserve1).mul(1000**2), \u0027UniswapV2: K\u0027);\n        }\n\n        _update(balance0, balance1, _reserve0, _reserve1);\n        emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);\n    }\n\n    // force balances to match reserves\n    function skim(address to) external override lock {\n        address _token0 = token0; // gas savings\n        address _token1 = token1; // gas savings\n        _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));\n        _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));\n    }\n\n    // force reserves to match balances\n    function sync() external override lock {\n        _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);\n    }\n\n\n\n    // Migrated over from UniswapV2ERC20. Needed for ^0.6.0\n    // ===============================================\n\n    function _mint(address to, uint value) internal {\n        totalSupply = totalSupply.add(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(address(0), to, value);\n    }\n\n    function _burn(address from, uint value) internal {\n        balanceOf[from] = balanceOf[from].sub(value);\n        totalSupply = totalSupply.sub(value);\n        emit Transfer(from, address(0), value);\n    }\n\n    function _approve(address owner, address spender, uint value) private {\n        allowance[owner][spender] = value;\n        emit Approval(owner, spender, value);\n    }\n\n    function _transfer(address from, address to, uint value) private {\n        balanceOf[from] = balanceOf[from].sub(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(from, to, value);\n    }\n\n    function approve(address spender, uint value) external override returns (bool) {\n        _approve(msg.sender, spender, value);\n        return true;\n    }\n\n    function transfer(address to, uint value) external override returns (bool) {\n        _transfer(msg.sender, to, value);\n        return true;\n    }\n\n    function transferFrom(address from, address to, uint value) external override returns (bool) {\n        if (allowance[from][msg.sender] != uint(-1)) {\n            allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);\n        }\n        _transfer(from, to, value);\n        return true;\n    }\n\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {\n        require(deadline \u003e= block.timestamp, \u0027UniswapV2: EXPIRED\u0027);\n        bytes32 digest = keccak256(\n            abi.encodePacked(\n                \u0027\\x19\\x01\u0027,\n                DOMAIN_SEPARATOR,\n                keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n            )\n        );\n        address recoveredAddress = ecrecover(digest, v, r, s);\n        require(recoveredAddress != address(0) \u0026\u0026 recoveredAddress == owner, \u0027UniswapV2: INVALID_SIGNATURE\u0027);\n        _approve(owner, spender, value);\n    }\n\n\n\n}"},"UniswapV2Router02.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./TransferHelper.sol\u0027;\n\nimport \u0027./IUniswapV2Router02.sol\u0027;\nimport \u0027./UniswapV2Library.sol\u0027;\nimport \u0027./SafeMath.sol\u0027;\nimport \u0027./IERC20.sol\u0027;\nimport \u0027./IWETH.sol\u0027;\n\ncontract UniswapV2Router02 is IUniswapV2Router02 {\n    using SafeMath for uint;\n\n    address public immutable override factory;\n    address public immutable override WETH;\n\n    modifier ensure(uint deadline) {\n        require(deadline \u003e= block.timestamp, \u0027UniswapV2Router: EXPIRED\u0027);\n        _;\n    }\n\n    constructor(address _factory, address _WETH) public {\n        factory = _factory;\n        WETH = _WETH;\n    }\n\n    receive() external payable {\n        assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract\n    }\n\n    // **** ADD LIQUIDITY ****\n    function _addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin\n    ) internal virtual returns (uint amountA, uint amountB) {\n        // create the pair if it doesn\u0027t exist yet\n        if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\n            IUniswapV2Factory(factory).createPair(tokenA, tokenB);\n        }\n        (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n        if (reserveA == 0 \u0026\u0026 reserveB == 0) {\n            (amountA, amountB) = (amountADesired, amountBDesired);\n        } else {\n            uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n            if (amountBOptimal \u003c= amountBDesired) {\n                require(amountBOptimal \u003e= amountBMin, \u0027UniswapV2Router: INSUFFICIENT_B_AMOUNT\u0027);\n                (amountA, amountB) = (amountADesired, amountBOptimal);\n            } else {\n                uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n                assert(amountAOptimal \u003c= amountADesired);\n                require(amountAOptimal \u003e= amountAMin, \u0027UniswapV2Router: INSUFFICIENT_A_AMOUNT\u0027);\n                (amountA, amountB) = (amountAOptimal, amountBDesired);\n            }\n        }\n    }\n    function addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\n        (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\n        TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\n        liquidity = IUniswapV2Pair(pair).mint(to);\n    }\n    function addLiquidityETH(\n        address token,\n        uint amountTokenDesired,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {\n        (amountToken, amountETH) = _addLiquidity(\n            token,\n            WETH,\n            amountTokenDesired,\n            msg.value,\n            amountTokenMin,\n            amountETHMin\n        );\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);\n        IWETH(WETH).deposit{value: amountETH}();\n        assert(IWETH(WETH).transfer(pair, amountETH));\n        liquidity = IUniswapV2Pair(pair).mint(to);\n        // refund dust eth, if any\n        if (msg.value \u003e amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);\n    }\n\n    // **** REMOVE LIQUIDITY ****\n    function removeLiquidity(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair\n        (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);\n        (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);\n        (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);\n        require(amountA \u003e= amountAMin, \u0027UniswapV2Router: INSUFFICIENT_A_AMOUNT\u0027);\n        require(amountB \u003e= amountBMin, \u0027UniswapV2Router: INSUFFICIENT_B_AMOUNT\u0027);\n    }\n    function removeLiquidityETH(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {\n        (amountToken, amountETH) = removeLiquidity(\n            token,\n            WETH,\n            liquidity,\n            amountTokenMin,\n            amountETHMin,\n            address(this),\n            deadline\n        );\n        TransferHelper.safeTransfer(token, to, amountToken);\n        IWETH(WETH).withdraw(amountETH);\n        TransferHelper.safeTransferETH(to, amountETH);\n    }\n    function removeLiquidityWithPermit(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountA, uint amountB) {\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);\n    }\n    function removeLiquidityETHWithPermit(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountToken, uint amountETH) {\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);\n    }\n\n    // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountETH) {\n        (, amountETH) = removeLiquidity(\n            token,\n            WETH,\n            liquidity,\n            amountTokenMin,\n            amountETHMin,\n            address(this),\n            deadline\n        );\n        TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));\n        IWETH(WETH).withdraw(amountETH);\n        TransferHelper.safeTransferETH(to, amountETH);\n    }\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountETH) {\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(\n            token, liquidity, amountTokenMin, amountETHMin, to, deadline\n        );\n    }\n\n    // **** SWAP ****\n    // requires the initial amount to have already been sent to the first pair\n    function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {\n        for (uint i; i \u003c path.length - 1; i++) {\n            (address input, address output) = (path[i], path[i + 1]);\n            (address token0,) = UniswapV2Library.sortTokens(input, output);\n            uint amountOut = amounts[i + 1];\n            (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));\n            address to = i \u003c path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n            IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(\n                amount0Out, amount1Out, to, new bytes(0)\n            );\n        }\n    }\n    function swapExactTokensForTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, to);\n    }\n    function swapTokensForExactTokens(\n        uint amountOut,\n        uint amountInMax,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= amountInMax, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, to);\n    }\n    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        IWETH(WETH).deposit{value: amounts[0]}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n        _swap(amounts, path, to);\n    }\n    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= amountInMax, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, address(this));\n        IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n    }\n    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, address(this));\n        IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n    }\n    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= msg.value, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        IWETH(WETH).deposit{value: amounts[0]}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n        _swap(amounts, path, to);\n        // refund dust eth, if any\n        if (msg.value \u003e amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);\n    }\n\n    // **** SWAP (supporting fee-on-transfer tokens) ****\n    // requires the initial amount to have already been sent to the first pair\n    function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {\n        for (uint i; i \u003c path.length - 1; i++) {\n            (address input, address output) = (path[i], path[i + 1]);\n            (address token0,) = UniswapV2Library.sortTokens(input, output);\n            IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));\n            uint amountInput;\n            uint amountOutput;\n            { // scope to avoid stack too deep errors\n            (uint reserve0, uint reserve1,) = pair.getReserves();\n            (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n            amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);\n            amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);\n            }\n            (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));\n            address to = i \u003c path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n            pair.swap(amount0Out, amount1Out, to, new bytes(0));\n        }\n    }\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) {\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n        );\n        uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);\n        _swapSupportingFeeOnTransferTokens(path, to);\n        require(\n            IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) \u003e= amountOutMin,\n            \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027\n        );\n    }\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    )\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        uint amountIn = msg.value;\n        IWETH(WETH).deposit{value: amountIn}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));\n        uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);\n        _swapSupportingFeeOnTransferTokens(path, to);\n        require(\n            IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) \u003e= amountOutMin,\n            \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027\n        );\n    }\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    )\n        external\n        virtual\n        override\n        ensure(deadline)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n        );\n        _swapSupportingFeeOnTransferTokens(path, address(this));\n        uint amountOut = IERC20(WETH).balanceOf(address(this));\n        require(amountOut \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        IWETH(WETH).withdraw(amountOut);\n        TransferHelper.safeTransferETH(to, amountOut);\n    }\n\n    // **** LIBRARY FUNCTIONS ****\n    function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {\n        return UniswapV2Library.quote(amountA, reserveA, reserveB);\n    }\n\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)\n        public\n        pure\n        virtual\n        override\n        returns (uint amountOut)\n    {\n        return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);\n    }\n\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)\n        public\n        pure\n        virtual\n        override\n        returns (uint amountIn)\n    {\n        return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);\n    }\n\n    function getAmountsOut(uint amountIn, address[] memory path)\n        public\n        view\n        virtual\n        override\n        returns (uint[] memory amounts)\n    {\n        return UniswapV2Library.getAmountsOut(factory, amountIn, path);\n    }\n\n    function getAmountsIn(uint amountOut, address[] memory path)\n        public\n        view\n        virtual\n        override\n        returns (uint[] memory amounts)\n    {\n        return UniswapV2Library.getAmountsIn(factory, amountOut, path);\n    }\n}"},"UniswapV2Router02_Modified.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IUniswapV2Factory.sol\u0027;\nimport \u0027./TransferHelper.sol\u0027;\n\nimport \u0027./IUniswapV2Router02.sol\u0027;\nimport \u0027./UniswapV2Library.sol\u0027;\nimport \u0027./SafeMath.sol\u0027;\nimport \u0027./IERC20.sol\u0027;\nimport \u0027./IWETH.sol\u0027;\n\ncontract UniswapV2Router02_Modified is IUniswapV2Router02 {\n    using SafeMath for uint;\n\n    address public immutable override factory;\n    address public immutable override WETH;\n\n    modifier ensure(uint deadline) {\n        require(deadline \u003e= block.timestamp, \u0027UniswapV2Router: EXPIRED\u0027);\n        _;\n    }\n\n    constructor(address _factory, address _WETH) public {\n        factory = _factory;\n        WETH = _WETH;\n    }\n\n    receive() external payable {\n        assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract\n    }\n\n    // **** ADD LIQUIDITY ****\n    function _addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin\n    ) internal virtual returns (uint amountA, uint amountB) {\n        // create the pair if it doesn\u0027t exist yet\n        if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\n            IUniswapV2Factory(factory).createPair(tokenA, tokenB);\n        }\n        (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n        if (reserveA == 0 \u0026\u0026 reserveB == 0) {\n            (amountA, amountB) = (amountADesired, amountBDesired);\n        } else {\n            uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n            if (amountBOptimal \u003c= amountBDesired) {\n                require(amountBOptimal \u003e= amountBMin, \u0027UniswapV2Router: INSUFFICIENT_B_AMOUNT\u0027);\n                (amountA, amountB) = (amountADesired, amountBOptimal);\n            } else {\n                uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n                assert(amountAOptimal \u003c= amountADesired);\n                require(amountAOptimal \u003e= amountAMin, \u0027UniswapV2Router: INSUFFICIENT_A_AMOUNT\u0027);\n                (amountA, amountB) = (amountAOptimal, amountBDesired);\n            }\n        }\n    }\n    function addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\n        (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\n        TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\n        liquidity = IUniswapV2Pair(pair).mint(to);\n    }\n    function addLiquidityETH(\n        address token,\n        uint amountTokenDesired,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {\n        (amountToken, amountETH) = _addLiquidity(\n            token,\n            WETH,\n            amountTokenDesired,\n            msg.value,\n            amountTokenMin,\n            amountETHMin\n        );\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);\n        \n        \n        TransferHelper.safeTransferFrom(WETH, msg.sender, pair, amountETH);\n\n        // IWETH(WETH).transferFrom(msg.sender, pair, amountETH);\n        // IWETH(WETH).deposit{value: amountETH}();\n        // assert(IWETH(WETH).transfer(pair, amountETH));\n\n        // require(false, \"HELLO: HOW ARE YOU TODAY!\");\n\n        liquidity = IUniswapV2Pair(pair).mint(to); // \u003c\u003c PROBLEM IS HERE\n\n        // refund dust eth, if any\n        if (msg.value \u003e amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);\n    }\n\n    // **** REMOVE LIQUIDITY ****\n    function removeLiquidity(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair\n        (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);\n        (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);\n        (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);\n        require(amountA \u003e= amountAMin, \u0027UniswapV2Router: INSUFFICIENT_A_AMOUNT\u0027);\n        require(amountB \u003e= amountBMin, \u0027UniswapV2Router: INSUFFICIENT_B_AMOUNT\u0027);\n    }\n    function removeLiquidityETH(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {\n        (amountToken, amountETH) = removeLiquidity(\n            token,\n            WETH,\n            liquidity,\n            amountTokenMin,\n            amountETHMin,\n            address(this),\n            deadline\n        );\n        TransferHelper.safeTransfer(token, to, amountToken);\n        IWETH(WETH).withdraw(amountETH);\n        TransferHelper.safeTransferETH(to, amountETH);\n    }\n    function removeLiquidityWithPermit(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountA, uint amountB) {\n        address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);\n    }\n    function removeLiquidityETHWithPermit(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountToken, uint amountETH) {\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);\n    }\n\n    // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) public virtual override ensure(deadline) returns (uint amountETH) {\n        (, amountETH) = removeLiquidity(\n            token,\n            WETH,\n            liquidity,\n            amountTokenMin,\n            amountETHMin,\n            address(this),\n            deadline\n        );\n        TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));\n        IWETH(WETH).withdraw(amountETH);\n        TransferHelper.safeTransferETH(to, amountETH);\n    }\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external virtual override returns (uint amountETH) {\n        address pair = UniswapV2Library.pairFor(factory, token, WETH);\n        uint value = approveMax ? uint(-1) : liquidity;\n        IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n        amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(\n            token, liquidity, amountTokenMin, amountETHMin, to, deadline\n        );\n    }\n\n    // **** SWAP ****\n    // requires the initial amount to have already been sent to the first pair\n    function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {\n        for (uint i; i \u003c path.length - 1; i++) {\n            (address input, address output) = (path[i], path[i + 1]);\n            (address token0,) = UniswapV2Library.sortTokens(input, output);\n            uint amountOut = amounts[i + 1];\n            (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));\n            address to = i \u003c path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n            IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(\n                amount0Out, amount1Out, to, new bytes(0)\n            );\n        }\n    }\n    function swapExactTokensForTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, to);\n    }\n    function swapTokensForExactTokens(\n        uint amountOut,\n        uint amountInMax,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= amountInMax, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, to);\n    }\n    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        IWETH(WETH).deposit{value: amounts[0]}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n        _swap(amounts, path, to);\n    }\n    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= amountInMax, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, address(this));\n        IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n    }\n    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n        require(amounts[amounts.length - 1] \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        TransferHelper.safeTransferFrom(\n            path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n        );\n        _swap(amounts, path, address(this));\n        IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n    }\n    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n        require(amounts[0] \u003c= msg.value, \u0027UniswapV2Router: EXCESSIVE_INPUT_AMOUNT\u0027);\n        IWETH(WETH).deposit{value: amounts[0]}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n        _swap(amounts, path, to);\n        // refund dust eth, if any\n        if (msg.value \u003e amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);\n    }\n\n    // **** SWAP (supporting fee-on-transfer tokens) ****\n    // requires the initial amount to have already been sent to the first pair\n    function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {\n        // for (uint i; i \u003c path.length - 1; i++) {\n        //     (address input, address output) = (path[i], path[i + 1]);\n        //     (address token0,) = UniswapV2Library.sortTokens(input, output);\n        //     IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));\n        //     uint amountInput;\n        //     uint amountOutput;\n        //     { // scope to avoid stack too deep errors\n        //     (uint reserve0, uint reserve1,) = pair.getReserves();\n        //     (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n        //     amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);\n        //     amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);\n        //     }\n        //     (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));\n        //     address to = i \u003c path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n        //     pair.swap(amount0Out, amount1Out, to, new bytes(0));\n        // }\n    }\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external virtual override ensure(deadline) {\n        // TransferHelper.safeTransferFrom(\n        //     path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n        // );\n        // uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);\n        // _swapSupportingFeeOnTransferTokens(path, to);\n        // require(\n        //     IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) \u003e= amountOutMin,\n        //     \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027\n        // );\n    }\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    )\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n    {\n        // require(path[0] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        // uint amountIn = msg.value;\n        // IWETH(WETH).deposit{value: amountIn}();\n        // assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));\n        // uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);\n        // _swapSupportingFeeOnTransferTokens(path, to);\n        // require(\n        //     IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) \u003e= amountOutMin,\n        //     \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027\n        // );\n    }\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    )\n        external\n        virtual\n        override\n        ensure(deadline)\n    {\n        // require(path[path.length - 1] == WETH, \u0027UniswapV2Router: INVALID_PATH\u0027);\n        // TransferHelper.safeTransferFrom(\n        //     path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n        // );\n        // _swapSupportingFeeOnTransferTokens(path, address(this));\n        // uint amountOut = IERC20(WETH).balanceOf(address(this));\n        // require(amountOut \u003e= amountOutMin, \u0027UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT\u0027);\n        // IWETH(WETH).withdraw(amountOut);\n        // TransferHelper.safeTransferETH(to, amountOut);\n    }\n\n    // **** LIBRARY FUNCTIONS ****\n    function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {\n        return UniswapV2Library.quote(amountA, reserveA, reserveB);\n    }\n\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)\n        public\n        pure\n        virtual\n        override\n        returns (uint amountOut)\n    {\n        return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);\n    }\n\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)\n        public\n        pure\n        virtual\n        override\n        returns (uint amountIn)\n    {\n        return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);\n    }\n\n    function getAmountsOut(uint amountIn, address[] memory path)\n        public\n        view\n        virtual\n        override\n        returns (uint[] memory amounts)\n    {\n        return UniswapV2Library.getAmountsOut(factory, amountIn, path);\n    }\n\n    function getAmountsIn(uint amountOut, address[] memory path)\n        public\n        view\n        virtual\n        override\n        returns (uint[] memory amounts)\n    {\n        return UniswapV2Library.getAmountsIn(factory, amountOut, path);\n    }\n}"},"UQ112x112.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\n// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))\n\n// range: [0, 2**112 - 1]\n// resolution: 1 / 2**112\n\nlibrary UQ112x112 {\n    uint224 constant Q112 = 2**112;\n\n    // encode a uint112 as a UQ112x112\n    function encode(uint112 y) internal pure returns (uint224 z) {\n        z = uint224(y) * Q112; // never overflows\n    }\n\n    // divide a UQ112x112 by a uint112, returning a UQ112x112\n    function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {\n        z = x / uint224(y);\n    }\n}"},"WETH.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity 0.6.11;\n\nimport \u0027./IWETH.sol\u0027;\n\n// Copyright (C) 2015, 2016, 2017 Dapphub\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see \u003chttp://www.gnu.org/licenses/\u003e.\n\ncontract WETH is IWETH {\n    string public name     = \"Wrapped Ether\";\n    string public symbol   = \"WETH\";\n    uint8  public decimals = 18;\n\n    event  Approval(address indexed src, address indexed guy, uint wad);\n    event  Transfer(address indexed src, address indexed dst, uint wad);\n    event  Deposit(address indexed dst, uint wad);\n    event  Withdrawal(address indexed src, uint wad);\n\n    mapping (address =\u003e uint)                       public  balanceOf;\n    mapping (address =\u003e mapping (address =\u003e uint))  public  allowance;\n\n    fallback() external payable {\n        deposit();\n    }\n\n    receive() external payable { }\n\n    constructor (address _creator_address ) public \n    {\n        balanceOf[_creator_address] = 1000000e18; // this is for testing only\n    }\n\n\n    function deposit() public override payable {\n        balanceOf[msg.sender] += msg.value;\n        emit Deposit(msg.sender, msg.value);\n    }\n    function withdraw(uint wad) override public {\n        require(balanceOf[msg.sender] \u003e= wad);\n        balanceOf[msg.sender] -= wad;\n        msg.sender.transfer(wad);\n        emit Withdrawal(msg.sender, wad);\n    }\n\n    function totalSupply() public view returns (uint) {\n        return address(this).balance;\n    }\n\n    function approve(address guy, uint wad) public returns (bool) {\n        allowance[msg.sender][guy] = wad;\n        emit Approval(msg.sender, guy, wad);\n        return true;\n    }\n\n    function transfer(address dst, uint wad) public override returns (bool) {\n        return transferFrom(msg.sender, dst, wad);\n    }\n\n    function transferFrom(address src, address dst, uint wad)\n        public\n        override\n        returns (bool)\n    {\n        require(balanceOf[src] \u003e= wad);\n\n        if (src != msg.sender \u0026\u0026 allowance[src][msg.sender] != uint(-1)) {\n            require(allowance[src][msg.sender] \u003e= wad);\n            allowance[src][msg.sender] -= wad;\n        }\n\n        balanceOf[src] -= wad;\n        balanceOf[dst] += wad;\n\n        emit Transfer(src, dst, wad);\n\n        return true;\n    }\n}\n\n\n/*\n                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. \u003chttp://fsf.org/\u003e\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers\u0027 and authors\u0027 protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users\u0027 and\nauthors\u0027 sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users\u0027 freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work\u0027s\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users\u0027 Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work\u0027s\nusers, your or third parties\u0027 legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program\u0027s source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation\u0027s users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party\u0027s predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor\u0027s \"contributor version\".\n\n  A contributor\u0027s \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor\u0027s essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient\u0027s use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others\u0027 Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy\u0027s\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    \u003cone line to give the program\u0027s name and a brief idea of what it does.\u003e\n    Copyright (C) \u003cyear\u003e  \u003cname of author\u003e\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see \u003chttp://www.gnu.org/licenses/\u003e.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    \u003cprogram\u003e  Copyright (C) \u003cyear\u003e  \u003cname of author\u003e\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\u0027.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c\u0027 for details.\n\nThe hypothetical commands `show w\u0027 and `show c\u0027 should show the appropriate\nparts of the General Public License.  Of course, your program\u0027s commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n\u003chttp://www.gnu.org/licenses/\u003e.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n\u003chttp://www.gnu.org/philosophy/why-not-lgpl.html\u003e.\n\n*/"}}