// Vulnerability label: DC1
{{
  "language": "Solidity",
  "settings": {
    "evmVersion": "istanbul",
    "libraries": {},
    "metadata": {
      "bytecodeHash": "ipfs",
      "useLiteralContent": true
    },
    "optimizer": {
      "enabled": true,
      "runs": 1000
    },
    "remappings": [],
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "abi"
        ]
      }
    }
  },
  "sources": {
    "contracts/CarefulMath.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\n/**\r\n  * @title Careful Math\r\n  * @author DeFiPie\r\n  * @notice Derived from OpenZeppelin's SafeMath library\r\n  *         https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol\r\n  */\r\ncontract CarefulMath {\r\n\r\n    /**\r\n     * @dev Possible error codes that we can return\r\n     */\r\n    enum MathError {\r\n        NO_ERROR,\r\n        DIVISION_BY_ZERO,\r\n        INTEGER_OVERFLOW,\r\n        INTEGER_UNDERFLOW\r\n    }\r\n\r\n    /**\r\n    * @dev Multiplies two numbers, returns an error on overflow.\r\n    */\r\n    function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n        if (a == 0) {\r\n            return (MathError.NO_ERROR, 0);\r\n        }\r\n\r\n        uint c = a * b;\r\n\r\n        if (c / a != b) {\r\n            return (MathError.INTEGER_OVERFLOW, 0);\r\n        } else {\r\n            return (MathError.NO_ERROR, c);\r\n        }\r\n    }\r\n\r\n    /**\r\n    * @dev Integer division of two numbers, truncating the quotient.\r\n    */\r\n    function divUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n        if (b == 0) {\r\n            return (MathError.DIVISION_BY_ZERO, 0);\r\n        }\r\n\r\n        return (MathError.NO_ERROR, a / b);\r\n    }\r\n\r\n    /**\r\n    * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).\r\n    */\r\n    function subUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n        if (b <= a) {\r\n            return (MathError.NO_ERROR, a - b);\r\n        } else {\r\n            return (MathError.INTEGER_UNDERFLOW, 0);\r\n        }\r\n    }\r\n\r\n    /**\r\n    * @dev Adds two numbers, returns an error on overflow.\r\n    */\r\n    function addUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n        uint c = a + b;\r\n\r\n        if (c >= a) {\r\n            return (MathError.NO_ERROR, c);\r\n        } else {\r\n            return (MathError.INTEGER_OVERFLOW, 0);\r\n        }\r\n    }\r\n\r\n    /**\r\n    * @dev add a and b and then subtract c\r\n    */\r\n    function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {\r\n        (MathError err0, uint sum) = addUInt(a, b);\r\n\r\n        if (err0 != MathError.NO_ERROR) {\r\n            return (err0, 0);\r\n        }\r\n\r\n        return subUInt(sum, c);\r\n    }\r\n}",
      "keccak256": "0xefaaed114e3f81484c1fa4166c972f6cf6dcd0ab746cab864a43aaabed75e918"
    },
    "contracts/Controller.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./Exponential.sol\";\r\nimport \"./PriceOracle.sol\";\r\nimport \"./ControllerInterface.sol\";\r\nimport \"./ControllerStorage.sol\";\r\nimport \"./PTokenInterfaces.sol\";\r\nimport \"./EIP20Interface.sol\";\r\nimport \"./Unitroller.sol\";\r\n\r\n/**\r\n * @title DeFiPie's Controller Contract\r\n * @author DeFiPie\r\n */\r\ncontract Controller is ControllerStorage, ControllerInterface, ControllerErrorReporter, Exponential {\r\n    /// @notice Emitted when an admin supports a market\r\n    event MarketListed(address pToken);\r\n\r\n    /// @notice Emitted when an account enters a market\r\n    event MarketEntered(address pToken, address account);\r\n\r\n    /// @notice Emitted when an account exits a market\r\n    event MarketExited(address pToken, address account);\r\n\r\n    /// @notice Emitted when close factor is changed by admin\r\n    event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);\r\n\r\n    /// @notice Emitted when a collateral factor is changed by admin\r\n    event NewCollateralFactor(address pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);\r\n\r\n    /// @notice Emitted when liquidation incentive is changed by admin\r\n    event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);\r\n\r\n    /// @notice Emitted when maxAssets is changed by admin\r\n    event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);\r\n\r\n    /// @notice Emitted when price oracle is changed\r\n    event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);\r\n\r\n    /// @notice Emitted when pause guardian is changed\r\n    event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);\r\n\r\n    /// @notice Emitted when an action is paused globally\r\n    event ActionPaused(string action, bool pauseState);\r\n\r\n    /// @notice Emitted when an action is paused on a market\r\n    event ActionPaused(address pToken, string action, bool pauseState);\r\n\r\n    /// @notice Emitted when a new PIE speed is calculated for a market\r\n    event PieSpeedUpdated(address indexed pToken, uint newSpeed);\r\n\r\n    /// @notice Emitted when PIE is distributed to a supplier\r\n    event DistributedSupplierPie(address indexed pToken, address indexed supplier, uint pieDelta, uint pieSupplyIndex);\r\n\r\n    /// @notice Emitted when PIE is distributed to a borrower\r\n    event DistributedBorrowerPie(address indexed pToken, address indexed borrower, uint pieDelta, uint pieBorrowIndex);\r\n\r\n    /// @notice The threshold above which the flywheel transfers PIE, in wei\r\n    uint public constant pieClaimThreshold = 0.001e18;\r\n\r\n    /// @notice The initial PIE index for a market\r\n    uint224 public constant pieInitialIndex = 1e36;\r\n\r\n    // closeFactorMantissa must be strictly greater than this value\r\n    uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05\r\n\r\n    // closeFactorMantissa must not exceed this value\r\n    uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9\r\n\r\n    // No collateralFactorMantissa may exceed this value\r\n    uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9\r\n\r\n    // liquidationIncentiveMantissa must be no less than this value\r\n    uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0\r\n\r\n    // liquidationIncentiveMantissa must be no greater than this value\r\n    uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5\r\n\r\n    constructor() {\r\n        admin = msg.sender;\r\n    }\r\n\r\n    /*** Assets You Are In ***/\r\n\r\n    /**\r\n     * @notice Returns the assets an account has entered\r\n     * @param account The address of the account to pull assets for\r\n     * @return A dynamic list with the assets the account has entered\r\n     */\r\n    function getAssetsIn(address account) external view returns (address[] memory) {\r\n        address[] memory assetsIn = accountAssets[account];\r\n\r\n        return assetsIn;\r\n    }\r\n\r\n    /**\r\n     * @notice Returns whether the given account is entered in the given asset\r\n     * @param account The address of the account to check\r\n     * @param pToken The pToken to check\r\n     * @return True if the account is in the asset, otherwise false.\r\n     */\r\n    function checkMembership(address account, address pToken) external view returns (bool) {\r\n        return markets[pToken].accountMembership[account];\r\n    }\r\n\r\n    /**\r\n     * @notice Add assets to be included in account liquidity calculation\r\n     * @param pTokens The list of addresses of the pToken markets to be enabled\r\n     * @return Success indicator for whether each corresponding market was entered\r\n     */\r\n    function enterMarkets(address[] memory pTokens) public override returns (uint[] memory) {\r\n        uint len = pTokens.length;\r\n\r\n        uint[] memory results = new uint[](len);\r\n        for (uint i = 0; i < len; i++) {\r\n            address pToken = pTokens[i];\r\n\r\n            results[i] = uint(addToMarketInternal(pToken, msg.sender));\r\n        }\r\n\r\n        return results;\r\n    }\r\n\r\n    /**\r\n     * @notice Add the market to the borrower's \"assets in\" for liquidity calculations\r\n     * @param pToken The market to enter\r\n     * @param borrower The address of the account to modify\r\n     * @return Success indicator for whether the market was entered\r\n     */\r\n    function addToMarketInternal(address pToken, address borrower) internal returns (Error) {\r\n        Market storage marketToJoin = markets[pToken];\r\n\r\n        if (!marketToJoin.isListed) {\r\n            // market is not listed, cannot join\r\n            return Error.MARKET_NOT_LISTED;\r\n        }\r\n\r\n        if (marketToJoin.accountMembership[borrower] == true) {\r\n            // already joined\r\n            return Error.NO_ERROR;\r\n        }\r\n\r\n        if (accountAssets[borrower].length >= maxAssets)  {\r\n            // no space, cannot join\r\n            return Error.TOO_MANY_ASSETS;\r\n        }\r\n\r\n        // survived the gauntlet, add to list\r\n        // NOTE: we store these somewhat redundantly as a significant optimization\r\n        //  this avoids having to iterate through the list for the most common use cases\r\n        //  that is, only when we need to perform liquidity checks\r\n        //  and not whenever we want to check if an account is in a particular market\r\n        marketToJoin.accountMembership[borrower] = true;\r\n        accountAssets[borrower].push(pToken);\r\n\r\n        emit MarketEntered(pToken, borrower);\r\n\r\n        return Error.NO_ERROR;\r\n    }\r\n\r\n    /**\r\n     * @notice Removes asset from sender's account liquidity calculation\r\n     * @dev Sender must not have an outstanding borrow balance in the asset,\r\n     *  or be providing neccessary collateral for an outstanding borrow.\r\n     * @param pTokenAddress The address of the asset to be removed\r\n     * @return Whether or not the account successfully exited the market\r\n     */\r\n    function exitMarket(address pTokenAddress) external override returns (uint) {\r\n        address pToken = pTokenAddress;\r\n        /* Get sender tokensHeld and amountOwed underlying from the pToken */\r\n        (uint oErr, uint tokensHeld, uint amountOwed, ) = PTokenInterface(pToken).getAccountSnapshot(msg.sender);\r\n        require(oErr == 0, \"exitMarket: getAccountSnapshot failed\"); // semi-opaque error code\r\n\r\n        /* Fail if the sender has a borrow balance */\r\n        if (amountOwed != 0) {\r\n            return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);\r\n        }\r\n\r\n        /* Fail if the sender is not permitted to redeem all of their tokens */\r\n        uint allowed = redeemAllowedInternal(pTokenAddress, msg.sender, tokensHeld);\r\n        if (allowed != 0) {\r\n            return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);\r\n        }\r\n\r\n        Market storage marketToExit = markets[pToken];\r\n\r\n        /* Return true if the sender is not already ‘in’ the market */\r\n        if (!marketToExit.accountMembership[msg.sender]) {\r\n            return uint(Error.NO_ERROR);\r\n        }\r\n\r\n        /* Set pToken account membership to false */\r\n        delete marketToExit.accountMembership[msg.sender];\r\n\r\n        /* Delete pToken from the account’s list of assets */\r\n        // load into memory for faster iteration\r\n        address[] memory userAssetList = accountAssets[msg.sender];\r\n        uint len = userAssetList.length;\r\n        uint assetIndex = len;\r\n        for (uint i = 0; i < len; i++) {\r\n            if (userAssetList[i] == pToken) {\r\n                assetIndex = i;\r\n                break;\r\n            }\r\n        }\r\n\r\n        // We *must* have found the asset in the list or our redundant data structure is broken\r\n        assert(assetIndex < len);\r\n\r\n        // copy last item in list to location of item to be removed, reduce length by 1\r\n        address[] storage storedList = accountAssets[msg.sender];\r\n        storedList[assetIndex] = storedList[storedList.length - 1];\r\n        storedList.pop(); //storedList.length--;\r\n\r\n        emit MarketExited(pToken, msg.sender);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /*** Policy Hooks ***/\r\n\r\n    /**\r\n     * @notice Checks if the account should be allowed to mint tokens in the given market\r\n     * @param pToken The market to verify the mint against\r\n     * @param minter The account which would get the minted tokens\r\n     * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens\r\n     * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n     */\r\n    function mintAllowed(address pToken, address minter, uint mintAmount) external override returns (uint) {\r\n        // Pausing is a very serious situation - we revert to sound the alarms\r\n        require(!mintGuardianPaused[pToken], \"mint is paused\");\r\n\r\n        // Shh - currently unused\r\n        minter;\r\n        mintAmount;\r\n\r\n        if (!markets[pToken].isListed) {\r\n            return uint(Error.MARKET_NOT_LISTED);\r\n        }\r\n\r\n        // Keep the flywheel moving\r\n        updatePieSupplyIndex(pToken);\r\n        distributeSupplierPie(pToken, minter, false);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n     * @notice Checks if the account should be allowed to redeem tokens in the given market\r\n     * @param pToken The market to verify the redeem against\r\n     * @param redeemer The account which would redeem the tokens\r\n     * @param redeemTokens The number of pTokens to exchange for the underlying asset in the market\r\n     * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n     */\r\n    function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external override returns (uint) {\r\n        uint allowed = redeemAllowedInternal(pToken, redeemer, redeemTokens);\r\n        if (allowed != uint(Error.NO_ERROR)) {\r\n            return allowed;\r\n        }\r\n\r\n        // Keep the flywheel moving\r\n        updatePieSupplyIndex(pToken);\r\n        distributeSupplierPie(pToken, redeemer, false);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) {\r\n        if (!markets[pToken].isListed) {\r\n            return uint(Error.MARKET_NOT_LISTED);\r\n        }\r\n\r\n        /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */\r\n        if (!markets[pToken].accountMembership[redeemer]) {\r\n            return uint(Error.NO_ERROR);\r\n        }\r\n\r\n        /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */\r\n        (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, pToken, redeemTokens, 0);\r\n        if (err != Error.NO_ERROR) {\r\n            return uint(err);\r\n        }\r\n        if (shortfall > 0) {\r\n            return uint(Error.INSUFFICIENT_LIQUIDITY);\r\n        }\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n     * @notice Validates redeem and reverts on rejection. May emit logs.\r\n     * @param pToken Asset being redeemed\r\n     * @param redeemer The address redeeming the tokens\r\n     * @param redeemAmount The amount of the underlying asset being redeemed\r\n     * @param redeemTokens The number of tokens being redeemed\r\n     */\r\n    function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {\r\n        // Shh - currently unused\r\n        pToken;\r\n        redeemer;\r\n\r\n        // Require tokens is zero or amount is also zero\r\n        if (redeemTokens == 0 && redeemAmount > 0) {\r\n            revert(\"redeemTokens zero\");\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Checks if the account should be allowed to borrow the underlying asset of the given market\r\n     * @param pToken The market to verify the borrow against\r\n     * @param borrower The account which would borrow the asset\r\n     * @param borrowAmount The amount of underlying the account would borrow\r\n     * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n     */\r\n    function borrowAllowed(address pToken, address borrower, uint borrowAmount) external override returns (uint) {\r\n        // Pausing is a very serious situation - we revert to sound the alarms\r\n        require(!borrowGuardianPaused[pToken], \"borrow is paused\");\r\n\r\n        if (!markets[pToken].isListed) {\r\n            return uint(Error.MARKET_NOT_LISTED);\r\n        }\r\n\r\n        Error err;\r\n\r\n        if (!markets[pToken].accountMembership[borrower]) {\r\n            // only pTokens may call borrowAllowed if borrower not in market\r\n            require(msg.sender == pToken, \"sender must be pToken\");\r\n\r\n            // attempt to add borrower to the market\r\n            err = addToMarketInternal(msg.sender, borrower);\r\n            if (err != Error.NO_ERROR) {\r\n                return uint(err);\r\n            }\r\n\r\n            // it should be impossible to break the important invariant\r\n            assert(markets[pToken].accountMembership[borrower]);\r\n        }\r\n\r\n        if (oracle.getUnderlyingPrice(pToken) == 0) {\r\n            return uint(Error.PRICE_ERROR);\r\n        }\r\n\r\n        uint shortfall;\r\n\r\n        (err, , shortfall) = getHypotheticalAccountLiquidityInternal(borrower, pToken, 0, borrowAmount);\r\n        if (err != Error.NO_ERROR) {\r\n            return uint(err);\r\n        }\r\n        if (shortfall > 0) {\r\n            return uint(Error.INSUFFICIENT_LIQUIDITY);\r\n        }\r\n\r\n        // Keep the flywheel moving\r\n        Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n        updatePieBorrowIndex(pToken, borrowIndex);\r\n        distributeBorrowerPie(pToken, borrower, borrowIndex, false);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n     * @notice Checks if the account should be allowed to repay a borrow in the given market\r\n     * @param pToken The market to verify the repay against\r\n     * @param payer The account which would repay the asset\r\n     * @param borrower The account which would borrowed the asset\r\n     * @param repayAmount The amount of the underlying asset the account would repay\r\n     * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n     */\r\n    function repayBorrowAllowed(\r\n        address pToken,\r\n        address payer,\r\n        address borrower,\r\n        uint repayAmount\r\n    ) external override returns (uint) {\r\n        // Shh - currently unused\r\n        payer;\r\n        borrower;\r\n        repayAmount;\r\n\r\n        if (!markets[pToken].isListed) {\r\n            return uint(Error.MARKET_NOT_LISTED);\r\n        }\r\n\r\n        // Keep the flywheel moving\r\n        Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n        updatePieBorrowIndex(pToken, borrowIndex);\r\n        distributeBorrowerPie(pToken, borrower, borrowIndex, false);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n     * @notice Checks if the liquidation should be allowed to occur\r\n     * @param pTokenBorrowed Asset which was borrowed by the borrower\r\n     * @param pTokenCollateral Asset which was used as collateral and will be seized\r\n     * @param liquidator The address repaying the borrow and seizing the collateral\r\n     * @param borrower The address of the borrower\r\n     * @param repayAmount The amount of underlying being repaid\r\n     */\r\n    function liquidateBorrowAllowed(\r\n        address pTokenBorrowed,\r\n        address pTokenCollateral,\r\n        address liquidator,\r\n        address borrower,\r\n        uint repayAmount\r\n    ) external override returns (uint) {\r\n        // Shh - currently unused\r\n        liquidator;\r\n\r\n        if (!markets[pTokenBorrowed].isListed || !markets[pTokenCollateral].isListed) {\r\n            return uint(Error.MARKET_NOT_LISTED);\r\n        }\r\n\r\n        /* The borrower must have shortfall in order to be liquidatable */\r\n        (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);\r\n        if (err != Error.NO_ERROR) {\r\n            return uint(err);\r\n        }\r\n        if (shortfall == 0) {\r\n            return uint(Error.INSUFFICIENT_SHORTFALL);\r\n        }\r\n\r\n        /* The liquidator may not repay more than what is allowed by the closeFactor */\r\n        uint borrowBalance = PTokenInterface(pTokenBorrowed).borrowBalanceStored(borrower);\r\n        (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);\r\n        if (mathErr != MathError.NO_ERROR) {\r\n            return uint(Error.MATH_ERROR);\r\n        }\r\n        if (repayAmount > maxClose) {\r\n            return uint(Error.TOO_MUCH_REPAY);\r\n        }\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n     * @notice Checks if the seizing of assets should be allowed to occur\r\n     * @param pTokenCollateral Asset which was used as collateral and will be seized\r\n     * @param pTokenBorrowed Asset which was borrowed by the borrower\r\n     * @param liquidator The address repaying the borrow and seizing the collateral\r\n     * @param borrower The address of the borrower\r\n     * @param seizeTokens The number of collateral tokens to seize\r\n     */\r\n    function seizeAllowed(\r\n        address pTokenCollateral,\r\n        address pTokenBorrowed,\r\n        address liquidator,\r\n        address borrower,\r\n        uint seizeTokens\r\n    ) external override returns (uint) {\r\n        // Pausing is a very serious situation - we revert to sound the alarms\r\n        require(!seizeGuardianPaused, \"seize is paused\");\r\n\r\n        // Shh - currently unused\r\n        seizeTokens;\r\n\r\n        if (!markets[pTokenCollateral].isListed || !markets[pTokenBorrowed].isListed) {\r\n            return uint(Error.MARKET_NOT_LISTED);\r\n        }\r\n\r\n        if (PTokenInterface(pTokenCollateral).controller() != PTokenInterface(pTokenBorrowed).controller()) {\r\n            return uint(Error.CONTROLLER_MISMATCH);\r\n        }\r\n\r\n        // Keep the flywheel moving\r\n        updatePieSupplyIndex(pTokenCollateral);\r\n        distributeSupplierPie(pTokenCollateral, borrower, false);\r\n        distributeSupplierPie(pTokenCollateral, liquidator, false);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n     * @notice Checks if the account should be allowed to transfer tokens in the given market\r\n     * @param pToken The market to verify the transfer against\r\n     * @param src The account which sources the tokens\r\n     * @param dst The account which receives the tokens\r\n     * @param transferTokens The number of pTokens to transfer\r\n     * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n     */\r\n    function transferAllowed(\r\n        address pToken,\r\n        address src,\r\n        address dst,\r\n        uint transferTokens\r\n    ) external override returns (uint) {\r\n        // Pausing is a very serious situation - we revert to sound the alarms\r\n        require(!transferGuardianPaused, \"transfer is paused\");\r\n\r\n        // Currently the only consideration is whether or not\r\n        //  the src is allowed to redeem this many tokens\r\n        uint allowed = redeemAllowedInternal(pToken, src, transferTokens);\r\n        if (allowed != uint(Error.NO_ERROR)) {\r\n            return allowed;\r\n        }\r\n\r\n        // Keep the flywheel moving\r\n        updatePieSupplyIndex(pToken);\r\n        distributeSupplierPie(pToken, src, false);\r\n        distributeSupplierPie(pToken, dst, false);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /*** Liquidity/Liquidation Calculations ***/\r\n\r\n    /**\r\n     * @dev Local vars for avoiding stack-depth limits in calculating account liquidity.\r\n     *  Note that `pTokenBalance` is the number of pTokens the account owns in the market,\r\n     *  whereas `borrowBalance` is the amount of underlying that the account has borrowed.\r\n     */\r\n    struct AccountLiquidityLocalVars {\r\n        uint sumCollateral;\r\n        uint sumBorrowPlusEffects;\r\n        uint pTokenBalance;\r\n        uint borrowBalance;\r\n        uint exchangeRateMantissa;\r\n        uint oraclePriceMantissa;\r\n        Exp collateralFactor;\r\n        Exp exchangeRate;\r\n        Exp oraclePrice;\r\n        Exp tokensToDenom;\r\n    }\r\n\r\n    /**\r\n     * @notice Determine the current account liquidity wrt collateral requirements\r\n     * @return (possible error code (semi-opaque),\r\n                account liquidity in excess of collateral requirements,\r\n     *          account shortfall below collateral requirements)\r\n     */\r\n    function getAccountLiquidity(address account) public view returns (uint, uint, uint) {\r\n        (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, address(0), 0, 0);\r\n\r\n        return (uint(err), liquidity, shortfall);\r\n    }\r\n\r\n    /**\r\n     * @notice Determine the current account liquidity wrt collateral requirements\r\n     * @return (possible error code,\r\n                account liquidity in excess of collateral requirements,\r\n     *          account shortfall below collateral requirements)\r\n     */\r\n    function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {\r\n        return getHypotheticalAccountLiquidityInternal(account, address(0), 0, 0);\r\n    }\r\n\r\n    /**\r\n     * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\r\n     * @param pTokenModify The market to hypothetically redeem/borrow in\r\n     * @param account The account to determine liquidity for\r\n     * @param redeemTokens The number of tokens to hypothetically redeem\r\n     * @param borrowAmount The amount of underlying to hypothetically borrow\r\n     * @return (possible error code (semi-opaque),\r\n                hypothetical account liquidity in excess of collateral requirements,\r\n     *          hypothetical account shortfall below collateral requirements)\r\n     */\r\n    function getHypotheticalAccountLiquidity(\r\n        address account,\r\n        address pTokenModify,\r\n        uint redeemTokens,\r\n        uint borrowAmount\r\n    ) public view virtual returns (uint, uint, uint) {\r\n        (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, pTokenModify, redeemTokens, borrowAmount);\r\n        return (uint(err), liquidity, shortfall);\r\n    }\r\n\r\n    /**\r\n     * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\r\n     * @param pTokenModify The market to hypothetically redeem/borrow in\r\n     * @param account The account to determine liquidity for\r\n     * @param redeemTokens The number of tokens to hypothetically redeem\r\n     * @param borrowAmount The amount of underlying to hypothetically borrow\r\n     * @dev Note that we calculate the exchangeRateStored for each collateral pToken using stored data,\r\n     *  without calculating accumulated interest.\r\n     * @return (possible error code,\r\n                hypothetical account liquidity in excess of collateral requirements,\r\n     *          hypothetical account shortfall below collateral requirements)\r\n     */\r\n    function getHypotheticalAccountLiquidityInternal(\r\n        address account,\r\n        address pTokenModify,\r\n        uint redeemTokens,\r\n        uint borrowAmount\r\n    ) internal view returns (Error, uint, uint) {\r\n\r\n        AccountLiquidityLocalVars memory vars; // Holds all our calculation results\r\n        uint oErr;\r\n        MathError mErr;\r\n\r\n        // For each asset the account is in\r\n        address[] memory assets = accountAssets[account];\r\n        for (uint i = 0; i < assets.length; i++) {\r\n            address asset = assets[i];\r\n\r\n            // Read the balances and exchange rate from the pToken\r\n            (oErr, vars.pTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = PTokenInterface(asset).getAccountSnapshot(account);\r\n            if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades\r\n                return (Error.SNAPSHOT_ERROR, 0, 0);\r\n            }\r\n            vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});\r\n            vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});\r\n\r\n            // Get the normalized price of the asset\r\n            vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);\r\n            if (vars.oraclePriceMantissa == 0) {\r\n                return (Error.PRICE_ERROR, 0, 0);\r\n            }\r\n            vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});\r\n\r\n            // Pre-compute a conversion factor from tokens -> ether (normalized price value)\r\n            (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);\r\n            if (mErr != MathError.NO_ERROR) {\r\n                return (Error.MATH_ERROR, 0, 0);\r\n            }\r\n\r\n            // sumCollateral += tokensToDenom * pTokenBalance\r\n            (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.pTokenBalance, vars.sumCollateral);\r\n            if (mErr != MathError.NO_ERROR) {\r\n                return (Error.MATH_ERROR, 0, 0);\r\n            }\r\n\r\n            // sumBorrowPlusEffects += oraclePrice * borrowBalance\r\n            (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);\r\n            if (mErr != MathError.NO_ERROR) {\r\n                return (Error.MATH_ERROR, 0, 0);\r\n            }\r\n\r\n            // Calculate effects of interacting with pTokenModify\r\n            if (asset == pTokenModify) {\r\n                // redeem effect\r\n                // sumBorrowPlusEffects += tokensToDenom * redeemTokens\r\n                (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);\r\n                if (mErr != MathError.NO_ERROR) {\r\n                    return (Error.MATH_ERROR, 0, 0);\r\n                }\r\n\r\n                // borrow effect\r\n                // sumBorrowPlusEffects += oraclePrice * borrowAmount\r\n                (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);\r\n                if (mErr != MathError.NO_ERROR) {\r\n                    return (Error.MATH_ERROR, 0, 0);\r\n                }\r\n            }\r\n        }\r\n\r\n        // These are safe, as the underflow condition is checked first\r\n        if (vars.sumCollateral > vars.sumBorrowPlusEffects) {\r\n            return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);\r\n        } else {\r\n            return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Calculate number of tokens of collateral asset to seize given an underlying amount\r\n     * @dev Used in liquidation (called in pToken.liquidateBorrowFresh)\r\n     * @param pTokenBorrowed The address of the borrowed pToken\r\n     * @param pTokenCollateral The address of the collateral pToken\r\n     * @param actualRepayAmount The amount of pTokenBorrowed underlying to convert into pTokenCollateral tokens\r\n     * @return (errorCode, number of pTokenCollateral tokens to be seized in a liquidation)\r\n     */\r\n    function liquidateCalculateSeizeTokens(\r\n        address pTokenBorrowed,\r\n        address pTokenCollateral,\r\n        uint actualRepayAmount\r\n    ) external view override returns (uint, uint) {\r\n        /* Read oracle prices for borrowed and collateral markets */\r\n        uint priceBorrowedMantissa = oracle.getUnderlyingPrice(pTokenBorrowed);\r\n        uint priceCollateralMantissa = oracle.getUnderlyingPrice(pTokenCollateral);\r\n        if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {\r\n            return (uint(Error.PRICE_ERROR), 0);\r\n        }\r\n\r\n        /*\r\n         * Get the exchange rate and calculate the number of collateral tokens to seize:\r\n         *  seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral\r\n         *  seizeTokens = seizeAmount / exchangeRate\r\n         *   = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)\r\n         */\r\n        uint exchangeRateMantissa = PTokenInterface(pTokenCollateral).exchangeRateStored(); // Note: reverts on error\r\n        uint seizeTokens;\r\n        Exp memory numerator;\r\n        Exp memory denominator;\r\n        Exp memory ratio;\r\n        MathError mathErr;\r\n\r\n        (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);\r\n        if (mathErr != MathError.NO_ERROR) {\r\n            return (uint(Error.MATH_ERROR), 0);\r\n        }\r\n\r\n        (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);\r\n        if (mathErr != MathError.NO_ERROR) {\r\n            return (uint(Error.MATH_ERROR), 0);\r\n        }\r\n\r\n        (mathErr, ratio) = divExp(numerator, denominator);\r\n        if (mathErr != MathError.NO_ERROR) {\r\n            return (uint(Error.MATH_ERROR), 0);\r\n        }\r\n\r\n        (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);\r\n        if (mathErr != MathError.NO_ERROR) {\r\n            return (uint(Error.MATH_ERROR), 0);\r\n        }\r\n\r\n        return (uint(Error.NO_ERROR), seizeTokens);\r\n    }\r\n\r\n    /*** Admin Functions ***/\r\n\r\n    /**\r\n      * @notice Sets a new price oracle for the controller\r\n      * @dev Admin function to set a new price oracle\r\n      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n      */\r\n    function _setPriceOracle(PriceOracle newOracle) public returns (uint) {\r\n        // Check caller is admin\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);\r\n        }\r\n\r\n        // Track the old oracle for the controller\r\n        PriceOracle oldOracle = oracle;\r\n\r\n        // Set controller's oracle to newOracle\r\n        oracle = newOracle;\r\n\r\n        // Emit NewPriceOracle(oldOracle, newOracle)\r\n        emit NewPriceOracle(oldOracle, newOracle);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n      * @notice Sets a PIE address for the controller\r\n      * @return uint 0=success\r\n      */\r\n    function _setPieAddress(address pieAddress_) public returns (uint) {\r\n        require(msg.sender == admin && pieAddress == address(0),\"pie address may only be initialized once\");\r\n\r\n        pieAddress = pieAddress_;\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n      * @notice Sets the closeFactor used when liquidating borrows\r\n      * @dev Admin function to set closeFactor\r\n      * @param newCloseFactorMantissa New close factor, scaled by 1e18\r\n      * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n      */\r\n    function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {\r\n        // Check caller is admin\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);\r\n        }\r\n\r\n        Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});\r\n        Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});\r\n        if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {\r\n            return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);\r\n        }\r\n\r\n        Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});\r\n        if (lessThanExp(highLimit, newCloseFactorExp)) {\r\n            return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);\r\n        }\r\n\r\n        uint oldCloseFactorMantissa = closeFactorMantissa;\r\n        closeFactorMantissa = newCloseFactorMantissa;\r\n        emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n      * @notice Sets the collateralFactor for a market\r\n      * @dev Admin function to set per-market collateralFactor\r\n      * @param pToken The market to set the factor on\r\n      * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18\r\n      * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n      */\r\n    function _setCollateralFactor(address pToken, uint newCollateralFactorMantissa) external returns (uint) {\r\n        // Check caller is admin\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);\r\n        }\r\n\r\n        // Verify market is listed\r\n        Market storage market = markets[pToken];\r\n        if (!market.isListed) {\r\n            return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);\r\n        }\r\n\r\n        Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});\r\n\r\n        // Check collateral factor <= 0.9\r\n        Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});\r\n        if (lessThanExp(highLimit, newCollateralFactorExp)) {\r\n            return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);\r\n        }\r\n\r\n        oracle.updateUnderlyingPrice(pToken);\r\n        // If collateral factor != 0, fail if price == 0\r\n        if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(pToken) == 0) {\r\n            return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);\r\n        }\r\n\r\n        // Set market's collateral factor to new collateral factor, remember old value\r\n        uint oldCollateralFactorMantissa = market.collateralFactorMantissa;\r\n        market.collateralFactorMantissa = newCollateralFactorMantissa;\r\n\r\n        // Emit event with asset, old collateral factor, and new collateral factor\r\n        emit NewCollateralFactor(pToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n      * @notice Sets maxAssets which controls how many markets can be entered\r\n      * @dev Admin function to set maxAssets\r\n      * @param newMaxAssets New max assets\r\n      * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n      */\r\n    function _setMaxAssets(uint newMaxAssets) external returns (uint) {\r\n        // Check caller is admin\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);\r\n        }\r\n\r\n        uint oldMaxAssets = maxAssets;\r\n        maxAssets = newMaxAssets;\r\n        emit NewMaxAssets(oldMaxAssets, newMaxAssets);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n      * @notice Sets liquidationIncentive\r\n      * @dev Admin function to set liquidationIncentive\r\n      * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18\r\n      * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n      */\r\n    function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {\r\n        // Check caller is admin\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);\r\n        }\r\n\r\n        // Check de-scaled min <= newLiquidationIncentive <= max\r\n        Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});\r\n        Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});\r\n        if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {\r\n            return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);\r\n        }\r\n\r\n        Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});\r\n        if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {\r\n            return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);\r\n        }\r\n\r\n        // Save current value for use in log\r\n        uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;\r\n\r\n        // Set liquidation incentive to new incentive\r\n        liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;\r\n\r\n        // Emit event with old incentive, new incentive\r\n        emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n      * @notice Add the market to the markets mapping and set it as listed\r\n      * @dev Admin function to set isListed and add support for the market\r\n      * @param pToken The address of the market (token) to list\r\n      * @return uint 0=success, otherwise a failure. (See enum Error for details)\r\n      */\r\n    function _supportMarket(address pToken) external returns (uint) {\r\n        if (msg.sender != admin && msg.sender != factory) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);\r\n        }\r\n\r\n        if (markets[pToken].isListed) {\r\n            return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);\r\n        }\r\n\r\n        PTokenInterface(pToken).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n        _addMarketInternal(pToken);\r\n\r\n        Market storage newMarket = markets[pToken];\r\n        newMarket.isListed = true;\r\n\r\n        emit MarketListed(pToken);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _addMarketInternal(address pToken) internal {\r\n        require(markets[pToken].isListed == false, \"market already added\");\r\n        allMarkets.push(pToken);\r\n    }\r\n\r\n    /**\r\n     * @notice Admin function to change the Pause Guardian\r\n     * @param newPauseGuardian The address of the new Pause Guardian\r\n     * @return uint 0=success, otherwise a failure. (See enum Error for details)\r\n     */\r\n    function _setPauseGuardian(address newPauseGuardian) public returns (uint) {\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);\r\n        }\r\n\r\n        // Save current value for inclusion in log\r\n        address oldPauseGuardian = pauseGuardian;\r\n\r\n        // Store pauseGuardian with value newPauseGuardian\r\n        pauseGuardian = newPauseGuardian;\r\n\r\n        // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)\r\n        emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _setMintPaused(address pToken, bool state) public returns (bool) {\r\n        require(markets[pToken].isListed, \"cannot pause a market that is not listed\");\r\n        require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n        require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n        mintGuardianPaused[pToken] = state;\r\n        emit ActionPaused(pToken, \"Mint\", state);\r\n        return state;\r\n    }\r\n\r\n    function _setBorrowPaused(address pToken, bool state) public returns (bool) {\r\n        require(markets[pToken].isListed, \"cannot pause a market that is not listed\");\r\n        require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n        require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n        borrowGuardianPaused[pToken] = state;\r\n        emit ActionPaused(pToken, \"Borrow\", state);\r\n        return state;\r\n    }\r\n\r\n    function _setTransferPaused(bool state) public returns (bool) {\r\n        require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n        require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n        transferGuardianPaused = state;\r\n        emit ActionPaused(\"Transfer\", state);\r\n        return state;\r\n    }\r\n\r\n    function _setSeizePaused(bool state) public returns (bool) {\r\n        require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n        require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n        seizeGuardianPaused = state;\r\n        emit ActionPaused(\"Seize\", state);\r\n        return state;\r\n    }\r\n\r\n    function _setFactoryContract(address _factory) external returns (uint) {\r\n        if (msg.sender != admin) {\r\n            return uint(Error.UNAUTHORIZED);\r\n        }\r\n\r\n        factory = _factory;\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _become(address payable unitroller) public {\r\n        require(msg.sender == Unitroller(unitroller).admin(), \"only unitroller admin can change brains\");\r\n        require(Unitroller(unitroller)._acceptImplementation() == 0, \"change not authorized\");\r\n    }\r\n\r\n    /*** Pie Distribution ***/\r\n\r\n    /**\r\n     * @notice Set PIE speed for a single market\r\n     * @param pToken The market whose PIE speed to update\r\n     * @param pieSpeed New PIE speed for market\r\n     */\r\n    function setPieSpeedInternal(address pToken, uint pieSpeed) internal {\r\n        uint currentPieSpeed = pieSpeeds[pToken];\r\n        if (currentPieSpeed != 0) {\r\n            // note that PIE speed could be set to 0 to halt liquidity rewards for a market\r\n            Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n            updatePieSupplyIndex(pToken);\r\n            updatePieBorrowIndex(pToken, borrowIndex);\r\n        } else if (pieSpeed != 0) {\r\n            // Add the PIE market\r\n            Market storage market = markets[pToken];\r\n            require(market.isListed == true, \"pie market is not listed\");\r\n\r\n            if (pieSupplyState[pToken].index == 0) {\r\n                pieSupplyState[pToken] = PieMarketState({\r\n                    index: pieInitialIndex,\r\n                    block: safe32(getBlockNumber(), \"block number exceeds 32 bits\")\r\n                });\r\n            } else {\r\n                pieSupplyState[pToken].block = safe32(getBlockNumber(), \"block number exceeds 32 bits\");\r\n            }\r\n\r\n            if (pieBorrowState[pToken].index == 0) {\r\n                pieBorrowState[pToken] = PieMarketState({\r\n                    index: pieInitialIndex,\r\n                    block: safe32(getBlockNumber(), \"block number exceeds 32 bits\")\r\n                });\r\n            } else {\r\n                pieBorrowState[pToken].block = safe32(getBlockNumber(), \"block number exceeds 32 bits\");\r\n            }\r\n        }\r\n\r\n        if (currentPieSpeed != pieSpeed) {\r\n            pieSpeeds[pToken] = pieSpeed;\r\n            emit PieSpeedUpdated(pToken, pieSpeed);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Accrue PIE to the market by updating the supply index\r\n     * @param pToken The market whose supply index to update\r\n     */\r\n    function updatePieSupplyIndex(address pToken) internal {\r\n        PieMarketState storage supplyState = pieSupplyState[pToken];\r\n        uint supplySpeed = pieSpeeds[pToken];\r\n        uint blockNumber = getBlockNumber();\r\n        uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));\r\n        if (deltaBlocks > 0 && supplySpeed > 0) {\r\n            uint supplyTokens = PTokenInterface(pToken).totalSupply();\r\n            uint pieAccrued = mul_(deltaBlocks, supplySpeed);\r\n            Double memory ratio = supplyTokens > 0 ? fraction(pieAccrued, supplyTokens) : Double({mantissa: 0});\r\n            Double memory index = add_(Double({mantissa: supplyState.index}), ratio);\r\n            pieSupplyState[pToken] = PieMarketState({\r\n                index: safe224(index.mantissa, \"new index exceeds 224 bits\"),\r\n                block: safe32(blockNumber, \"block number exceeds 32 bits\")\r\n            });\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Accrue PIE to the market by updating the borrow index\r\n     * @param pToken The market whose borrow index to update\r\n     */\r\n    function updatePieBorrowIndex(address pToken, Exp memory marketBorrowIndex) internal {\r\n        PieMarketState storage borrowState = pieBorrowState[pToken];\r\n        uint borrowSpeed = pieSpeeds[pToken];\r\n        uint blockNumber = getBlockNumber();\r\n        uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));\r\n        if (deltaBlocks > 0 && borrowSpeed > 0) {\r\n            uint borrowAmount = div_(PTokenInterface(pToken).totalBorrows(), marketBorrowIndex);\r\n            uint pieAccrued = mul_(deltaBlocks, borrowSpeed);\r\n            Double memory ratio = borrowAmount > 0 ? fraction(pieAccrued, borrowAmount) : Double({mantissa: 0});\r\n            Double memory index = add_(Double({mantissa: borrowState.index}), ratio);\r\n            pieBorrowState[pToken] = PieMarketState({\r\n                index: safe224(index.mantissa, \"new index exceeds 224 bits\"),\r\n                block: safe32(blockNumber, \"block number exceeds 32 bits\")\r\n            });\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Calculate PIE accrued by a supplier and possibly transfer it to them\r\n     * @param pToken The market in which the supplier is interacting\r\n     * @param supplier The address of the supplier to distribute PIE to\r\n     */\r\n    function distributeSupplierPie(address pToken, address supplier, bool distributeAll) internal {\r\n        PieMarketState storage supplyState = pieSupplyState[pToken];\r\n        Double memory supplyIndex = Double({mantissa: supplyState.index});\r\n        Double memory supplierIndex = Double({mantissa: pieSupplierIndex[pToken][supplier]});\r\n        pieSupplierIndex[pToken][supplier] = supplyIndex.mantissa;\r\n\r\n        if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {\r\n            supplierIndex.mantissa = pieInitialIndex;\r\n        }\r\n\r\n        Double memory deltaIndex = sub_(supplyIndex, supplierIndex);\r\n        uint supplierTokens = PTokenInterface(pToken).balanceOf(supplier);\r\n        uint supplierDelta = mul_(supplierTokens, deltaIndex);\r\n        uint supplierAccrued = add_(pieAccrued[supplier], supplierDelta);\r\n        pieAccrued[supplier] = transferPie(supplier, supplierAccrued, distributeAll ? 0 : pieClaimThreshold);\r\n        emit DistributedSupplierPie(pToken, supplier, supplierDelta, supplyIndex.mantissa);\r\n    }\r\n\r\n    /**\r\n     * @notice Calculate PIE accrued by a borrower and possibly transfer it to them\r\n     * @dev Borrowers will not begin to accrue until after the first interaction with the protocol.\r\n     * @param pToken The market in which the borrower is interacting\r\n     * @param borrower The address of the borrower to distribute PIE to\r\n     */\r\n    function distributeBorrowerPie(\r\n        address pToken,\r\n        address borrower,\r\n        Exp memory marketBorrowIndex,\r\n        bool distributeAll\r\n    ) internal {\r\n        PieMarketState storage borrowState = pieBorrowState[pToken];\r\n        Double memory borrowIndex = Double({mantissa: borrowState.index});\r\n        Double memory borrowerIndex = Double({mantissa: pieBorrowerIndex[pToken][borrower]});\r\n        pieBorrowerIndex[pToken][borrower] = borrowIndex.mantissa;\r\n\r\n        if (borrowerIndex.mantissa > 0) {\r\n            Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);\r\n            uint borrowerAmount = div_(PTokenInterface(pToken).borrowBalanceStored(borrower), marketBorrowIndex);\r\n            uint borrowerDelta = mul_(borrowerAmount, deltaIndex);\r\n            uint borrowerAccrued = add_(pieAccrued[borrower], borrowerDelta);\r\n            pieAccrued[borrower] = transferPie(borrower, borrowerAccrued, distributeAll ? 0 : pieClaimThreshold);\r\n            emit DistributedBorrowerPie(pToken, borrower, borrowerDelta, borrowIndex.mantissa);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Claim all the pie accrued by holder in all markets\r\n     * @param holder The address to claim PIE for\r\n     */\r\n    function claimPie(address holder) public {\r\n        claimPie(holder, allMarkets);\r\n    }\r\n\r\n    /**\r\n     * @notice Claim all the pie accrued by holder in the specified markets\r\n     * @param holder The address to claim PIE for\r\n     * @param pTokens The list of markets to claim PIE in\r\n     */\r\n    function claimPie(address holder, address[] memory pTokens) public {\r\n        address[] memory holders = new address[](1);\r\n        holders[0] = holder;\r\n        claimPie(holders, pTokens, true, true);\r\n    }\r\n\r\n    /**\r\n     * @notice Claim all pie accrued by the holders\r\n     * @param holders The addresses to claim PIE for\r\n     * @param pTokens The list of markets to claim PIE in\r\n     * @param borrowers Whether or not to claim PIE earned by borrowing\r\n     * @param suppliers Whether or not to claim PIE earned by supplying\r\n     */\r\n    function claimPie(address[] memory holders, address[] memory pTokens, bool borrowers, bool suppliers) public {\r\n        for (uint i = 0; i < pTokens.length; i++) {\r\n            address pToken = pTokens[i];\r\n            require(markets[pToken].isListed, \"market must be listed\");\r\n            if (borrowers == true) {\r\n                Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n                updatePieBorrowIndex(pToken, borrowIndex);\r\n                for (uint j = 0; j < holders.length; j++) {\r\n                    distributeBorrowerPie(pToken, holders[j], borrowIndex, true);\r\n                }\r\n            }\r\n            if (suppliers == true) {\r\n                updatePieSupplyIndex(pToken);\r\n                for (uint j = 0; j < holders.length; j++) {\r\n                    distributeSupplierPie(pToken, holders[j], true);\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Transfer PIE to the user\r\n     * @dev Note: If there is not enough PIE, we do not perform the transfer all.\r\n     * @param user The address of the user to transfer PIE to\r\n     * @param userAccrued The amount of PIE to (possibly) transfer\r\n     * @return The userAccrued of PIE which was NOT transferred to the user\r\n     */\r\n    function transferPie(address user, uint userAccrued, uint threshold) internal returns (uint) {\r\n        if (userAccrued >= threshold && userAccrued > 0) {\r\n            address pie = getPieAddress();\r\n            uint pieRemaining = EIP20Interface(pie).balanceOf(address(this));\r\n            if (userAccrued <= pieRemaining) {\r\n                EIP20Interface(pie).transfer(user, userAccrued);\r\n                return 0;\r\n            }\r\n        }\r\n        return userAccrued;\r\n    }\r\n\r\n    /*** Pie Distribution Admin ***/\r\n\r\n    /**\r\n    * @notice Set PIE speed for a single market\r\n    * @param pToken The market whose PIE speed to update\r\n    * @param pieSpeed New PIE speed for market\r\n    */\r\n    function _setPieSpeed(address pToken, uint pieSpeed) public {\r\n        require(msg.sender == admin, \"only admin can set pie speed\");\r\n        setPieSpeedInternal(pToken, pieSpeed);\r\n    }\r\n\r\n    /**\r\n     * @notice Return all of the markets\r\n     * @dev The automatic getter may be used to access an individual market.\r\n     * @return The list of market addresses\r\n     */\r\n    function getAllMarkets() public view returns (address[] memory) {\r\n        return allMarkets;\r\n    }\r\n\r\n    function getBlockNumber() public view virtual returns (uint) {\r\n        return block.number;\r\n    }\r\n\r\n    /**\r\n     * @notice Return the address of the PIE token\r\n     * @return The address of PIE\r\n     */\r\n    function getPieAddress() public view virtual returns (address) {\r\n        return pieAddress;\r\n    }\r\n\r\n    function getOracle() public view override returns (PriceOracle) {\r\n        return oracle;\r\n    }\r\n}",
      "keccak256": "0x2ab167ec7a01e80f750f1b794239ea335c0285e98c3404f9392ebd5d6f5f7e16"
    },
    "contracts/ControllerInterface.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./PriceOracle.sol\";\r\n\r\nabstract contract ControllerInterface {\r\n    /// @notice Indicator that this is a Controller contract (for inspection)\r\n    bool public constant isController = true;\r\n\r\n    /*** Assets You Are In ***/\r\n\r\n    function enterMarkets(address[] calldata pTokens) external virtual returns (uint[] memory);\r\n    function exitMarket(address pToken) external virtual returns (uint);\r\n\r\n    /*** Policy Hooks ***/\r\n\r\n    function mintAllowed(address pToken, address minter, uint mintAmount) external virtual returns (uint);\r\n    function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external virtual returns (uint);\r\n    function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external virtual;\r\n    function borrowAllowed(address pToken, address borrower, uint borrowAmount) external virtual returns (uint);\r\n\r\n    function repayBorrowAllowed(\r\n        address pToken,\r\n        address payer,\r\n        address borrower,\r\n        uint repayAmount) external virtual returns (uint);\r\n\r\n    function liquidateBorrowAllowed(\r\n        address pTokenBorrowed,\r\n        address pTokenCollateral,\r\n        address liquidator,\r\n        address borrower,\r\n        uint repayAmount) external virtual returns (uint);\r\n\r\n    function seizeAllowed(\r\n        address pTokenCollateral,\r\n        address pTokenBorrowed,\r\n        address liquidator,\r\n        address borrower,\r\n        uint seizeTokens) external virtual returns (uint);\r\n\r\n    function transferAllowed(address pToken, address src, address dst, uint transferTokens) external virtual returns (uint);\r\n\r\n    /*** Liquidity/Liquidation Calculations ***/\r\n\r\n    function liquidateCalculateSeizeTokens(\r\n        address pTokenBorrowed,\r\n        address pTokenCollateral,\r\n        uint repayAmount) external view virtual returns (uint, uint);\r\n\r\n    function getOracle() external view virtual returns (PriceOracle);\r\n}\r\n",
      "keccak256": "0x2f7251d9b6a6df0522aa1b52d86ebbea11edff0c258af55d889c745ef81c2af2"
    },
    "contracts/ControllerStorage.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./PriceOracle.sol\";\r\n\r\ncontract UnitrollerAdminStorage {\r\n    /**\r\n    * @notice Administrator for this contract\r\n    */\r\n    address public admin;\r\n\r\n    /**\r\n    * @notice Pending administrator for this contract\r\n    */\r\n    address public pendingAdmin;\r\n\r\n    /**\r\n    * @notice Active brains of Unitroller\r\n    */\r\n    address public controllerImplementation;\r\n\r\n    /**\r\n    * @notice Pending brains of Unitroller\r\n    */\r\n    address public pendingControllerImplementation;\r\n}\r\n\r\ncontract ControllerStorage is UnitrollerAdminStorage {\r\n    /**\r\n     * @notice Oracle which gives the price of any given asset\r\n     */\r\n    PriceOracle public oracle;\r\n\r\n    /**\r\n     * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow\r\n     */\r\n    uint public closeFactorMantissa;\r\n\r\n    /**\r\n     * @notice Multiplier representing the discount on collateral that a liquidator receives\r\n     */\r\n    uint public liquidationIncentiveMantissa;\r\n\r\n    /**\r\n     * @notice Max number of assets a single account can participate in (borrow or use as collateral)\r\n     */\r\n    uint public maxAssets;\r\n\r\n    /**\r\n     * @notice Per-account mapping of \"assets you are in\", capped by maxAssets\r\n     */\r\n    mapping(address => address[]) public accountAssets;\r\n\r\n    /// @notice isListed Whether or not this market is listed\r\n    /**\r\n     * @notice collateralFactorMantissa Multiplier representing the most one can borrow against their collateral in this market.\r\n     *  For instance, 0.9 to allow borrowing 90% of collateral value.\r\n     *  Must be between 0 and 1, and stored as a mantissa.\r\n     */\r\n    /// @notice accountMembership Per-market mapping of \"accounts in this asset\"\r\n    /// @notice isPied Whether or not this market receives PIE\r\n    struct Market {\r\n        bool isListed;\r\n        uint collateralFactorMantissa;\r\n        mapping(address => bool) accountMembership;\r\n        bool isPied;\r\n    }\r\n\r\n    /**\r\n     * @notice Official mapping of pTokens -> Market metadata\r\n     * @dev Used e.g. to determine if a market is supported\r\n     */\r\n    mapping(address => Market) public markets;\r\n\r\n    /**\r\n     * @notice The Pause Guardian can pause certain actions as a safety mechanism.\r\n     *  Actions which allow users to remove their own assets cannot be paused.\r\n     *  Liquidation / seizing / transfer can only be paused globally, not by market.\r\n     */\r\n    address public pauseGuardian;\r\n    bool public _mintGuardianPaused;\r\n    bool public _borrowGuardianPaused;\r\n    bool public transferGuardianPaused;\r\n    bool public seizeGuardianPaused;\r\n    mapping(address => bool) public mintGuardianPaused;\r\n    mapping(address => bool) public borrowGuardianPaused;\r\n\r\n    /// @notice index The market's last updated pieBorrowIndex or pieSupplyIndex\r\n    /// @notice block The block number the index was last updated at\r\n    struct PieMarketState {\r\n        uint224 index;\r\n        uint32 block;\r\n    }\r\n\r\n    /// @notice A list of all markets\r\n    address[] public allMarkets;\r\n\r\n    /// @notice The rate at which the flywheel distributes PIE, per block\r\n    uint public pieRate;\r\n\r\n    /// @notice Address of the PIE token\r\n    address public pieAddress;\r\n\r\n    // @notice Address of the factory\r\n    address public factory;\r\n\r\n    /// @notice The portion of pieRate that each market currently receives\r\n    mapping(address => uint) public pieSpeeds;\r\n\r\n    /// @notice The PIE market supply state for each market\r\n    mapping(address => PieMarketState) public pieSupplyState;\r\n\r\n    /// @notice The PIE market borrow state for each market\r\n    mapping(address => PieMarketState) public pieBorrowState;\r\n\r\n    /// @notice The PIE borrow index for each market for each supplier as of the last time they accrued PIE\r\n    mapping(address => mapping(address => uint)) public pieSupplierIndex;\r\n\r\n    /// @notice The PIE borrow index for each market for each borrower as of the last time they accrued PIE\r\n    mapping(address => mapping(address => uint)) public pieBorrowerIndex;\r\n\r\n    /// @notice The PIE accrued but not yet transferred to each user\r\n    mapping(address => uint) public pieAccrued;\r\n}",
      "keccak256": "0x072d5f766cd5ca80514c814eed5b029ce7ab3d25c0d15e0840f2869ae53c0cae"
    },
    "contracts/EIP20Interface.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\n/**\r\n * @title ERC 20 Token Standard Interface\r\n *  https://eips.ethereum.org/EIPS/eip-20\r\n */\r\ninterface EIP20Interface {\r\n    function name() external view returns (string memory);\r\n    function symbol() external view returns (string memory);\r\n    function decimals() external view returns (uint8);\r\n\r\n    /**\r\n      * @notice Get the total number of tokens in circulation\r\n      * @return The supply of tokens\r\n      */\r\n    function totalSupply() external view returns (uint256);\r\n\r\n    /**\r\n     * @notice Gets the balance of the specified address\r\n     * @param owner The address from which the balance will be retrieved\r\n     * @return The balance\r\n     */\r\n    function balanceOf(address owner) external view returns (uint256);\r\n\r\n    /**\r\n      * @notice Transfer `amount` tokens from `msg.sender` to `dst`\r\n      * @param dst The address of the destination account\r\n      * @param amount The number of tokens to transfer\r\n      * @return Whether or not the transfer succeeded\r\n      */\r\n    function transfer(address dst, uint256 amount) external returns (bool);\r\n\r\n    /**\r\n      * @notice Transfer `amount` tokens from `src` to `dst`\r\n      * @param src The address of the source account\r\n      * @param dst The address of the destination account\r\n      * @param amount The number of tokens to transfer\r\n      * @return Whether or not the transfer succeeded\r\n      */\r\n    function transferFrom(address src, address dst, uint256 amount) external returns (bool);\r\n\r\n    /**\r\n      * @notice Approve `spender` to transfer up to `amount` from `src`\r\n      * @dev This will overwrite the approval amount for `spender`\r\n      *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\r\n      * @param spender The address of the account which may transfer tokens\r\n      * @param amount The number of tokens that are approved (-1 means infinite)\r\n      * @return Whether or not the approval succeeded\r\n      */\r\n    function approve(address spender, uint256 amount) external returns (bool);\r\n\r\n    /**\r\n      * @notice Get the current allowance from `owner` for `spender`\r\n      * @param owner The address of the account which owns the tokens to be spent\r\n      * @param spender The address of the account which may transfer tokens\r\n      * @return The number of tokens allowed to be spent (-1 means infinite)\r\n      */\r\n    function allowance(address owner, address spender) external view returns (uint256);\r\n\r\n    event Transfer(address indexed from, address indexed to, uint256 amount);\r\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\r\n}\r\n",
      "keccak256": "0xc91d2e339f7530a36f019778a91fc039e75465cc00e8cdc675e3d8231b5dcc39"
    },
    "contracts/ErrorReporter.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\ncontract ControllerErrorReporter {\r\n    enum Error {\r\n        NO_ERROR,\r\n        UNAUTHORIZED,\r\n        CONTROLLER_MISMATCH,\r\n        INSUFFICIENT_SHORTFALL,\r\n        INSUFFICIENT_LIQUIDITY,\r\n        INVALID_CLOSE_FACTOR,\r\n        INVALID_COLLATERAL_FACTOR,\r\n        INVALID_LIQUIDATION_INCENTIVE,\r\n        MARKET_NOT_ENTERED, // no longer possible\r\n        MARKET_NOT_LISTED,\r\n        MARKET_ALREADY_LISTED,\r\n        MATH_ERROR,\r\n        NONZERO_BORROW_BALANCE,\r\n        PRICE_ERROR,\r\n        PRICE_UPDATE_ERROR,\r\n        REJECTION,\r\n        SNAPSHOT_ERROR,\r\n        TOO_MANY_ASSETS,\r\n        TOO_MUCH_REPAY\r\n    }\r\n\r\n    enum FailureInfo {\r\n        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n        ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,\r\n        EXIT_MARKET_BALANCE_OWED,\r\n        EXIT_MARKET_REJECTION,\r\n        SET_CLOSE_FACTOR_OWNER_CHECK,\r\n        SET_CLOSE_FACTOR_VALIDATION,\r\n        SET_COLLATERAL_FACTOR_OWNER_CHECK,\r\n        SET_COLLATERAL_FACTOR_NO_EXISTS,\r\n        SET_COLLATERAL_FACTOR_VALIDATION,\r\n        SET_COLLATERAL_FACTOR_WITHOUT_PRICE,\r\n        SET_IMPLEMENTATION_OWNER_CHECK,\r\n        SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,\r\n        SET_LIQUIDATION_INCENTIVE_VALIDATION,\r\n        SET_MAX_ASSETS_OWNER_CHECK,\r\n        SET_PAUSE_GUARDIAN_OWNER_CHECK,\r\n        SET_PENDING_ADMIN_OWNER_CHECK,\r\n        SET_PENDING_IMPLEMENTATION_OWNER_CHECK,\r\n        SET_PRICE_ORACLE_OWNER_CHECK,\r\n        SUPPORT_MARKET_EXISTS,\r\n        SUPPORT_MARKET_OWNER_CHECK\r\n    }\r\n\r\n    /**\r\n      * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n      * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n      **/\r\n    event Failure(uint error, uint info, uint detail);\r\n\r\n    /**\r\n      * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n      */\r\n    function fail(Error err, FailureInfo info) internal returns (uint) {\r\n        emit Failure(uint(err), uint(info), 0);\r\n\r\n        return uint(err);\r\n    }\r\n\r\n    /**\r\n      * @dev use this when reporting an opaque error from an upgradeable collaborator contract\r\n      */\r\n    function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {\r\n        emit Failure(uint(err), uint(info), opaqueError);\r\n\r\n        return uint(err);\r\n    }\r\n}\r\n\r\ncontract TokenErrorReporter {\r\n    enum Error {\r\n        NO_ERROR,\r\n        UNAUTHORIZED,\r\n        BAD_INPUT,\r\n        CONTROLLER_REJECTION,\r\n        CONTROLLER_CALCULATION_ERROR,\r\n        INTEREST_RATE_MODEL_ERROR,\r\n        INVALID_ACCOUNT_PAIR,\r\n        INVALID_CLOSE_AMOUNT_REQUESTED,\r\n        INVALID_COLLATERAL_FACTOR,\r\n        MATH_ERROR,\r\n        MARKET_NOT_FRESH,\r\n        MARKET_NOT_LISTED,\r\n        TOKEN_INSUFFICIENT_ALLOWANCE,\r\n        TOKEN_INSUFFICIENT_BALANCE,\r\n        TOKEN_INSUFFICIENT_CASH,\r\n        TOKEN_TRANSFER_IN_FAILED,\r\n        TOKEN_TRANSFER_OUT_FAILED\r\n    }\r\n\r\n    /*\r\n     * Note: FailureInfo (but not Error) is kept in alphabetical order\r\n     *       This is because FailureInfo grows significantly faster, and\r\n     *       the order of Error has some meaning, while the order of FailureInfo\r\n     *       is entirely arbitrary.\r\n     */\r\n    enum FailureInfo {\r\n        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n        ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,\r\n        ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,\r\n        ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,\r\n        ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,\r\n        ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,\r\n        ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,\r\n        BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\r\n        BORROW_ACCRUE_INTEREST_FAILED,\r\n        BORROW_CASH_NOT_AVAILABLE,\r\n        BORROW_FRESHNESS_CHECK,\r\n        BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\r\n        BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\r\n        BORROW_MARKET_NOT_LISTED,\r\n        BORROW_CONTROLLER_REJECTION,\r\n        LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,\r\n        LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,\r\n        LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,\r\n        LIQUIDATE_CONTROLLER_REJECTION,\r\n        LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,\r\n        LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,\r\n        LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,\r\n        LIQUIDATE_FRESHNESS_CHECK,\r\n        LIQUIDATE_LIQUIDATOR_IS_BORROWER,\r\n        LIQUIDATE_REPAY_BORROW_FRESH_FAILED,\r\n        LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,\r\n        LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,\r\n        LIQUIDATE_SEIZE_CONTROLLER_REJECTION,\r\n        LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,\r\n        LIQUIDATE_SEIZE_TOO_MUCH,\r\n        MINT_ACCRUE_INTEREST_FAILED,\r\n        MINT_CONTROLLER_REJECTION,\r\n        MINT_EXCHANGE_CALCULATION_FAILED,\r\n        MINT_EXCHANGE_RATE_READ_FAILED,\r\n        MINT_FRESHNESS_CHECK,\r\n        MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\r\n        MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\r\n        MINT_TRANSFER_IN_FAILED,\r\n        MINT_TRANSFER_IN_NOT_POSSIBLE,\r\n        REDEEM_ACCRUE_INTEREST_FAILED,\r\n        REDEEM_CONTROLLER_REJECTION,\r\n        REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,\r\n        REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,\r\n        REDEEM_EXCHANGE_RATE_READ_FAILED,\r\n        REDEEM_FRESHNESS_CHECK,\r\n        REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\r\n        REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\r\n        REDEEM_TRANSFER_OUT_NOT_POSSIBLE,\r\n        REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,\r\n        REDUCE_RESERVES_ADMIN_CHECK,\r\n        REDUCE_RESERVES_CASH_NOT_AVAILABLE,\r\n        REDUCE_RESERVES_FRESH_CHECK,\r\n        REDUCE_RESERVES_VALIDATION,\r\n        REPAY_BEHALF_ACCRUE_INTEREST_FAILED,\r\n        REPAY_BORROW_ACCRUE_INTEREST_FAILED,\r\n        REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\r\n        REPAY_BORROW_CONTROLLER_REJECTION,\r\n        REPAY_BORROW_FRESHNESS_CHECK,\r\n        REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\r\n        REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\r\n        REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,\r\n        SET_COLLATERAL_FACTOR_OWNER_CHECK,\r\n        SET_COLLATERAL_FACTOR_VALIDATION,\r\n        SET_CONTROLLER_OWNER_CHECK,\r\n        SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,\r\n        SET_INTEREST_RATE_MODEL_FRESH_CHECK,\r\n        SET_INTEREST_RATE_MODEL_OWNER_CHECK,\r\n        SET_MAX_ASSETS_OWNER_CHECK,\r\n        SET_ORACLE_MARKET_NOT_LISTED,\r\n        SET_PENDING_ADMIN_OWNER_CHECK,\r\n        SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,\r\n        SET_RESERVE_FACTOR_ADMIN_CHECK,\r\n        SET_RESERVE_FACTOR_FRESH_CHECK,\r\n        SET_RESERVE_FACTOR_BOUNDS_CHECK,\r\n        TRANSFER_CONTROLLER_REJECTION,\r\n        TRANSFER_NOT_ALLOWED,\r\n        TRANSFER_NOT_ENOUGH,\r\n        TRANSFER_TOO_MUCH,\r\n        ADD_RESERVES_ACCRUE_INTEREST_FAILED,\r\n        ADD_RESERVES_FRESH_CHECK,\r\n        ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE,\r\n        SET_NEW_IMPLEMENTATION\r\n    }\r\n\r\n    /**\r\n      * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n      * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n      **/\r\n    event Failure(uint error, uint info, uint detail);\r\n\r\n    /**\r\n      * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n      */\r\n    function fail(Error err, FailureInfo info) internal returns (uint) {\r\n        emit Failure(uint(err), uint(info), 0);\r\n\r\n        return uint(err);\r\n    }\r\n\r\n    /**\r\n      * @dev use this when reporting an opaque error from an upgradeable collaborator contract\r\n      */\r\n    function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {\r\n        emit Failure(uint(err), uint(info), opaqueError);\r\n\r\n        return uint(err);\r\n    }\r\n}\r\n\r\ncontract OracleErrorReporter {\r\n    enum Error {\r\n        NO_ERROR,\r\n        POOL_OR_COIN_EXIST,\r\n        UNAUTHORIZED,\r\n        UPDATE_PRICE\r\n    }\r\n\r\n    enum FailureInfo {\r\n        ADD_POOL_OR_COIN,\r\n        NO_PAIR,\r\n        NO_RESERVES,\r\n        PERIOD_NOT_ELAPSED,\r\n        SET_NEW_IMPLEMENTATION,\r\n        UPDATE_DATA\r\n    }\r\n\r\n    /**\r\n      * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n      * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n      **/\r\n    event Failure(uint error, uint info, uint detail);\r\n\r\n    /**\r\n      * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n      */\r\n    function fail(Error err, FailureInfo info) internal returns (uint) {\r\n        emit Failure(uint(err), uint(info), 0);\r\n\r\n        return uint(err);\r\n    }\r\n}\r\n\r\ncontract FactoryErrorReporter {\r\n    enum Error {\r\n        NO_ERROR,\r\n        INVALID_POOL,\r\n        MARKET_NOT_LISTED,\r\n        UNAUTHORIZED\r\n    }\r\n\r\n    enum FailureInfo {\r\n        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n        CREATE_PETH_POOL,\r\n        CREATE_PPIE_POOL,\r\n        DEFICIENCY_LIQUIDITY_IN_POOL_OR_PAIR_IS_NOT_EXIST,\r\n        SET_MIN_LIQUIDITY_OWNER_CHECK,\r\n        SET_NEW_CONTROLLER,\r\n        SET_NEW_DECIMALS,\r\n        SET_NEW_EXCHANGE_RATE,\r\n        SET_NEW_IMPLEMENTATION,\r\n        SET_NEW_INTEREST_RATE_MODEL,\r\n        SET_NEW_ORACLE,\r\n        SET_NEW_RESERVE_FACTOR,\r\n        SET_PENDING_ADMIN_OWNER_CHECK,\r\n        SUPPORT_MARKET_BAD_RESULT\r\n    }\r\n\r\n    /**\r\n      * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n      * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n      **/\r\n    event Failure(uint error, uint info, uint detail);\r\n\r\n    /**\r\n      * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n      */\r\n    function fail(Error err, FailureInfo info) internal returns (uint) {\r\n        emit Failure(uint(err), uint(info), 0);\r\n\r\n        return uint(err);\r\n    }\r\n}\r\n\r\ncontract RegistryErrorReporter {\r\n    enum Error {\r\n        NO_ERROR,\r\n        UNAUTHORIZED\r\n    }\r\n\r\n    enum FailureInfo {\r\n        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n        SET_NEW_IMPLEMENTATION,\r\n        SET_PENDING_ADMIN_OWNER_CHECK,\r\n        SET_NEW_FACTORY\r\n    }\r\n\r\n    /**\r\n      * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n      * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n      **/\r\n    event Failure(uint error, uint info, uint detail);\r\n\r\n    /**\r\n      * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n      */\r\n    function fail(Error err, FailureInfo info) internal returns (uint) {\r\n        emit Failure(uint(err), uint(info), 0);\r\n\r\n        return uint(err);\r\n    }\r\n}",
      "keccak256": "0x948366f49dabf42cb502d5f962702ab4e2bb5ce819ddc5c86594111763ae8e84"
    },
    "contracts/Exponential.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./CarefulMath.sol\";\r\n\r\n/**\r\n * @title Exponential module for storing fixed-precision decimals\r\n * @author DeFiPie\r\n * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.\r\n *         Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:\r\n *         `Exp({mantissa: 5100000000000000000})`.\r\n */\r\ncontract Exponential is CarefulMath {\r\n    uint constant expScale = 1e18;\r\n    uint constant doubleScale = 1e36;\r\n    uint constant halfExpScale = expScale/2;\r\n    uint constant mantissaOne = expScale;\r\n\r\n    struct Exp {\r\n        uint mantissa;\r\n    }\r\n\r\n    struct Double {\r\n        uint mantissa;\r\n    }\r\n\r\n    /**\r\n     * @dev Creates an exponential from numerator and denominator values.\r\n     *      Note: Returns an error if (`num` * 10e18) > MAX_INT,\r\n     *            or if `denom` is zero.\r\n     */\r\n    function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {\r\n        (MathError err0, uint scaledNumerator) = mulUInt(num, expScale);\r\n        if (err0 != MathError.NO_ERROR) {\r\n            return (err0, Exp({mantissa: 0}));\r\n        }\r\n\r\n        (MathError err1, uint rational) = divUInt(scaledNumerator, denom);\r\n        if (err1 != MathError.NO_ERROR) {\r\n            return (err1, Exp({mantissa: 0}));\r\n        }\r\n\r\n        return (MathError.NO_ERROR, Exp({mantissa: rational}));\r\n    }\r\n\r\n    /**\r\n     * @dev Adds two exponentials, returning a new exponential.\r\n     */\r\n    function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n        (MathError error, uint result) = addUInt(a.mantissa, b.mantissa);\r\n\r\n        return (error, Exp({mantissa: result}));\r\n    }\r\n\r\n    /**\r\n     * @dev Subtracts two exponentials, returning a new exponential.\r\n     */\r\n    function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n        (MathError error, uint result) = subUInt(a.mantissa, b.mantissa);\r\n\r\n        return (error, Exp({mantissa: result}));\r\n    }\r\n\r\n    /**\r\n     * @dev Multiply an Exp by a scalar, returning a new Exp.\r\n     */\r\n    function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {\r\n        (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);\r\n        if (err0 != MathError.NO_ERROR) {\r\n            return (err0, Exp({mantissa: 0}));\r\n        }\r\n\r\n        return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));\r\n    }\r\n\r\n    /**\r\n     * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.\r\n     */\r\n    function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {\r\n        (MathError err, Exp memory product) = mulScalar(a, scalar);\r\n        if (err != MathError.NO_ERROR) {\r\n            return (err, 0);\r\n        }\r\n\r\n        return (MathError.NO_ERROR, truncate(product));\r\n    }\r\n\r\n    /**\r\n     * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.\r\n     */\r\n    function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {\r\n        (MathError err, Exp memory product) = mulScalar(a, scalar);\r\n        if (err != MathError.NO_ERROR) {\r\n            return (err, 0);\r\n        }\r\n\r\n        return addUInt(truncate(product), addend);\r\n    }\r\n\r\n    /**\r\n     * @dev Divide an Exp by a scalar, returning a new Exp.\r\n     */\r\n    function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {\r\n        (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);\r\n        if (err0 != MathError.NO_ERROR) {\r\n            return (err0, Exp({mantissa: 0}));\r\n        }\r\n\r\n        return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));\r\n    }\r\n\r\n    /**\r\n     * @dev Divide a scalar by an Exp, returning a new Exp.\r\n     */\r\n    function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {\r\n        /*\r\n          We are doing this as:\r\n          getExp(mulUInt(expScale, scalar), divisor.mantissa)\r\n\r\n          How it works:\r\n          Exp = a / b;\r\n          Scalar = s;\r\n          `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`\r\n        */\r\n        (MathError err0, uint numerator) = mulUInt(expScale, scalar);\r\n        if (err0 != MathError.NO_ERROR) {\r\n            return (err0, Exp({mantissa: 0}));\r\n        }\r\n        return getExp(numerator, divisor.mantissa);\r\n    }\r\n\r\n    /**\r\n     * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.\r\n     */\r\n    function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {\r\n        (MathError err, Exp memory fraction_) = divScalarByExp(scalar, divisor);\r\n        if (err != MathError.NO_ERROR) {\r\n            return (err, 0);\r\n        }\r\n\r\n        return (MathError.NO_ERROR, truncate(fraction_));\r\n    }\r\n\r\n    /**\r\n     * @dev Multiplies two exponentials, returning a new exponential.\r\n     */\r\n    function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n\r\n        (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);\r\n        if (err0 != MathError.NO_ERROR) {\r\n            return (err0, Exp({mantissa: 0}));\r\n        }\r\n\r\n        // We add half the scale before dividing so that we get rounding instead of truncation.\r\n        //  See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717\r\n        // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.\r\n        (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);\r\n        if (err1 != MathError.NO_ERROR) {\r\n            return (err1, Exp({mantissa: 0}));\r\n        }\r\n\r\n        (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);\r\n        // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.\r\n        assert(err2 == MathError.NO_ERROR);\r\n\r\n        return (MathError.NO_ERROR, Exp({mantissa: product}));\r\n    }\r\n\r\n    /**\r\n     * @dev Multiplies two exponentials given their mantissas, returning a new exponential.\r\n     */\r\n    function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {\r\n        return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));\r\n    }\r\n\r\n    /**\r\n     * @dev Multiplies three exponentials, returning a new exponential.\r\n     */\r\n    function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {\r\n        (MathError err, Exp memory ab) = mulExp(a, b);\r\n        if (err != MathError.NO_ERROR) {\r\n            return (err, ab);\r\n        }\r\n        return mulExp(ab, c);\r\n    }\r\n\r\n    /**\r\n     * @dev Divides two exponentials, returning a new exponential.\r\n     *     (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,\r\n     *  which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)\r\n     */\r\n    function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n        return getExp(a.mantissa, b.mantissa);\r\n    }\r\n\r\n    /**\r\n     * @dev Truncates the given exp to a whole number value.\r\n     *      For example, truncate(Exp{mantissa: 15 * expScale}) = 15\r\n     */\r\n    function truncate(Exp memory exp) pure internal returns (uint) {\r\n        // Note: We are not using careful math here as we're performing a division that cannot fail\r\n        return exp.mantissa / expScale;\r\n    }\r\n\r\n    /**\r\n     * @dev Checks if first Exp is less than second Exp.\r\n     */\r\n    function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {\r\n        return left.mantissa < right.mantissa;\r\n    }\r\n\r\n    /**\r\n     * @dev Checks if left Exp <= right Exp.\r\n     */\r\n    function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {\r\n        return left.mantissa <= right.mantissa;\r\n    }\r\n\r\n    /**\r\n     * @dev Checks if left Exp > right Exp.\r\n     */\r\n    function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {\r\n        return left.mantissa > right.mantissa;\r\n    }\r\n\r\n    /**\r\n     * @dev returns true if Exp is exactly zero\r\n     */\r\n    function isZeroExp(Exp memory value) pure internal returns (bool) {\r\n        return value.mantissa == 0;\r\n    }\r\n\r\n    function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {\r\n        require(n < 2**224, errorMessage);\r\n        return uint224(n);\r\n    }\r\n\r\n    function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {\r\n        require(n < 2**32, errorMessage);\r\n        return uint32(n);\r\n    }\r\n\r\n    function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n        return Exp({mantissa: add_(a.mantissa, b.mantissa)});\r\n    }\r\n\r\n    function add_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n        return Double({mantissa: add_(a.mantissa, b.mantissa)});\r\n    }\r\n\r\n    function add_(uint a, uint b) pure internal returns (uint) {\r\n        return add_(a, b, \"addition overflow\");\r\n    }\r\n\r\n    function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n        uint c = a + b;\r\n        require(c >= a, errorMessage);\r\n        return c;\r\n    }\r\n\r\n    function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n        return Exp({mantissa: sub_(a.mantissa, b.mantissa)});\r\n    }\r\n\r\n    function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n        return Double({mantissa: sub_(a.mantissa, b.mantissa)});\r\n    }\r\n\r\n    function sub_(uint a, uint b) pure internal returns (uint) {\r\n        return sub_(a, b, \"subtraction underflow\");\r\n    }\r\n\r\n    function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n        require(b <= a, errorMessage);\r\n        return a - b;\r\n    }\r\n\r\n    function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n        return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});\r\n    }\r\n\r\n    function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {\r\n        return Exp({mantissa: mul_(a.mantissa, b)});\r\n    }\r\n\r\n    function mul_(uint a, Exp memory b) pure internal returns (uint) {\r\n        return mul_(a, b.mantissa) / expScale;\r\n    }\r\n\r\n    function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n        return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});\r\n    }\r\n\r\n    function mul_(Double memory a, uint b) pure internal returns (Double memory) {\r\n        return Double({mantissa: mul_(a.mantissa, b)});\r\n    }\r\n\r\n    function mul_(uint a, Double memory b) pure internal returns (uint) {\r\n        return mul_(a, b.mantissa) / doubleScale;\r\n    }\r\n\r\n    function mul_(uint a, uint b) pure internal returns (uint) {\r\n        return mul_(a, b, \"multiplication overflow\");\r\n    }\r\n\r\n    function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n        if (a == 0 || b == 0) {\r\n            return 0;\r\n        }\r\n        uint c = a * b;\r\n        require(c / a == b, errorMessage);\r\n        return c;\r\n    }\r\n\r\n    function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n        return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});\r\n    }\r\n\r\n    function div_(Exp memory a, uint b) pure internal returns (Exp memory) {\r\n        return Exp({mantissa: div_(a.mantissa, b)});\r\n    }\r\n\r\n    function div_(uint a, Exp memory b) pure internal returns (uint) {\r\n        return div_(mul_(a, expScale), b.mantissa);\r\n    }\r\n\r\n    function div_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n        return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});\r\n    }\r\n\r\n    function div_(Double memory a, uint b) pure internal returns (Double memory) {\r\n        return Double({mantissa: div_(a.mantissa, b)});\r\n    }\r\n\r\n    function div_(uint a, Double memory b) pure internal returns (uint) {\r\n        return div_(mul_(a, doubleScale), b.mantissa);\r\n    }\r\n\r\n    function div_(uint a, uint b) pure internal returns (uint) {\r\n        return div_(a, b, \"divide by zero\");\r\n    }\r\n\r\n    function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n        require(b > 0, errorMessage);\r\n        return a / b;\r\n    }\r\n\r\n    function fraction(uint a, uint b) pure internal returns (Double memory) {\r\n        return Double({mantissa: div_(mul_(a, doubleScale), b)});\r\n    }\r\n}\r\n",
      "keccak256": "0xf71e80181d7633e12561f6c1bb8a2ffea45eb9faacbe7011c889a9680ea8c9b6"
    },
    "contracts/IPriceFeeds.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./SafeMath.sol\";\r\n\r\ninterface AggregatorInterface {\r\n    function latestAnswer() external view returns (int256);\r\n}\r\n\r\nlibrary UQ112x112 {\r\n    uint224 constant Q112 = 2**112;\r\n\r\n    // encode a uint112 as a UQ112x112\r\n    function encode(uint112 y) internal pure returns (uint224 z) {\r\n        z = uint224(y) * Q112; // never overflows\r\n    }\r\n\r\n    // divide a UQ112x112 by a uint112, returning a UQ112x112\r\n    function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {\r\n        z = x / uint224(y);\r\n    }\r\n}\r\n\r\nlibrary FixedPoint {\r\n    // range: [0, 2**112 - 1]\r\n    // resolution: 1 / 2**112\r\n    struct uq112x112 {\r\n        uint224 _x;\r\n    }\r\n\r\n    // range: [0, 2**144 - 1]\r\n    // resolution: 1 / 2**112\r\n    struct uq144x112 {\r\n        uint _x;\r\n    }\r\n\r\n    uint8 private constant RESOLUTION = 112;\r\n\r\n    // multiply a UQ112x112 by a uint, returning a UQ144x112\r\n    // reverts on overflow\r\n    function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {\r\n        uint z;\r\n        require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), \"FixedPoint: MULTIPLICATION_OVERFLOW\");\r\n        return uq144x112(z);\r\n    }\r\n\r\n    // decode a UQ144x112 into a uint144 by truncating after the radix point\r\n    function decode144(uq144x112 memory self) internal pure returns (uint144) {\r\n        return uint144(self._x >> RESOLUTION);\r\n    }\r\n}\r\n\r\ninterface IUniswapV2Pair {\r\n    function token0() external view returns (address);\r\n    function token1() external view returns (address);\r\n    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\r\n    function price0CumulativeLast() external view returns (uint);\r\n    function price1CumulativeLast() external view returns (uint);\r\n}\r\n\r\ninterface IUniswapV2Factory {\r\n    function getPair(address tokenA, address tokenB) external view returns (address pair);\r\n}\r\n",
      "keccak256": "0x61ff8b54546ff946ba1fa24c387b27e8fcedb94428f241f87ddca49e0e4cc2a7"
    },
    "contracts/InterestRateModel.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\n/**\r\n  * @title DeFiPie's InterestRateModel Interface\r\n  * @author DeFiPie\r\n  */\r\nabstract contract InterestRateModel {\r\n    /// @notice Indicator that this is an InterestRateModel contract (for inspection)\r\n    bool public constant isInterestRateModel = true;\r\n\r\n    /**\r\n      * @notice Calculates the current borrow interest rate per block\r\n      * @param cash The total amount of cash the market has\r\n      * @param borrows The total amount of borrows the market has outstanding\r\n      * @param reserves The total amount of reserves the market has\r\n      * @return The borrow rate per block (as a percentage, and scaled by 1e18)\r\n      */\r\n    function getBorrowRate(uint cash, uint borrows, uint reserves) external view virtual returns (uint);\r\n\r\n    /**\r\n      * @notice Calculates the current supply interest rate per block\r\n      * @param cash The total amount of cash the market has\r\n      * @param borrows The total amount of borrows the market has outstanding\r\n      * @param reserves The total amount of reserves the market has\r\n      * @param reserveFactorMantissa The current reserve factor the market has\r\n      * @return The supply rate per block (as a percentage, and scaled by 1e18)\r\n      */\r\n    function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view virtual returns (uint);\r\n\r\n}\r\n",
      "keccak256": "0x08fe717d48dd399f24624a8395c0f0c3784d99af419dd80ba651e754e531837c"
    },
    "contracts/PErc20Delegator.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ProxyWithRegistry.sol\";\r\nimport \"./RegistryInterface.sol\";\r\n\r\n/**\r\n * @title DeFiPie's PErc20Delegator Contract\r\n * @notice PTokens which wrap an EIP-20 underlying and delegate to an implementation\r\n * @author DeFiPie\r\n */\r\ncontract PErc20Delegator is ProxyWithRegistry {\r\n\r\n    /**\r\n     * @notice Construct a new money market\r\n     * @param underlying_ The address of the underlying asset\r\n     * @param controller_ The address of the Controller\r\n     * @param interestRateModel_ The address of the interest rate model\r\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\r\n     * @param initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18\r\n     * @param name_ ERC-20 name of this token\r\n     * @param symbol_ ERC-20 symbol of this token\r\n     * @param decimals_ ERC-20 decimal precision of this token\r\n     * @param registry_ The address of the registry contract\r\n     */\r\n    constructor(\r\n        address underlying_,\r\n        address controller_,\r\n        address interestRateModel_,\r\n        uint initialExchangeRateMantissa_,\r\n        uint initialReserveFactorMantissa_,\r\n        string memory name_,\r\n        string memory symbol_,\r\n        uint8 decimals_,\r\n        address registry_\r\n    ) {\r\n        // Set registry\r\n        _setRegistry(registry_);\r\n\r\n        // First delegate gets to initialize the delegator (i.e. storage contract)\r\n        delegateTo(_pTokenImplementation(), abi.encodeWithSignature(\"initialize(address,address,address,address,uint256,uint256,string,string,uint8)\",\r\n                                                            underlying_,\r\n                                                            registry_,\r\n                                                            controller_,\r\n                                                            interestRateModel_,\r\n                                                            initialExchangeRateMantissa_,\r\n                                                            initialReserveFactorMantissa_,\r\n                                                            name_,\r\n                                                            symbol_,\r\n                                                            decimals_));\r\n    }\r\n\r\n    /**\r\n     * @notice Internal method to delegate execution to another contract\r\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n     * @param callee The contract to delegatecall\r\n     * @param data The raw data to delegatecall\r\n     * @return The returned bytes from the delegatecall\r\n     */\r\n    function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\r\n        (bool success, bytes memory returnData) = callee.delegatecall(data);\r\n        assembly {\r\n            if eq(success, 0) {\r\n                revert(add(returnData, 0x20), returndatasize())\r\n            }\r\n        }\r\n        return returnData;\r\n    }\r\n\r\n    function delegateAndReturn() internal returns (bytes memory) {\r\n        (bool success, ) = _pTokenImplementation().delegatecall(msg.data);\r\n\r\n        assembly {\r\n            let free_mem_ptr := mload(0x40)\r\n            returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n            switch success\r\n            case 0 { revert(free_mem_ptr, returndatasize()) }\r\n            default { return(free_mem_ptr, returndatasize()) }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Delegates execution to an implementation contract\r\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n     */\r\n    fallback() external {\r\n        // delegate all other functions to current implementation\r\n        delegateAndReturn();\r\n    }\r\n}\r\n",
      "keccak256": "0x2198b59ab7bba35d9e818e62be7ae97c30425104cfac6fda7dfdd41f3f3c8dfb"
    },
    "contracts/PEtherDelegator.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ProxyWithRegistry.sol\";\r\nimport \"./RegistryInterface.sol\";\r\nimport \"./ErrorReporter.sol\";\r\n\r\n/**\r\n * @title DeFiPie's PETHDelegator Contract\r\n * @notice PETH which wrap a delegate to an implementation\r\n * @author DeFiPie\r\n */\r\ncontract PETHDelegator is ImplementationStorage, ProxyWithRegistry, TokenErrorReporter {\r\n\r\n    /**\r\n      * @notice Emitted when implementation is changed\r\n      */\r\n    event NewImplementation(address oldImplementation, address newImplementation);\r\n\r\n    /**\r\n     * @notice Construct a new money market\r\n     * @param pETHImplementation_ The address of the PEthImplementation\r\n     * @param controller_ The address of the Controller\r\n     * @param interestRateModel_ The address of the interest rate model\r\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\r\n     * @param initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18\r\n     * @param name_ ERC-20 name of this token\r\n     * @param symbol_ ERC-20 symbol of this token\r\n     * @param decimals_ ERC-20 decimal precision of this token\r\n     * @param registry_ The address of the registry contract\r\n     */\r\n    constructor(\r\n        address pETHImplementation_,\r\n        address controller_,\r\n        address interestRateModel_,\r\n        uint initialExchangeRateMantissa_,\r\n        uint initialReserveFactorMantissa_,\r\n        string memory name_,\r\n        string memory symbol_,\r\n        uint8 decimals_,\r\n        address registry_\r\n    ) {\r\n        // Set registry\r\n        _setRegistry(registry_);\r\n        _setImplementation(pETHImplementation_);\r\n\r\n        // First delegate gets to initialize the delegator (i.e. storage contract)\r\n        delegateTo(implementation, abi.encodeWithSignature(\"initialize(address,address,address,uint256,uint256,string,string,uint8)\",\r\n                                                            registry_,\r\n                                                            controller_,\r\n                                                            interestRateModel_,\r\n                                                            initialExchangeRateMantissa_,\r\n                                                            initialReserveFactorMantissa_,\r\n                                                            name_,\r\n                                                            symbol_,\r\n                                                            decimals_));\r\n    }\r\n\r\n    /**\r\n     * @notice Internal method to delegate execution to another contract\r\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n     * @param callee The contract to delegatecall\r\n     * @param data The raw data to delegatecall\r\n     * @return The returned bytes from the delegatecall\r\n     */\r\n    function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\r\n        (bool success, bytes memory returnData) = callee.delegatecall(data);\r\n        assembly {\r\n            if eq(success, 0) {\r\n                revert(add(returnData, 0x20), returndatasize())\r\n            }\r\n        }\r\n        return returnData;\r\n    }\r\n\r\n    function delegateAndReturn() private returns (bytes memory) {\r\n        (bool success, ) = implementation.delegatecall(msg.data);\r\n\r\n        assembly {\r\n            let free_mem_ptr := mload(0x40)\r\n            returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n            switch success\r\n            case 0 { revert(free_mem_ptr, returndatasize()) }\r\n            default { return(free_mem_ptr, returndatasize()) }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Delegates execution to an implementation contract\r\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n     */\r\n    fallback() external payable {\r\n        // delegate all other functions to current implementation\r\n        delegateAndReturn();\r\n    }\r\n\r\n    receive() external payable {\r\n        // delegate all other functions to current implementation\r\n        delegateAndReturn();\r\n    }\r\n\r\n    function setImplementation(address newImplementation) external returns(uint) {\r\n        if (msg.sender != RegistryInterface(registry).admin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION);\r\n        }\r\n\r\n        address oldImplementation = implementation;\r\n        _setImplementation(newImplementation);\r\n\r\n        emit NewImplementation(oldImplementation, implementation);\r\n\r\n        return(uint(Error.NO_ERROR));\r\n    }\r\n}\r\n",
      "keccak256": "0x80673fd7df1543bb5b6a67a32583ccac7a1a914e199598a565e3209f02c4aff2"
    },
    "contracts/PPIEDelegator.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ProxyWithRegistry.sol\";\r\nimport \"./RegistryInterface.sol\";\r\nimport \"./ErrorReporter.sol\";\r\n\r\n/**\r\n * @title DeFiPie's PPIEDelegator Contract\r\n * @notice PPIE which wrap an EIP-20 underlying and delegate to an implementation\r\n * @author DeFiPie\r\n */\r\ncontract PPIEDelegator is ImplementationStorage, ProxyWithRegistry, TokenErrorReporter {\r\n\r\n    /**\r\n      * @notice Emitted when implementation is changed\r\n      */\r\n    event NewImplementation(address oldImplementation, address newImplementation);\r\n\r\n    /**\r\n     * @notice Construct a new money market\r\n     * @param underlying_ The address of the underlying asset\r\n     * @param pPIEImplementation_ The address of the PPIEImplementation\r\n     * @param controller_ The address of the Controller\r\n     * @param interestRateModel_ The address of the interest rate model\r\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\r\n     * @param initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18\r\n     * @param name_ ERC-20 name of this token\r\n     * @param symbol_ ERC-20 symbol of this token\r\n     * @param decimals_ ERC-20 decimal precision of this token\r\n     * @param registry_ The address of the registry contract\r\n     */\r\n    constructor(\r\n        address underlying_,\r\n        address pPIEImplementation_,\r\n        address controller_,\r\n        address interestRateModel_,\r\n        uint initialExchangeRateMantissa_,\r\n        uint initialReserveFactorMantissa_,\r\n        string memory name_,\r\n        string memory symbol_,\r\n        uint8 decimals_,\r\n        address registry_\r\n    ) {\r\n        // Set registry\r\n        _setRegistry(registry_);\r\n        _setImplementation(pPIEImplementation_);\r\n\r\n        // First delegate gets to initialize the delegator (i.e. storage contract)\r\n        delegateTo(implementation, abi.encodeWithSignature(\"initialize(address,address,address,address,uint256,uint256,string,string,uint8)\",\r\n                                                        underlying_,\r\n                                                        registry_,\r\n                                                        controller_,\r\n                                                        interestRateModel_,\r\n                                                        initialExchangeRateMantissa_,\r\n                                                        initialReserveFactorMantissa_,\r\n                                                        name_,\r\n                                                        symbol_,\r\n                                                        decimals_));\r\n    }\r\n\r\n    /**\r\n     * @notice Internal method to delegate execution to another contract\r\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n     * @param callee The contract to delegatecall\r\n     * @param data The raw data to delegatecall\r\n     * @return The returned bytes from the delegatecall\r\n     */\r\n    function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\r\n        (bool success, bytes memory returnData) = callee.delegatecall(data);\r\n        assembly {\r\n            if eq(success, 0) {\r\n                revert(add(returnData, 0x20), returndatasize())\r\n            }\r\n        }\r\n        return returnData;\r\n    }\r\n\r\n    function delegateAndReturn() internal returns (bytes memory) {\r\n        (bool success, ) = implementation.delegatecall(msg.data);\r\n\r\n        assembly {\r\n            let free_mem_ptr := mload(0x40)\r\n            returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n            switch success\r\n            case 0 { revert(free_mem_ptr, returndatasize()) }\r\n            default { return(free_mem_ptr, returndatasize()) }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Delegates execution to an implementation contract\r\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n     */\r\n    fallback() external {\r\n        // delegate all other functions to current implementation\r\n        delegateAndReturn();\r\n    }\r\n\r\n    function setImplementation(address newImplementation) external returns(uint) {\r\n        if (msg.sender != RegistryInterface(registry).admin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION);\r\n        }\r\n\r\n        address oldImplementation = implementation;\r\n        _setImplementation(newImplementation);\r\n\r\n        emit NewImplementation(oldImplementation, implementation);\r\n\r\n        return(uint(Error.NO_ERROR));\r\n    }\r\n}\r\n",
      "keccak256": "0x4efaa4feffa24983088a3e7729bdcd6b3473a0910b6f14c6ea2c29ea84e4b4de"
    },
    "contracts/PTokenFactory.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport './PErc20Delegator.sol';\r\nimport './RegistryInterface.sol';\r\nimport './EIP20Interface.sol';\r\nimport './Strings.sol';\r\nimport \"./IPriceFeeds.sol\";\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./SafeMath.sol\";\r\nimport \"./PEtherDelegator.sol\";\r\nimport \"./PPIEDelegator.sol\";\r\nimport \"./Controller.sol\";\r\nimport \"./UniswapPriceOracle.sol\";\r\n\r\ncontract PTokenFactory is FactoryErrorReporter {\r\n    using strings for *;\r\n    using SafeMath for uint;\r\n\r\n    UniswapPriceOracle public oracle;\r\n    uint public minUniswapLiquidity;\r\n\r\n    // decimals for pToken\r\n    uint8 public decimals = 8;\r\n\r\n    // default parameters for pToken\r\n    address public controller;\r\n    address public interestRateModel;\r\n    uint256 public initialExchangeRateMantissa;\r\n    uint256 public initialReserveFactorMantissa;\r\n\r\n    /**\r\n     * Fired on creation new pToken proxy\r\n     * @param newPToken Address of new PToken proxy contract\r\n     */\r\n    event PTokenCreated(address newPToken);\r\n\r\n    RegistryInterface public registry;\r\n\r\n    constructor(\r\n        RegistryInterface registry_,\r\n        uint minUniswapLiquidity_,\r\n        address oracle_,\r\n        address _controller,\r\n        address _interestRateModel,\r\n        uint256 _initialExchangeRateMantissa,\r\n        uint256 _initialReserveFactorMantissa\r\n    ) {\r\n        registry = registry_;\r\n        minUniswapLiquidity = minUniswapLiquidity_;\r\n        oracle = UniswapPriceOracle(oracle_);\r\n        controller = _controller;\r\n        interestRateModel = _interestRateModel;\r\n        initialExchangeRateMantissa = _initialExchangeRateMantissa;\r\n        initialReserveFactorMantissa = _initialReserveFactorMantissa;\r\n    }\r\n\r\n    /**\r\n     * Creates new pToken proxy contract and adds pToken to the controller\r\n     * @param underlying_ The address of the underlying asset\r\n     */\r\n    function createPToken(address underlying_) external returns (uint) {\r\n        if (!checkPair(underlying_)) {\r\n            return fail(Error.INVALID_POOL, FailureInfo.DEFICIENCY_LIQUIDITY_IN_POOL_OR_PAIR_IS_NOT_EXIST);\r\n        }\r\n\r\n        (string memory name, string memory symbol) = _createPTokenNameAndSymbol(underlying_);\r\n\r\n        uint power = EIP20Interface(underlying_).decimals();\r\n        uint exchangeRateMantissa = calcExchangeRate(power);\r\n\r\n        PErc20Delegator newPToken = new PErc20Delegator(underlying_, controller, interestRateModel, exchangeRateMantissa, initialReserveFactorMantissa, name, symbol, decimals, address(registry));\r\n\r\n        uint256 result = Controller(controller)._supportMarket(address(newPToken));\r\n        if (result != 0) {\r\n            return fail(Error.MARKET_NOT_LISTED, FailureInfo.SUPPORT_MARKET_BAD_RESULT);\r\n        }\r\n\r\n        registry.addPToken(underlying_, address(newPToken));\r\n\r\n        emit PTokenCreated(address(newPToken));\r\n\r\n        oracle.update(underlying_);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function createPETH(address pETHImplementation_) external virtual returns (uint) {\r\n        if (msg.sender != getAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.CREATE_PETH_POOL);\r\n        }\r\n\r\n        string memory name = \"DeFiPie ETH\";\r\n        string memory symbol = \"pETH\";\r\n\r\n        uint power = 18;\r\n        uint exchangeRateMantissa = calcExchangeRate(power);\r\n\r\n        PETHDelegator newPETH = new PETHDelegator(pETHImplementation_, controller, interestRateModel, exchangeRateMantissa, initialReserveFactorMantissa, name, symbol, decimals, address(registry));\r\n\r\n        uint256 result = Controller(controller)._supportMarket(address(newPETH));\r\n        if (result != 0) {\r\n            return fail(Error.MARKET_NOT_LISTED, FailureInfo.SUPPORT_MARKET_BAD_RESULT);\r\n        }\r\n\r\n        registry.addPETH(address(newPETH));\r\n\r\n        emit PTokenCreated(address(newPETH));\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function createPPIE(address underlying_, address pPIEImplementation_) external virtual returns (uint) {\r\n        if (msg.sender != getAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.CREATE_PPIE_POOL);\r\n        }\r\n\r\n        string memory name = \"DeFiPie PIE\";\r\n        string memory symbol = \"pPIE\";\r\n\r\n        uint power = EIP20Interface(underlying_).decimals();\r\n        uint exchangeRateMantissa = calcExchangeRate(power);\r\n\r\n        PPIEDelegator newPPIE = new PPIEDelegator(underlying_, pPIEImplementation_, controller, interestRateModel, exchangeRateMantissa, initialReserveFactorMantissa, name, symbol, decimals, address(registry));\r\n\r\n        uint256 result = Controller(controller)._supportMarket(address(newPPIE));\r\n        if (result != 0) {\r\n            return fail(Error.MARKET_NOT_LISTED, FailureInfo.SUPPORT_MARKET_BAD_RESULT);\r\n        }\r\n\r\n        registry.addPPIE(address(newPPIE));\r\n\r\n        emit PTokenCreated(address(newPPIE));\r\n\r\n        oracle.update(underlying_);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function checkPair(address asset) public view returns (bool) {\r\n        (address pair, uint112 ethEquivalentReserves) = oracle.searchPair(asset);\r\n\r\n        return bool(pair != address(0) && ethEquivalentReserves >= minUniswapLiquidity);\r\n    }\r\n\r\n    function setMinUniswapLiquidity(uint minUniswapLiquidity_) public returns (uint) {\r\n        if (msg.sender != getAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_MIN_LIQUIDITY_OWNER_CHECK);\r\n        }\r\n\r\n        minUniswapLiquidity = minUniswapLiquidity_;\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function setOracle(address oracle_) public returns (uint) {\r\n        if (msg.sender != getAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_ORACLE);\r\n        }\r\n\r\n        oracle = UniswapPriceOracle(oracle_);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n     *  Sets address of actual controller contract\r\n     *  @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details)\r\n     */\r\n    function setController(address newController) external returns (uint) {\r\n        if (msg.sender != getAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_CONTROLLER);\r\n        }\r\n        controller = newController;\r\n\r\n        return(uint(Error.NO_ERROR));\r\n    }\r\n\r\n    /**\r\n     *  Sets address of actual interestRateModel contract\r\n     *  @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details)\r\n     */\r\n    function setInterestRateModel(address newInterestRateModel) external returns (uint) {\r\n        if (msg.sender != getAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_INTEREST_RATE_MODEL);\r\n        }\r\n\r\n        interestRateModel = newInterestRateModel;\r\n\r\n        return(uint(Error.NO_ERROR));\r\n    }\r\n\r\n    /**\r\n     *  Sets initial exchange rate\r\n     *  @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details)\r\n     */\r\n    function setInitialExchangeRateMantissa(uint _initialExchangeRateMantissa) external returns (uint) {\r\n        if (msg.sender != getAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_EXCHANGE_RATE);\r\n        }\r\n\r\n        initialExchangeRateMantissa = _initialExchangeRateMantissa;\r\n\r\n        return(uint(Error.NO_ERROR));\r\n    }\r\n\r\n    function setInitialReserveFactorMantissa(uint _initialReserveFactorMantissa) external returns (uint) {\r\n        if (msg.sender != getAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_RESERVE_FACTOR);\r\n        }\r\n\r\n        initialReserveFactorMantissa = _initialReserveFactorMantissa;\r\n\r\n        return(uint(Error.NO_ERROR));\r\n    }\r\n\r\n    function setPTokenDecimals(uint _decimals) external returns (uint) {\r\n        if (msg.sender != getAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_DECIMALS);\r\n        }\r\n\r\n        decimals = uint8(_decimals);\r\n\r\n        return(uint(Error.NO_ERROR));\r\n    }\r\n\r\n    function getAdmin() public view returns(address payable) {\r\n        return registry.admin();\r\n    }\r\n\r\n    function _createPTokenNameAndSymbol(address underlying) internal view returns (string memory, string memory) {\r\n        string memory name = (\"DeFiPie \".toSlice().concat(EIP20Interface(underlying).name().toSlice()));\r\n        string memory symbol = (\"p\".toSlice().concat(EIP20Interface(underlying).symbol().toSlice()));\r\n        return (name, symbol);\r\n    }\r\n\r\n    function calcExchangeRate(uint power) internal view returns (uint) {\r\n        uint factor;\r\n\r\n        if (decimals >= power) {\r\n            factor = 10**(decimals - power);\r\n            return initialExchangeRateMantissa.div(factor);\r\n        } else {\r\n            factor = 10**(power - decimals);\r\n            return initialExchangeRateMantissa.mul(factor);\r\n        }\r\n    }\r\n}",
      "keccak256": "0x55c5649f2878001e193c7bd0cd3e4f4773a4543ff6875e70dc630ad372f40f9b"
    },
    "contracts/PTokenInterfaces.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ControllerInterface.sol\";\r\nimport \"./InterestRateModel.sol\";\r\nimport \"./ProxyWithRegistry.sol\";\r\n\r\ncontract PTokenStorage is ProxyWithRegistryStorage {\r\n    /**\r\n     * @dev Guard variable for re-entrancy checks\r\n     */\r\n    bool internal _notEntered;\r\n\r\n    /**\r\n     * @notice EIP-20 token name for this token\r\n     */\r\n    string public name;\r\n\r\n    /**\r\n     * @notice EIP-20 token symbol for this token\r\n     */\r\n    string public symbol;\r\n\r\n    /**\r\n     * @notice EIP-20 token decimals for this token\r\n     */\r\n    uint8 public decimals;\r\n\r\n    /**\r\n     * @dev Maximum borrow rate that can ever be applied (.0005% / block)\r\n     */\r\n\r\n    uint internal constant borrowRateMaxMantissa = 0.0005e16;\r\n\r\n    /**\r\n     * @dev Maximum fraction of interest that can be set aside for reserves\r\n     */\r\n    uint internal constant reserveFactorMaxMantissa = 1e18;\r\n\r\n    /**\r\n     * @notice Contract which oversees inter-pToken operations\r\n     */\r\n    ControllerInterface public controller;\r\n\r\n    /**\r\n     * @notice Model which tells what the current interest rate should be\r\n     */\r\n    InterestRateModel public interestRateModel;\r\n\r\n    /**\r\n     * @dev Initial exchange rate used when minting the first PTokens (used when totalSupply = 0)\r\n     */\r\n    uint internal initialExchangeRateMantissa;\r\n\r\n    /**\r\n     * @notice Fraction of interest currently set aside for reserves\r\n     */\r\n    uint public reserveFactorMantissa;\r\n\r\n    /**\r\n     * @notice Block number that interest was last accrued at\r\n     */\r\n    uint public accrualBlockNumber;\r\n\r\n    /**\r\n     * @notice Accumulator of the total earned interest rate since the opening of the market\r\n     */\r\n    uint public borrowIndex;\r\n\r\n    /**\r\n     * @notice Total amount of outstanding borrows of the underlying in this market\r\n     */\r\n    uint public totalBorrows;\r\n\r\n    /**\r\n     * @notice Total amount of reserves of the underlying held in this market\r\n     */\r\n    uint public totalReserves;\r\n\r\n    /**\r\n     * @notice Total number of tokens in circulation\r\n     */\r\n    uint public totalSupply;\r\n\r\n    /**\r\n     * @dev Official record of token balances for each account\r\n     */\r\n    mapping (address => uint) internal accountTokens;\r\n\r\n    /**\r\n     * @dev Approved token transfer amounts on behalf of others\r\n     */\r\n    mapping (address => mapping (address => uint)) internal transferAllowances;\r\n\r\n    /**\r\n     * @notice Container for borrow balance information\r\n     * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action\r\n     * @member interestIndex Global borrowIndex as of the most recent balance-changing action\r\n     */\r\n    struct BorrowSnapshot {\r\n        uint principal;\r\n        uint interestIndex;\r\n    }\r\n\r\n    /**\r\n     * @dev Mapping of account addresses to outstanding borrow balances\r\n     */\r\n    mapping(address => BorrowSnapshot) internal accountBorrows;\r\n}\r\n\r\nabstract contract PTokenInterface is PTokenStorage {\r\n    /**\r\n     * @notice Indicator that this is a PToken contract (for inspection)\r\n     */\r\n    bool public constant isPToken = true;\r\n\r\n\r\n    /*** Market Events ***/\r\n\r\n    /**\r\n     * @notice Event emitted when interest is accrued\r\n     */\r\n    event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows, uint totalReserves);\r\n\r\n    /**\r\n     * @notice Event emitted when tokens are minted\r\n     */\r\n    event Mint(address minter, uint mintAmount, uint mintTokens);\r\n\r\n    /**\r\n     * @notice Event emitted when tokens are redeemed\r\n     */\r\n    event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);\r\n\r\n    /**\r\n     * @notice Event emitted when underlying is borrowed\r\n     */\r\n    event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);\r\n\r\n    /**\r\n     * @notice Event emitted when a borrow is repaid\r\n     */\r\n    event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);\r\n\r\n    /**\r\n     * @notice Event emitted when a borrow is liquidated\r\n     */\r\n    event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address pTokenCollateral, uint seizeTokens);\r\n\r\n\r\n    /*** Admin Events ***/\r\n\r\n    /**\r\n     * @notice Event emitted when controller is changed\r\n     */\r\n    event NewController(ControllerInterface oldController, ControllerInterface newController);\r\n\r\n    /**\r\n     * @notice Event emitted when interestRateModel is changed\r\n     */\r\n    event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);\r\n\r\n    /**\r\n     * @notice Event emitted when the reserve factor is changed\r\n     */\r\n    event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);\r\n\r\n    /**\r\n     * @notice Event emitted when the reserves are added\r\n     */\r\n    event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);\r\n\r\n    /**\r\n     * @notice Event emitted when the reserves are reduced\r\n     */\r\n    event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);\r\n\r\n    /**\r\n     * @notice EIP20 Transfer event\r\n     */\r\n    event Transfer(address indexed from, address indexed to, uint amount);\r\n\r\n    /**\r\n     * @notice EIP20 Approval event\r\n     */\r\n    event Approval(address indexed owner, address indexed spender, uint amount);\r\n\r\n    /*** User Interface ***/\r\n\r\n    function transfer(address dst, uint amount) external virtual returns (bool);\r\n    function transferFrom(address src, address dst, uint amount) external virtual returns (bool);\r\n    function approve(address spender, uint amount) external virtual returns (bool);\r\n    function allowance(address owner, address spender) external view virtual returns (uint);\r\n    function balanceOf(address owner) external view virtual returns (uint);\r\n    function balanceOfUnderlying(address owner) external virtual returns (uint);\r\n    function getAccountSnapshot(address account) external view virtual returns (uint, uint, uint, uint);\r\n    function borrowRatePerBlock() external view virtual returns (uint);\r\n    function supplyRatePerBlock() external view virtual returns (uint);\r\n    function totalBorrowsCurrent() external virtual returns (uint);\r\n    function borrowBalanceCurrent(address account) external virtual returns (uint);\r\n    function borrowBalanceStored(address account) public view virtual returns (uint);\r\n    function exchangeRateCurrent() public virtual returns (uint);\r\n    function exchangeRateStored() public view virtual returns (uint);\r\n    function getCash() external view virtual returns (uint);\r\n    function accrueInterest() public virtual returns (uint);\r\n    function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint);\r\n\r\n    /*** Admin Functions ***/\r\n\r\n    function _setController(ControllerInterface newController) public virtual returns (uint);\r\n    function _setReserveFactor(uint newReserveFactorMantissa) external virtual returns (uint);\r\n    function _reduceReserves(uint reduceAmount) external virtual returns (uint);\r\n    function _setInterestRateModel(InterestRateModel newInterestRateModel) public virtual returns (uint);\r\n}\r\n\r\ncontract PErc20Storage {\r\n    /**\r\n     * @notice Underlying asset for this PToken\r\n     */\r\n    address public underlying;\r\n}\r\n\r\nabstract contract PErc20Interface is PErc20Storage {\r\n\r\n    /*** User Interface ***/\r\n\r\n    function mint(uint mintAmount) external virtual returns (uint);\r\n    function redeem(uint redeemTokens) external virtual returns (uint);\r\n    function redeemUnderlying(uint redeemAmount) external virtual returns (uint);\r\n    function borrow(uint borrowAmount) external virtual returns (uint);\r\n    function repayBorrow(uint repayAmount) external virtual returns (uint);\r\n    function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint);\r\n    function liquidateBorrow(address borrower, uint repayAmount, PTokenInterface pTokenCollateral) external virtual returns (uint);\r\n\r\n    /*** Admin Functions ***/\r\n\r\n    function _addReserves(uint addAmount) external virtual returns (uint);\r\n}\r\n\r\ncontract PPIEStorage {\r\n    /// @notice A record of each accounts delegate\r\n    mapping (address => address) public delegates;\r\n\r\n    /// @notice A checkpoint for marking number of votes from a given block\r\n    struct Checkpoint {\r\n        uint32 fromBlock;\r\n        uint96 votes;\r\n    }\r\n\r\n    /// @notice A record of votes checkpoints for each account, by index\r\n    mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;\r\n\r\n    /// @notice The number of checkpoints for each account\r\n    mapping (address => uint32) public numCheckpoints;\r\n\r\n    /// @notice The EIP-712 typehash for the contract's domain\r\n    bytes32 public constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\r\n\r\n    /// @notice The EIP-712 typehash for the delegation struct used by the contract\r\n    bytes32 public constant DELEGATION_TYPEHASH = keccak256(\"Delegation(address delegatee,uint256 nonce,uint256 expiry)\");\r\n\r\n    /// @notice A record of states for signing / validating signatures\r\n    mapping (address => uint) public nonces;\r\n}\r\n\r\nabstract contract PPIEInterface is PPIEStorage {\r\n    /// @notice An event thats emitted when an account changes its delegate\r\n    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\r\n\r\n    /// @notice An event thats emitted when a delegate account's vote balance changes\r\n    event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);\r\n\r\n    function delegate(address delegatee) external virtual;\r\n    function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external virtual;\r\n    function getCurrentVotes(address account) external view virtual returns (uint96);\r\n    function getPriorVotes(address account, uint blockNumber) external view virtual returns (uint96);\r\n}",
      "keccak256": "0x437e378db9ba0a7b0a2a38ed89c7e76c07355d096e936ae88fa11765db747af3"
    },
    "contracts/PriceOracle.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nabstract contract PriceOracle {\r\n    /// @notice Indicator that this is a PriceOracle contract (for inspection)\r\n    bool public constant isPriceOracle = true;\r\n\r\n    event PriceUpdated(address asset, uint price);\r\n\r\n    /**\r\n      * @notice Get the underlying price of a pToken asset\r\n      * @param pToken The pToken to get the underlying price of\r\n      * @return The underlying asset price mantissa (scaled by 1e18).\r\n      *  Zero means the price is unavailable.\r\n      */\r\n    function getUnderlyingPrice(address pToken) external view virtual returns (uint);\r\n\r\n    function updateUnderlyingPrice(address pToken) external virtual returns (uint);\r\n}",
      "keccak256": "0x2580c6d431e99799ef8cbcf5d9f00d9ef52c821902f1a87842913111baabbcb3"
    },
    "contracts/ProxyWithRegistry.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./RegistryInterface.sol\";\r\n\r\ncontract ProxyWithRegistryStorage {\r\n\r\n    /**\r\n     * @notice Address of the registry contract\r\n     */\r\n    address public registry;\r\n}\r\n\r\nabstract contract ProxyWithRegistryInterface is ProxyWithRegistryStorage {\r\n    function _setRegistry(address _registry) internal virtual;\r\n    function _pTokenImplementation() internal view virtual returns (address);\r\n}\r\n\r\ncontract ProxyWithRegistry is ProxyWithRegistryInterface {\r\n    /**\r\n     *  Returns actual address of the implementation contract from current registry\r\n     *  @return registry Address of the registry\r\n     */\r\n    function _pTokenImplementation() internal view override returns (address) {\r\n        return RegistryInterface(registry).pTokenImplementation();\r\n    }\r\n\r\n    function _setRegistry(address _registry) internal override {\r\n        registry = _registry;\r\n    }\r\n}\r\n\r\ncontract ImplementationStorage {\r\n\r\n    address public implementation;\r\n\r\n    function _setImplementation(address implementation_) internal {\r\n        implementation = implementation_;\r\n    }\r\n}",
      "keccak256": "0x68816cfe421911a10fd675907ced65682b5dccb579d4e8d55d5aa5372978df41"
    },
    "contracts/Registry.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./PTokenInterfaces.sol\";\r\nimport './RegistryStorage.sol';\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./Controller.sol\";\r\nimport \"./PTokenFactory.sol\";\r\n\r\ncontract Registry is RegistryStorage, RegistryErrorReporter {\r\n\r\n    address public factory;\r\n    address public pTokenImplementation;\r\n\r\n    mapping (address => address) public pTokens;\r\n    address public pETH;\r\n    address public pPIE;\r\n\r\n    /*** Admin Events ***/\r\n\r\n    /**\r\n     * @notice Event emitted when pendingAdmin is changed\r\n     */\r\n    event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);\r\n\r\n    /**\r\n     * @notice Event emitted when pendingAdmin is accepted, which means admin is updated\r\n     */\r\n    event NewAdmin(address oldAdmin, address newAdmin);\r\n\r\n    /**\r\n      * @notice Emitted when PTokenImplementation is changed\r\n      */\r\n    event NewPTokenImplementation(address oldImplementation, address newImplementation);\r\n\r\n    /**\r\n      * @notice Emitted when Factory address is changed\r\n      */\r\n    event NewFactory(address oldFactory, address newFactory);\r\n\r\n    /**\r\n      * @notice Emitted when admin remove pToken\r\n      */\r\n    event RemovePToken(address pToken);\r\n\r\n    constructor() {}\r\n\r\n    function initialize(address _pTokenImplementation) public {\r\n        require(pTokenImplementation == address(0), \"Registry may only be initialized once\");\r\n\r\n        pTokenImplementation = _pTokenImplementation;\r\n    }\r\n\r\n    /**\r\n     *  Sets address of actual pToken implementation contract\r\n     *  @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details)\r\n     */\r\n    function setPTokenImplementation(address newImplementation) external returns (uint) {\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION);\r\n        }\r\n\r\n        address oldImplementation = pTokenImplementation;\r\n        pTokenImplementation = newImplementation;\r\n\r\n        emit NewPTokenImplementation(oldImplementation, pTokenImplementation);\r\n\r\n        return(uint(Error.NO_ERROR));\r\n    }\r\n\r\n    function _setFactoryContract(address _factory) external returns (uint) {\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_FACTORY);\r\n        }\r\n\r\n        address oldFactory = factory;\r\n        factory = _factory;\r\n\r\n        emit NewFactory(oldFactory, factory);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function addPToken(address underlying, address pToken) public returns (uint) {\r\n        require(msg.sender == admin || msg.sender == factory, \"Only admin or factory can add PTokens\");\r\n\r\n        PTokenInterface(pToken).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n        require(pTokens[underlying] == address(0), \"Token already added\");\r\n        pTokens[underlying] = pToken;\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function addPETH(address pETH_) public returns (uint) {\r\n        require(msg.sender == admin || msg.sender == factory, \"Only admin or factory can add PETH\");\r\n\r\n        PTokenInterface(pETH_).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n        require(pETH == address(0), \"ETH already added\");\r\n        pETH = pETH_;\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function addPPIE(address pPIE_) public returns (uint) {\r\n        require(msg.sender == admin || msg.sender == factory, \"Only admin or factory can add PPIE\");\r\n\r\n        PTokenInterface(pPIE_).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n        require(pPIE == address(0), \"PIE already added\");\r\n        pPIE = pPIE_;\r\n\r\n        address underlying = PErc20Storage(pPIE).underlying();\r\n        pTokens[underlying] = pPIE;\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function removePToken(address pToken) public returns (uint) {\r\n        require(msg.sender == admin, \"Only admin can remove PTokens\");\r\n\r\n        PTokenInterface(pToken).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n        address underlying = PErc20Storage(pToken).underlying();\r\n        require(pTokens[underlying] != address(0), \"Token not added\");\r\n        delete pTokens[underlying];\r\n\r\n        emit RemovePToken(pToken);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n}",
      "keccak256": "0x1a54a753d7a36c4702c7df4b5240a8b07680d44ff11810c8f7ee803df8f1f9fd"
    },
    "contracts/RegistryInterface.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\ninterface RegistryInterface {\r\n\r\n    /**\r\n     *  Returns admin address for cToken contracts\r\n     *  @return admin address\r\n     */\r\n    function admin() external view returns (address payable);\r\n\r\n    /**\r\n     *  Returns address of actual PToken implementation contract\r\n     *  @return Address of contract\r\n     */\r\n    function pTokenImplementation() external view returns (address);\r\n\r\n    function addPToken(address underlying, address pToken) external returns(uint);\r\n    function addPETH(address pETH_) external returns(uint);\r\n    function addPPIE(address pPIE_) external returns(uint);\r\n}\r\n",
      "keccak256": "0x743428865dba35a57df98d12887e91b2ced03d7825989f928448305b596dda4d"
    },
    "contracts/RegistryStorage.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\ncontract RegistryStorage {\r\n    address public implementation;\r\n    address public admin;\r\n    address public pendingAdmin;\r\n}",
      "keccak256": "0x70c747fb4090fd2668bec5d0b906c0bdd2c3bb367ff3d2bb1120c26fbd1a2923"
    },
    "contracts/SafeMath.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\n// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol\r\n// Subject to the MIT license.\r\n\r\n/**\r\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\r\n * checks.\r\n *\r\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\r\n * in bugs, because programmers usually assume that an overflow raises an\r\n * error, which is the standard behavior in high level programming languages.\r\n * `SafeMath` restores this intuition by reverting the transaction when an\r\n * operation overflows.\r\n *\r\n * Using this library instead of the unchecked operations eliminates an entire\r\n * class of bugs, so it's recommended to use it always.\r\n */\r\nlibrary SafeMath {\r\n    /**\r\n     * @dev Returns the addition of two unsigned integers, reverting on overflow.\r\n     *\r\n     * Counterpart to Solidity's `+` operator.\r\n     *\r\n     * Requirements:\r\n     * - Addition cannot overflow.\r\n     */\r\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\r\n        uint256 c = a + b;\r\n        require(c >= a, \"SafeMath: addition overflow\");\r\n\r\n        return c;\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.\r\n     *\r\n     * Counterpart to Solidity's `+` operator.\r\n     *\r\n     * Requirements:\r\n     * - Addition cannot overflow.\r\n     */\r\n    function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n        uint256 c = a + b;\r\n        require(c >= a, errorMessage);\r\n\r\n        return c;\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).\r\n     *\r\n     * Counterpart to Solidity's `-` operator.\r\n     *\r\n     * Requirements:\r\n     * - Subtraction cannot underflow.\r\n     */\r\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\r\n        return sub(a, b, \"SafeMath: subtraction underflow\");\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).\r\n     *\r\n     * Counterpart to Solidity's `-` operator.\r\n     *\r\n     * Requirements:\r\n     * - Subtraction cannot underflow.\r\n     */\r\n    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n        require(b <= a, errorMessage);\r\n        uint256 c = a - b;\r\n\r\n        return c;\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the multiplication of two unsigned integers, reverting on overflow.\r\n     *\r\n     * Counterpart to Solidity's `*` operator.\r\n     *\r\n     * Requirements:\r\n     * - Multiplication cannot overflow.\r\n     */\r\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n        // benefit is lost if 'b' is also tested.\r\n        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\r\n        if (a == 0) {\r\n            return 0;\r\n        }\r\n\r\n        uint256 c = a * b;\r\n        require(c / a == b, \"SafeMath: multiplication overflow\");\r\n\r\n        return c;\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the multiplication of two unsigned integers, reverting on overflow.\r\n     *\r\n     * Counterpart to Solidity's `*` operator.\r\n     *\r\n     * Requirements:\r\n     * - Multiplication cannot overflow.\r\n     */\r\n    function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n        // benefit is lost if 'b' is also tested.\r\n        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\r\n        if (a == 0) {\r\n            return 0;\r\n        }\r\n\r\n        uint256 c = a * b;\r\n        require(c / a == b, errorMessage);\r\n\r\n        return c;\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the integer division of two unsigned integers.\r\n     * Reverts on division by zero. The result is rounded towards zero.\r\n     *\r\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\r\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\r\n     * uses an invalid opcode to revert (consuming all remaining gas).\r\n     *\r\n     * Requirements:\r\n     * - The divisor cannot be zero.\r\n     */\r\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\r\n        return div(a, b, \"SafeMath: division by zero\");\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the integer division of two unsigned integers.\r\n     * Reverts with custom message on division by zero. The result is rounded towards zero.\r\n     *\r\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\r\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\r\n     * uses an invalid opcode to revert (consuming all remaining gas).\r\n     *\r\n     * Requirements:\r\n     * - The divisor cannot be zero.\r\n     */\r\n    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n        // Solidity only automatically asserts when dividing by 0\r\n        require(b > 0, errorMessage);\r\n        uint256 c = a / b;\r\n        // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n\r\n        return c;\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\r\n     * Reverts when dividing by zero.\r\n     *\r\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\r\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\r\n     * invalid opcode to revert (consuming all remaining gas).\r\n     *\r\n     * Requirements:\r\n     * - The divisor cannot be zero.\r\n     */\r\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\r\n        return mod(a, b, \"SafeMath: modulo by zero\");\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\r\n     * Reverts with custom message when dividing by zero.\r\n     *\r\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\r\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\r\n     * invalid opcode to revert (consuming all remaining gas).\r\n     *\r\n     * Requirements:\r\n     * - The divisor cannot be zero.\r\n     */\r\n    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n        require(b != 0, errorMessage);\r\n        return a % b;\r\n    }\r\n}\r\n",
      "keccak256": "0x1b91ef15073e3694faa078ab1d588c180155a8d36e469fa0bdb01dd2b207d0df"
    },
    "contracts/Strings.sol": {
      "content": "/*\r\n * @title String & slice utility library for Solidity contracts.\r\n * @author Nick Johnson <arachnid@notdot.net>\r\n *\r\n * @dev Functionality in this library is largely implemented using an\r\n *      abstraction called a 'slice'. A slice represents a part of a string -\r\n *      anything from the entire string to a single character, or even no\r\n *      characters at all (a 0-length slice). Since a slice only has to specify\r\n *      an offset and a length, copying and manipulating slices is a lot less\r\n *      expensive than copying and manipulating the strings they reference.\r\n *\r\n *      To further reduce gas costs, most functions on slice that need to return\r\n *      a slice modify the original one instead of allocating a new one; for\r\n *      instance, `s.split(\".\")` will return the text up to the first '.',\r\n *      modifying s to only contain the remainder of the string after the '.'.\r\n *      In situations where you do not want to modify the original slice, you\r\n *      can make a copy first with `.copy()`, for example:\r\n *      `s.copy().split(\".\")`. Try and avoid using this idiom in loops; since\r\n *      Solidity has no memory management, it will result in allocating many\r\n *      short-lived slices that are later discarded.\r\n *\r\n *      Functions that return two slices come in two versions: a non-allocating\r\n *      version that takes the second slice as an argument, modifying it in\r\n *      place, and an allocating version that allocates and returns the second\r\n *      slice; see `nextRune` for example.\r\n *\r\n *      Functions that have to copy string data will return strings rather than\r\n *      slices; these can be cast back to slices for further processing if\r\n *      required.\r\n *\r\n *      For convenience, some functions are provided with non-modifying\r\n *      variants that create a new slice and return both; for instance,\r\n *      `s.splitNew('.')` leaves s unmodified, and returns two values\r\n *      corresponding to the left and right parts of the string.\r\n */\r\n\r\npragma solidity ^0.7.6;\r\n\r\nlibrary strings {\r\n    struct slice {\r\n        uint _len;\r\n        uint _ptr;\r\n    }\r\n\r\n    function memcpy(uint dest, uint src, uint leng) private pure {\r\n        // Copy word-length chunks while possible\r\n        for(; leng >= 32; leng -= 32) {\r\n            assembly {\r\n                mstore(dest, mload(src))\r\n            }\r\n            dest += 32;\r\n            src += 32;\r\n        }\r\n\r\n        // Copy remaining bytes\r\n        uint mask = 256 ** (32 - leng) - 1;\r\n        assembly {\r\n            let srcpart := and(mload(src), not(mask))\r\n            let destpart := and(mload(dest), mask)\r\n            mstore(dest, or(destpart, srcpart))\r\n        }\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a slice containing the entire string.\r\n     * @param self The string to make a slice from.\r\n     * @return A newly allocated slice containing the entire string.\r\n     */\r\n    function toSlice(string memory self) internal pure returns (slice memory) {\r\n        uint ptr;\r\n        assembly {\r\n            ptr := add(self, 0x20)\r\n        }\r\n        return slice(bytes(self).length, ptr);\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the length of a null-terminated bytes32 string.\r\n     * @param self The value to find the length of.\r\n     * @return The length of the string, from 0 to 32.\r\n     */\r\n    function len(bytes32 self) internal pure returns (uint) {\r\n        uint ret;\r\n        if (self == 0)\r\n            return 0;\r\n        if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {\r\n            ret += 16;\r\n            self = bytes32(uint(self) / 0x100000000000000000000000000000000);\r\n        }\r\n        if (uint(self) & 0xffffffffffffffff == 0) {\r\n            ret += 8;\r\n            self = bytes32(uint(self) / 0x10000000000000000);\r\n        }\r\n        if (uint(self) & 0xffffffff == 0) {\r\n            ret += 4;\r\n            self = bytes32(uint(self) / 0x100000000);\r\n        }\r\n        if (uint(self) & 0xffff == 0) {\r\n            ret += 2;\r\n            self = bytes32(uint(self) / 0x10000);\r\n        }\r\n        if (uint(self) & 0xff == 0) {\r\n            ret += 1;\r\n        }\r\n        return 32 - ret;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a slice containing the entire bytes32, interpreted as a\r\n     *      null-terminated utf-8 string.\r\n     * @param self The bytes32 value to convert to a slice.\r\n     * @return A new slice containing the value of the input argument up to the\r\n     *         first null.\r\n     */\r\n    function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {\r\n        // Allocate space for `self` in memory, copy it there, and point ret at it\r\n        assembly {\r\n            let ptr := mload(0x40)\r\n            mstore(0x40, add(ptr, 0x20))\r\n            mstore(ptr, self)\r\n            mstore(add(ret, 0x20), ptr)\r\n        }\r\n        ret._len = len(self);\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a new slice containing the same data as the current slice.\r\n     * @param self The slice to copy.\r\n     * @return A new slice containing the same data as `self`.\r\n     */\r\n    function copy(slice memory self) internal pure returns (slice memory) {\r\n        return slice(self._len, self._ptr);\r\n    }\r\n\r\n    /*\r\n     * @dev Copies a slice to a new string.\r\n     * @param self The slice to copy.\r\n     * @return A newly allocated string containing the slice's text.\r\n     */\r\n    function toString(slice memory self) internal pure returns (string memory) {\r\n        string memory ret = new string(self._len);\r\n        uint retptr;\r\n        assembly { retptr := add(ret, 32) }\r\n\r\n        memcpy(retptr, self._ptr, self._len);\r\n        return ret;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the length in runes of the slice. Note that this operation\r\n     *      takes time proportional to the length of the slice; avoid using it\r\n     *      in loops, and call `slice.empty()` if you only need to know whether\r\n     *      the slice is empty or not.\r\n     * @param self The slice to operate on.\r\n     * @return The length of the slice in runes.\r\n     */\r\n    function len(slice memory self) internal pure returns (uint l) {\r\n        // Starting at ptr-31 means the LSB will be the byte we care about\r\n        uint ptr = self._ptr - 31;\r\n        uint end = ptr + self._len;\r\n        for (l = 0; ptr < end; l++) {\r\n            uint8 b;\r\n            assembly { b := and(mload(ptr), 0xFF) }\r\n            if (b < 0x80) {\r\n                ptr += 1;\r\n            } else if(b < 0xE0) {\r\n                ptr += 2;\r\n            } else if(b < 0xF0) {\r\n                ptr += 3;\r\n            } else if(b < 0xF8) {\r\n                ptr += 4;\r\n            } else if(b < 0xFC) {\r\n                ptr += 5;\r\n            } else {\r\n                ptr += 6;\r\n            }\r\n        }\r\n    }\r\n\r\n    /*\r\n     * @dev Returns true if the slice is empty (has a length of 0).\r\n     * @param self The slice to operate on.\r\n     * @return True if the slice is empty, False otherwise.\r\n     */\r\n    function empty(slice memory self) internal pure returns (bool) {\r\n        return self._len == 0;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a negative number if `other` comes lexicographically after\r\n     *      `self`, a positive number if it comes before, or zero if the\r\n     *      contents of the two slices are equal. Comparison is done per-rune,\r\n     *      on unicode codepoints.\r\n     * @param self The first slice to compare.\r\n     * @param other The second slice to compare.\r\n     * @return The result of the comparison.\r\n     */\r\n    function compare(slice memory self, slice memory other) internal pure returns (int) {\r\n        uint shortest = self._len;\r\n        if (other._len < self._len)\r\n            shortest = other._len;\r\n\r\n        uint selfptr = self._ptr;\r\n        uint otherptr = other._ptr;\r\n        for (uint idx = 0; idx < shortest; idx += 32) {\r\n            uint a;\r\n            uint b;\r\n            assembly {\r\n                a := mload(selfptr)\r\n                b := mload(otherptr)\r\n            }\r\n            if (a != b) {\r\n                // Mask out irrelevant bytes and check again\r\n                uint256 mask = uint256(-1); // 0xffff...\r\n                if(shortest < 32) {\r\n                    mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);\r\n                }\r\n                uint256 diff = (a & mask) - (b & mask);\r\n                if (diff != 0)\r\n                    return int(diff);\r\n            }\r\n            selfptr += 32;\r\n            otherptr += 32;\r\n        }\r\n        return int(self._len) - int(other._len);\r\n    }\r\n\r\n    /*\r\n     * @dev Returns true if the two slices contain the same text.\r\n     * @param self The first slice to compare.\r\n     * @param self The second slice to compare.\r\n     * @return True if the slices are equal, false otherwise.\r\n     */\r\n    function equals(slice memory self, slice memory other) internal pure returns (bool) {\r\n        return compare(self, other) == 0;\r\n    }\r\n\r\n    /*\r\n     * @dev Extracts the first rune in the slice into `rune`, advancing the\r\n     *      slice to point to the next rune and returning `self`.\r\n     * @param self The slice to operate on.\r\n     * @param rune The slice that will contain the first rune.\r\n     * @return `rune`.\r\n     */\r\n    function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {\r\n        rune._ptr = self._ptr;\r\n\r\n        if (self._len == 0) {\r\n            rune._len = 0;\r\n            return rune;\r\n        }\r\n\r\n        uint l;\r\n        uint b;\r\n        // Load the first byte of the rune into the LSBs of b\r\n        assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }\r\n        if (b < 0x80) {\r\n            l = 1;\r\n        } else if(b < 0xE0) {\r\n            l = 2;\r\n        } else if(b < 0xF0) {\r\n            l = 3;\r\n        } else {\r\n            l = 4;\r\n        }\r\n\r\n        // Check for truncated codepoints\r\n        if (l > self._len) {\r\n            rune._len = self._len;\r\n            self._ptr += self._len;\r\n            self._len = 0;\r\n            return rune;\r\n        }\r\n\r\n        self._ptr += l;\r\n        self._len -= l;\r\n        rune._len = l;\r\n        return rune;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the first rune in the slice, advancing the slice to point\r\n     *      to the next rune.\r\n     * @param self The slice to operate on.\r\n     * @return A slice containing only the first rune from `self`.\r\n     */\r\n    function nextRune(slice memory self) internal pure returns (slice memory ret) {\r\n        nextRune(self, ret);\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the number of the first codepoint in the slice.\r\n     * @param self The slice to operate on.\r\n     * @return The number of the first codepoint in the slice.\r\n     */\r\n    function ord(slice memory self) internal pure returns (uint ret) {\r\n        if (self._len == 0) {\r\n            return 0;\r\n        }\r\n\r\n        uint word;\r\n        uint length;\r\n        uint divisor = 2 ** 248;\r\n\r\n        // Load the rune into the MSBs of b\r\n        assembly { word:= mload(mload(add(self, 32))) }\r\n        uint b = word / divisor;\r\n        if (b < 0x80) {\r\n            ret = b;\r\n            length = 1;\r\n        } else if(b < 0xE0) {\r\n            ret = b & 0x1F;\r\n            length = 2;\r\n        } else if(b < 0xF0) {\r\n            ret = b & 0x0F;\r\n            length = 3;\r\n        } else {\r\n            ret = b & 0x07;\r\n            length = 4;\r\n        }\r\n\r\n        // Check for truncated codepoints\r\n        if (length > self._len) {\r\n            return 0;\r\n        }\r\n\r\n        for (uint i = 1; i < length; i++) {\r\n            divisor = divisor / 256;\r\n            b = (word / divisor) & 0xFF;\r\n            if (b & 0xC0 != 0x80) {\r\n                // Invalid UTF-8 sequence\r\n                return 0;\r\n            }\r\n            ret = (ret * 64) | (b & 0x3F);\r\n        }\r\n\r\n        return ret;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns the keccak-256 hash of the slice.\r\n     * @param self The slice to hash.\r\n     * @return The hash of the slice.\r\n     */\r\n    function keccak(slice memory self) internal pure returns (bytes32 ret) {\r\n        assembly {\r\n            ret := keccak256(mload(add(self, 32)), mload(self))\r\n        }\r\n    }\r\n\r\n    /*\r\n     * @dev Returns true if `self` starts with `needle`.\r\n     * @param self The slice to operate on.\r\n     * @param needle The slice to search for.\r\n     * @return True if the slice starts with the provided text, false otherwise.\r\n     */\r\n    function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {\r\n        if (self._len < needle._len) {\r\n            return false;\r\n        }\r\n\r\n        if (self._ptr == needle._ptr) {\r\n            return true;\r\n        }\r\n\r\n        bool equal;\r\n        assembly {\r\n            let length := mload(needle)\r\n            let selfptr := mload(add(self, 0x20))\r\n            let needleptr := mload(add(needle, 0x20))\r\n            equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n        }\r\n        return equal;\r\n    }\r\n\r\n    /*\r\n     * @dev If `self` starts with `needle`, `needle` is removed from the\r\n     *      beginning of `self`. Otherwise, `self` is unmodified.\r\n     * @param self The slice to operate on.\r\n     * @param needle The slice to search for.\r\n     * @return `self`\r\n     */\r\n    function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n        if (self._len < needle._len) {\r\n            return self;\r\n        }\r\n\r\n        bool equal = true;\r\n        if (self._ptr != needle._ptr) {\r\n            assembly {\r\n                let length := mload(needle)\r\n                let selfptr := mload(add(self, 0x20))\r\n                let needleptr := mload(add(needle, 0x20))\r\n                equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n            }\r\n        }\r\n\r\n        if (equal) {\r\n            self._len -= needle._len;\r\n            self._ptr += needle._len;\r\n        }\r\n\r\n        return self;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns true if the slice ends with `needle`.\r\n     * @param self The slice to operate on.\r\n     * @param needle The slice to search for.\r\n     * @return True if the slice starts with the provided text, false otherwise.\r\n     */\r\n    function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {\r\n        if (self._len < needle._len) {\r\n            return false;\r\n        }\r\n\r\n        uint selfptr = self._ptr + self._len - needle._len;\r\n\r\n        if (selfptr == needle._ptr) {\r\n            return true;\r\n        }\r\n\r\n        bool equal;\r\n        assembly {\r\n            let length := mload(needle)\r\n            let needleptr := mload(add(needle, 0x20))\r\n            equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n        }\r\n\r\n        return equal;\r\n    }\r\n\r\n    /*\r\n     * @dev If `self` ends with `needle`, `needle` is removed from the\r\n     *      end of `self`. Otherwise, `self` is unmodified.\r\n     * @param self The slice to operate on.\r\n     * @param needle The slice to search for.\r\n     * @return `self`\r\n     */\r\n    function until(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n        if (self._len < needle._len) {\r\n            return self;\r\n        }\r\n\r\n        uint selfptr = self._ptr + self._len - needle._len;\r\n        bool equal = true;\r\n        if (selfptr != needle._ptr) {\r\n            assembly {\r\n                let length := mload(needle)\r\n                let needleptr := mload(add(needle, 0x20))\r\n                equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n            }\r\n        }\r\n\r\n        if (equal) {\r\n            self._len -= needle._len;\r\n        }\r\n\r\n        return self;\r\n    }\r\n\r\n    // Returns the memory address of the first byte of the first occurrence of\r\n    // `needle` in `self`, or the first byte after `self` if not found.\r\n    function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\r\n        uint ptr = selfptr;\r\n        uint idx;\r\n\r\n        if (needlelen <= selflen) {\r\n            if (needlelen <= 32) {\r\n                bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\r\n\r\n                bytes32 needledata;\r\n                assembly { needledata := and(mload(needleptr), mask) }\r\n\r\n                uint end = selfptr + selflen - needlelen;\r\n                bytes32 ptrdata;\r\n                assembly { ptrdata := and(mload(ptr), mask) }\r\n\r\n                while (ptrdata != needledata) {\r\n                    if (ptr >= end)\r\n                        return selfptr + selflen;\r\n                    ptr++;\r\n                    assembly { ptrdata := and(mload(ptr), mask) }\r\n                }\r\n                return ptr;\r\n            } else {\r\n                // For long needles, use hashing\r\n                bytes32 hash;\r\n                assembly { hash := keccak256(needleptr, needlelen) }\r\n\r\n                for (idx = 0; idx <= selflen - needlelen; idx++) {\r\n                    bytes32 testHash;\r\n                    assembly { testHash := keccak256(ptr, needlelen) }\r\n                    if (hash == testHash)\r\n                        return ptr;\r\n                    ptr += 1;\r\n                }\r\n            }\r\n        }\r\n        return selfptr + selflen;\r\n    }\r\n\r\n    // Returns the memory address of the first byte after the last occurrence of\r\n    // `needle` in `self`, or the address of `self` if not found.\r\n    function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\r\n        uint ptr;\r\n\r\n        if (needlelen <= selflen) {\r\n            if (needlelen <= 32) {\r\n                bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\r\n\r\n                bytes32 needledata;\r\n                assembly { needledata := and(mload(needleptr), mask) }\r\n\r\n                ptr = selfptr + selflen - needlelen;\r\n                bytes32 ptrdata;\r\n                assembly { ptrdata := and(mload(ptr), mask) }\r\n\r\n                while (ptrdata != needledata) {\r\n                    if (ptr <= selfptr)\r\n                        return selfptr;\r\n                    ptr--;\r\n                    assembly { ptrdata := and(mload(ptr), mask) }\r\n                }\r\n                return ptr + needlelen;\r\n            } else {\r\n                // For long needles, use hashing\r\n                bytes32 hash;\r\n                assembly { hash := keccak256(needleptr, needlelen) }\r\n                ptr = selfptr + (selflen - needlelen);\r\n                while (ptr >= selfptr) {\r\n                    bytes32 testHash;\r\n                    assembly { testHash := keccak256(ptr, needlelen) }\r\n                    if (hash == testHash)\r\n                        return ptr + needlelen;\r\n                    ptr -= 1;\r\n                }\r\n            }\r\n        }\r\n        return selfptr;\r\n    }\r\n\r\n    /*\r\n     * @dev Modifies `self` to contain everything from the first occurrence of\r\n     *      `needle` to the end of the slice. `self` is set to the empty slice\r\n     *      if `needle` is not found.\r\n     * @param self The slice to search and modify.\r\n     * @param needle The text to search for.\r\n     * @return `self`.\r\n     */\r\n    function find(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n        uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n        self._len -= ptr - self._ptr;\r\n        self._ptr = ptr;\r\n        return self;\r\n    }\r\n\r\n    /*\r\n     * @dev Modifies `self` to contain the part of the string from the start of\r\n     *      `self` to the end of the first occurrence of `needle`. If `needle`\r\n     *      is not found, `self` is set to the empty slice.\r\n     * @param self The slice to search and modify.\r\n     * @param needle The text to search for.\r\n     * @return `self`.\r\n     */\r\n    function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n        uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n        self._len = ptr - self._ptr;\r\n        return self;\r\n    }\r\n\r\n    /*\r\n     * @dev Splits the slice, setting `self` to everything after the first\r\n     *      occurrence of `needle`, and `token` to everything before it. If\r\n     *      `needle` does not occur in `self`, `self` is set to the empty slice,\r\n     *      and `token` is set to the entirety of `self`.\r\n     * @param self The slice to split.\r\n     * @param needle The text to search for in `self`.\r\n     * @param token An output parameter to which the first token is written.\r\n     * @return `token`.\r\n     */\r\n    function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {\r\n        uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n        token._ptr = self._ptr;\r\n        token._len = ptr - self._ptr;\r\n        if (ptr == self._ptr + self._len) {\r\n            // Not found\r\n            self._len = 0;\r\n        } else {\r\n            self._len -= token._len + needle._len;\r\n            self._ptr = ptr + needle._len;\r\n        }\r\n        return token;\r\n    }\r\n\r\n    /*\r\n     * @dev Splits the slice, setting `self` to everything after the first\r\n     *      occurrence of `needle`, and returning everything before it. If\r\n     *      `needle` does not occur in `self`, `self` is set to the empty slice,\r\n     *      and the entirety of `self` is returned.\r\n     * @param self The slice to split.\r\n     * @param needle The text to search for in `self`.\r\n     * @return The part of `self` up to the first occurrence of `delim`.\r\n     */\r\n    function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {\r\n        split(self, needle, token);\r\n    }\r\n\r\n    /*\r\n     * @dev Splits the slice, setting `self` to everything before the last\r\n     *      occurrence of `needle`, and `token` to everything after it. If\r\n     *      `needle` does not occur in `self`, `self` is set to the empty slice,\r\n     *      and `token` is set to the entirety of `self`.\r\n     * @param self The slice to split.\r\n     * @param needle The text to search for in `self`.\r\n     * @param token An output parameter to which the first token is written.\r\n     * @return `token`.\r\n     */\r\n    function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {\r\n        uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n        token._ptr = ptr;\r\n        token._len = self._len - (ptr - self._ptr);\r\n        if (ptr == self._ptr) {\r\n            // Not found\r\n            self._len = 0;\r\n        } else {\r\n            self._len -= token._len + needle._len;\r\n        }\r\n        return token;\r\n    }\r\n\r\n    /*\r\n     * @dev Splits the slice, setting `self` to everything before the last\r\n     *      occurrence of `needle`, and returning everything after it. If\r\n     *      `needle` does not occur in `self`, `self` is set to the empty slice,\r\n     *      and the entirety of `self` is returned.\r\n     * @param self The slice to split.\r\n     * @param needle The text to search for in `self`.\r\n     * @return The part of `self` after the last occurrence of `delim`.\r\n     */\r\n    function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {\r\n        rsplit(self, needle, token);\r\n    }\r\n\r\n    /*\r\n     * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.\r\n     * @param self The slice to search.\r\n     * @param needle The text to search for in `self`.\r\n     * @return The number of occurrences of `needle` found in `self`.\r\n     */\r\n    function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {\r\n        uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;\r\n        while (ptr <= self._ptr + self._len) {\r\n            cnt++;\r\n            ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;\r\n        }\r\n    }\r\n\r\n    /*\r\n     * @dev Returns True if `self` contains `needle`.\r\n     * @param self The slice to search.\r\n     * @param needle The text to search for in `self`.\r\n     * @return True if `needle` is found in `self`, false otherwise.\r\n     */\r\n    function contains(slice memory self, slice memory needle) internal pure returns (bool) {\r\n        return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;\r\n    }\r\n\r\n    /*\r\n     * @dev Returns a newly allocated string containing the concatenation of\r\n     *      `self` and `other`.\r\n     * @param self The first slice to concatenate.\r\n     * @param other The second slice to concatenate.\r\n     * @return The concatenation of the two strings.\r\n     */\r\n    function concat(slice memory self, slice memory other) internal pure returns (string memory) {\r\n        string memory ret = new string(self._len + other._len);\r\n        uint retptr;\r\n        assembly { retptr := add(ret, 32) }\r\n        memcpy(retptr, self._ptr, self._len);\r\n        memcpy(retptr + self._len, other._ptr, other._len);\r\n        return ret;\r\n    }\r\n\r\n    /*\r\n     * @dev Joins an array of slices, using `self` as a delimiter, returning a\r\n     *      newly allocated string.\r\n     * @param self The delimiter to use.\r\n     * @param parts A list of slices to join.\r\n     * @return A newly allocated string containing all the slices in `parts`,\r\n     *         joined with `self`.\r\n     */\r\n    function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {\r\n        if (parts.length == 0)\r\n            return \"\";\r\n\r\n        uint length = self._len * (parts.length - 1);\r\n        for(uint i = 0; i < parts.length; i++)\r\n            length += parts[i]._len;\r\n\r\n        string memory ret = new string(length);\r\n        uint retptr;\r\n        assembly { retptr := add(ret, 32) }\r\n\r\n        for(uint i = 0; i < parts.length; i++) {\r\n            memcpy(retptr, parts[i]._ptr, parts[i]._len);\r\n            retptr += parts[i]._len;\r\n            if (i < parts.length - 1) {\r\n                memcpy(retptr, self._ptr, self._len);\r\n                retptr += self._len;\r\n            }\r\n        }\r\n\r\n        return ret;\r\n    }\r\n}\r\n",
      "keccak256": "0xecfb4178b1cb415e544d3632d5f235cf5163e5d9ccae5bf7b33ff29802d84bde"
    },
    "contracts/UniswapPriceOracle.sol": {
      "content": "pragma solidity ^0.7.6;\r\npragma abicoder v2;\r\n\r\nimport \"./PriceOracle.sol\";\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./PTokenInterfaces.sol\";\r\nimport \"./SafeMath.sol\";\r\nimport \"./UniswapPriceOracleStorage.sol\";\r\nimport \"./EIP20Interface.sol\";\r\nimport \"./Controller.sol\";\r\nimport \"./PTokenFactory.sol\";\r\n\r\ncontract UniswapPriceOracle is UniswapPriceOracleStorageV1, PriceOracle, OracleErrorReporter {\r\n    using FixedPoint for *;\r\n    using SafeMath for uint;\r\n\r\n    event PoolAdded(uint id, address poolFactory);\r\n    event PoolRemoved(uint id, address poolFactory);\r\n    event PoolUpdated(uint id, address poolFactory);\r\n\r\n    event StableCoinAdded(uint id, address coin);\r\n    event StableCoinRemoved(uint id, address coin);\r\n    event StableCoinUpdated(uint id, address coin);\r\n\r\n    event AssetPairUpdated(address asset, address pair);\r\n\r\n    constructor() {}\r\n\r\n    function initialize(\r\n        address poolFactory_,\r\n        address WETHToken_,\r\n        address ETHUSDPriceFeed_\r\n    )\r\n        public\r\n    {\r\n        require(\r\n            WETHToken == address(0) &&\r\n            ETHUSDPriceFeed == address(0)\r\n            , \"Oracle: may only be initialized once\"\r\n        );\r\n\r\n        WETHToken = WETHToken_;\r\n        ETHUSDPriceFeed = ETHUSDPriceFeed_;\r\n\r\n        require(\r\n            poolFactory_ != address(0)\r\n            , 'Oracle: invalid address for factory'\r\n        );\r\n\r\n        poolFactories.push(poolFactory_);\r\n\r\n        emit PoolAdded(0, poolFactory_);\r\n    }\r\n\r\n    function updateUnderlyingPrice(address pToken) public override returns (uint) {\r\n        if (pToken == Registry(registry).pETH()) {\r\n            return uint(Error.NO_ERROR);\r\n        }\r\n\r\n        address asset = PErc20Interface(pToken).underlying();\r\n\r\n        return update(asset);\r\n    }\r\n\r\n    // Get the most recent price for a asset in USD with 18 decimals of precision.\r\n    function getPriceInUSD(address asset) public view virtual returns (uint) {\r\n        uint ETHUSDPrice = uint(AggregatorInterface(ETHUSDPriceFeed).latestAnswer());\r\n        uint AssetETHCourse = getCourseInETH(asset);\r\n\r\n        // div 1e8 is chainlink precision for ETH\r\n        return ETHUSDPrice.mul(AssetETHCourse).div(1e8);\r\n    }\r\n\r\n    function getCourseInETH(address asset) public view returns (uint) {\r\n        if (asset == Registry(registry).pETH()) {\r\n            // ether always worth 1\r\n            return 1e18;\r\n        }\r\n\r\n        return averagePrices[asset];\r\n    }\r\n\r\n    function update(address asset) public returns (uint) {\r\n        uint112 reserve0;\r\n        uint112 reserve1;\r\n        uint32 blockTimeStamp;\r\n        address pair;\r\n\r\n        if (isNewAsset(asset)) {\r\n            if (assetPair[asset] == address(0)) {\r\n                // first update from factory or other users\r\n                (pair, ) = searchPair(asset);\r\n            } else {\r\n                // after updatePair function\r\n                pair = assetPair[asset];\r\n            }\r\n\r\n            if (pair != address(0)) {\r\n                assetPair[asset] = pair;\r\n\r\n                (reserve0, reserve1, blockTimeStamp) = getReservesFromPair(asset);\r\n\r\n                if (reserve1 < minReserveLiquidity) {\r\n                    return fail(Error.UPDATE_PRICE, FailureInfo.NO_RESERVES);\r\n                }\r\n\r\n                cumulativePrices[pair][asset].priceAverage = FixedPoint.uq112x112(uqdiv(encode(reserve1), reserve0));\r\n            } else {\r\n                return fail(Error.UPDATE_PRICE, FailureInfo.NO_PAIR);\r\n            }\r\n        } else {\r\n            // second and next updates\r\n            (, , blockTimeStamp) = getReservesFromPair(asset);\r\n\r\n            if (reserve1 < minReserveLiquidity) {\r\n                cumulativePrices[assetPair[asset]][asset].priceAverage._x = 0;\r\n                cumulativePrices[assetPair[asset]][asset].priceCumulativePrevious = 0;\r\n                cumulativePrices[assetPair[asset]][asset].blockTimeStampPrevious = 0;\r\n\r\n                return fail(Error.UPDATE_PRICE, FailureInfo.NO_RESERVES);\r\n            }\r\n\r\n            if (!isPeriodElapsed(asset)) {\r\n                return fail(Error.UPDATE_PRICE, FailureInfo.PERIOD_NOT_ELAPSED);\r\n            }\r\n\r\n            pair = assetPair[asset];\r\n\r\n            uint32 timeElapsed = blockTimeStamp - cumulativePrices[pair][asset].blockTimeStampPrevious;\r\n\r\n            // overflow is desired, casting never truncates\r\n            // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed\r\n            if (asset == IUniswapV2Pair(pair).token0()) {\r\n                cumulativePrices[pair][asset].priceAverage = FixedPoint.uq112x112(uint224((IUniswapV2Pair(pair).price0CumulativeLast() - cumulativePrices[pair][asset].priceCumulativePrevious) / timeElapsed));\r\n            } else {\r\n                cumulativePrices[pair][asset].priceAverage = FixedPoint.uq112x112(uint224((IUniswapV2Pair(pair).price1CumulativeLast() - cumulativePrices[pair][asset].priceCumulativePrevious) / timeElapsed));\r\n            }\r\n        }\r\n\r\n        cumulativePrices[pair][asset].blockTimeStampPrevious = blockTimeStamp;\r\n\r\n        // update data\r\n        if (asset == IUniswapV2Pair(pair).token0()) {\r\n            cumulativePrices[pair][asset].priceCumulativePrevious = IUniswapV2Pair(pair).price0CumulativeLast();\r\n        } else {\r\n            cumulativePrices[pair][asset].priceCumulativePrevious = IUniswapV2Pair(pair).price1CumulativeLast();\r\n        }\r\n\r\n        averagePrices[asset] = calcCourseInETH(asset);\r\n\r\n        emit PriceUpdated(asset, getCourseInETH(asset));\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function checkAndUpdateAllNewAssets() public {\r\n        PTokenFactory factory = PTokenFactory(Registry(registry).factory());\r\n        Controller controller = Controller(factory.controller());\r\n\r\n        address[] memory allMarkets = Controller(controller).getAllMarkets();\r\n\r\n        updateNewAssets(allMarkets);\r\n    }\r\n\r\n    function updateNewAssets(address[] memory pTokens) public {\r\n        address asset;\r\n\r\n        for(uint i = 0; i < pTokens.length; i++) {\r\n            if (pTokens[i] == Registry(registry).pETH()) {\r\n                continue;\r\n            }\r\n\r\n            asset = PErc20Interface(pTokens[i]).underlying();\r\n\r\n            if (isNewAsset(asset)) {\r\n                update(asset);\r\n            }\r\n        }\r\n    }\r\n\r\n    function getUnderlyingPrice(address pToken) public view override virtual returns (uint) {\r\n        if (pToken == Registry(registry).pETH()) {\r\n            return getPriceInUSD(Registry(registry).pETH());\r\n        }\r\n\r\n        address asset = PErc20Interface(pToken).underlying();\r\n        uint price = getPriceInUSD(asset);\r\n        uint decimals = EIP20Interface(asset).decimals();\r\n\r\n        return price.mul(10 ** (36 - decimals)).div(1e18);\r\n    }\r\n\r\n    function isNewAsset(address asset) public view returns (bool) {\r\n        return bool(cumulativePrices[assetPair[asset]][asset].blockTimeStampPrevious == 0);\r\n    }\r\n\r\n    function getPoolPair(address asset, uint poolId) public view returns (address) {\r\n        IUniswapV2Factory factory = IUniswapV2Factory(poolFactories[poolId]);\r\n\r\n        return factory.getPair(WETHToken, asset);\r\n    }\r\n\r\n    function getPoolPairWithStableCoin(address asset, uint poolId, uint stableCoinId) public view returns (address) {\r\n        IUniswapV2Factory factory = IUniswapV2Factory(poolFactories[poolId]);\r\n\r\n        return factory.getPair(stableCoins[stableCoinId], asset);\r\n    }\r\n\r\n    function getReservesFromPair(address asset) public view returns (uint112, uint112, uint32) {\r\n        uint112 assetReserve;\r\n        uint112 ethOrCoinReserves;\r\n        uint32 blockTimeStamp;\r\n\r\n        IUniswapV2Pair pair = IUniswapV2Pair(assetPair[asset]);\r\n\r\n        address token0 = pair.token0();\r\n\r\n        if (token0 == asset) {\r\n            (assetReserve, ethOrCoinReserves, blockTimeStamp) = pair.getReserves();\r\n        } else {\r\n            (ethOrCoinReserves, assetReserve, blockTimeStamp) = pair.getReserves();\r\n        }\r\n\r\n        return (assetReserve, ethOrCoinReserves, blockTimeStamp);\r\n    }\r\n\r\n    function isPeriodElapsed(address asset) public view returns (bool) {\r\n        IUniswapV2Pair pair = IUniswapV2Pair(assetPair[asset]);\r\n\r\n        ( , , uint32 blockTimeStamp) = pair.getReserves();\r\n\r\n        uint timeElapsed = uint(blockTimeStamp).sub(uint(cumulativePrices[assetPair[asset]][asset].blockTimeStampPrevious));\r\n\r\n        return bool(timeElapsed > period);\r\n    }\r\n\r\n    function calcCourseInETH(address asset) public view returns (uint) {\r\n        if (asset == Registry(registry).pETH()) {\r\n            // ether always worth 1\r\n            return 1e18;\r\n        }\r\n\r\n        uint power = EIP20Interface(asset).decimals();\r\n        uint amountIn = 10**power;\r\n\r\n        return getETHAmount(asset, amountIn);\r\n    }\r\n\r\n    function getETHAmount(address asset, uint amountIn) public view returns (uint) {\r\n        address pair = assetPair[asset];\r\n\r\n        address token0 = IUniswapV2Pair(pair).token0();\r\n        address token1 = IUniswapV2Pair(pair).token1();\r\n\r\n        uint power;\r\n        uint result = cumulativePrices[pair][asset].priceAverage.mul(amountIn).decode144();\r\n\r\n        if (token0 == WETHToken || token1 == WETHToken) {\r\n            // asset and weth pool\r\n            return result;\r\n        } else {\r\n            // asset and stable coin pool\r\n            if (token0 == asset) {\r\n                power = EIP20Interface(token1).decimals();\r\n                return result.mul(getCourseInETH(token1)).div(10**power);\r\n            } else {\r\n                power = EIP20Interface(token0).decimals();\r\n                return result.mul(getCourseInETH(token0)).div(10**power);\r\n            }\r\n        }\r\n    }\r\n\r\n    function searchPair(address asset) public view returns (address, uint112) {\r\n        address pair;\r\n        uint112 maxReserves;\r\n\r\n        IUniswapV2Pair tempPair;\r\n        uint112 ETHReserves;\r\n\r\n        for (uint i = 0; i < poolFactories.length; i++) {\r\n            tempPair = IUniswapV2Pair(getPoolPair(asset, i));\r\n\r\n            if (address(tempPair) != address(0)) {\r\n                if (tempPair.token0() == asset) {\r\n                    (, ETHReserves, ) = tempPair.getReserves();\r\n                } else {\r\n                    (ETHReserves, , ) = tempPair.getReserves();\r\n                }\r\n\r\n                if (ETHReserves > maxReserves) {\r\n                    maxReserves = ETHReserves;\r\n                    pair = address(tempPair);\r\n                }\r\n            }\r\n\r\n            for (uint j = 0; j < stableCoins.length; j++) {\r\n                tempPair = IUniswapV2Pair(getPoolPairWithStableCoin(asset, i, j));\r\n\r\n                if (address(tempPair) != address(0)) {\r\n                    uint112 stableCoinReserve;\r\n                    uint power;\r\n\r\n                    address token0 = tempPair.token0();\r\n                    address token1 = tempPair.token1();\r\n\r\n                    if (token0 == asset) {\r\n                        (, stableCoinReserve,) = tempPair.getReserves();\r\n                        power = EIP20Interface(token1).decimals();\r\n                        ETHReserves = uint112(getCourseInETH(token1) * stableCoinReserve / (10**power));\r\n                    } else {\r\n                        (stableCoinReserve, , ) = tempPair.getReserves();\r\n                        power = EIP20Interface(token0).decimals();\r\n                        ETHReserves = uint112(getCourseInETH(token0) * stableCoinReserve / (10**power));\r\n                    }\r\n\r\n                    if (ETHReserves > maxReserves) {\r\n                        maxReserves = ETHReserves;\r\n                        pair = address(tempPair);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        return (pair, maxReserves);\r\n    }\r\n\r\n    function _setNewAddresses(address WETHToken_, address ETHUSDPriceFeed_) external returns (uint) {\r\n        // Check caller = admin\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n        }\r\n\r\n        WETHToken = WETHToken_;\r\n        ETHUSDPriceFeed = ETHUSDPriceFeed_;\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _setMinReserveLiquidity(uint minReserveLiquidity_) public returns (uint) {\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n        }\r\n\r\n        minReserveLiquidity = minReserveLiquidity_;\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _setPeriod(uint period_) public returns (uint) {\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n        }\r\n\r\n        period = period_;\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _addPool(address poolFactory_) public returns (uint) {\r\n        // Check caller = admin\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.ADD_POOL_OR_COIN);\r\n        }\r\n\r\n        require(\r\n            poolFactory_ != address(0)\r\n            , 'Oracle: invalid address for factory'\r\n        );\r\n\r\n        for (uint i = 0; i < poolFactories.length; i++) {\r\n            if (poolFactories[i] == poolFactory_) {\r\n                return fail(Error.POOL_OR_COIN_EXIST, FailureInfo.ADD_POOL_OR_COIN);\r\n            }\r\n        }\r\n\r\n        poolFactories.push(poolFactory_);\r\n        uint poolId = poolFactories.length - 1;\r\n\r\n        emit PoolAdded(poolId, poolFactory_);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _removePool(uint poolId) public returns (uint) {\r\n        // Check caller = admin\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n        }\r\n\r\n        require(\r\n            poolFactories.length > 1\r\n            , 'Oracle: must have one pool'\r\n        );\r\n\r\n        uint lastId = poolFactories.length - 1;\r\n\r\n        address factory = poolFactories[lastId];\r\n        poolFactories.pop();\r\n        emit PoolRemoved(lastId, factory);\r\n\r\n        if (lastId != poolId) {\r\n            poolFactories[poolId] = factory;\r\n            emit PoolUpdated(poolId, factory);\r\n        }\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _updatePool(uint poolId, address poolFactory_) public returns (uint) {\r\n        // Check caller = admin\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n        }\r\n\r\n        require(\r\n            poolFactory_ != address(0)\r\n            , 'Oracle: invalid address for factory'\r\n        );\r\n\r\n        for (uint i = 0; i < poolFactories.length; i++) {\r\n            if (poolFactories[i] == poolFactory_) {\r\n                return fail(Error.POOL_OR_COIN_EXIST, FailureInfo.UPDATE_DATA);\r\n            }\r\n        }\r\n\r\n        poolFactories[poolId] = poolFactory_;\r\n\r\n        emit PoolUpdated(poolId, poolFactory_);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _addStableCoin(address stableCoin_) public returns (uint) {\r\n        // Check caller = admin\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.ADD_POOL_OR_COIN);\r\n        }\r\n\r\n        require(\r\n            stableCoin_ != address(0)\r\n            , 'Oracle: invalid address for stable coin'\r\n        );\r\n\r\n        for (uint i = 0; i < stableCoins.length; i++) {\r\n            if (stableCoins[i] == stableCoin_) {\r\n                return fail(Error.POOL_OR_COIN_EXIST, FailureInfo.ADD_POOL_OR_COIN);\r\n            }\r\n        }\r\n\r\n        stableCoins.push(stableCoin_);\r\n\r\n        emit StableCoinAdded(stableCoins.length - 1, stableCoin_);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _removeStableCoin(uint coinId) public returns (uint) {\r\n        // Check caller = admin\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n        }\r\n\r\n        require(\r\n            stableCoins.length > 0\r\n            , 'Oracle: stable coins are empty'\r\n        );\r\n\r\n\r\n        uint lastId = stableCoins.length - 1;\r\n\r\n        address stableCoin = stableCoins[lastId];\r\n        stableCoins.pop();\r\n        emit StableCoinRemoved(lastId, stableCoin);\r\n\r\n        if (lastId != coinId) {\r\n            stableCoins[coinId] = stableCoin;\r\n            emit StableCoinUpdated(coinId, stableCoin);\r\n        }\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _updateStableCoin(uint coinId, address stableCoin_) public returns (uint) {\r\n        // Check caller = admin\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n        }\r\n\r\n        require(\r\n            stableCoin_ != address(0)\r\n            , 'Oracle: invalid address for stable coin'\r\n        );\r\n\r\n        for (uint i = 0; i < stableCoins.length; i++) {\r\n            if (stableCoins[i] == stableCoin_) {\r\n                return fail(Error.POOL_OR_COIN_EXIST, FailureInfo.UPDATE_DATA);\r\n            }\r\n        }\r\n\r\n        stableCoins[coinId] = stableCoin_;\r\n\r\n        emit StableCoinUpdated(coinId, stableCoin_);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    function _updateAssetPair(address asset, address pair) public returns (uint) {\r\n        // Check caller = admin\r\n        if (msg.sender != getMyAdmin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n        }\r\n\r\n        require(\r\n            pair != address(0)\r\n            , 'Oracle: invalid address for pair'\r\n        );\r\n\r\n        cumulativePrices[assetPair[asset]][asset].priceAverage._x = 0;\r\n        cumulativePrices[assetPair[asset]][asset].priceCumulativePrevious = 0;\r\n        cumulativePrices[assetPair[asset]][asset].blockTimeStampPrevious = 0;\r\n\r\n        assetPair[asset] = pair;\r\n\r\n        emit AssetPairUpdated(asset, pair);\r\n\r\n        return update(asset);\r\n    }\r\n\r\n    function getAllPoolFactories() public view returns (address[] memory) {\r\n        return poolFactories;\r\n    }\r\n\r\n    function getAllStableCoins() public view returns (address[] memory) {\r\n        return stableCoins;\r\n    }\r\n\r\n    function getMyAdmin() public view returns (address) {\r\n        return Registry(registry).admin();\r\n    }\r\n\r\n    // encode a uint112 as a UQ112x112\r\n    function encode(uint112 y) internal view returns (uint224 z) {\r\n        z = uint224(y) * uint224(Q112); // never overflows\r\n    }\r\n\r\n    // divide a UQ112x112 by a uint112, returning a UQ112x112\r\n    function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {\r\n        z = x / uint224(y);\r\n    }\r\n\r\n}",
      "keccak256": "0x9d0c58aa71e58642f4f61663523f92b3888cc1a290260b5b95cf2c912419d9da"
    },
    "contracts/UniswapPriceOracleProxy.sol": {
      "content": "pragma solidity ^0.7.6;\r\npragma abicoder v2;\r\n\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./UniswapPriceOracleStorage.sol\";\r\nimport \"./RegistryInterface.sol\";\r\n\r\ncontract UniswapPriceOracleProxy is UniswapPriceOracleProxyStorage, OracleErrorReporter {\r\n\r\n    /*** Admin Events ***/\r\n\r\n    /**\r\n      * @notice Emitted when implementation is changed\r\n      */\r\n    event NewImplementation(address oldImplementation, address newImplementation);\r\n\r\n    constructor(\r\n        address implementation_,\r\n        address registry_,\r\n        address uniswapFactory_,\r\n        address WETHToken_,\r\n        address ETHUSDPriceFeed_\r\n    ) {\r\n        implementation = implementation_;\r\n        registry = registry_;\r\n\r\n        delegateTo(implementation, abi.encodeWithSignature(\"initialize(address,address,address)\",\r\n                                                            uniswapFactory_,\r\n                                                            WETHToken_,\r\n                                                            ETHUSDPriceFeed_));\r\n    }\r\n\r\n    function setOracleImplementation(address newImplementation) external returns(uint256) {\r\n        if (msg.sender != RegistryInterface(registry).admin()) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION);\r\n        }\r\n\r\n        address oldImplementation = implementation;\r\n        implementation = newImplementation;\r\n\r\n        emit NewImplementation(oldImplementation, implementation);\r\n\r\n        return(uint(Error.NO_ERROR));\r\n    }\r\n\r\n    /**\r\n     * @notice Internal method to delegate execution to another contract\r\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n     * @param callee The contract to delegatecall\r\n     * @param data The raw data to delegatecall\r\n     * @return The returned bytes from the delegatecall\r\n     */\r\n    function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\r\n        (bool success, bytes memory returnData) = callee.delegatecall(data);\r\n        assembly {\r\n            if eq(success, 0) {\r\n                revert(add(returnData, 0x20), returndatasize())\r\n            }\r\n        }\r\n        return returnData;\r\n    }\r\n\r\n    function delegateAndReturn() private returns (bytes memory) {\r\n        (bool success, ) = implementation.delegatecall(msg.data);\r\n\r\n        assembly {\r\n            let free_mem_ptr := mload(0x40)\r\n            returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n            switch success\r\n            case 0 { revert(free_mem_ptr, returndatasize()) }\r\n            default { return(free_mem_ptr, returndatasize()) }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Delegates execution to an implementation contract\r\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n     */\r\n    fallback() external {\r\n        // delegate all other functions to current implementation\r\n        delegateAndReturn();\r\n    }\r\n}\r\n",
      "keccak256": "0x376b4a93bb29de0261060d0a4295100007c49f7e170985fc9ca6383bf11a2445"
    },
    "contracts/UniswapPriceOracleStorage.sol": {
      "content": "pragma solidity ^0.7.6;\r\npragma abicoder v2;\r\n\r\nimport './Registry.sol';\r\nimport \"./IPriceFeeds.sol\";\r\n\r\ncontract UniswapPriceOracleProxyStorage {\r\n    address public implementation;\r\n    address public registry;\r\n    uint public Q112 = 2**112;\r\n    uint public period = 10 minutes;\r\n}\r\n\r\ncontract UniswapPriceOracleStorageV1 is UniswapPriceOracleProxyStorage {\r\n    uint public minReserveLiquidity;\r\n\r\n    address public WETHToken;\r\n    address public ETHUSDPriceFeed;\r\n\r\n    struct PoolCumulativePrice {\r\n        FixedPoint.uq112x112 priceAverage;\r\n        uint priceCumulativePrevious;\r\n        uint32 blockTimeStampPrevious;\r\n    }\r\n\r\n    // asset => assetPair => data from pool\r\n    mapping(address => mapping (address => PoolCumulativePrice)) public cumulativePrices;\r\n    mapping(address => uint) public averagePrices;\r\n\r\n    // asset => pair with reserves\r\n    mapping(address => address) public assetPair;\r\n\r\n    address[] public poolFactories;\r\n    address[] public stableCoins;\r\n}",
      "keccak256": "0x0951746320a9bc53dd621b6ac1618b93d12ee85d65a424ce26cf25dfc9781c3f"
    },
    "contracts/Unitroller.sol": {
      "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./ControllerStorage.sol\";\r\n/**\r\n * @title ControllerCore\r\n * @dev Storage for the controller is at this address, while execution is delegated to the `controllerImplementation`.\r\n * PTokens should reference this contract as their controller.\r\n */\r\ncontract Unitroller is UnitrollerAdminStorage, ControllerErrorReporter {\r\n\r\n    /**\r\n      * @notice Emitted when pendingControllerImplementation is changed\r\n      */\r\n    event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);\r\n\r\n    /**\r\n      * @notice Emitted when pendingControllerImplementation is accepted, which means controller implementation is updated\r\n      */\r\n    event NewImplementation(address oldImplementation, address newImplementation);\r\n\r\n    /**\r\n      * @notice Emitted when pendingAdmin is changed\r\n      */\r\n    event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);\r\n\r\n    /**\r\n      * @notice Emitted when pendingAdmin is accepted, which means admin is updated\r\n      */\r\n    event NewAdmin(address oldAdmin, address newAdmin);\r\n\r\n    constructor() {\r\n        // Set admin to caller\r\n        admin = msg.sender;\r\n    }\r\n\r\n    /*** Admin Functions ***/\r\n    function _setPendingImplementation(address newPendingImplementation) public returns (uint) {\r\n\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);\r\n        }\r\n\r\n        address oldPendingImplementation = pendingControllerImplementation;\r\n\r\n        pendingControllerImplementation = newPendingImplementation;\r\n\r\n        emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n    * @notice Accepts new implementation of controller. msg.sender must be pendingImplementation\r\n    * @dev Admin function for new implementation to accept it's role as implementation\r\n    * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n    */\r\n    function _acceptImplementation() public returns (uint) {\r\n        // Check caller is pendingImplementation and pendingImplementation ≠ address(0)\r\n        if (msg.sender != pendingControllerImplementation || pendingControllerImplementation == address(0)) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);\r\n        }\r\n\r\n        // Save current values for inclusion in log\r\n        address oldImplementation = controllerImplementation;\r\n        address oldPendingImplementation = pendingControllerImplementation;\r\n\r\n        controllerImplementation = pendingControllerImplementation;\r\n\r\n        pendingControllerImplementation = address(0);\r\n\r\n        emit NewImplementation(oldImplementation, controllerImplementation);\r\n        emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n\r\n    /**\r\n      * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\r\n      * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\r\n      * @param newPendingAdmin New pending admin.\r\n      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n      */\r\n    function _setPendingAdmin(address newPendingAdmin) public returns (uint) {\r\n        // Check caller = admin\r\n        if (msg.sender != admin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);\r\n        }\r\n\r\n        // Save current value, if any, for inclusion in log\r\n        address oldPendingAdmin = pendingAdmin;\r\n\r\n        // Store pendingAdmin with value newPendingAdmin\r\n        pendingAdmin = newPendingAdmin;\r\n\r\n        // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)\r\n        emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n      * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\r\n      * @dev Admin function for pending admin to accept role and update admin\r\n      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n      */\r\n    function _acceptAdmin() public returns (uint) {\r\n        // Check caller is pendingAdmin\r\n        if (msg.sender != pendingAdmin) {\r\n            return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);\r\n        }\r\n\r\n        // Save current values for inclusion in log\r\n        address oldAdmin = admin;\r\n        address oldPendingAdmin = pendingAdmin;\r\n\r\n        // Store admin with value pendingAdmin\r\n        admin = pendingAdmin;\r\n\r\n        // Clear the pending value\r\n        pendingAdmin = address(0);\r\n\r\n        emit NewAdmin(oldAdmin, admin);\r\n        emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\r\n\r\n        return uint(Error.NO_ERROR);\r\n    }\r\n\r\n    /**\r\n     * @dev Delegates execution to an implementation contract.\r\n     * It returns to the external caller whatever the implementation returns\r\n     * or forwards reverts.\r\n     */\r\n    fallback() payable external {\r\n        // delegate all other functions to current implementation\r\n        (bool success, ) = controllerImplementation.delegatecall(msg.data);\r\n\r\n        assembly {\r\n        let free_mem_ptr := mload(0x40)\r\n            returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n            switch success\r\n            case 0 { revert(free_mem_ptr, returndatasize()) }\r\n            default { return(free_mem_ptr, returndatasize()) }\r\n        }\r\n    }\r\n}",
      "keccak256": "0x7d8ac328a0094317e760fd9f22b93baf5785105d9114fc8ebd875e60b50e8ed9"
    }
  }
}}