// Vulnerability label: DC1
{{
  "language": "Solidity",
  "settings": {
    "evmVersion": "istanbul",
    "libraries": {},
    "metadata": {
      "bytecodeHash": "ipfs",
      "useLiteralContent": true
    },
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "remappings": [],
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "abi"
        ]
      }
    }
  },
  "sources": {
    "contracts/CarefulMath.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0xa0038a60af8bdaab5926cc5d49573b35673de557eb3e65be8f68807e9db1b068"
    },
    "contracts/Controller.sol": {
      "content": "pragma solidity ^0.7.4;\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 market pieed status is changed\r\n    event MarketPied(address pToken, bool isPied);\r\n\r\n    /// @notice Emitted when PIE rate is changed\r\n    event NewPieRate(uint oldPieRate, uint newPieRate);\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    function refreshPieSpeeds() public {\r\n        require(msg.sender == tx.origin, \"only externally owned accounts may refresh speeds\");\r\n        refreshPieSpeedsInternal();\r\n    }\r\n\r\n    /**\r\n     * @notice Recalculate and update PIE speeds for all PIE markets\r\n     */\r\n    function refreshPieSpeedsInternal() internal {\r\n        address[] memory allMarkets_ = allMarkets;\r\n\r\n        for (uint i = 0; i < allMarkets_.length; i++) {\r\n            address pToken = allMarkets_[i];\r\n            Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n            updatePieSupplyIndex(pToken);\r\n            updatePieBorrowIndex(pToken, borrowIndex);\r\n        }\r\n\r\n        Exp memory totalUtility = Exp({mantissa: 0});\r\n        Exp[] memory utilities = new Exp[](allMarkets_.length);\r\n        for (uint i = 0; i < allMarkets_.length; i++) {\r\n            address pToken = allMarkets_[i];\r\n            if (markets[pToken].isPied) {\r\n                oracle.updateUnderlyingPrice(pToken);\r\n                Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(pToken)});\r\n                Exp memory interestPerBlock = mul_(Exp({mantissa: PTokenInterface(pToken).borrowRatePerBlock()}), PTokenInterface(pToken).totalBorrows());\r\n                Exp memory utility = mul_(interestPerBlock, assetPrice);\r\n                utilities[i] = utility;\r\n                totalUtility = add_(totalUtility, utility);\r\n            }\r\n        }\r\n\r\n        for (uint i = 0; i < allMarkets_.length; i++) {\r\n            address pToken = allMarkets[i];\r\n            uint newSpeed = totalUtility.mantissa > 0 ? mul_(pieRate, div_(utilities[i], totalUtility)) : 0;\r\n            pieSpeeds[pToken] = newSpeed;\r\n            emit PieSpeedUpdated(pToken, newSpeed);\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        } else if (deltaBlocks > 0) {\r\n            supplyState.block = safe32(blockNumber, \"block number exceeds 32 bits\");\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        } else if (deltaBlocks > 0) {\r\n            borrowState.block = safe32(blockNumber, \"block number exceeds 32 bits\");\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 Transfer PIE to the user, if they are above the threshold\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 amount 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    /**\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    /*** Pie Distribution Admin ***/\r\n\r\n    /**\r\n     * @notice Set the amount of PIE distributed per block\r\n     * @param pieRate_ The amount of PIE wei per block to distribute\r\n     */\r\n    function _setPieRate(uint pieRate_) public {\r\n        require(msg.sender == admin, \"only admin can change pie rate\");\r\n\r\n        uint oldRate = pieRate;\r\n        pieRate = pieRate_;\r\n        emit NewPieRate(oldRate, pieRate_);\r\n\r\n        refreshPieSpeedsInternal();\r\n    }\r\n\r\n    function _addPieMarkets(address[] memory pTokens) public {\r\n        require(msg.sender == admin, \"only admin can add pie market\");\r\n\r\n        for (uint i = 0; i < pTokens.length; i++) {\r\n            _addPieMarketInternal(pTokens[i]);\r\n        }\r\n\r\n        refreshPieSpeedsInternal();\r\n    }\r\n\r\n    function _addPieMarketInternal(address pToken) internal {\r\n        Market storage market = markets[pToken];\r\n        require(market.isListed == true, \"pie market is not listed\");\r\n        require(market.isPied == false, \"pie market already added\");\r\n\r\n        market.isPied = true;\r\n        emit MarketPied(pToken, true);\r\n\r\n        if (pieSupplyState[pToken].index == 0 && pieSupplyState[pToken].block == 0) {\r\n            pieSupplyState[pToken] = PieMarketState({\r\n                index: pieInitialIndex,\r\n                block: safe32(getBlockNumber(), \"block number exceeds 32 bits\")\r\n            });\r\n        }\r\n\r\n        if (pieBorrowState[pToken].index == 0 && pieBorrowState[pToken].block == 0) {\r\n            pieBorrowState[pToken] = PieMarketState({\r\n                index: pieInitialIndex,\r\n                block: safe32(getBlockNumber(), \"block number exceeds 32 bits\")\r\n            });\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @notice Remove a market from pieMarkets, preventing it from earning PIE in the flywheel\r\n     * @param pToken The address of the market to drop\r\n     */\r\n    function _dropPieMarket(address pToken) public {\r\n        require(msg.sender == admin, \"only admin can drop pie market\");\r\n\r\n        Market storage market = markets[pToken];\r\n        require(market.isPied == true, \"market is not a pie market\");\r\n\r\n        market.isPied = false;\r\n        emit MarketPied(pToken, false);\r\n\r\n        refreshPieSpeedsInternal();\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": "0xdb50127f3e7987bdb1fcf3f9234565c1eb4dfa35f71d5c037c85a441ccba101c"
    },
    "contracts/ControllerInterface.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0x09cc90ca2f75b3e16a22d3660d4bc3ad4a06d54e14964ebde913d0d4cde68c20"
    },
    "contracts/ControllerStorage.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0x1bfdd440933895c6990ab553fa9f5ae957da2da44008f61f73402adafe432ea7"
    },
    "contracts/EIP20Interface.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0x92fd3d8420359169f9fb602b3110a0cbced85bc550415df4fc6c3aca1a8e5692"
    },
    "contracts/ErrorReporter.sol": {
      "content": "pragma solidity ^0.7.4;\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        UNAUTHORIZED,\r\n        UPDATE_PRICE\r\n    }\r\n\r\n    enum FailureInfo {\r\n        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n        NO_RESERVES,\r\n        PERIOD_NOT_ELAPSED,\r\n        SET_NEW_ADDRESSES,\r\n        SET_NEW_IMPLEMENTATION,\r\n        SET_PENDING_ADMIN_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\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    //TODO: Add more cases\r\n    enum FailureInfo {\r\n        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n        CREATE_PETH_POOL,\r\n        CREATE_PPIE_POOL,\r\n        DEFICIENCY_ETH_LIQUIDITY_IN_POOL,\r\n        PAIR_IS_NOT_EXIST,\r\n        SET_MIN_LIQUIDITY_OWNER_CHECK,\r\n        SET_NEW_CONTROLLER,\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    //TODO: Add more cases\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": "0xe1bcb3a482a468266ee892e6df9f563fc2513931fa929b3a6188353ffc491aa3"
    },
    "contracts/Exponential.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0x82fb044f3cb920550077e453201b2fafed4739b88e840f13d8b74a921534d21c"
    },
    "contracts/InterestRateModel.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0x888dd34d8e448ed26653b79a3a9eff0a7784dc5bc599dcfe25524ed3f87b9d71"
    },
    "contracts/PTokenInterfaces.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0x36f635640f4319082a79e98de8ac6eba5e190056176c3a87015c23c20ec94f1a"
    },
    "contracts/PriceOracle.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0x9819a9a63bfc68ed841974b5da2f0ee27ae4baae87670fb99188a33186f35404"
    },
    "contracts/ProxyWithRegistry.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0xbca7f4ac024754179b7448e1a6d76ad3c029c1544e0c128e1d5000eea7f30b8a"
    },
    "contracts/RegistryInterface.sol": {
      "content": "pragma solidity ^0.7.4;\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": "0x445e9bfc9f8cbd6c5c9107048c1e78fe646636826696aefbba726911afe7fb87"
    },
    "contracts/Unitroller.sol": {
      "content": "pragma solidity ^0.7.4;\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 and pendingAdmin ≠ address(0)\r\n        if (msg.sender != pendingAdmin || msg.sender == address(0)) {\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\r\n    receive() payable external {\r\n        require(msg.value == 0, \"unitroller should not get ether\");\r\n    }\r\n}",
      "keccak256": "0x94e274a94d0ed9885b4ce0c37ce8a059426b94d471f77b7a8d2ed9b18d6393d6"
    }
  }
}}