{
  "language": "Solidity",
  "sources": {
    "contracts/CarefulMath.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\n/**\n * @title Careful Math\n * @author Compound\n * @notice Derived from OpenZeppelin's SafeMath library\n *         https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol\n */\ncontract CarefulMath {\n    /**\n     * @dev Possible error codes that we can return\n     */\n    enum MathError {\n        NO_ERROR,\n        DIVISION_BY_ZERO,\n        INTEGER_OVERFLOW,\n        INTEGER_UNDERFLOW\n    }\n\n    /**\n     * @dev Multiplies two numbers, returns an error on overflow.\n     */\n    function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {\n        if (a == 0) {\n            return (MathError.NO_ERROR, 0);\n        }\n\n        uint256 c = a * b;\n\n        if (c / a != b) {\n            return (MathError.INTEGER_OVERFLOW, 0);\n        } else {\n            return (MathError.NO_ERROR, c);\n        }\n    }\n\n    /**\n     * @dev Integer division of two numbers, truncating the quotient.\n     */\n    function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {\n        if (b == 0) {\n            return (MathError.DIVISION_BY_ZERO, 0);\n        }\n\n        return (MathError.NO_ERROR, a / b);\n    }\n\n    /**\n     * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).\n     */\n    function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {\n        if (b <= a) {\n            return (MathError.NO_ERROR, a - b);\n        } else {\n            return (MathError.INTEGER_UNDERFLOW, 0);\n        }\n    }\n\n    /**\n     * @dev Adds two numbers, returns an error on overflow.\n     */\n    function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {\n        uint256 c = a + b;\n\n        if (c >= a) {\n            return (MathError.NO_ERROR, c);\n        } else {\n            return (MathError.INTEGER_OVERFLOW, 0);\n        }\n    }\n\n    /**\n     * @dev add a and b and then subtract c\n     */\n    function addThenSubUInt(\n        uint256 a,\n        uint256 b,\n        uint256 c\n    ) internal pure returns (MathError, uint256) {\n        (MathError err0, uint256 sum) = addUInt(a, b);\n\n        if (err0 != MathError.NO_ERROR) {\n            return (err0, 0);\n        }\n\n        return subUInt(sum, c);\n    }\n}\n"
    },
    "contracts/Exponential.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./CarefulMath.sol\";\n\n/**\n * @title Exponential module for storing fixed-precision decimals\n * @author Compound\n * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.\n *         Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:\n *         `Exp({mantissa: 5100000000000000000})`.\n */\ncontract Exponential is CarefulMath {\n    uint256 constant expScale = 1e18;\n    uint256 constant doubleScale = 1e36;\n    uint256 constant halfExpScale = expScale / 2;\n    uint256 constant mantissaOne = expScale;\n\n    struct Exp {\n        uint256 mantissa;\n    }\n\n    struct Double {\n        uint256 mantissa;\n    }\n\n    /**\n     * @dev Creates an exponential from numerator and denominator values.\n     *      Note: Returns an error if (`num` * 10e18) > MAX_INT,\n     *            or if `denom` is zero.\n     */\n    function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) {\n        (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale);\n        if (err0 != MathError.NO_ERROR) {\n            return (err0, Exp({mantissa: 0}));\n        }\n\n        (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom);\n        if (err1 != MathError.NO_ERROR) {\n            return (err1, Exp({mantissa: 0}));\n        }\n\n        return (MathError.NO_ERROR, Exp({mantissa: rational}));\n    }\n\n    /**\n     * @dev Adds two exponentials, returning a new exponential.\n     */\n    function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {\n        (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa);\n\n        return (error, Exp({mantissa: result}));\n    }\n\n    /**\n     * @dev Subtracts two exponentials, returning a new exponential.\n     */\n    function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {\n        (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa);\n\n        return (error, Exp({mantissa: result}));\n    }\n\n    /**\n     * @dev Multiply an Exp by a scalar, returning a new Exp.\n     */\n    function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {\n        (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar);\n        if (err0 != MathError.NO_ERROR) {\n            return (err0, Exp({mantissa: 0}));\n        }\n\n        return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));\n    }\n\n    /**\n     * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.\n     */\n    function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) {\n        (MathError err, Exp memory product) = mulScalar(a, scalar);\n        if (err != MathError.NO_ERROR) {\n            return (err, 0);\n        }\n\n        return (MathError.NO_ERROR, truncate(product));\n    }\n\n    /**\n     * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.\n     */\n    function mulScalarTruncateAddUInt(\n        Exp memory a,\n        uint256 scalar,\n        uint256 addend\n    ) internal pure returns (MathError, uint256) {\n        (MathError err, Exp memory product) = mulScalar(a, scalar);\n        if (err != MathError.NO_ERROR) {\n            return (err, 0);\n        }\n\n        return addUInt(truncate(product), addend);\n    }\n\n    /**\n     * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.\n     */\n    function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) {\n        Exp memory product = mul_(a, scalar);\n        return truncate(product);\n    }\n\n    /**\n     * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.\n     */\n    function mul_ScalarTruncateAddUInt(\n        Exp memory a,\n        uint256 scalar,\n        uint256 addend\n    ) internal pure returns (uint256) {\n        Exp memory product = mul_(a, scalar);\n        return add_(truncate(product), addend);\n    }\n\n    /**\n     * @dev Divide an Exp by a scalar, returning a new Exp.\n     */\n    function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {\n        (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar);\n        if (err0 != MathError.NO_ERROR) {\n            return (err0, Exp({mantissa: 0}));\n        }\n\n        return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));\n    }\n\n    /**\n     * @dev Divide a scalar by an Exp, returning a new Exp.\n     */\n    function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) {\n        /*\n          We are doing this as:\n          getExp(mulUInt(expScale, scalar), divisor.mantissa)\n\n          How it works:\n          Exp = a / b;\n          Scalar = s;\n          `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`\n        */\n        (MathError err0, uint256 numerator) = mulUInt(expScale, scalar);\n        if (err0 != MathError.NO_ERROR) {\n            return (err0, Exp({mantissa: 0}));\n        }\n        return getExp(numerator, divisor.mantissa);\n    }\n\n    /**\n     * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.\n     */\n    function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) {\n        (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);\n        if (err != MathError.NO_ERROR) {\n            return (err, 0);\n        }\n\n        return (MathError.NO_ERROR, truncate(fraction));\n    }\n\n    /**\n     * @dev Divide a scalar by an Exp, returning a new Exp.\n     */\n    function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) {\n        /*\n          We are doing this as:\n          getExp(mulUInt(expScale, scalar), divisor.mantissa)\n\n          How it works:\n          Exp = a / b;\n          Scalar = s;\n          `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`\n        */\n        uint256 numerator = mul_(expScale, scalar);\n        return Exp({mantissa: div_(numerator, divisor)});\n    }\n\n    /**\n     * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.\n     */\n    function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) {\n        Exp memory fraction = div_ScalarByExp(scalar, divisor);\n        return truncate(fraction);\n    }\n\n    /**\n     * @dev Multiplies two exponentials, returning a new exponential.\n     */\n    function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {\n        (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);\n        if (err0 != MathError.NO_ERROR) {\n            return (err0, Exp({mantissa: 0}));\n        }\n\n        // We add half the scale before dividing so that we get rounding instead of truncation.\n        //  See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717\n        // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.\n        (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);\n        if (err1 != MathError.NO_ERROR) {\n            return (err1, Exp({mantissa: 0}));\n        }\n\n        (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale);\n        // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.\n        assert(err2 == MathError.NO_ERROR);\n\n        return (MathError.NO_ERROR, Exp({mantissa: product}));\n    }\n\n    /**\n     * @dev Multiplies two exponentials given their mantissas, returning a new exponential.\n     */\n    function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) {\n        return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));\n    }\n\n    /**\n     * @dev Multiplies three exponentials, returning a new exponential.\n     */\n    function mulExp3(\n        Exp memory a,\n        Exp memory b,\n        Exp memory c\n    ) internal pure returns (MathError, Exp memory) {\n        (MathError err, Exp memory ab) = mulExp(a, b);\n        if (err != MathError.NO_ERROR) {\n            return (err, ab);\n        }\n        return mulExp(ab, c);\n    }\n\n    /**\n     * @dev Divides two exponentials, returning a new exponential.\n     *     (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,\n     *  which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)\n     */\n    function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {\n        return getExp(a.mantissa, b.mantissa);\n    }\n\n    /**\n     * @dev Truncates the given exp to a whole number value.\n     *      For example, truncate(Exp{mantissa: 15 * expScale}) = 15\n     */\n    function truncate(Exp memory exp) internal pure returns (uint256) {\n        // Note: We are not using careful math here as we're performing a division that cannot fail\n        return exp.mantissa / expScale;\n    }\n\n    /**\n     * @dev Checks if first Exp is less than second Exp.\n     */\n    function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {\n        return left.mantissa < right.mantissa;\n    }\n\n    /**\n     * @dev Checks if left Exp <= right Exp.\n     */\n    function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) {\n        return left.mantissa <= right.mantissa;\n    }\n\n    /**\n     * @dev returns true if Exp is exactly zero\n     */\n    function isZeroExp(Exp memory value) internal pure returns (bool) {\n        return value.mantissa == 0;\n    }\n\n    function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) {\n        require(n < 2**224, errorMessage);\n        return uint224(n);\n    }\n\n    function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {\n        require(n < 2**32, errorMessage);\n        return uint32(n);\n    }\n\n    function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {\n        return Exp({mantissa: add_(a.mantissa, b.mantissa)});\n    }\n\n    function add_(Double memory a, Double memory b) internal pure returns (Double memory) {\n        return Double({mantissa: add_(a.mantissa, b.mantissa)});\n    }\n\n    function add_(uint256 a, uint256 b) internal pure returns (uint256) {\n        return add_(a, b, \"addition overflow\");\n    }\n\n    function add_(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c >= a, errorMessage);\n        return c;\n    }\n\n    function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {\n        return Exp({mantissa: sub_(a.mantissa, b.mantissa)});\n    }\n\n    function sub_(Double memory a, Double memory b) internal pure returns (Double memory) {\n        return Double({mantissa: sub_(a.mantissa, b.mantissa)});\n    }\n\n    function sub_(uint256 a, uint256 b) internal pure returns (uint256) {\n        return sub_(a, b, \"subtraction underflow\");\n    }\n\n    function sub_(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        require(b <= a, errorMessage);\n        return a - b;\n    }\n\n    function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {\n        return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});\n    }\n\n    function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {\n        return Exp({mantissa: mul_(a.mantissa, b)});\n    }\n\n    function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {\n        return mul_(a, b.mantissa) / expScale;\n    }\n\n    function mul_(Double memory a, Double memory b) internal pure returns (Double memory) {\n        return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});\n    }\n\n    function mul_(Double memory a, uint256 b) internal pure returns (Double memory) {\n        return Double({mantissa: mul_(a.mantissa, b)});\n    }\n\n    function mul_(uint256 a, Double memory b) internal pure returns (uint256) {\n        return mul_(a, b.mantissa) / doubleScale;\n    }\n\n    function mul_(uint256 a, uint256 b) internal pure returns (uint256) {\n        return mul_(a, b, \"multiplication overflow\");\n    }\n\n    function mul_(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        if (a == 0 || b == 0) {\n            return 0;\n        }\n        uint256 c = a * b;\n        require(c / a == b, errorMessage);\n        return c;\n    }\n\n    function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {\n        return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});\n    }\n\n    function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {\n        return Exp({mantissa: div_(a.mantissa, b)});\n    }\n\n    function div_(uint256 a, Exp memory b) internal pure returns (uint256) {\n        return div_(mul_(a, expScale), b.mantissa);\n    }\n\n    function div_(Double memory a, Double memory b) internal pure returns (Double memory) {\n        return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});\n    }\n\n    function div_(Double memory a, uint256 b) internal pure returns (Double memory) {\n        return Double({mantissa: div_(a.mantissa, b)});\n    }\n\n    function div_(uint256 a, Double memory b) internal pure returns (uint256) {\n        return div_(mul_(a, doubleScale), b.mantissa);\n    }\n\n    function div_(uint256 a, uint256 b) internal pure returns (uint256) {\n        return div_(a, b, \"divide by zero\");\n    }\n\n    function div_(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        require(b > 0, errorMessage);\n        return a / b;\n    }\n\n    function fraction(uint256 a, uint256 b) internal pure returns (Double memory) {\n        return Double({mantissa: div_(mul_(a, doubleScale), b)});\n    }\n\n    // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0\n    // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687\n    function sqrt(uint256 x) internal pure returns (uint256) {\n        if (x == 0) return 0;\n        uint256 xx = x;\n        uint256 r = 1;\n\n        if (xx >= 0x100000000000000000000000000000000) {\n            xx >>= 128;\n            r <<= 64;\n        }\n        if (xx >= 0x10000000000000000) {\n            xx >>= 64;\n            r <<= 32;\n        }\n        if (xx >= 0x100000000) {\n            xx >>= 32;\n            r <<= 16;\n        }\n        if (xx >= 0x10000) {\n            xx >>= 16;\n            r <<= 8;\n        }\n        if (xx >= 0x100) {\n            xx >>= 8;\n            r <<= 4;\n        }\n        if (xx >= 0x10) {\n            xx >>= 4;\n            r <<= 2;\n        }\n        if (xx >= 0x8) {\n            r <<= 1;\n        }\n\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1; // Seven iterations should be enough\n        uint256 r1 = x / r;\n        return (r < r1 ? r : r1);\n    }\n}\n"
    },
    "contracts/PriceOracle/PriceOracleProxyUSD.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"../JErc20.sol\";\nimport \"../JToken.sol\";\nimport \"./PriceOracle.sol\";\nimport \"../Exponential.sol\";\nimport \"../EIP20Interface.sol\";\n\ninterface AggregatorV3Interface {\n    function decimals() external view returns (uint8);\n\n    function description() external view returns (string memory);\n\n    function version() external view returns (uint256);\n\n    // getRoundData and latestRoundData should both raise \"No data present\"\n    // if they do not have data to report, instead of returning unset values\n    // which could be misinterpreted as actual reported values.\n    function getRoundData(uint80 _roundId)\n        external\n        view\n        returns (\n            uint80 roundId,\n            int256 answer,\n            uint256 startedAt,\n            uint256 updatedAt,\n            uint80 answeredInRound\n        );\n\n    function latestRoundData()\n        external\n        view\n        returns (\n            uint80 roundId,\n            int256 answer,\n            uint256 startedAt,\n            uint256 updatedAt,\n            uint80 answeredInRound\n        );\n}\n\ncontract PriceOracleProxyUSD is PriceOracle, Exponential {\n    /// @notice Fallback price feed - not used\n    mapping(address => uint256) internal prices;\n\n    /// @notice Admin address\n    address public admin;\n\n    /// @notice Guardian address\n    address public guardian;\n\n    /// @notice Chainlink Aggregators\n    mapping(address => AggregatorV3Interface) public aggregators;\n\n    /**\n     * @param admin_ The address of admin to set aggregators\n     */\n    constructor(address admin_) public {\n        admin = admin_;\n    }\n\n    /**\n     * @notice Get the underlying price of a listed jToken asset\n     * @param jToken The jToken to get the underlying price of\n     * @return The underlying asset price mantissa (scaled by 1e18)\n     */\n    function getUnderlyingPrice(JToken jToken) public view returns (uint256) {\n        address jTokenAddress = address(jToken);\n\n        AggregatorV3Interface aggregator = aggregators[jTokenAddress];\n        if (address(aggregator) != address(0)) {\n            uint256 price = getPriceFromChainlink(aggregator);\n            uint256 underlyingDecimals = EIP20Interface(JErc20(jTokenAddress).underlying()).decimals();\n            if (underlyingDecimals <= 18) {\n                return mul_(price, 10**(18 - underlyingDecimals));\n            }\n            return div_(price, 10**(underlyingDecimals - 18));\n        }\n\n        address asset = address(JErc20(jTokenAddress).underlying());\n\n        uint256 price = prices[asset];\n        require(price > 0, \"invalid price\");\n        return price;\n    }\n\n    /*** Internal fucntions ***/\n\n    /**\n     * @notice Get price from ChainLink\n     * @param aggregator The ChainLink aggregator to get the price of\n     * @return The price\n     */\n    function getPriceFromChainlink(AggregatorV3Interface aggregator) internal view returns (uint256) {\n        (, int256 price, , , ) = aggregator.latestRoundData();\n        require(price > 0, \"invalid price\");\n\n        // Extend the decimals to 1e18.\n        return mul_(uint256(price), 10**(18 - uint256(aggregator.decimals())));\n    }\n\n    /*** Admin or guardian functions ***/\n\n    event AggregatorUpdated(address jTokenAddress, address source);\n    event SetGuardian(address guardian);\n    event SetAdmin(address admin);\n\n    /**\n     * @notice Set guardian for price oracle proxy\n     * @param _guardian The new guardian\n     */\n    function _setGuardian(address _guardian) external {\n        require(msg.sender == admin, \"only the admin may set new guardian\");\n        guardian = _guardian;\n        emit SetGuardian(guardian);\n    }\n\n    /**\n     * @notice Set admin for price oracle proxy\n     * @param _admin The new admin\n     */\n    function _setAdmin(address _admin) external {\n        require(msg.sender == admin, \"only the admin may set new admin\");\n        admin = _admin;\n        emit SetAdmin(admin);\n    }\n\n    /**\n     * @notice Set ChainLink aggregators for multiple jTokens\n     * @param jTokenAddresses The list of jTokens\n     * @param sources The list of ChainLink aggregator sources\n     */\n    function _setAggregators(address[] calldata jTokenAddresses, address[] calldata sources) external {\n        require(msg.sender == admin || msg.sender == guardian, \"only the admin or guardian may set the aggregators\");\n        require(jTokenAddresses.length == sources.length, \"mismatched data\");\n        for (uint256 i = 0; i < jTokenAddresses.length; i++) {\n            if (sources[i] != address(0)) {\n                require(msg.sender == admin, \"guardian may only clear the aggregator\");\n            }\n            aggregators[jTokenAddresses[i]] = AggregatorV3Interface(sources[i]);\n            emit AggregatorUpdated(jTokenAddresses[i], sources[i]);\n        }\n    }\n\n    /**\n     * @notice Set the price of underlying asset\n     * @param jToken The jToken to get underlying asset from\n     * @param underlyingPriceMantissa The new price for the underling asset\n     */\n    function _setUnderlyingPrice(JToken jToken, uint256 underlyingPriceMantissa) external {\n        require(msg.sender == admin, \"only the admin may set the underlying price\");\n        address asset = address(JErc20(address(jToken)).underlying());\n        prices[asset] = underlyingPriceMantissa;\n    }\n\n    /**\n     * @notice Set the price of the underlying asset directly\n     * @param asset The address of the underlying asset\n     * @param price The new price of the asset\n     */\n    function setDirectPrice(address asset, uint256 price) external {\n        require(msg.sender == admin, \"only the admin may set the direct price\");\n        prices[asset] = price;\n    }\n}\n"
    },
    "contracts/JErc20.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JToken.sol\";\n\n/**\n * @title Compound's JErc20 Contract\n * @notice JTokens which wrap an EIP-20 underlying\n * @author Compound\n */\ncontract JErc20 is JToken, JErc20Interface, JProtocolSeizeShareStorage {\n    /**\n     * @notice Initialize the new money market\n     * @param underlying_ The address of the underlying asset\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ ERC-20 name of this token\n     * @param symbol_ ERC-20 symbol of this token\n     * @param decimals_ ERC-20 decimal precision of this token\n     */\n    function initialize(\n        address underlying_,\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_\n    ) public {\n        // JToken initialize does the bulk of the work\n        super.initialize(joetroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);\n\n        // Set underlying and sanity check it\n        underlying = underlying_;\n        EIP20Interface(underlying).totalSupply();\n    }\n\n    /*** User Interface ***/\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param mintAmount The amount of the underlying asset to supply\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function mint(uint256 mintAmount) external returns (uint256) {\n        (uint256 err, ) = mintInternal(mintAmount, false);\n        return err;\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeem(uint256 redeemTokens) external returns (uint256) {\n        return redeemInternal(redeemTokens, false);\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {\n        return redeemUnderlyingInternal(redeemAmount, false);\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrow(uint256 borrowAmount) external returns (uint256) {\n        return borrowInternal(borrowAmount, false);\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrow(uint256 repayAmount) external returns (uint256) {\n        (uint256 err, ) = repayBorrowInternal(repayAmount, false);\n        return err;\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) {\n        (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount, false);\n        return err;\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function liquidateBorrow(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) external returns (uint256) {\n        (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, jTokenCollateral, false);\n        return err;\n    }\n\n    /**\n     * @notice The sender adds to reserves.\n     * @param addAmount The amount fo underlying token to add as reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReserves(uint256 addAmount) external returns (uint256) {\n        return _addReservesInternal(addAmount, false);\n    }\n\n    /*** Safe Token ***/\n\n    /**\n     * @notice Gets balance of this contract in terms of the underlying\n     * @dev This excludes the value of the current message, if any\n     * @return The quantity of underlying tokens owned by this contract\n     */\n    function getCashPrior() internal view returns (uint256) {\n        EIP20Interface token = EIP20Interface(underlying);\n        return token.balanceOf(address(this));\n    }\n\n    /**\n     * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.\n     *      This will revert due to insufficient balance or insufficient allowance.\n     *      This function returns the actual amount received,\n     *      which may be less than `amount` if there is a fee attached to the transfer.\n     *\n     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n     */\n    function doTransferIn(\n        address from,\n        uint256 amount,\n        bool isNative\n    ) internal returns (uint256) {\n        isNative; // unused\n\n        EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n        uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this));\n        token.transferFrom(from, address(this), amount);\n\n        bool success;\n        assembly {\n            switch returndatasize()\n            case 0 {\n                // This is a non-standard ERC-20\n                success := not(0) // set success to true\n            }\n            case 32 {\n                // This is a compliant ERC-20\n                returndatacopy(0, 0, 32)\n                success := mload(0) // Set `success = returndata` of external call\n            }\n            default {\n                // This is an excessively non-compliant ERC-20, revert.\n                revert(0, 0)\n            }\n        }\n        require(success, \"TOKEN_TRANSFER_IN_FAILED\");\n\n        // Calculate the amount that was *actually* transferred\n        uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this));\n        return sub_(balanceAfter, balanceBefore);\n    }\n\n    /**\n     * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory\n     *      error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to\n     *      insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified\n     *      it is >= amount, this should not revert in normal conditions.\n     *\n     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n     */\n    function doTransferOut(\n        address payable to,\n        uint256 amount,\n        bool isNative\n    ) internal {\n        isNative; // unused\n\n        EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n        token.transfer(to, amount);\n\n        bool success;\n        assembly {\n            switch returndatasize()\n            case 0 {\n                // This is a non-standard ERC-20\n                success := not(0) // set success to true\n            }\n            case 32 {\n                // This is a complaint ERC-20\n                returndatacopy(0, 0, 32)\n                success := mload(0) // Set `success = returndata` of external call\n            }\n            default {\n                // This is an excessively non-compliant ERC-20, revert.\n                revert(0, 0)\n            }\n        }\n        require(success, \"TOKEN_TRANSFER_OUT_FAILED\");\n    }\n\n    /**\n     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n     * @dev Called by both `transfer` and `transferFrom` internally\n     * @param spender The address of the account performing the transfer\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param tokens The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferTokens(\n        address spender,\n        address src,\n        address dst,\n        uint256 tokens\n    ) internal returns (uint256) {\n        /* Fail if transfer not allowed */\n        uint256 allowed = joetroller.transferAllowed(address(this), src, dst, tokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.TRANSFER_JOETROLLER_REJECTION, allowed);\n        }\n\n        /* Do not allow self-transfers */\n        if (src == dst) {\n            return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);\n        }\n\n        /* Get the allowance, infinite for the account owner */\n        uint256 startingAllowance = 0;\n        if (spender == src) {\n            startingAllowance = uint256(-1);\n        } else {\n            startingAllowance = transferAllowances[src][spender];\n        }\n\n        /* Do the calculations, checking for {under,over}flow */\n        accountTokens[src] = sub_(accountTokens[src], tokens);\n        accountTokens[dst] = add_(accountTokens[dst], tokens);\n\n        /* Eat some of the allowance (if necessary) */\n        if (startingAllowance != uint256(-1)) {\n            transferAllowances[src][spender] = sub_(startingAllowance, tokens);\n        }\n\n        /* We emit a Transfer event */\n        emit Transfer(src, dst, tokens);\n\n        // unused function\n        // joetroller.transferVerify(address(this), src, dst, tokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Get the account's jToken balances\n     * @param account The address of the account\n     */\n    function getJTokenBalanceInternal(address account) internal view returns (uint256) {\n        return accountTokens[account];\n    }\n\n    struct MintLocalVars {\n        uint256 exchangeRateMantissa;\n        uint256 mintTokens;\n        uint256 actualMintAmount;\n    }\n\n    /**\n     * @notice User supplies assets into the market and receives jTokens in exchange\n     * @dev Assumes interest has already been accrued up to the current timestamp\n     * @param minter The address of the account which is supplying the assets\n     * @param mintAmount The amount of the underlying asset to supply\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n     */\n    function mintFresh(\n        address minter,\n        uint256 mintAmount,\n        bool isNative\n    ) internal returns (uint256, uint256) {\n        /* Fail if mint not allowed */\n        uint256 allowed = joetroller.mintAllowed(address(this), minter, mintAmount);\n        if (allowed != 0) {\n            return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.MINT_JOETROLLER_REJECTION, allowed), 0);\n        }\n\n        /*\n         * Return if mintAmount is zero.\n         * Put behind `mintAllowed` for accuring potential JOE rewards.\n         */\n        if (mintAmount == 0) {\n            return (uint256(Error.NO_ERROR), 0);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);\n        }\n\n        MintLocalVars memory vars;\n\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         *  We call `doTransferIn` for the minter and the mintAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  `doTransferIn` reverts if anything goes wrong, since we can't be sure if\n         *  side-effects occurred. The function returns the amount actually transferred,\n         *  in case of a fee. On success, the jToken holds an additional `actualMintAmount`\n         *  of cash.\n         */\n        vars.actualMintAmount = doTransferIn(minter, mintAmount, isNative);\n\n        /*\n         * We get the current exchange rate and calculate the number of jTokens to be minted:\n         *  mintTokens = actualMintAmount / exchangeRate\n         */\n        vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));\n\n        /*\n         * We calculate the new total supply of jTokens and minter token balance, checking for overflow:\n         *  totalSupply = totalSupply + mintTokens\n         *  accountTokens[minter] = accountTokens[minter] + mintTokens\n         */\n        totalSupply = add_(totalSupply, vars.mintTokens);\n        accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens);\n\n        /* We emit a Mint event, and a Transfer event */\n        emit Mint(minter, vars.actualMintAmount, vars.mintTokens);\n        emit Transfer(address(this), minter, vars.mintTokens);\n\n        /* We call the defense hook */\n        // unused function\n        // joetroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);\n\n        return (uint256(Error.NO_ERROR), vars.actualMintAmount);\n    }\n\n    struct RedeemLocalVars {\n        uint256 exchangeRateMantissa;\n        uint256 redeemTokens;\n        uint256 redeemAmount;\n        uint256 totalSupplyNew;\n        uint256 accountTokensNew;\n    }\n\n    /**\n     * @notice User redeems jTokens in exchange for the underlying asset\n     * @dev Assumes interest has already been accrued up to the current timestamp. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero.\n     * @param redeemer The address of the account which is redeeming the tokens\n     * @param redeemTokensIn The number of jTokens to redeem into underlying\n     * @param redeemAmountIn The number of underlying tokens to receive from redeeming jTokens\n     * @param isNative The amount is in native or not\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemFresh(\n        address payable redeemer,\n        uint256 redeemTokensIn,\n        uint256 redeemAmountIn,\n        bool isNative\n    ) internal returns (uint256) {\n        require(redeemTokensIn == 0 || redeemAmountIn == 0, \"one of redeemTokensIn or redeemAmountIn must be zero\");\n\n        RedeemLocalVars memory vars;\n\n        /* exchangeRate = invoke Exchange Rate Stored() */\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /* If redeemTokensIn > 0: */\n        if (redeemTokensIn > 0) {\n            /*\n             * We calculate the exchange rate and the amount of underlying to be redeemed:\n             *  redeemTokens = redeemTokensIn\n             *  redeemAmount = redeemTokensIn x exchangeRateCurrent\n             */\n            vars.redeemTokens = redeemTokensIn;\n            vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);\n        } else {\n            /*\n             * We get the current exchange rate and calculate the amount to be redeemed:\n             *  redeemTokens = redeemAmountIn / exchangeRate\n             *  redeemAmount = redeemAmountIn\n             */\n            vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));\n            vars.redeemAmount = redeemAmountIn;\n        }\n\n        /* Fail if redeem not allowed */\n        uint256 allowed = joetroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REDEEM_JOETROLLER_REJECTION, allowed);\n        }\n\n        /*\n         * Return if redeemTokensIn and redeemAmountIn are zero.\n         * Put behind `redeemAllowed` for accuring potential JOE rewards.\n         */\n        if (redeemTokensIn == 0 && redeemAmountIn == 0) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);\n        }\n\n        /*\n         * We calculate the new total supply and redeemer balance, checking for underflow:\n         *  totalSupplyNew = totalSupply - redeemTokens\n         *  accountTokensNew = accountTokens[redeemer] - redeemTokens\n         */\n        vars.totalSupplyNew = sub_(totalSupply, vars.redeemTokens);\n        vars.accountTokensNew = sub_(accountTokens[redeemer], vars.redeemTokens);\n\n        /* Fail gracefully if protocol has insufficient cash */\n        if (getCashPrior() < vars.redeemAmount) {\n            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We invoke doTransferOut for the redeemer and the redeemAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken has redeemAmount less of cash.\n         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         */\n        doTransferOut(redeemer, vars.redeemAmount, isNative);\n\n        /* We write previously calculated values into storage */\n        totalSupply = vars.totalSupplyNew;\n        accountTokens[redeemer] = vars.accountTokensNew;\n\n        /* We emit a Transfer event, and a Redeem event */\n        emit Transfer(redeemer, address(this), vars.redeemTokens);\n        emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        /* We call the defense hook */\n        joetroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another JToken.\n     *  Its absolutely critical to use msg.sender as the seizer jToken and not a parameter.\n     * @param seizerToken The contract seizing the collateral (i.e. borrowed jToken)\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seizeInternal(\n        address seizerToken,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) internal returns (uint256) {\n        /* Fail if seize not allowed */\n        uint256 allowed = joetroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_JOETROLLER_REJECTION, allowed);\n        }\n\n        /*\n         * Return if seizeTokens is zero.\n         * Put behind `seizeAllowed` for accuring potential JOE rewards.\n         */\n        if (seizeTokens == 0) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Fail if borrower = liquidator */\n        if (borrower == liquidator) {\n            return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);\n        }\n\n        uint256 protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}));\n        uint256 liquidatorSeizeTokens = sub_(seizeTokens, protocolSeizeTokens);\n\n        uint256 exchangeRateMantissa = exchangeRateStoredInternal();\n        uint256 protocolSeizeAmount = mul_ScalarTruncate(Exp({mantissa: exchangeRateMantissa}), protocolSeizeTokens);\n\n        /*\n         * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:\n         *  borrowerTokensNew = accountTokens[borrower] - seizeTokens\n         *  liquidatorTokensNew = accountTokens[liquidator] + seizeTokens\n         */\n        accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens);\n        accountTokens[liquidator] = add_(accountTokens[liquidator], liquidatorSeizeTokens);\n        totalReserves = add_(totalReserves, protocolSeizeAmount);\n        totalSupply = sub_(totalSupply, protocolSeizeTokens);\n\n        /* Emit a Transfer event */\n        emit Transfer(borrower, liquidator, seizeTokens);\n        emit ReservesAdded(address(this), protocolSeizeAmount, totalReserves);\n\n        /* We call the defense hook */\n        // unused function\n        // joetroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n}\n"
    },
    "contracts/JToken.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JoetrollerInterface.sol\";\nimport \"./JTokenInterfaces.sol\";\nimport \"./ErrorReporter.sol\";\nimport \"./Exponential.sol\";\nimport \"./EIP20Interface.sol\";\nimport \"./EIP20NonStandardInterface.sol\";\nimport \"./InterestRateModel.sol\";\n\n/**\n * @title Compound's JToken Contract\n * @notice Abstract base for JTokens\n * @author Compound\n */\ncontract JToken is JTokenInterface, Exponential, TokenErrorReporter {\n    /**\n     * @notice Initialize the money market\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ EIP-20 name of this token\n     * @param symbol_ EIP-20 symbol of this token\n     * @param decimals_ EIP-20 decimal precision of this token\n     */\n    function initialize(\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_\n    ) public {\n        require(msg.sender == admin, \"only admin may initialize the market\");\n        require(accrualBlockTimestamp == 0 && borrowIndex == 0, \"market may only be initialized once\");\n\n        // Set initial exchange rate\n        initialExchangeRateMantissa = initialExchangeRateMantissa_;\n        require(initialExchangeRateMantissa > 0, \"initial exchange rate must be greater than zero.\");\n\n        // Set the joetroller\n        uint256 err = _setJoetroller(joetroller_);\n        require(err == uint256(Error.NO_ERROR), \"setting joetroller failed\");\n\n        // Initialize block timestamp and borrow index (block timestamp mocks depend on joetroller being set)\n        accrualBlockTimestamp = getBlockTimestamp();\n        borrowIndex = mantissaOne;\n\n        // Set the interest rate model (depends on block timestamp / borrow index)\n        err = _setInterestRateModelFresh(interestRateModel_);\n        require(err == uint256(Error.NO_ERROR), \"setting interest rate model failed\");\n\n        name = name_;\n        symbol = symbol_;\n        decimals = decimals_;\n\n        // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)\n        _notEntered = true;\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {\n        return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `src` to `dst`\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferFrom(\n        address src,\n        address dst,\n        uint256 amount\n    ) external nonReentrant returns (bool) {\n        return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Approve `spender` to transfer up to `amount` from `src`\n     * @dev This will overwrite the approval amount for `spender`\n     *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n     * @param spender The address of the account which may transfer tokens\n     * @param amount The number of tokens that are approved (-1 means infinite)\n     * @return Whether or not the approval succeeded\n     */\n    function approve(address spender, uint256 amount) external returns (bool) {\n        address src = msg.sender;\n        transferAllowances[src][spender] = amount;\n        emit Approval(src, spender, amount);\n        return true;\n    }\n\n    /**\n     * @notice Get the current allowance from `owner` for `spender`\n     * @param owner The address of the account which owns the tokens to be spent\n     * @param spender The address of the account which may transfer tokens\n     * @return The number of tokens allowed to be spent (-1 means infinite)\n     */\n    function allowance(address owner, address spender) external view returns (uint256) {\n        return transferAllowances[owner][spender];\n    }\n\n    /**\n     * @notice Get the token balance of the `owner`\n     * @param owner The address of the account to query\n     * @return The number of tokens owned by `owner`\n     */\n    function balanceOf(address owner) external view returns (uint256) {\n        return accountTokens[owner];\n    }\n\n    /**\n     * @notice Get the underlying balance of the `owner`\n     * @dev This also accrues interest in a transaction\n     * @param owner The address of the account to query\n     * @return The amount of underlying owned by `owner`\n     */\n    function balanceOfUnderlying(address owner) external returns (uint256) {\n        Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});\n        return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);\n    }\n\n    /**\n     * @notice Get a snapshot of the account's balances, and the cached exchange rate\n     * @dev This is used by joetroller to more efficiently perform liquidity checks.\n     * @param account Address of the account to snapshot\n     * @return (possible error, token balance, borrow balance, exchange rate mantissa)\n     */\n    function getAccountSnapshot(address account)\n        external\n        view\n        returns (\n            uint256,\n            uint256,\n            uint256,\n            uint256\n        )\n    {\n        uint256 jTokenBalance = getJTokenBalanceInternal(account);\n        uint256 borrowBalance = borrowBalanceStoredInternal(account);\n        uint256 exchangeRateMantissa = exchangeRateStoredInternal();\n\n        return (uint256(Error.NO_ERROR), jTokenBalance, borrowBalance, exchangeRateMantissa);\n    }\n\n    /**\n     * @dev Function to simply retrieve block timestamp\n     *  This exists mainly for inheriting test contracts to stub this result.\n     */\n    function getBlockTimestamp() internal view returns (uint256) {\n        return block.timestamp;\n    }\n\n    /**\n     * @notice Returns the current per-sec borrow interest rate for this jToken\n     * @return The borrow interest rate per sec, scaled by 1e18\n     */\n    function borrowRatePerSecond() external view returns (uint256) {\n        return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);\n    }\n\n    /**\n     * @notice Returns the current per-sec supply interest rate for this jToken\n     * @return The supply interest rate per sec, scaled by 1e18\n     */\n    function supplyRatePerSecond() external view returns (uint256) {\n        return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);\n    }\n\n    /**\n     * @notice Returns the estimated per-sec borrow interest rate for this jToken after some change\n     * @return The borrow interest rate per sec, scaled by 1e18\n     */\n    function estimateBorrowRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) {\n        uint256 cashPriorNew;\n        uint256 totalBorrowsNew;\n\n        if (repay) {\n            cashPriorNew = add_(getCashPrior(), change);\n            totalBorrowsNew = sub_(totalBorrows, change);\n        } else {\n            cashPriorNew = sub_(getCashPrior(), change);\n            totalBorrowsNew = add_(totalBorrows, change);\n        }\n        return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves);\n    }\n\n    /**\n     * @notice Returns the estimated per-sec supply interest rate for this jToken after some change\n     * @return The supply interest rate per sec, scaled by 1e18\n     */\n    function estimateSupplyRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) {\n        uint256 cashPriorNew;\n        uint256 totalBorrowsNew;\n\n        if (repay) {\n            cashPriorNew = add_(getCashPrior(), change);\n            totalBorrowsNew = sub_(totalBorrows, change);\n        } else {\n            cashPriorNew = sub_(getCashPrior(), change);\n            totalBorrowsNew = add_(totalBorrows, change);\n        }\n\n        return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa);\n    }\n\n    /**\n     * @notice Returns the current total borrows plus accrued interest\n     * @return The total borrows with interest\n     */\n    function totalBorrowsCurrent() external nonReentrant returns (uint256) {\n        require(accrueInterest() == uint256(Error.NO_ERROR), \"accrue interest failed\");\n        return totalBorrows;\n    }\n\n    /**\n     * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex\n     * @param account The address whose balance should be calculated after updating borrowIndex\n     * @return The calculated balance\n     */\n    function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) {\n        require(accrueInterest() == uint256(Error.NO_ERROR), \"accrue interest failed\");\n        return borrowBalanceStored(account);\n    }\n\n    /**\n     * @notice Return the borrow balance of account based on stored data\n     * @param account The address whose balance should be calculated\n     * @return The calculated balance\n     */\n    function borrowBalanceStored(address account) public view returns (uint256) {\n        return borrowBalanceStoredInternal(account);\n    }\n\n    /**\n     * @notice Return the borrow balance of account based on stored data\n     * @param account The address whose balance should be calculated\n     * @return the calculated balance or 0 if error code is non-zero\n     */\n    function borrowBalanceStoredInternal(address account) internal view returns (uint256) {\n        /* Get borrowBalance and borrowIndex */\n        BorrowSnapshot storage borrowSnapshot = accountBorrows[account];\n\n        /* If borrowBalance = 0 then borrowIndex is likely also 0.\n         * Rather than failing the calculation with a division by 0, we immediately return 0 in this case.\n         */\n        if (borrowSnapshot.principal == 0) {\n            return 0;\n        }\n\n        /* Calculate new borrow balance using the interest index:\n         *  recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex\n         */\n        uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex);\n        uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex);\n        return result;\n    }\n\n    /**\n     * @notice Accrue interest then return the up-to-date exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateCurrent() public nonReentrant returns (uint256) {\n        require(accrueInterest() == uint256(Error.NO_ERROR), \"accrue interest failed\");\n        return exchangeRateStored();\n    }\n\n    /**\n     * @notice Calculates the exchange rate from the underlying to the JToken\n     * @dev This function does not accrue interest before calculating the exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateStored() public view returns (uint256) {\n        return exchangeRateStoredInternal();\n    }\n\n    /**\n     * @notice Calculates the exchange rate from the underlying to the JToken\n     * @dev This function does not accrue interest before calculating the exchange rate\n     * @return calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateStoredInternal() internal view returns (uint256) {\n        uint256 _totalSupply = totalSupply;\n        if (_totalSupply == 0) {\n            /*\n             * If there are no tokens minted:\n             *  exchangeRate = initialExchangeRate\n             */\n            return initialExchangeRateMantissa;\n        } else {\n            /*\n             * Otherwise:\n             *  exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply\n             */\n            uint256 totalCash = getCashPrior();\n            uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves);\n            uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply}));\n            return exchangeRate;\n        }\n    }\n\n    /**\n     * @notice Get cash balance of this jToken in the underlying asset\n     * @return The quantity of underlying asset owned by this contract\n     */\n    function getCash() external view returns (uint256) {\n        return getCashPrior();\n    }\n\n    /**\n     * @notice Applies accrued interest to total borrows and reserves\n     * @dev This calculates interest accrued from the last checkpointed timestamp\n     *   up to the current timestamp and writes new checkpoint to storage.\n     */\n    function accrueInterest() public returns (uint256) {\n        /* Remember the initial block timestamp */\n        uint256 currentBlockTimestamp = getBlockTimestamp();\n        uint256 accrualBlockTimestampPrior = accrualBlockTimestamp;\n\n        /* Short-circuit accumulating 0 interest */\n        if (accrualBlockTimestampPrior == currentBlockTimestamp) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Read the previous values out of storage */\n        uint256 cashPrior = getCashPrior();\n        uint256 borrowsPrior = totalBorrows;\n        uint256 reservesPrior = totalReserves;\n        uint256 borrowIndexPrior = borrowIndex;\n\n        /* Calculate the current borrow interest rate */\n        uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);\n        require(borrowRateMantissa <= borrowRateMaxMantissa, \"borrow rate is absurdly high\");\n\n        /* Calculate the number of seconds elapsed since the last accrual */\n        uint256 timestampDelta = sub_(currentBlockTimestamp, accrualBlockTimestampPrior);\n\n        /*\n         * Calculate the interest accumulated into borrows and reserves and the new index:\n         *  simpleInterestFactor = borrowRate * timestampDelta\n         *  interestAccumulated = simpleInterestFactor * totalBorrows\n         *  totalBorrowsNew = interestAccumulated + totalBorrows\n         *  totalReservesNew = interestAccumulated * reserveFactor + totalReserves\n         *  borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex\n         */\n\n        Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), timestampDelta);\n        uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);\n        uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior);\n        uint256 totalReservesNew = mul_ScalarTruncateAddUInt(\n            Exp({mantissa: reserveFactorMantissa}),\n            interestAccumulated,\n            reservesPrior\n        );\n        uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /* We write the previously calculated values into storage */\n        accrualBlockTimestamp = currentBlockTimestamp;\n        borrowIndex = borrowIndexNew;\n        totalBorrows = totalBorrowsNew;\n        totalReserves = totalReservesNew;\n\n        /* We emit an AccrueInterest event */\n        emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param mintAmount The amount of the underlying asset to supply\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n     */\n    function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n            return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);\n        }\n        // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to\n        return mintFresh(msg.sender, mintAmount, isNative);\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @param isNative The amount is in native or not\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed\n            return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);\n        }\n        // redeemFresh emits redeem-specific logs on errors, so we don't need to\n        return redeemFresh(msg.sender, redeemTokens, 0, isNative);\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to receive from redeeming jTokens\n     * @param isNative The amount is in native or not\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed\n            return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);\n        }\n        // redeemFresh emits redeem-specific logs on errors, so we don't need to\n        return redeemFresh(msg.sender, 0, redeemAmount, isNative);\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @param isNative The amount is in native or not\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n            return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);\n        }\n        // borrowFresh emits borrow-specific logs on errors, so we don't need to\n        return borrowFresh(msg.sender, borrowAmount, isNative);\n    }\n\n    struct BorrowLocalVars {\n        MathError mathErr;\n        uint256 accountBorrows;\n        uint256 accountBorrowsNew;\n        uint256 totalBorrowsNew;\n    }\n\n    /**\n     * @notice Users borrow assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @param isNative The amount is in native or not\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrowFresh(\n        address payable borrower,\n        uint256 borrowAmount,\n        bool isNative\n    ) internal returns (uint256) {\n        /* Fail if borrow not allowed */\n        uint256 allowed = joetroller.borrowAllowed(address(this), borrower, borrowAmount);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.BORROW_JOETROLLER_REJECTION, allowed);\n        }\n\n        /*\n         * Return if borrowAmount is zero.\n         * Put behind `borrowAllowed` for accuring potential JOE rewards.\n         */\n        if (borrowAmount == 0) {\n            accountBorrows[borrower].principal = borrowBalanceStoredInternal(borrower);\n            accountBorrows[borrower].interestIndex = borrowIndex;\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);\n        }\n\n        /* Fail gracefully if protocol has insufficient underlying cash */\n        if (getCashPrior() < borrowAmount) {\n            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);\n        }\n\n        BorrowLocalVars memory vars;\n\n        /*\n         * We calculate the new borrower and total borrow balances, failing on overflow:\n         *  accountBorrowsNew = accountBorrows + borrowAmount\n         *  totalBorrowsNew = totalBorrows + borrowAmount\n         */\n        vars.accountBorrows = borrowBalanceStoredInternal(borrower);\n        vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount);\n        vars.totalBorrowsNew = add_(totalBorrows, borrowAmount);\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We invoke doTransferOut for the borrower and the borrowAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken borrowAmount less of cash.\n         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         */\n        doTransferOut(borrower, borrowAmount, isNative);\n\n        /* We write the previously calculated values into storage */\n        accountBorrows[borrower].principal = vars.accountBorrowsNew;\n        accountBorrows[borrower].interestIndex = borrowIndex;\n        totalBorrows = vars.totalBorrowsNew;\n\n        /* We emit a Borrow event */\n        emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);\n\n        /* We call the defense hook */\n        // unused function\n        // joetroller.borrowVerify(address(this), borrower, borrowAmount);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @param repayAmount The amount to repay\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n     */\n    function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n            return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);\n        }\n        // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to\n        return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative);\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount The amount to repay\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n     */\n    function repayBorrowBehalfInternal(\n        address borrower,\n        uint256 repayAmount,\n        bool isNative\n    ) internal nonReentrant returns (uint256, uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n            return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);\n        }\n        // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to\n        return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative);\n    }\n\n    struct RepayBorrowLocalVars {\n        Error err;\n        MathError mathErr;\n        uint256 repayAmount;\n        uint256 borrowerIndex;\n        uint256 accountBorrows;\n        uint256 accountBorrowsNew;\n        uint256 totalBorrowsNew;\n        uint256 actualRepayAmount;\n    }\n\n    /**\n     * @notice Borrows are repaid by another user (possibly the borrower).\n     * @param payer the account paying off the borrow\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount the amount of undelrying tokens being returned\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n     */\n    function repayBorrowFresh(\n        address payer,\n        address borrower,\n        uint256 repayAmount,\n        bool isNative\n    ) internal returns (uint256, uint256) {\n        /* Fail if repayBorrow not allowed */\n        uint256 allowed = joetroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);\n        if (allowed != 0) {\n            return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REPAY_BORROW_JOETROLLER_REJECTION, allowed), 0);\n        }\n\n        /*\n         * Return if repayAmount is zero.\n         * Put behind `repayBorrowAllowed` for accuring potential JOE rewards.\n         */\n        if (repayAmount == 0) {\n            accountBorrows[borrower].principal = borrowBalanceStoredInternal(borrower);\n            accountBorrows[borrower].interestIndex = borrowIndex;\n            return (uint256(Error.NO_ERROR), 0);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);\n        }\n\n        RepayBorrowLocalVars memory vars;\n\n        /* We remember the original borrowerIndex for verification purposes */\n        vars.borrowerIndex = accountBorrows[borrower].interestIndex;\n\n        /* We fetch the amount the borrower owes, with accumulated interest */\n        vars.accountBorrows = borrowBalanceStoredInternal(borrower);\n\n        /* If repayAmount == -1, repayAmount = accountBorrows */\n        if (repayAmount == uint256(-1)) {\n            vars.repayAmount = vars.accountBorrows;\n        } else {\n            vars.repayAmount = repayAmount;\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We call doTransferIn for the payer and the repayAmount\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken holds an additional repayAmount of cash.\n         *  doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         *   it returns the amount actually transferred, in case of a fee.\n         */\n        vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative);\n\n        /*\n         * We calculate the new borrower and total borrow balances, failing on underflow:\n         *  accountBorrowsNew = accountBorrows - actualRepayAmount\n         *  totalBorrowsNew = totalBorrows - actualRepayAmount\n         */\n        vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount);\n        vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount);\n\n        /* We write the previously calculated values into storage */\n        accountBorrows[borrower].principal = vars.accountBorrowsNew;\n        accountBorrows[borrower].interestIndex = borrowIndex;\n        totalBorrows = vars.totalBorrowsNew;\n\n        /* We emit a RepayBorrow event */\n        emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);\n\n        /* We call the defense hook */\n        // unused function\n        // joetroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);\n\n        return (uint256(Error.NO_ERROR), vars.actualRepayAmount);\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n     */\n    function liquidateBorrowInternal(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral,\n        bool isNative\n    ) internal nonReentrant returns (uint256, uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\n            return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);\n        }\n\n        error = jTokenCollateral.accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\n            return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);\n        }\n\n        // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to\n        return liquidateBorrowFresh(msg.sender, borrower, repayAmount, jTokenCollateral, isNative);\n    }\n\n    /**\n     * @notice The liquidator liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param liquidator The address repaying the borrow and seizing collateral\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n     */\n    function liquidateBorrowFresh(\n        address liquidator,\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral,\n        bool isNative\n    ) internal returns (uint256, uint256) {\n        /* Fail if liquidate not allowed */\n        uint256 allowed = joetroller.liquidateBorrowAllowed(\n            address(this),\n            address(jTokenCollateral),\n            liquidator,\n            borrower,\n            repayAmount\n        );\n        if (allowed != 0) {\n            return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_JOETROLLER_REJECTION, allowed), 0);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);\n        }\n\n        /* Verify jTokenCollateral market's block timestamp equals current block timestamp */\n        if (jTokenCollateral.accrualBlockTimestamp() != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);\n        }\n\n        /* Fail if borrower = liquidator */\n        if (borrower == liquidator) {\n            return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);\n        }\n\n        /* Fail if repayAmount = 0 */\n        if (repayAmount == 0) {\n            return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);\n        }\n\n        /* Fail if repayAmount = -1 */\n        if (repayAmount == uint256(-1)) {\n            return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);\n        }\n\n        /* Fail if repayBorrow fails */\n        (uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(\n            liquidator,\n            borrower,\n            repayAmount,\n            isNative\n        );\n        if (repayBorrowError != uint256(Error.NO_ERROR)) {\n            return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /* We calculate the number of collateral tokens that will be seized */\n        (uint256 amountSeizeError, uint256 seizeTokens) = joetroller.liquidateCalculateSeizeTokens(\n            address(this),\n            address(jTokenCollateral),\n            actualRepayAmount\n        );\n        require(amountSeizeError == uint256(Error.NO_ERROR), \"LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED\");\n\n        /* Revert if borrower collateral token balance < seizeTokens */\n        require(jTokenCollateral.balanceOf(borrower) >= seizeTokens, \"LIQUIDATE_SEIZE_TOO_MUCH\");\n\n        // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call\n        uint256 seizeError;\n        if (address(jTokenCollateral) == address(this)) {\n            seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);\n        } else {\n            seizeError = jTokenCollateral.seize(liquidator, borrower, seizeTokens);\n        }\n\n        /* Revert if seize tokens fails (since we cannot be sure of side effects) */\n        require(seizeError == uint256(Error.NO_ERROR), \"token seizure failed\");\n\n        /* We emit a LiquidateBorrow event */\n        emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(jTokenCollateral), seizeTokens);\n\n        /* We call the defense hook */\n        // unused function\n        // joetroller.liquidateBorrowVerify(address(this), address(jTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);\n\n        return (uint256(Error.NO_ERROR), actualRepayAmount);\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Will fail unless called by another jToken during the process of liquidation.\n     *  Its absolutely critical to use msg.sender as the borrowed jToken and not a parameter.\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seize(\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external nonReentrant returns (uint256) {\n        return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);\n    }\n\n    /*** Admin Functions ***/\n\n    /**\n     * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @param newPendingAdmin New pending admin.\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) {\n        // Check caller = admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);\n        }\n\n        // Save current value, if any, for inclusion in log\n        address oldPendingAdmin = pendingAdmin;\n\n        // Store pendingAdmin with value newPendingAdmin\n        pendingAdmin = newPendingAdmin;\n\n        // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)\n        emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\n     * @dev Admin function for pending admin to accept role and update admin\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _acceptAdmin() external returns (uint256) {\n        // Check caller is pendingAdmin and pendingAdmin ≠ address(0)\n        if (msg.sender != pendingAdmin || msg.sender == address(0)) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);\n        }\n\n        // Save current values for inclusion in log\n        address oldAdmin = admin;\n        address oldPendingAdmin = pendingAdmin;\n\n        // Store admin with value pendingAdmin\n        admin = pendingAdmin;\n\n        // Clear the pending value\n        pendingAdmin = address(0);\n\n        emit NewAdmin(oldAdmin, admin);\n        emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sets a new joetroller for the market\n     * @dev Admin function to set a new joetroller\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_JOETROLLER_OWNER_CHECK);\n        }\n\n        JoetrollerInterface oldJoetroller = joetroller;\n        // Ensure invoke joetroller.isJoetroller() returns true\n        require(newJoetroller.isJoetroller(), \"marker method returned false\");\n\n        // Set market's joetroller to newJoetroller\n        joetroller = newJoetroller;\n\n        // Emit NewJoetroller(oldJoetroller, newJoetroller)\n        emit NewJoetroller(oldJoetroller, newJoetroller);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh\n     * @dev Admin function to accrue interest and set a new reserve factor\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.\n            return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);\n        }\n        // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.\n        return _setReserveFactorFresh(newReserveFactorMantissa);\n    }\n\n    /**\n     * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)\n     * @dev Admin function to set a new reserve factor\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);\n        }\n\n        // Verify market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);\n        }\n\n        // Check newReserveFactor ≤ maxReserveFactor\n        if (newReserveFactorMantissa > reserveFactorMaxMantissa) {\n            return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);\n        }\n\n        uint256 oldReserveFactorMantissa = reserveFactorMantissa;\n        reserveFactorMantissa = newReserveFactorMantissa;\n\n        emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Accrues interest and reduces reserves by transferring from msg.sender\n     * @param addAmount Amount of addition to reserves\n     * @param isNative The amount is in native or not\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.\n            return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);\n        }\n\n        // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.\n        (error, ) = _addReservesFresh(addAmount, isNative);\n        return error;\n    }\n\n    /**\n     * @notice Add reserves by transferring from caller\n     * @dev Requires fresh interest accrual\n     * @param addAmount Amount of addition to reserves\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees\n     */\n    function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) {\n        // totalReserves + actualAddAmount\n        uint256 totalReservesNew;\n        uint256 actualAddAmount;\n\n        // We fail gracefully unless market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We call doTransferIn for the caller and the addAmount\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken holds an additional addAmount of cash.\n         *  doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         *  it returns the amount actually transferred, in case of a fee.\n         */\n\n        actualAddAmount = doTransferIn(msg.sender, addAmount, isNative);\n\n        totalReservesNew = add_(totalReserves, actualAddAmount);\n\n        // Store reserves[n+1] = reserves[n] + actualAddAmount\n        totalReserves = totalReservesNew;\n\n        /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */\n        emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);\n\n        /* Return (NO_ERROR, actualAddAmount) */\n        return (uint256(Error.NO_ERROR), actualAddAmount);\n    }\n\n    /**\n     * @notice Accrues interest and reduces reserves by transferring to admin\n     * @param reduceAmount Amount of reduction to reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.\n            return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);\n        }\n        // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.\n        return _reduceReservesFresh(reduceAmount);\n    }\n\n    /**\n     * @notice Reduces reserves by transferring to admin\n     * @dev Requires fresh interest accrual\n     * @param reduceAmount Amount of reduction to reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) {\n        // totalReserves - reduceAmount\n        uint256 totalReservesNew;\n\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);\n        }\n\n        // We fail gracefully unless market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);\n        }\n\n        // Fail gracefully if protocol has insufficient underlying cash\n        if (getCashPrior() < reduceAmount) {\n            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);\n        }\n\n        // Check reduceAmount ≤ reserves[n] (totalReserves)\n        if (reduceAmount > totalReserves) {\n            return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        totalReservesNew = sub_(totalReserves, reduceAmount);\n\n        // Store reserves[n+1] = reserves[n] - reduceAmount\n        totalReserves = totalReservesNew;\n\n        // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n        // Restrict reducing reserves in native token. Implementations except `JWrappedNative` won't use parameter `isNative`.\n        doTransferOut(admin, reduceAmount, true);\n\n        emit ReservesReduced(admin, reduceAmount, totalReservesNew);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh\n     * @dev Admin function to accrue interest and update the interest rate model\n     * @param newInterestRateModel the new interest rate model to use\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed\n            return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);\n        }\n        // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.\n        return _setInterestRateModelFresh(newInterestRateModel);\n    }\n\n    /**\n     * @notice updates the interest rate model (*requires fresh interest accrual)\n     * @dev Admin function to update the interest rate model\n     * @param newInterestRateModel the new interest rate model to use\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) {\n        // Used to store old model for use in the event that is emitted on success\n        InterestRateModel oldInterestRateModel;\n\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);\n        }\n\n        // We fail gracefully unless market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);\n        }\n\n        // Track the market's current interest rate model\n        oldInterestRateModel = interestRateModel;\n\n        // Ensure invoke newInterestRateModel.isInterestRateModel() returns true\n        require(newInterestRateModel.isInterestRateModel(), \"marker method returned false\");\n\n        // Set the interest rate model to newInterestRateModel\n        interestRateModel = newInterestRateModel;\n\n        // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)\n        emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /*** Safe Token ***/\n\n    /**\n     * @notice Gets balance of this contract in terms of the underlying\n     * @dev This excludes the value of the current message, if any\n     * @return The quantity of underlying owned by this contract\n     */\n    function getCashPrior() internal view returns (uint256);\n\n    /**\n     * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.\n     *  This may revert due to insufficient balance or insufficient allowance.\n     */\n    function doTransferIn(\n        address from,\n        uint256 amount,\n        bool isNative\n    ) internal returns (uint256);\n\n    /**\n     * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.\n     *  If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.\n     *  If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.\n     */\n    function doTransferOut(\n        address payable to,\n        uint256 amount,\n        bool isNative\n    ) internal;\n\n    /**\n     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n     * @dev Called by both `transfer` and `transferFrom` internally\n     */\n    function transferTokens(\n        address spender,\n        address src,\n        address dst,\n        uint256 tokens\n    ) internal returns (uint256);\n\n    /**\n     * @notice Get the account's jToken balances\n     */\n    function getJTokenBalanceInternal(address account) internal view returns (uint256);\n\n    /**\n     * @notice User supplies assets into the market and receives jTokens in exchange\n     * @dev Assumes interest has already been accrued up to the current timestamp\n     */\n    function mintFresh(\n        address minter,\n        uint256 mintAmount,\n        bool isNative\n    ) internal returns (uint256, uint256);\n\n    /**\n     * @notice User redeems jTokens in exchange for the underlying asset\n     * @dev Assumes interest has already been accrued up to the current timestamp\n     */\n    function redeemFresh(\n        address payable redeemer,\n        uint256 redeemTokensIn,\n        uint256 redeemAmountIn,\n        bool isNative\n    ) internal returns (uint256);\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another JToken.\n     *  Its absolutely critical to use msg.sender as the seizer jToken and not a parameter.\n     */\n    function seizeInternal(\n        address seizerToken,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) internal returns (uint256);\n\n    /*** Reentrancy Guard ***/\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     */\n    modifier nonReentrant() {\n        require(_notEntered, \"re-entered\");\n        _notEntered = false;\n        _;\n        _notEntered = true; // get a gas-refund post-Istanbul\n    }\n}\n"
    },
    "contracts/PriceOracle/PriceOracle.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"../JToken.sol\";\n\ncontract PriceOracle {\n    /**\n     * @notice Get the underlying price of a jToken asset\n     * @param jToken The jToken to get the underlying price of\n     * @return The underlying asset price mantissa (scaled by 1e18).\n     *  Zero means the price is unavailable.\n     */\n    function getUnderlyingPrice(JToken jToken) external view returns (uint256);\n}\n"
    },
    "contracts/EIP20Interface.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\n/**\n * @title ERC 20 Token Standard Interface\n *  https://eips.ethereum.org/EIPS/eip-20\n */\ninterface EIP20Interface {\n    function name() external view returns (string memory);\n\n    function symbol() external view returns (string memory);\n\n    function decimals() external view returns (uint8);\n\n    /**\n     * @notice Get the total number of tokens in circulation\n     * @return The supply of tokens\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @notice Gets the balance of the specified address\n     * @param owner The address from which the balance will be retrieved\n     * @return The balance\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transfer(address dst, uint256 amount) external returns (bool success);\n\n    /**\n     * @notice Transfer `amount` tokens from `src` to `dst`\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferFrom(\n        address src,\n        address dst,\n        uint256 amount\n    ) external returns (bool success);\n\n    /**\n     * @notice Approve `spender` to transfer up to `amount` from `src`\n     * @dev This will overwrite the approval amount for `spender`\n     *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n     * @param spender The address of the account which may transfer tokens\n     * @param amount The number of tokens that are approved (-1 means infinite)\n     * @return Whether or not the approval succeeded\n     */\n    function approve(address spender, uint256 amount) external returns (bool success);\n\n    /**\n     * @notice Get the current allowance from `owner` for `spender`\n     * @param owner The address of the account which owns the tokens to be spent\n     * @param spender The address of the account which may transfer tokens\n     * @return The number of tokens allowed to be spent (-1 means infinite)\n     */\n    function allowance(address owner, address spender) external view returns (uint256 remaining);\n\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n}\n"
    },
    "contracts/JoetrollerInterface.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JToken.sol\";\nimport \"./JoetrollerStorage.sol\";\n\ncontract JoetrollerInterface {\n    /// @notice Indicator that this is a Joetroller contract (for inspection)\n    bool public constant isJoetroller = true;\n\n    /*** Assets You Are In ***/\n\n    function enterMarkets(address[] calldata jTokens) external returns (uint256[] memory);\n\n    function exitMarket(address jToken) external returns (uint256);\n\n    /*** Policy Hooks ***/\n\n    function mintAllowed(\n        address jToken,\n        address minter,\n        uint256 mintAmount\n    ) external returns (uint256);\n\n    function mintVerify(\n        address jToken,\n        address minter,\n        uint256 mintAmount,\n        uint256 mintTokens\n    ) external;\n\n    function redeemAllowed(\n        address jToken,\n        address redeemer,\n        uint256 redeemTokens\n    ) external returns (uint256);\n\n    function redeemVerify(\n        address jToken,\n        address redeemer,\n        uint256 redeemAmount,\n        uint256 redeemTokens\n    ) external;\n\n    function borrowAllowed(\n        address jToken,\n        address borrower,\n        uint256 borrowAmount\n    ) external returns (uint256);\n\n    function borrowVerify(\n        address jToken,\n        address borrower,\n        uint256 borrowAmount\n    ) external;\n\n    function repayBorrowAllowed(\n        address jToken,\n        address payer,\n        address borrower,\n        uint256 repayAmount\n    ) external returns (uint256);\n\n    function repayBorrowVerify(\n        address jToken,\n        address payer,\n        address borrower,\n        uint256 repayAmount,\n        uint256 borrowerIndex\n    ) external;\n\n    function liquidateBorrowAllowed(\n        address jTokenBorrowed,\n        address jTokenCollateral,\n        address liquidator,\n        address borrower,\n        uint256 repayAmount\n    ) external returns (uint256);\n\n    function liquidateBorrowVerify(\n        address jTokenBorrowed,\n        address jTokenCollateral,\n        address liquidator,\n        address borrower,\n        uint256 repayAmount,\n        uint256 seizeTokens\n    ) external;\n\n    function seizeAllowed(\n        address jTokenCollateral,\n        address jTokenBorrowed,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external returns (uint256);\n\n    function seizeVerify(\n        address jTokenCollateral,\n        address jTokenBorrowed,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external;\n\n    function transferAllowed(\n        address jToken,\n        address src,\n        address dst,\n        uint256 transferTokens\n    ) external returns (uint256);\n\n    function transferVerify(\n        address jToken,\n        address src,\n        address dst,\n        uint256 transferTokens\n    ) external;\n\n    /*** Liquidity/Liquidation Calculations ***/\n\n    function liquidateCalculateSeizeTokens(\n        address jTokenBorrowed,\n        address jTokenCollateral,\n        uint256 repayAmount\n    ) external view returns (uint256, uint256);\n}\n\ninterface JoetrollerInterfaceExtension {\n    function checkMembership(address account, JToken jToken) external view returns (bool);\n\n    function updateJTokenVersion(address jToken, JoetrollerV1Storage.Version version) external;\n\n    function flashloanAllowed(\n        address jToken,\n        address receiver,\n        uint256 amount,\n        bytes calldata params\n    ) external view returns (bool);\n}\n"
    },
    "contracts/JTokenInterfaces.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JoetrollerInterface.sol\";\nimport \"./InterestRateModel.sol\";\nimport \"./ERC3156FlashBorrowerInterface.sol\";\n\ncontract JTokenStorage {\n    /**\n     * @dev Guard variable for re-entrancy checks\n     */\n    bool internal _notEntered;\n\n    /**\n     * @notice EIP-20 token name for this token\n     */\n    string public name;\n\n    /**\n     * @notice EIP-20 token symbol for this token\n     */\n    string public symbol;\n\n    /**\n     * @notice EIP-20 token decimals for this token\n     */\n    uint8 public decimals;\n\n    /**\n     * @notice Maximum borrow rate that can ever be applied (.0005% / sec)\n     */\n\n    uint256 internal constant borrowRateMaxMantissa = 0.0005e16;\n\n    /**\n     * @notice Maximum fraction of interest that can be set aside for reserves\n     */\n    uint256 internal constant reserveFactorMaxMantissa = 1e18;\n\n    /**\n     * @notice Administrator for this contract\n     */\n    address payable public admin;\n\n    /**\n     * @notice Pending administrator for this contract\n     */\n    address payable public pendingAdmin;\n\n    /**\n     * @notice Contract which oversees inter-jToken operations\n     */\n    JoetrollerInterface public joetroller;\n\n    /**\n     * @notice Model which tells what the current interest rate should be\n     */\n    InterestRateModel public interestRateModel;\n\n    /**\n     * @notice Initial exchange rate used when minting the first JTokens (used when totalSupply = 0)\n     */\n    uint256 internal initialExchangeRateMantissa;\n\n    /**\n     * @notice Fraction of interest currently set aside for reserves\n     */\n    uint256 public reserveFactorMantissa;\n\n    /**\n     * @notice Block timestamp that interest was last accrued at\n     */\n    uint256 public accrualBlockTimestamp;\n\n    /**\n     * @notice Accumulator of the total earned interest rate since the opening of the market\n     */\n    uint256 public borrowIndex;\n\n    /**\n     * @notice Total amount of outstanding borrows of the underlying in this market\n     */\n    uint256 public totalBorrows;\n\n    /**\n     * @notice Total amount of reserves of the underlying held in this market\n     */\n    uint256 public totalReserves;\n\n    /**\n     * @notice Total number of tokens in circulation\n     */\n    uint256 public totalSupply;\n\n    /**\n     * @notice Official record of token balances for each account\n     */\n    mapping(address => uint256) internal accountTokens;\n\n    /**\n     * @notice Approved token transfer amounts on behalf of others\n     */\n    mapping(address => mapping(address => uint256)) internal transferAllowances;\n\n    /**\n     * @notice Container for borrow balance information\n     * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action\n     * @member interestIndex Global borrowIndex as of the most recent balance-changing action\n     */\n    struct BorrowSnapshot {\n        uint256 principal;\n        uint256 interestIndex;\n    }\n\n    /**\n     * @notice Mapping of account addresses to outstanding borrow balances\n     */\n    mapping(address => BorrowSnapshot) internal accountBorrows;\n}\n\ncontract JErc20Storage {\n    /**\n     * @notice Underlying asset for this JToken\n     */\n    address public underlying;\n\n    /**\n     * @notice Implementation address for this contract\n     */\n    address public implementation;\n}\n\ncontract JSupplyCapStorage {\n    /**\n     * @notice Internal cash counter for this JToken. Should equal underlying.balanceOf(address(this)) for CERC20.\n     */\n    uint256 public internalCash;\n}\n\ncontract JCollateralCapStorage {\n    /**\n     * @notice Total number of tokens used as collateral in circulation.\n     */\n    uint256 public totalCollateralTokens;\n\n    /**\n     * @notice Record of token balances which could be treated as collateral for each account.\n     *         If collateral cap is not set, the value should be equal to accountTokens.\n     */\n    mapping(address => uint256) public accountCollateralTokens;\n\n    /**\n     * @notice Check if accountCollateralTokens have been initialized.\n     */\n    mapping(address => bool) public isCollateralTokenInit;\n\n    /**\n     * @notice Collateral cap for this JToken, zero for no cap.\n     */\n    uint256 public collateralCap;\n}\n\n/*** Interface ***/\n\ncontract JTokenInterface is JTokenStorage {\n    /**\n     * @notice Indicator that this is a JToken contract (for inspection)\n     */\n    bool public constant isJToken = true;\n\n    /*** Market Events ***/\n\n    /**\n     * @notice Event emitted when interest is accrued\n     */\n    event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);\n\n    /**\n     * @notice Event emitted when tokens are minted\n     */\n    event Mint(address minter, uint256 mintAmount, uint256 mintTokens);\n\n    /**\n     * @notice Event emitted when tokens are redeemed\n     */\n    event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);\n\n    /**\n     * @notice Event emitted when underlying is borrowed\n     */\n    event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);\n\n    /**\n     * @notice Event emitted when a borrow is repaid\n     */\n    event RepayBorrow(\n        address payer,\n        address borrower,\n        uint256 repayAmount,\n        uint256 accountBorrows,\n        uint256 totalBorrows\n    );\n\n    /**\n     * @notice Event emitted when a borrow is liquidated\n     */\n    event LiquidateBorrow(\n        address liquidator,\n        address borrower,\n        uint256 repayAmount,\n        address jTokenCollateral,\n        uint256 seizeTokens\n    );\n\n    /*** Admin Events ***/\n\n    /**\n     * @notice Event emitted when pendingAdmin is changed\n     */\n    event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);\n\n    /**\n     * @notice Event emitted when pendingAdmin is accepted, which means admin is updated\n     */\n    event NewAdmin(address oldAdmin, address newAdmin);\n\n    /**\n     * @notice Event emitted when joetroller is changed\n     */\n    event NewJoetroller(JoetrollerInterface oldJoetroller, JoetrollerInterface newJoetroller);\n\n    /**\n     * @notice Event emitted when interestRateModel is changed\n     */\n    event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);\n\n    /**\n     * @notice Event emitted when the reserve factor is changed\n     */\n    event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);\n\n    /**\n     * @notice Event emitted when the reserves are added\n     */\n    event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);\n\n    /**\n     * @notice Event emitted when the reserves are reduced\n     */\n    event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);\n\n    /**\n     * @notice EIP20 Transfer event\n     */\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    /**\n     * @notice EIP20 Approval event\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    /**\n     * @notice Failure event\n     */\n    event Failure(uint256 error, uint256 info, uint256 detail);\n\n    /*** User Interface ***/\n\n    function transfer(address dst, uint256 amount) external returns (bool);\n\n    function transferFrom(\n        address src,\n        address dst,\n        uint256 amount\n    ) external returns (bool);\n\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    function balanceOf(address owner) external view returns (uint256);\n\n    function balanceOfUnderlying(address owner) external returns (uint256);\n\n    function getAccountSnapshot(address account)\n        external\n        view\n        returns (\n            uint256,\n            uint256,\n            uint256,\n            uint256\n        );\n\n    function borrowRatePerSecond() external view returns (uint256);\n\n    function supplyRatePerSecond() external view returns (uint256);\n\n    function totalBorrowsCurrent() external returns (uint256);\n\n    function borrowBalanceCurrent(address account) external returns (uint256);\n\n    function borrowBalanceStored(address account) public view returns (uint256);\n\n    function exchangeRateCurrent() public returns (uint256);\n\n    function exchangeRateStored() public view returns (uint256);\n\n    function getCash() external view returns (uint256);\n\n    function accrueInterest() public returns (uint256);\n\n    function seize(\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external returns (uint256);\n\n    /*** Admin Functions ***/\n\n    function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256);\n\n    function _acceptAdmin() external returns (uint256);\n\n    function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256);\n\n    function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);\n\n    function _reduceReserves(uint256 reduceAmount) external returns (uint256);\n\n    function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256);\n}\n\ncontract JErc20Interface is JErc20Storage {\n    /*** User Interface ***/\n\n    function mint(uint256 mintAmount) external returns (uint256);\n\n    function redeem(uint256 redeemTokens) external returns (uint256);\n\n    function redeemUnderlying(uint256 redeemAmount) external returns (uint256);\n\n    function borrow(uint256 borrowAmount) external returns (uint256);\n\n    function repayBorrow(uint256 repayAmount) external returns (uint256);\n\n    function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);\n\n    function liquidateBorrow(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) external returns (uint256);\n\n    function _addReserves(uint256 addAmount) external returns (uint256);\n}\n\ncontract JWrappedNativeInterface is JErc20Interface {\n    /**\n     * @notice Flash loan fee ratio\n     */\n    uint256 public constant flashFeeBips = 8;\n\n    /*** Market Events ***/\n\n    /**\n     * @notice Event emitted when a flashloan occured\n     */\n    event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee);\n\n    /*** User Interface ***/\n\n    function mintNative() external payable returns (uint256);\n\n    function redeemNative(uint256 redeemTokens) external returns (uint256);\n\n    function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256);\n\n    function borrowNative(uint256 borrowAmount) external returns (uint256);\n\n    function repayBorrowNative() external payable returns (uint256);\n\n    function repayBorrowBehalfNative(address borrower) external payable returns (uint256);\n\n    function liquidateBorrowNative(address borrower, JTokenInterface jTokenCollateral)\n        external\n        payable\n        returns (uint256);\n\n    function flashLoan(\n        ERC3156FlashBorrowerInterface receiver,\n        address initiator,\n        uint256 amount,\n        bytes calldata data\n    ) external returns (bool);\n\n    function _addReservesNative() external payable returns (uint256);\n}\n\ncontract JCapableErc20Interface is JErc20Interface, JSupplyCapStorage {\n    /**\n     * @notice Flash loan fee ratio\n     */\n    uint256 public constant flashFeeBips = 8;\n\n    /*** Market Events ***/\n\n    /**\n     * @notice Event emitted when a flashloan occured\n     */\n    event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee);\n\n    /*** User Interface ***/\n\n    function gulp() external;\n}\n\ncontract JCollateralCapErc20Interface is JCapableErc20Interface, JCollateralCapStorage {\n    /*** Admin Events ***/\n\n    /**\n     * @notice Event emitted when collateral cap is set\n     */\n    event NewCollateralCap(address token, uint256 newCap);\n\n    /**\n     * @notice Event emitted when user collateral is changed\n     */\n    event UserCollateralChanged(address account, uint256 newCollateralTokens);\n\n    /*** User Interface ***/\n\n    function registerCollateral(address account) external returns (uint256);\n\n    function unregisterCollateral(address account) external;\n\n    function flashLoan(\n        ERC3156FlashBorrowerInterface receiver,\n        address initiator,\n        uint256 amount,\n        bytes calldata data\n    ) external returns (bool);\n\n    /*** Admin Functions ***/\n\n    function _setCollateralCap(uint256 newCollateralCap) external;\n}\n\ncontract JDelegatorInterface {\n    /**\n     * @notice Emitted when implementation is changed\n     */\n    event NewImplementation(address oldImplementation, address newImplementation);\n\n    /**\n     * @notice Called by the admin to update the implementation of the delegator\n     * @param implementation_ The address of the new implementation for delegation\n     * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation\n     * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n     */\n    function _setImplementation(\n        address implementation_,\n        bool allowResign,\n        bytes memory becomeImplementationData\n    ) public;\n}\n\ncontract JDelegateInterface {\n    /**\n     * @notice Called by the delegator on a delegate to initialize it for duty\n     * @dev Should revert if any issues arise which make it unfit for delegation\n     * @param data The encoded bytes data for any initialization\n     */\n    function _becomeImplementation(bytes memory data) public;\n\n    /**\n     * @notice Called by the delegator on a delegate to forfeit its responsibility\n     */\n    function _resignImplementation() public;\n}\n\n/*** External interface ***/\n\n/**\n * @title Flash loan receiver interface\n */\ninterface IFlashloanReceiver {\n    function executeOperation(\n        address sender,\n        address underlying,\n        uint256 amount,\n        uint256 fee,\n        bytes calldata params\n    ) external;\n}\n\ncontract JProtocolSeizeShareStorage {\n    /**\n     * @notice Event emitted when the protocol share of seized collateral is changed\n     */\n    event NewProtocolSeizeShare(uint256 oldProtocolSeizeShareMantissa, uint256 newProtocolSeizeShareMantissa);\n\n    /**\n     * @notice Share of seized collateral that is added to reserves\n     */\n    uint256 public protocolSeizeShareMantissa;\n\n    /**\n     * @notice Maximum fraction of seized collateral that can be set aside for reserves\n     */\n    uint256 internal constant protocolSeizeShareMaxMantissa = 1e18;\n}\n"
    },
    "contracts/ErrorReporter.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\ncontract JoetrollerErrorReporter {\n    enum Error {\n        NO_ERROR,\n        UNAUTHORIZED,\n        JOETROLLER_MISMATCH,\n        INSUFFICIENT_SHORTFALL,\n        INSUFFICIENT_LIQUIDITY,\n        INVALID_CLOSE_FACTOR,\n        INVALID_COLLATERAL_FACTOR,\n        INVALID_LIQUIDATION_INCENTIVE,\n        MARKET_NOT_ENTERED, // no longer possible\n        MARKET_NOT_LISTED,\n        MARKET_ALREADY_LISTED,\n        MATH_ERROR,\n        NONZERO_BORROW_BALANCE,\n        PRICE_ERROR,\n        REJECTION,\n        SNAPSHOT_ERROR,\n        TOO_MANY_ASSETS,\n        TOO_MUCH_REPAY\n    }\n\n    enum FailureInfo {\n        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\n        ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,\n        EXIT_MARKET_BALANCE_OWED,\n        EXIT_MARKET_REJECTION,\n        SET_CLOSE_FACTOR_OWNER_CHECK,\n        SET_CLOSE_FACTOR_VALIDATION,\n        SET_COLLATERAL_FACTOR_OWNER_CHECK,\n        SET_COLLATERAL_FACTOR_NO_EXISTS,\n        SET_COLLATERAL_FACTOR_VALIDATION,\n        SET_COLLATERAL_FACTOR_WITHOUT_PRICE,\n        SET_IMPLEMENTATION_OWNER_CHECK,\n        SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,\n        SET_LIQUIDATION_INCENTIVE_VALIDATION,\n        SET_MAX_ASSETS_OWNER_CHECK,\n        SET_PENDING_ADMIN_OWNER_CHECK,\n        SET_PENDING_IMPLEMENTATION_OWNER_CHECK,\n        SET_PRICE_ORACLE_OWNER_CHECK,\n        SUPPORT_MARKET_EXISTS,\n        SUPPORT_MARKET_OWNER_CHECK,\n        SET_PAUSE_GUARDIAN_OWNER_CHECK\n    }\n\n    /**\n     * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\n     * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\n     **/\n    event Failure(uint256 error, uint256 info, uint256 detail);\n\n    /**\n     * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\n     */\n    function fail(Error err, FailureInfo info) internal returns (uint256) {\n        emit Failure(uint256(err), uint256(info), 0);\n\n        return uint256(err);\n    }\n\n    /**\n     * @dev use this when reporting an opaque error from an upgradeable collaborator contract\n     */\n    function failOpaque(\n        Error err,\n        FailureInfo info,\n        uint256 opaqueError\n    ) internal returns (uint256) {\n        emit Failure(uint256(err), uint256(info), opaqueError);\n\n        return uint256(err);\n    }\n}\n\ncontract TokenErrorReporter {\n    enum Error {\n        NO_ERROR,\n        UNAUTHORIZED,\n        BAD_INPUT,\n        JOETROLLER_REJECTION,\n        JOETROLLER_CALCULATION_ERROR,\n        INTEREST_RATE_MODEL_ERROR,\n        INVALID_ACCOUNT_PAIR,\n        INVALID_CLOSE_AMOUNT_REQUESTED,\n        INVALID_COLLATERAL_FACTOR,\n        MATH_ERROR,\n        MARKET_NOT_FRESH,\n        MARKET_NOT_LISTED,\n        TOKEN_INSUFFICIENT_ALLOWANCE,\n        TOKEN_INSUFFICIENT_BALANCE,\n        TOKEN_INSUFFICIENT_CASH,\n        TOKEN_TRANSFER_IN_FAILED,\n        TOKEN_TRANSFER_OUT_FAILED\n    }\n\n    /*\n     * Note: FailureInfo (but not Error) is kept in alphabetical order\n     *       This is because FailureInfo grows significantly faster, and\n     *       the order of Error has some meaning, while the order of FailureInfo\n     *       is entirely arbitrary.\n     */\n    enum FailureInfo {\n        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\n        ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,\n        BORROW_ACCRUE_INTEREST_FAILED,\n        BORROW_CASH_NOT_AVAILABLE,\n        BORROW_FRESHNESS_CHECK,\n        BORROW_MARKET_NOT_LISTED,\n        BORROW_JOETROLLER_REJECTION,\n        LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,\n        LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,\n        LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,\n        LIQUIDATE_JOETROLLER_REJECTION,\n        LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,\n        LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,\n        LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,\n        LIQUIDATE_FRESHNESS_CHECK,\n        LIQUIDATE_LIQUIDATOR_IS_BORROWER,\n        LIQUIDATE_REPAY_BORROW_FRESH_FAILED,\n        LIQUIDATE_SEIZE_JOETROLLER_REJECTION,\n        LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,\n        LIQUIDATE_SEIZE_TOO_MUCH,\n        MINT_ACCRUE_INTEREST_FAILED,\n        MINT_JOETROLLER_REJECTION,\n        MINT_FRESHNESS_CHECK,\n        MINT_TRANSFER_IN_FAILED,\n        MINT_TRANSFER_IN_NOT_POSSIBLE,\n        REDEEM_ACCRUE_INTEREST_FAILED,\n        REDEEM_JOETROLLER_REJECTION,\n        REDEEM_FRESHNESS_CHECK,\n        REDEEM_TRANSFER_OUT_NOT_POSSIBLE,\n        REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,\n        REDUCE_RESERVES_ADMIN_CHECK,\n        REDUCE_RESERVES_CASH_NOT_AVAILABLE,\n        REDUCE_RESERVES_FRESH_CHECK,\n        REDUCE_RESERVES_VALIDATION,\n        REPAY_BEHALF_ACCRUE_INTEREST_FAILED,\n        REPAY_BORROW_ACCRUE_INTEREST_FAILED,\n        REPAY_BORROW_JOETROLLER_REJECTION,\n        REPAY_BORROW_FRESHNESS_CHECK,\n        REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,\n        SET_COLLATERAL_FACTOR_OWNER_CHECK,\n        SET_COLLATERAL_FACTOR_VALIDATION,\n        SET_JOETROLLER_OWNER_CHECK,\n        SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,\n        SET_INTEREST_RATE_MODEL_FRESH_CHECK,\n        SET_INTEREST_RATE_MODEL_OWNER_CHECK,\n        SET_MAX_ASSETS_OWNER_CHECK,\n        SET_ORACLE_MARKET_NOT_LISTED,\n        SET_PENDING_ADMIN_OWNER_CHECK,\n        SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,\n        SET_RESERVE_FACTOR_ADMIN_CHECK,\n        SET_RESERVE_FACTOR_FRESH_CHECK,\n        SET_RESERVE_FACTOR_BOUNDS_CHECK,\n        TRANSFER_JOETROLLER_REJECTION,\n        TRANSFER_NOT_ALLOWED,\n        ADD_RESERVES_ACCRUE_INTEREST_FAILED,\n        ADD_RESERVES_FRESH_CHECK,\n        ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE,\n        SET_PROTOCOL_SEIZE_SHARE_ACCRUE_INTEREST_FAILED,\n        SET_PROTOCOL_SEIZE_SHARE_ADMIN_CHECK,\n        SET_PROTOCOL_SEIZE_SHARE_FRESH_CHECK,\n        SET_PROTOCOL_SEIZE_SHARE_BOUNDS_CHECK\n    }\n\n    /**\n     * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\n     * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\n     **/\n    event Failure(uint256 error, uint256 info, uint256 detail);\n\n    /**\n     * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\n     */\n    function fail(Error err, FailureInfo info) internal returns (uint256) {\n        emit Failure(uint256(err), uint256(info), 0);\n\n        return uint256(err);\n    }\n\n    /**\n     * @dev use this when reporting an opaque error from an upgradeable collaborator contract\n     */\n    function failOpaque(\n        Error err,\n        FailureInfo info,\n        uint256 opaqueError\n    ) internal returns (uint256) {\n        emit Failure(uint256(err), uint256(info), opaqueError);\n\n        return uint256(err);\n    }\n}\n"
    },
    "contracts/EIP20NonStandardInterface.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\n/**\n * @title EIP20NonStandardInterface\n * @dev Version of ERC20 with no return values for `transfer` and `transferFrom`\n *  See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n */\ninterface EIP20NonStandardInterface {\n    /**\n     * @notice Get the total number of tokens in circulation\n     * @return The supply of tokens\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @notice Gets the balance of the specified address\n     * @param owner The address from which the balance will be retrieved\n     * @return The balance\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    ///\n    /// !!!!!!!!!!!!!!\n    /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification\n    /// !!!!!!!!!!!!!!\n    ///\n\n    /**\n     * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     */\n    function transfer(address dst, uint256 amount) external;\n\n    ///\n    /// !!!!!!!!!!!!!!\n    /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification\n    /// !!!!!!!!!!!!!!\n    ///\n\n    /**\n     * @notice Transfer `amount` tokens from `src` to `dst`\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     */\n    function transferFrom(\n        address src,\n        address dst,\n        uint256 amount\n    ) external;\n\n    /**\n     * @notice Approve `spender` to transfer up to `amount` from `src`\n     * @dev This will overwrite the approval amount for `spender`\n     *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n     * @param spender The address of the account which may transfer tokens\n     * @param amount The number of tokens that are approved\n     * @return Whether or not the approval succeeded\n     */\n    function approve(address spender, uint256 amount) external returns (bool success);\n\n    /**\n     * @notice Get the current allowance from `owner` for `spender`\n     * @param owner The address of the account which owns the tokens to be spent\n     * @param spender The address of the account which may transfer tokens\n     * @return The number of tokens allowed to be spent\n     */\n    function allowance(address owner, address spender) external view returns (uint256 remaining);\n\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n}\n"
    },
    "contracts/InterestRateModel.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\n/**\n * @title Compound's InterestRateModel Interface\n * @author Compound\n */\ncontract InterestRateModel {\n    /// @notice Indicator that this is an InterestRateModel contract (for inspection)\n    bool public constant isInterestRateModel = true;\n\n    /**\n     * @notice Calculates the current borrow interest rate per sec\n     * @param cash The total amount of cash the market has\n     * @param borrows The total amount of borrows the market has outstanding\n     * @param reserves The total amnount of reserves the market has\n     * @return The borrow rate per sec (as a percentage, and scaled by 1e18)\n     */\n    function getBorrowRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves\n    ) external view returns (uint256);\n\n    /**\n     * @notice Calculates the current supply interest rate per sec\n     * @param cash The total amount of cash the market has\n     * @param borrows The total amount of borrows the market has outstanding\n     * @param reserves The total amnount of reserves the market has\n     * @param reserveFactorMantissa The current reserve factor the market has\n     * @return The supply rate per sec (as a percentage, and scaled by 1e18)\n     */\n    function getSupplyRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves,\n        uint256 reserveFactorMantissa\n    ) external view returns (uint256);\n}\n"
    },
    "contracts/JoetrollerStorage.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JToken.sol\";\nimport \"./PriceOracle/PriceOracle.sol\";\n\ncontract UnitrollerAdminStorage {\n    /**\n     * @notice Administrator for this contract\n     */\n    address public admin;\n\n    /**\n     * @notice Pending administrator for this contract\n     */\n    address public pendingAdmin;\n\n    /**\n     * @notice Active brains of Unitroller\n     */\n    address public implementation;\n\n    /**\n     * @notice Pending brains of Unitroller\n     */\n    address public pendingImplementation;\n}\n\ncontract JoetrollerV1Storage is UnitrollerAdminStorage {\n    /**\n     * @notice Oracle which gives the price of any given asset\n     */\n    PriceOracle public oracle;\n\n    /**\n     * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow\n     */\n    uint256 public closeFactorMantissa;\n\n    /**\n     * @notice Multiplier representing the discount on collateral that a liquidator receives\n     */\n    uint256 public liquidationIncentiveMantissa;\n\n    /**\n     * @notice Per-account mapping of \"assets you are in\"\n     */\n    mapping(address => JToken[]) public accountAssets;\n\n    enum Version {\n        VANILLA,\n        COLLATERALCAP,\n        WRAPPEDNATIVE\n    }\n\n    struct Market {\n        /// @notice Whether or not this market is listed\n        bool isListed;\n        /**\n         * @notice Multiplier representing the most one can borrow against their collateral in this market.\n         *  For instance, 0.9 to allow borrowing 90% of collateral value.\n         *  Must be between 0 and 1, and stored as a mantissa.\n         */\n        uint256 collateralFactorMantissa;\n        /// @notice Per-market mapping of \"accounts in this asset\"\n        mapping(address => bool) accountMembership;\n        /// @notice JToken version\n        Version version;\n    }\n\n    /**\n     * @notice Official mapping of jTokens -> Market metadata\n     * @dev Used e.g. to determine if a market is supported\n     */\n    mapping(address => Market) public markets;\n\n    /**\n     * @notice The Pause Guardian can pause certain actions as a safety mechanism.\n     *  Actions which allow users to remove their own assets cannot be paused.\n     *  Liquidation / seizing / transfer can only be paused globally, not by market.\n     */\n    address public pauseGuardian;\n    bool public _mintGuardianPaused;\n    bool public _borrowGuardianPaused;\n    bool public transferGuardianPaused;\n    bool public seizeGuardianPaused;\n    mapping(address => bool) public mintGuardianPaused;\n    mapping(address => bool) public borrowGuardianPaused;\n\n    /// @notice A list of all markets\n    JToken[] public allMarkets;\n\n    // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.\n    address public borrowCapGuardian;\n\n    // @notice Borrow caps enforced by borrowAllowed for each jToken address. Defaults to zero which corresponds to unlimited borrowing.\n    mapping(address => uint256) public borrowCaps;\n\n    // @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market.\n    address public supplyCapGuardian;\n\n    // @notice Supply caps enforced by mintAllowed for each jToken address. Defaults to zero which corresponds to unlimited supplying.\n    mapping(address => uint256) public supplyCaps;\n\n    // @notice creditLimits allowed specific protocols to borrow and repay without collateral.\n    mapping(address => uint256) public creditLimits;\n\n    // @notice flashloanGuardianPaused can pause flash loan as a safety mechanism.\n    mapping(address => bool) public flashloanGuardianPaused;\n\n    // @notice rewardDistributor The module that handles reward distribution.\n    address payable public rewardDistributor;\n}\n"
    },
    "contracts/ERC3156FlashBorrowerInterface.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\ninterface ERC3156FlashBorrowerInterface {\n    /**\n     * @dev Receive a flash loan.\n     * @param initiator The initiator of the loan.\n     * @param token The loan currency.\n     * @param amount The amount of tokens lent.\n     * @param fee The additional amount of tokens to repay.\n     * @param data Arbitrary data structure, intended to contain user-defined parameters.\n     * @return The keccak256 hash of \"ERC3156FlashBorrower.onFlashLoan\"\n     */\n    function onFlashLoan(\n        address initiator,\n        address token,\n        uint256 amount,\n        uint256 fee,\n        bytes calldata data\n    ) external returns (bytes32);\n}\n"
    },
    "contracts/Lens/JoeLensView.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\npragma experimental ABIEncoderV2;\n\nimport \"../JErc20.sol\";\nimport \"../Joetroller.sol\";\nimport \"../JToken.sol\";\nimport \"../PriceOracle/PriceOracle.sol\";\nimport \"../EIP20Interface.sol\";\nimport \"../Exponential.sol\";\n\ninterface JJLPInterface {\n    function claimJoe(address) external returns (uint256);\n}\n\ninterface JJTokenInterface {\n    function claimJoe(address) external returns (uint256);\n}\n\n/**\n * @notice This is a version of JoeLens that only contains view functions.\n */\ncontract JoeLensView is Exponential {\n    string public nativeSymbol;\n\n    constructor(string memory _nativeSymbol) public {\n        nativeSymbol = _nativeSymbol;\n    }\n\n    /*** Market info functions ***/\n    struct JTokenMetadata {\n        address jToken;\n        uint256 exchangeRateStored;\n        uint256 supplyRatePerSecond;\n        uint256 borrowRatePerSecond;\n        uint256 reserveFactorMantissa;\n        uint256 totalBorrows;\n        uint256 totalReserves;\n        uint256 totalSupply;\n        uint256 totalCash;\n        uint256 totalCollateralTokens;\n        bool isListed;\n        uint256 collateralFactorMantissa;\n        address underlyingAssetAddress;\n        uint256 jTokenDecimals;\n        uint256 underlyingDecimals;\n        JoetrollerV1Storage.Version version;\n        uint256 collateralCap;\n        uint256 underlyingPrice;\n        bool supplyPaused;\n        bool borrowPaused;\n        uint256 supplyCap;\n        uint256 borrowCap;\n    }\n\n    function jTokenMetadataAll(JToken[] calldata jTokens) external view returns (JTokenMetadata[] memory) {\n        uint256 jTokenCount = jTokens.length;\n        require(jTokenCount > 0, \"invalid input\");\n        JTokenMetadata[] memory res = new JTokenMetadata[](jTokenCount);\n        Joetroller joetroller = Joetroller(address(jTokens[0].joetroller()));\n        PriceOracle priceOracle = joetroller.oracle();\n        for (uint256 i = 0; i < jTokenCount; i++) {\n            require(address(joetroller) == address(jTokens[i].joetroller()), \"mismatch joetroller\");\n            res[i] = jTokenMetadataInternal(jTokens[i], joetroller, priceOracle);\n        }\n        return res;\n    }\n\n    function jTokenMetadata(JToken jToken) public view returns (JTokenMetadata memory) {\n        Joetroller joetroller = Joetroller(address(jToken.joetroller()));\n        PriceOracle priceOracle = joetroller.oracle();\n        return jTokenMetadataInternal(jToken, joetroller, priceOracle);\n    }\n\n    function jTokenMetadataInternal(\n        JToken jToken,\n        Joetroller joetroller,\n        PriceOracle priceOracle\n    ) internal view returns (JTokenMetadata memory) {\n        uint256 exchangeRateStored = jToken.exchangeRateStored();\n        (bool isListed, uint256 collateralFactorMantissa, JoetrollerV1Storage.Version version) = joetroller.markets(\n            address(jToken)\n        );\n        address underlyingAssetAddress;\n        uint256 underlyingDecimals;\n        uint256 collateralCap;\n        uint256 totalCollateralTokens;\n\n        if (compareStrings(jToken.symbol(), nativeSymbol)) {\n            underlyingAssetAddress = address(0);\n            underlyingDecimals = 18;\n        } else {\n            JErc20 jErc20 = JErc20(address(jToken));\n            underlyingAssetAddress = jErc20.underlying();\n            underlyingDecimals = EIP20Interface(jErc20.underlying()).decimals();\n        }\n\n        if (version == JoetrollerV1Storage.Version.COLLATERALCAP) {\n            collateralCap = JCollateralCapErc20Interface(address(jToken)).collateralCap();\n            totalCollateralTokens = JCollateralCapErc20Interface(address(jToken)).totalCollateralTokens();\n        }\n\n        return\n            JTokenMetadata({\n                jToken: address(jToken),\n                exchangeRateStored: exchangeRateStored,\n                supplyRatePerSecond: jToken.supplyRatePerSecond(),\n                borrowRatePerSecond: jToken.borrowRatePerSecond(),\n                reserveFactorMantissa: jToken.reserveFactorMantissa(),\n                totalBorrows: jToken.totalBorrows(),\n                totalReserves: jToken.totalReserves(),\n                totalSupply: jToken.totalSupply(),\n                totalCash: jToken.getCash(),\n                totalCollateralTokens: totalCollateralTokens,\n                isListed: isListed,\n                collateralFactorMantissa: collateralFactorMantissa,\n                underlyingAssetAddress: underlyingAssetAddress,\n                jTokenDecimals: jToken.decimals(),\n                underlyingDecimals: underlyingDecimals,\n                version: version,\n                collateralCap: collateralCap,\n                underlyingPrice: priceOracle.getUnderlyingPrice(jToken),\n                supplyPaused: joetroller.mintGuardianPaused(address(jToken)),\n                borrowPaused: joetroller.borrowGuardianPaused(address(jToken)),\n                supplyCap: joetroller.supplyCaps(address(jToken)),\n                borrowCap: joetroller.borrowCaps(address(jToken))\n            });\n    }\n\n    /*** Account JToken info functions ***/\n\n    struct JTokenBalances {\n        address jToken;\n        uint256 jTokenBalance; // Same as collateral balance - the number of jTokens held\n        uint256 balanceOfUnderlyingStored; // Balance of underlying asset supplied by. Accrue interest is not called.\n        uint256 supplyValueUSD;\n        uint256 collateralValueUSD; // This is supplyValueUSD multiplied by collateral factor\n        uint256 borrowBalanceStored; // Borrow balance without accruing interest\n        uint256 borrowValueUSD;\n        uint256 underlyingTokenBalance; // Underlying balance current held in user's wallet\n        uint256 underlyingTokenAllowance;\n        bool collateralEnabled;\n    }\n\n    function jTokenBalancesAll(JToken[] memory jTokens, address account) public view returns (JTokenBalances[] memory) {\n        uint256 jTokenCount = jTokens.length;\n        JTokenBalances[] memory res = new JTokenBalances[](jTokenCount);\n        for (uint256 i = 0; i < jTokenCount; i++) {\n            res[i] = jTokenBalances(jTokens[i], account);\n        }\n        return res;\n    }\n\n    function jTokenBalances(JToken jToken, address account) public view returns (JTokenBalances memory) {\n        JTokenBalances memory vars;\n        Joetroller joetroller = Joetroller(address(jToken.joetroller()));\n\n        vars.jToken = address(jToken);\n        vars.collateralEnabled = joetroller.checkMembership(account, jToken);\n\n        if (compareStrings(jToken.symbol(), nativeSymbol)) {\n            vars.underlyingTokenBalance = account.balance;\n            vars.underlyingTokenAllowance = account.balance;\n        } else {\n            JErc20 jErc20 = JErc20(address(jToken));\n            EIP20Interface underlying = EIP20Interface(jErc20.underlying());\n            vars.underlyingTokenBalance = underlying.balanceOf(account);\n            vars.underlyingTokenAllowance = underlying.allowance(account, address(jToken));\n        }\n\n        uint256 exchangeRateStored;\n        (, vars.jTokenBalance, vars.borrowBalanceStored, exchangeRateStored) = jToken.getAccountSnapshot(account);\n\n        Exp memory exchangeRate = Exp({mantissa: exchangeRateStored});\n        vars.balanceOfUnderlyingStored = mul_ScalarTruncate(exchangeRate, vars.jTokenBalance);\n        PriceOracle priceOracle = joetroller.oracle();\n        uint256 underlyingPrice = priceOracle.getUnderlyingPrice(jToken);\n\n        (, uint256 collateralFactorMantissa, ) = joetroller.markets(address(jToken));\n\n        Exp memory supplyValueInUnderlying = Exp({mantissa: vars.balanceOfUnderlyingStored});\n        vars.supplyValueUSD = mul_ScalarTruncate(supplyValueInUnderlying, underlyingPrice);\n\n        Exp memory collateralFactor = Exp({mantissa: collateralFactorMantissa});\n        vars.collateralValueUSD = mul_ScalarTruncate(collateralFactor, vars.supplyValueUSD);\n\n        Exp memory borrowBalance = Exp({mantissa: vars.borrowBalanceStored});\n        vars.borrowValueUSD = mul_ScalarTruncate(borrowBalance, underlyingPrice);\n\n        return vars;\n    }\n\n    struct AccountLimits {\n        JToken[] markets;\n        uint256 liquidity;\n        uint256 shortfall;\n        uint256 totalCollateralValueUSD;\n        uint256 totalBorrowValueUSD;\n        uint256 healthFactor;\n    }\n\n    function getAccountLimits(Joetroller joetroller, address account) public view returns (AccountLimits memory) {\n        AccountLimits memory vars;\n        uint256 errorCode;\n\n        (errorCode, vars.liquidity, vars.shortfall) = joetroller.getAccountLiquidity(account);\n        require(errorCode == 0, \"Can't get account liquidity\");\n\n        vars.markets = joetroller.getAssetsIn(account);\n        JTokenBalances[] memory jTokenBalancesList = jTokenBalancesAll(vars.markets, account);\n        for (uint256 i = 0; i < jTokenBalancesList.length; i++) {\n            vars.totalCollateralValueUSD = add_(vars.totalCollateralValueUSD, jTokenBalancesList[i].collateralValueUSD);\n            vars.totalBorrowValueUSD = add_(vars.totalBorrowValueUSD, jTokenBalancesList[i].borrowValueUSD);\n        }\n\n        Exp memory totalBorrows = Exp({mantissa: vars.totalBorrowValueUSD});\n\n        vars.healthFactor = vars.totalCollateralValueUSD == 0 ? 0 : vars.totalBorrowValueUSD > 0\n            ? div_(vars.totalCollateralValueUSD, totalBorrows)\n            : 100;\n\n        return vars;\n    }\n\n    function compareStrings(string memory a, string memory b) internal pure returns (bool) {\n        return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));\n    }\n}\n"
    },
    "contracts/Joetroller.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\npragma experimental ABIEncoderV2;\n\nimport \"./JToken.sol\";\nimport \"./EIP20Interface.sol\";\nimport \"./ErrorReporter.sol\";\nimport \"./Exponential.sol\";\nimport \"./PriceOracle/PriceOracle.sol\";\nimport \"./JoetrollerInterface.sol\";\nimport \"./JoetrollerStorage.sol\";\nimport \"./RewardDistributor.sol\";\nimport \"./Unitroller.sol\";\n\n/**\n * @title Compound's Joetroller Contract\n * @author Compound (modified by Cream)\n */\ncontract Joetroller is JoetrollerV1Storage, JoetrollerInterface, JoetrollerErrorReporter, Exponential {\n    /// @notice Emitted when an admin supports a market\n    event MarketListed(JToken jToken);\n\n    /// @notice Emitted when an admin delists a market\n    event MarketDelisted(JToken jToken);\n\n    /// @notice Emitted when an account enters a market\n    event MarketEntered(JToken jToken, address account);\n\n    /// @notice Emitted when an account exits a market\n    event MarketExited(JToken jToken, address account);\n\n    /// @notice Emitted when close factor is changed by admin\n    event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa);\n\n    /// @notice Emitted when a collateral factor is changed by admin\n    event NewCollateralFactor(JToken jToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa);\n\n    /// @notice Emitted when liquidation incentive is changed by admin\n    event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa);\n\n    /// @notice Emitted when price oracle is changed\n    event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);\n\n    /// @notice Emitted when pause guardian is changed\n    event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);\n\n    /// @notice Emitted when an action is paused globally\n    event ActionPaused(string action, bool pauseState);\n\n    /// @notice Emitted when an action is paused on a market\n    event ActionPaused(JToken jToken, string action, bool pauseState);\n\n    /// @notice Emitted when borrow cap for a jToken is changed\n    event NewBorrowCap(JToken indexed jToken, uint256 newBorrowCap);\n\n    /// @notice Emitted when borrow cap guardian is changed\n    event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);\n\n    /// @notice Emitted when supply cap for a jToken is changed\n    event NewSupplyCap(JToken indexed jToken, uint256 newSupplyCap);\n\n    /// @notice Emitted when supply cap guardian is changed\n    event NewSupplyCapGuardian(address oldSupplyCapGuardian, address newSupplyCapGuardian);\n\n    /// @notice Emitted when protocol's credit limit has changed\n    event CreditLimitChanged(address protocol, uint256 creditLimit);\n\n    /// @notice Emitted when jToken version is changed\n    event NewJTokenVersion(JToken jToken, Version oldVersion, Version newVersion);\n\n    // No collateralFactorMantissa may exceed this value\n    uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9\n\n    constructor() public {\n        admin = msg.sender;\n    }\n\n    /**\n     * @notice Return all of the markets\n     * @dev The automatic getter may be used to access an individual market.\n     * @return The list of market addresses\n     */\n    function getAllMarkets() public view returns (JToken[] memory) {\n        return allMarkets;\n    }\n\n    function getBlockTimestamp() public view returns (uint256) {\n        return block.timestamp;\n    }\n\n    /*** Assets You Are In ***/\n\n    /**\n     * @notice Returns the assets an account has entered\n     * @param account The address of the account to pull assets for\n     * @return A dynamic list with the assets the account has entered\n     */\n    function getAssetsIn(address account) external view returns (JToken[] memory) {\n        JToken[] memory assetsIn = accountAssets[account];\n\n        return assetsIn;\n    }\n\n    /**\n     * @notice Returns whether the given account is entered in the given asset\n     * @param account The address of the account to check\n     * @param jToken The jToken to check\n     * @return True if the account is in the asset, otherwise false.\n     */\n    function checkMembership(address account, JToken jToken) external view returns (bool) {\n        return markets[address(jToken)].accountMembership[account];\n    }\n\n    /**\n     * @notice Add assets to be included in account liquidity calculation\n     * @param jTokens The list of addresses of the jToken markets to be enabled\n     * @return Success indicator for whether each corresponding market was entered\n     */\n    function enterMarkets(address[] memory jTokens) public returns (uint256[] memory) {\n        uint256 len = jTokens.length;\n\n        uint256[] memory results = new uint256[](len);\n        for (uint256 i = 0; i < len; i++) {\n            JToken jToken = JToken(jTokens[i]);\n\n            results[i] = uint256(addToMarketInternal(jToken, msg.sender));\n        }\n\n        return results;\n    }\n\n    /**\n     * @notice Add the market to the borrower's \"assets in\" for liquidity calculations\n     * @param jToken The market to enter\n     * @param borrower The address of the account to modify\n     * @return Success indicator for whether the market was entered\n     */\n    function addToMarketInternal(JToken jToken, address borrower) internal returns (Error) {\n        Market storage marketToJoin = markets[address(jToken)];\n\n        if (!marketToJoin.isListed) {\n            // market is not listed, cannot join\n            return Error.MARKET_NOT_LISTED;\n        }\n\n        if (marketToJoin.version == Version.COLLATERALCAP) {\n            // register collateral for the borrower if the token is CollateralCap version.\n            JCollateralCapErc20Interface(address(jToken)).registerCollateral(borrower);\n        }\n\n        if (marketToJoin.accountMembership[borrower] == true) {\n            // already joined\n            return Error.NO_ERROR;\n        }\n\n        // survived the gauntlet, add to list\n        // NOTE: we store these somewhat redundantly as a significant optimization\n        //  this avoids having to iterate through the list for the most common use cases\n        //  that is, only when we need to perform liquidity checks\n        //  and not whenever we want to check if an account is in a particular market\n        marketToJoin.accountMembership[borrower] = true;\n        accountAssets[borrower].push(jToken);\n\n        emit MarketEntered(jToken, borrower);\n\n        return Error.NO_ERROR;\n    }\n\n    /**\n     * @notice Removes asset from sender's account liquidity calculation\n     * @dev Sender must not have an outstanding borrow balance in the asset,\n     *  or be providing necessary collateral for an outstanding borrow.\n     * @param jTokenAddress The address of the asset to be removed\n     * @return Whether or not the account successfully exited the market\n     */\n    function exitMarket(address jTokenAddress) external returns (uint256) {\n        JToken jToken = JToken(jTokenAddress);\n        /* Get sender tokensHeld and amountOwed underlying from the jToken */\n        (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = jToken.getAccountSnapshot(msg.sender);\n        require(oErr == 0, \"exitMarket: getAccountSnapshot failed\"); // semi-opaque error code\n\n        /* Fail if the sender has a borrow balance */\n        if (amountOwed != 0) {\n            return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);\n        }\n\n        /* Fail if the sender is not permitted to redeem all of their tokens */\n        uint256 allowed = redeemAllowedInternal(jTokenAddress, msg.sender, tokensHeld);\n        if (allowed != 0) {\n            return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);\n        }\n\n        Market storage marketToExit = markets[jTokenAddress];\n\n        if (marketToExit.version == Version.COLLATERALCAP) {\n            JCollateralCapErc20Interface(jTokenAddress).unregisterCollateral(msg.sender);\n        }\n\n        /* Return true if the sender is not already ‘in’ the market */\n        if (!marketToExit.accountMembership[msg.sender]) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Set jToken account membership to false */\n        delete marketToExit.accountMembership[msg.sender];\n\n        /* Delete jToken from the account’s list of assets */\n        // load into memory for faster iteration\n        JToken[] memory userAssetList = accountAssets[msg.sender];\n        uint256 len = userAssetList.length;\n        uint256 assetIndex = len;\n        for (uint256 i = 0; i < len; i++) {\n            if (userAssetList[i] == jToken) {\n                assetIndex = i;\n                break;\n            }\n        }\n\n        // We *must* have found the asset in the list or our redundant data structure is broken\n        assert(assetIndex < len);\n\n        // copy last item in list to location of item to be removed, reduce length by 1\n        JToken[] storage storedList = accountAssets[msg.sender];\n        if (assetIndex != storedList.length - 1) {\n            storedList[assetIndex] = storedList[storedList.length - 1];\n        }\n        storedList.length--;\n\n        emit MarketExited(jToken, msg.sender);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Return whether a specific market is listed or not\n     * @param jTokenAddress The address of the asset to be checked\n     * @return Whether or not the market is listed\n     */\n    function isMarketListed(address jTokenAddress) public view returns (bool) {\n        return markets[jTokenAddress].isListed;\n    }\n\n    /*** Policy Hooks ***/\n\n    /**\n     * @notice Checks if the account should be allowed to mint tokens in the given market\n     * @param jToken The market to verify the mint against\n     * @param minter The account which would get the minted tokens\n     * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens\n     * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n     */\n    function mintAllowed(\n        address jToken,\n        address minter,\n        uint256 mintAmount\n    ) external returns (uint256) {\n        // Pausing is a very serious situation - we revert to sound the alarms\n        require(!mintGuardianPaused[jToken], \"mint is paused\");\n        require(!isCreditAccount(minter), \"credit account cannot mint\");\n\n        if (!isMarketListed(jToken)) {\n            return uint256(Error.MARKET_NOT_LISTED);\n        }\n\n        uint256 supplyCap = supplyCaps[jToken];\n        // Supply cap of 0 corresponds to unlimited supplying\n        if (supplyCap != 0) {\n            uint256 totalCash = JToken(jToken).getCash();\n            uint256 totalBorrows = JToken(jToken).totalBorrows();\n            uint256 totalReserves = JToken(jToken).totalReserves();\n            // totalSupplies = totalCash + totalBorrows - totalReserves\n            (MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves);\n            require(mathErr == MathError.NO_ERROR, \"totalSupplies failed\");\n\n            uint256 nextTotalSupplies = add_(totalSupplies, mintAmount);\n            require(nextTotalSupplies < supplyCap, \"market supply cap reached\");\n        }\n\n        // Keep the flywheel moving\n        RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, minter);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Validates mint and reverts on rejection. May emit logs.\n     * @param jToken Asset being minted\n     * @param minter The address minting the tokens\n     * @param actualMintAmount The amount of the underlying asset being minted\n     * @param mintTokens The number of tokens being minted\n     */\n    function mintVerify(\n        address jToken,\n        address minter,\n        uint256 actualMintAmount,\n        uint256 mintTokens\n    ) external {\n        // Shh - currently unused\n        jToken;\n        minter;\n        actualMintAmount;\n        mintTokens;\n\n        // Shh - we don't ever want this hook to be marked pure\n        if (false) {\n            closeFactorMantissa = closeFactorMantissa;\n        }\n    }\n\n    /**\n     * @notice Checks if the account should be allowed to redeem tokens in the given market\n     * @param jToken The market to verify the redeem against\n     * @param redeemer The account which would redeem the tokens\n     * @param redeemTokens The number of jTokens to exchange for the underlying asset in the market\n     * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n     */\n    function redeemAllowed(\n        address jToken,\n        address redeemer,\n        uint256 redeemTokens\n    ) external returns (uint256) {\n        uint256 allowed = redeemAllowedInternal(jToken, redeemer, redeemTokens);\n        if (allowed != uint256(Error.NO_ERROR)) {\n            return allowed;\n        }\n\n        // Keep the flywheel going\n        RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, redeemer);\n        return uint256(Error.NO_ERROR);\n    }\n\n    function redeemAllowedInternal(\n        address jToken,\n        address redeemer,\n        uint256 redeemTokens\n    ) internal view returns (uint256) {\n        if (!isMarketListed(jToken)) {\n            return uint256(Error.MARKET_NOT_LISTED);\n        }\n\n        /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */\n        if (!markets[jToken].accountMembership[redeemer]) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */\n        (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(\n            redeemer,\n            JToken(jToken),\n            redeemTokens,\n            0\n        );\n        if (err != Error.NO_ERROR) {\n            return uint256(err);\n        }\n        if (shortfall > 0) {\n            return uint256(Error.INSUFFICIENT_LIQUIDITY);\n        }\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Validates redeem and reverts on rejection. May emit logs.\n     * @param jToken Asset being redeemed\n     * @param redeemer The address redeeming the tokens\n     * @param redeemAmount The amount of the underlying asset being redeemed\n     * @param redeemTokens The number of tokens being redeemed\n     */\n    function redeemVerify(\n        address jToken,\n        address redeemer,\n        uint256 redeemAmount,\n        uint256 redeemTokens\n    ) external {\n        // Shh - currently unused\n        jToken;\n        redeemer;\n\n        // Require tokens is zero or amount is also zero\n        if (redeemTokens == 0 && redeemAmount > 0) {\n            revert(\"redeemTokens zero\");\n        }\n    }\n\n    /**\n     * @notice Checks if the account should be allowed to borrow the underlying asset of the given market\n     * @param jToken The market to verify the borrow against\n     * @param borrower The account which would borrow the asset\n     * @param borrowAmount The amount of underlying the account would borrow\n     * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n     */\n    function borrowAllowed(\n        address jToken,\n        address borrower,\n        uint256 borrowAmount\n    ) external returns (uint256) {\n        // Pausing is a very serious situation - we revert to sound the alarms\n        require(!borrowGuardianPaused[jToken], \"borrow is paused\");\n\n        if (!isMarketListed(jToken)) {\n            return uint256(Error.MARKET_NOT_LISTED);\n        }\n\n        if (!markets[jToken].accountMembership[borrower]) {\n            // only jTokens may call borrowAllowed if borrower not in market\n            require(msg.sender == jToken, \"sender must be jToken\");\n\n            // attempt to add borrower to the market\n            Error err = addToMarketInternal(JToken(jToken), borrower);\n            if (err != Error.NO_ERROR) {\n                return uint256(err);\n            }\n\n            // it should be impossible to break the important invariant\n            assert(markets[jToken].accountMembership[borrower]);\n        }\n\n        if (oracle.getUnderlyingPrice(JToken(jToken)) == 0) {\n            return uint256(Error.PRICE_ERROR);\n        }\n\n        uint256 borrowCap = borrowCaps[jToken];\n        // Borrow cap of 0 corresponds to unlimited borrowing\n        if (borrowCap != 0) {\n            uint256 totalBorrows = JToken(jToken).totalBorrows();\n            uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount);\n            require(nextTotalBorrows < borrowCap, \"market borrow cap reached\");\n        }\n\n        (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(\n            borrower,\n            JToken(jToken),\n            0,\n            borrowAmount\n        );\n        if (err != Error.NO_ERROR) {\n            return uint256(err);\n        }\n        if (shortfall > 0) {\n            return uint256(Error.INSUFFICIENT_LIQUIDITY);\n        }\n\n        // Keep the flywheel going\n        Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()});\n        RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Validates borrow and reverts on rejection. May emit logs.\n     * @param jToken Asset whose underlying is being borrowed\n     * @param borrower The address borrowing the underlying\n     * @param borrowAmount The amount of the underlying asset requested to borrow\n     */\n    function borrowVerify(\n        address jToken,\n        address borrower,\n        uint256 borrowAmount\n    ) external {\n        // Shh - currently unused\n        jToken;\n        borrower;\n        borrowAmount;\n\n        // Shh - we don't ever want this hook to be marked pure\n        if (false) {\n            closeFactorMantissa = closeFactorMantissa;\n        }\n    }\n\n    /**\n     * @notice Checks if the account should be allowed to repay a borrow in the given market\n     * @param jToken The market to verify the repay against\n     * @param payer The account which would repay the asset\n     * @param borrower The account which borrowed the asset\n     * @param repayAmount The amount of the underlying asset the account would repay\n     * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n     */\n    function repayBorrowAllowed(\n        address jToken,\n        address payer,\n        address borrower,\n        uint256 repayAmount\n    ) external returns (uint256) {\n        // Shh - currently unused\n        payer;\n        borrower;\n        repayAmount;\n\n        if (!isMarketListed(jToken)) {\n            return uint256(Error.MARKET_NOT_LISTED);\n        }\n\n        // Keep the flywheel going\n        Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()});\n        RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex);\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Validates repayBorrow and reverts on rejection. May emit logs.\n     * @param jToken Asset being repaid\n     * @param payer The address repaying the borrow\n     * @param borrower The address of the borrower\n     * @param actualRepayAmount The amount of underlying being repaid\n     */\n    function repayBorrowVerify(\n        address jToken,\n        address payer,\n        address borrower,\n        uint256 actualRepayAmount,\n        uint256 borrowerIndex\n    ) external {\n        // Shh - currently unused\n        jToken;\n        payer;\n        borrower;\n        actualRepayAmount;\n        borrowerIndex;\n\n        // Shh - we don't ever want this hook to be marked pure\n        if (false) {\n            closeFactorMantissa = closeFactorMantissa;\n        }\n    }\n\n    /**\n     * @notice Checks if the liquidation should be allowed to occur\n     * @param jTokenBorrowed Asset which was borrowed by the borrower\n     * @param jTokenCollateral Asset which was used as collateral and will be seized\n     * @param liquidator The address repaying the borrow and seizing the collateral\n     * @param borrower The address of the borrower\n     * @param repayAmount The amount of underlying being repaid\n     */\n    function liquidateBorrowAllowed(\n        address jTokenBorrowed,\n        address jTokenCollateral,\n        address liquidator,\n        address borrower,\n        uint256 repayAmount\n    ) external returns (uint256) {\n        require(!isCreditAccount(borrower), \"cannot liquidate credit account\");\n\n        // Shh - currently unused\n        liquidator;\n\n        if (!isMarketListed(jTokenBorrowed) || !isMarketListed(jTokenCollateral)) {\n            return uint256(Error.MARKET_NOT_LISTED);\n        }\n\n        /* The borrower must have shortfall in order to be liquidatable */\n        (Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower);\n        if (err != Error.NO_ERROR) {\n            return uint256(err);\n        }\n        if (shortfall == 0) {\n            return uint256(Error.INSUFFICIENT_SHORTFALL);\n        }\n\n        /* The liquidator may not repay more than what is allowed by the closeFactor */\n        uint256 borrowBalance = JToken(jTokenBorrowed).borrowBalanceStored(borrower);\n        uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);\n        if (repayAmount > maxClose) {\n            return uint256(Error.TOO_MUCH_REPAY);\n        }\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Validates liquidateBorrow and reverts on rejection. May emit logs.\n     * @param jTokenBorrowed Asset which was borrowed by the borrower\n     * @param jTokenCollateral Asset which was used as collateral and will be seized\n     * @param liquidator The address repaying the borrow and seizing the collateral\n     * @param borrower The address of the borrower\n     * @param actualRepayAmount The amount of underlying being repaid\n     */\n    function liquidateBorrowVerify(\n        address jTokenBorrowed,\n        address jTokenCollateral,\n        address liquidator,\n        address borrower,\n        uint256 actualRepayAmount,\n        uint256 seizeTokens\n    ) external {\n        // Shh - currently unused\n        jTokenBorrowed;\n        jTokenCollateral;\n        liquidator;\n        borrower;\n        actualRepayAmount;\n        seizeTokens;\n\n        // Shh - we don't ever want this hook to be marked pure\n        if (false) {\n            closeFactorMantissa = closeFactorMantissa;\n        }\n    }\n\n    /**\n     * @notice Checks if the seizing of assets should be allowed to occur\n     * @param jTokenCollateral Asset which was used as collateral and will be seized\n     * @param jTokenBorrowed Asset which was borrowed by the borrower\n     * @param liquidator The address repaying the borrow and seizing the collateral\n     * @param borrower The address of the borrower\n     * @param seizeTokens The number of collateral tokens to seize\n     */\n    function seizeAllowed(\n        address jTokenCollateral,\n        address jTokenBorrowed,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external returns (uint256) {\n        // Pausing is a very serious situation - we revert to sound the alarms\n        require(!seizeGuardianPaused, \"seize is paused\");\n        require(!isCreditAccount(borrower), \"cannot sieze from credit account\");\n\n        // Shh - currently unused\n        liquidator;\n        seizeTokens;\n\n        if (!isMarketListed(jTokenCollateral) || !isMarketListed(jTokenBorrowed)) {\n            return uint256(Error.MARKET_NOT_LISTED);\n        }\n\n        if (JToken(jTokenCollateral).joetroller() != JToken(jTokenBorrowed).joetroller()) {\n            return uint256(Error.JOETROLLER_MISMATCH);\n        }\n\n        // Keep the flywheel moving\n        RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, borrower);\n        RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, liquidator);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Validates seize and reverts on rejection. May emit logs.\n     * @param jTokenCollateral Asset which was used as collateral and will be seized\n     * @param jTokenBorrowed Asset which was borrowed by the borrower\n     * @param liquidator The address repaying the borrow and seizing the collateral\n     * @param borrower The address of the borrower\n     * @param seizeTokens The number of collateral tokens to seize\n     */\n    function seizeVerify(\n        address jTokenCollateral,\n        address jTokenBorrowed,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external {\n        // Shh - currently unused\n        jTokenCollateral;\n        jTokenBorrowed;\n        liquidator;\n        borrower;\n        seizeTokens;\n\n        // Shh - we don't ever want this hook to be marked pure\n        if (false) {\n            closeFactorMantissa = closeFactorMantissa;\n        }\n    }\n\n    /**\n     * @notice Checks if the account should be allowed to transfer tokens in the given market\n     * @param jToken The market to verify the transfer against\n     * @param src The account which sources the tokens\n     * @param dst The account which receives the tokens\n     * @param transferTokens The number of jTokens to transfer\n     * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n     */\n    function transferAllowed(\n        address jToken,\n        address src,\n        address dst,\n        uint256 transferTokens\n    ) external returns (uint256) {\n        // Pausing is a very serious situation - we revert to sound the alarms\n        require(!transferGuardianPaused, \"transfer is paused\");\n        require(!isCreditAccount(dst), \"cannot transfer to a credit account\");\n\n        // Shh - currently unused\n        dst;\n\n        // Currently the only consideration is whether or not\n        //  the src is allowed to redeem this many tokens\n        uint256 allowed = redeemAllowedInternal(jToken, src, transferTokens);\n        if (allowed != uint256(Error.NO_ERROR)) {\n            return allowed;\n        }\n\n        // Keep the flywheel moving\n        RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, src);\n        RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, dst);\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Validates transfer and reverts on rejection. May emit logs.\n     * @param jToken Asset being transferred\n     * @param src The account which sources the tokens\n     * @param dst The account which receives the tokens\n     * @param transferTokens The number of jTokens to transfer\n     */\n    function transferVerify(\n        address jToken,\n        address src,\n        address dst,\n        uint256 transferTokens\n    ) external {\n        // Shh - currently unused\n        jToken;\n        src;\n        dst;\n        transferTokens;\n\n        // Shh - we don't ever want this hook to be marked pure\n        if (false) {\n            closeFactorMantissa = closeFactorMantissa;\n        }\n    }\n\n    /**\n     * @notice Checks if the account should be allowed to transfer tokens in the given market\n     * @param jToken The market to verify the transfer against\n     * @param receiver The account which receives the tokens\n     * @param amount The amount of the tokens\n     * @param params The other parameters\n     */\n\n    function flashloanAllowed(\n        address jToken,\n        address receiver,\n        uint256 amount,\n        bytes calldata params\n    ) external view returns (bool) {\n        return !flashloanGuardianPaused[jToken];\n    }\n\n    /**\n     * @notice Update JToken's version.\n     * @param jToken Version of the asset being updated\n     * @param newVersion The new version\n     */\n    function updateJTokenVersion(address jToken, Version newVersion) external {\n        require(msg.sender == jToken, \"only jToken could update its version\");\n\n        // This function will be called when a new JToken implementation becomes active.\n        // If a new JToken is newly created, this market is not listed yet. The version of\n        // this market will be taken care of when calling `_supportMarket`.\n        if (isMarketListed(jToken)) {\n            Version oldVersion = markets[jToken].version;\n            markets[jToken].version = newVersion;\n\n            emit NewJTokenVersion(JToken(jToken), oldVersion, newVersion);\n        }\n    }\n\n    /**\n     * @notice Check if the account is a credit account\n     * @param account The account needs to be checked\n     * @return The account is a credit account or not\n     */\n    function isCreditAccount(address account) public view returns (bool) {\n        return creditLimits[account] > 0;\n    }\n\n    /*** Liquidity/Liquidation Calculations ***/\n\n    /**\n     * @dev Local vars for avoiding stack-depth limits in calculating account liquidity.\n     *  Note that `jTokenBalance` is the number of jTokens the account owns in the market,\n     *  whereas `borrowBalance` is the amount of underlying that the account has borrowed.\n     */\n    struct AccountLiquidityLocalVars {\n        uint256 sumCollateral;\n        uint256 sumBorrowPlusEffects;\n        uint256 jTokenBalance;\n        uint256 borrowBalance;\n        uint256 exchangeRateMantissa;\n        uint256 oraclePriceMantissa;\n        Exp collateralFactor;\n        Exp exchangeRate;\n        Exp oraclePrice;\n        Exp tokensToDenom;\n    }\n\n    /**\n     * @notice Determine the current account liquidity wrt collateral requirements\n     * @return (possible error code (semi-opaque),\n                account liquidity in excess of collateral requirements,\n     *          account shortfall below collateral requirements)\n     */\n    function getAccountLiquidity(address account)\n        public\n        view\n        returns (\n            uint256,\n            uint256,\n            uint256\n        )\n    {\n        (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(\n            account,\n            JToken(0),\n            0,\n            0\n        );\n\n        return (uint256(err), liquidity, shortfall);\n    }\n\n    /**\n     * @notice Determine the current account liquidity wrt collateral requirements\n     * @return (possible error code,\n                account liquidity in excess of collateral requirements,\n     *          account shortfall below collateral requirements)\n     */\n    function getAccountLiquidityInternal(address account)\n        internal\n        view\n        returns (\n            Error,\n            uint256,\n            uint256\n        )\n    {\n        return getHypotheticalAccountLiquidityInternal(account, JToken(0), 0, 0);\n    }\n\n    /**\n     * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\n     * @param jTokenModify The market to hypothetically redeem/borrow in\n     * @param account The account to determine liquidity for\n     * @param redeemTokens The number of tokens to hypothetically redeem\n     * @param borrowAmount The amount of underlying to hypothetically borrow\n     * @return (possible error code (semi-opaque),\n                hypothetical account liquidity in excess of collateral requirements,\n     *          hypothetical account shortfall below collateral requirements)\n     */\n    function getHypotheticalAccountLiquidity(\n        address account,\n        address jTokenModify,\n        uint256 redeemTokens,\n        uint256 borrowAmount\n    )\n        public\n        view\n        returns (\n            uint256,\n            uint256,\n            uint256\n        )\n    {\n        (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(\n            account,\n            JToken(jTokenModify),\n            redeemTokens,\n            borrowAmount\n        );\n        return (uint256(err), liquidity, shortfall);\n    }\n\n    /**\n     * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\n     * @param jTokenModify The market to hypothetically redeem/borrow in\n     * @param account The account to determine liquidity for\n     * @param redeemTokens The number of tokens to hypothetically redeem\n     * @param borrowAmount The amount of underlying to hypothetically borrow\n     * @dev Note that we calculate the exchangeRateStored for each collateral jToken using stored data,\n     *  without calculating accumulated interest.\n     * @return (possible error code,\n                hypothetical account liquidity in excess of collateral requirements,\n     *          hypothetical account shortfall below collateral requirements)\n     */\n    function getHypotheticalAccountLiquidityInternal(\n        address account,\n        JToken jTokenModify,\n        uint256 redeemTokens,\n        uint256 borrowAmount\n    )\n        internal\n        view\n        returns (\n            Error,\n            uint256,\n            uint256\n        )\n    {\n        // If credit limit is set to MAX, no need to check account liquidity.\n        if (creditLimits[account] == uint256(-1)) {\n            return (Error.NO_ERROR, uint256(-1), 0);\n        }\n\n        AccountLiquidityLocalVars memory vars; // Holds all our calculation results\n        uint256 oErr;\n\n        // For each asset the account is in\n        JToken[] memory assets = accountAssets[account];\n        for (uint256 i = 0; i < assets.length; i++) {\n            JToken asset = assets[i];\n\n            // Read the balances and exchange rate from the jToken\n            (oErr, vars.jTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(\n                account\n            );\n            if (oErr != 0) {\n                // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades\n                return (Error.SNAPSHOT_ERROR, 0, 0);\n            }\n\n            // Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed.\n            // If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it.\n            if (vars.jTokenBalance == 0 && vars.borrowBalance == 0 && asset != jTokenModify) {\n                continue;\n            }\n\n            vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});\n            vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});\n\n            // Get the normalized price of the asset\n            vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);\n            if (vars.oraclePriceMantissa == 0) {\n                return (Error.PRICE_ERROR, 0, 0);\n            }\n            vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});\n\n            // Pre-compute a conversion factor from tokens -> ether (normalized price value)\n            vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);\n\n            // sumCollateral += tokensToDenom * jTokenBalance\n            vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.jTokenBalance, vars.sumCollateral);\n\n            // sumBorrowPlusEffects += oraclePrice * borrowBalance\n            vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(\n                vars.oraclePrice,\n                vars.borrowBalance,\n                vars.sumBorrowPlusEffects\n            );\n\n            // Calculate effects of interacting with jTokenModify\n            if (asset == jTokenModify) {\n                // redeem effect\n                // sumBorrowPlusEffects += tokensToDenom * redeemTokens\n                vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(\n                    vars.tokensToDenom,\n                    redeemTokens,\n                    vars.sumBorrowPlusEffects\n                );\n\n                // borrow effect\n                // sumBorrowPlusEffects += oraclePrice * borrowAmount\n                vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(\n                    vars.oraclePrice,\n                    borrowAmount,\n                    vars.sumBorrowPlusEffects\n                );\n            }\n        }\n\n        // If credit limit is set, no need to consider collateral.\n        if (creditLimits[account] > 0) {\n            vars.sumCollateral = creditLimits[account];\n        }\n\n        // These are safe, as the underflow condition is checked first\n        if (vars.sumCollateral > vars.sumBorrowPlusEffects) {\n            return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);\n        } else {\n            return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);\n        }\n    }\n\n    /**\n     * @notice Calculate number of tokens of collateral asset to seize given an underlying amount\n     * @dev Used in liquidation (called in jToken.liquidateBorrowFresh)\n     * @param jTokenBorrowed The address of the borrowed jToken\n     * @param jTokenCollateral The address of the collateral jToken\n     * @param actualRepayAmount The amount of jTokenBorrowed underlying to convert into jTokenCollateral tokens\n     * @return (errorCode, number of jTokenCollateral tokens to be seized in a liquidation)\n     */\n    function liquidateCalculateSeizeTokens(\n        address jTokenBorrowed,\n        address jTokenCollateral,\n        uint256 actualRepayAmount\n    ) external view returns (uint256, uint256) {\n        /* Read oracle prices for borrowed and collateral markets */\n        uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(JToken(jTokenBorrowed));\n        uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(JToken(jTokenCollateral));\n        if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {\n            return (uint256(Error.PRICE_ERROR), 0);\n        }\n\n        /*\n         * Get the exchange rate and calculate the number of collateral tokens to seize:\n         *  seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral\n         *  seizeTokens = seizeAmount / exchangeRate\n         *   = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)\n         */\n        uint256 exchangeRateMantissa = JToken(jTokenCollateral).exchangeRateStored(); // Note: reverts on error\n        Exp memory numerator = mul_(\n            Exp({mantissa: liquidationIncentiveMantissa}),\n            Exp({mantissa: priceBorrowedMantissa})\n        );\n        Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));\n        Exp memory ratio = div_(numerator, denominator);\n        uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);\n\n        return (uint256(Error.NO_ERROR), seizeTokens);\n    }\n\n    /*** Admin Functions ***/\n\n    function _setRewardDistributor(address payable newRewardDistributor) public returns (uint256) {\n        if (msg.sender != admin) {\n            return uint256(Error.UNAUTHORIZED);\n        }\n        (bool success, ) = newRewardDistributor.call.value(0)(abi.encodeWithSignature(\"initialize()\", 0));\n        if (!success) {\n            return uint256(Error.REJECTION);\n        }\n\n        address oldRewardDistributor = rewardDistributor;\n        rewardDistributor = newRewardDistributor;\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sets a new price oracle for the joetroller\n     * @dev Admin function to set a new price oracle\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setPriceOracle(PriceOracle newOracle) public returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);\n        }\n\n        // Track the old oracle for the joetroller\n        PriceOracle oldOracle = oracle;\n\n        // Set joetroller's oracle to newOracle\n        oracle = newOracle;\n\n        // Emit NewPriceOracle(oldOracle, newOracle)\n        emit NewPriceOracle(oldOracle, newOracle);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sets the closeFactor used when liquidating borrows\n     * @dev Admin function to set closeFactor\n     * @param newCloseFactorMantissa New close factor, scaled by 1e18\n     * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\n     */\n    function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);\n        }\n\n        uint256 oldCloseFactorMantissa = closeFactorMantissa;\n        closeFactorMantissa = newCloseFactorMantissa;\n        emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sets the collateralFactor for a market\n     * @dev Admin function to set per-market collateralFactor\n     * @param jToken The market to set the factor on\n     * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18\n     * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\n     */\n    function _setCollateralFactor(JToken jToken, uint256 newCollateralFactorMantissa) external returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);\n        }\n\n        // Verify market is listed\n        Market storage market = markets[address(jToken)];\n        if (!market.isListed) {\n            return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);\n        }\n\n        Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});\n\n        // Check collateral factor <= 0.9\n        Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});\n        if (lessThanExp(highLimit, newCollateralFactorExp)) {\n            return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);\n        }\n\n        // If collateral factor != 0, fail if price == 0\n        if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(jToken) == 0) {\n            return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);\n        }\n\n        // Set market's collateral factor to new collateral factor, remember old value\n        uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa;\n        market.collateralFactorMantissa = newCollateralFactorMantissa;\n\n        // Emit event with asset, old collateral factor, and new collateral factor\n        emit NewCollateralFactor(jToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sets liquidationIncentive\n     * @dev Admin function to set liquidationIncentive\n     * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18\n     * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\n     */\n    function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);\n        }\n\n        // Save current value for use in log\n        uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;\n\n        // Set liquidation incentive to new incentive\n        liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;\n\n        // Emit event with old incentive, new incentive\n        emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Add the market to the markets mapping and set it as listed\n     * @dev Admin function to set isListed and add support for the market\n     * @param jToken The address of the market (token) to list\n     * @param version The version of the market (token)\n     * @return uint 0=success, otherwise a failure. (See enum Error for details)\n     */\n    function _supportMarket(JToken jToken, Version version) external returns (uint256) {\n        require(msg.sender == admin, \"only admin may support market\");\n        require(!isMarketListed(address(jToken)), \"market already listed\");\n\n        jToken.isJToken(); // Sanity check to make sure its really a JToken\n\n        markets[address(jToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version});\n\n        _addMarketInternal(address(jToken));\n\n        emit MarketListed(jToken);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Remove the market from the markets mapping\n     * @param jToken The address of the market (token) to delist\n     */\n    function _delistMarket(JToken jToken) external {\n        require(msg.sender == admin, \"only admin may delist market\");\n        require(isMarketListed(address(jToken)), \"market not listed\");\n        require(jToken.totalSupply() == 0, \"market not empty\");\n\n        jToken.isJToken(); // Sanity check to make sure its really a JToken\n\n        delete markets[address(jToken)];\n\n        for (uint256 i = 0; i < allMarkets.length; i++) {\n            if (allMarkets[i] == jToken) {\n                allMarkets[i] = allMarkets[allMarkets.length - 1];\n                delete allMarkets[allMarkets.length - 1];\n                allMarkets.length--;\n                break;\n            }\n        }\n\n        emit MarketDelisted(jToken);\n    }\n\n    function _addMarketInternal(address jToken) internal {\n        for (uint256 i = 0; i < allMarkets.length; i++) {\n            require(allMarkets[i] != JToken(jToken), \"market already added\");\n        }\n        allMarkets.push(JToken(jToken));\n    }\n\n    /**\n     * @notice Admin function to change the Supply Cap Guardian\n     * @param newSupplyCapGuardian The address of the new Supply Cap Guardian\n     */\n    function _setSupplyCapGuardian(address newSupplyCapGuardian) external {\n        require(msg.sender == admin, \"only admin can set supply cap guardian\");\n\n        // Save current value for inclusion in log\n        address oldSupplyCapGuardian = supplyCapGuardian;\n\n        // Store supplyCapGuardian with value newSupplyCapGuardian\n        supplyCapGuardian = newSupplyCapGuardian;\n\n        // Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian)\n        emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian);\n    }\n\n    /**\n     * @notice Set the given supply caps for the given jToken markets. Supplying that brings total supplys to or above supply cap will revert.\n     * @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows\n     *      already exceeded the cap, it will prevent anyone to borrow.\n     * @param jTokens The addresses of the markets (tokens) to change the supply caps for\n     * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.\n     */\n    function _setMarketSupplyCaps(JToken[] calldata jTokens, uint256[] calldata newSupplyCaps) external {\n        require(\n            msg.sender == admin || msg.sender == supplyCapGuardian,\n            \"only admin or supply cap guardian can set supply caps\"\n        );\n\n        uint256 numMarkets = jTokens.length;\n        uint256 numSupplyCaps = newSupplyCaps.length;\n\n        require(numMarkets != 0 && numMarkets == numSupplyCaps, \"invalid input\");\n\n        for (uint256 i = 0; i < numMarkets; i++) {\n            supplyCaps[address(jTokens[i])] = newSupplyCaps[i];\n            emit NewSupplyCap(jTokens[i], newSupplyCaps[i]);\n        }\n    }\n\n    /**\n     * @notice Set the given borrow caps for the given jToken markets. Borrowing that brings total borrows to or above borrow cap will revert.\n     * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies\n     *      already exceeded the cap, it will prevent anyone to mint.\n     * @param jTokens The addresses of the markets (tokens) to change the borrow caps for\n     * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.\n     */\n    function _setMarketBorrowCaps(JToken[] calldata jTokens, uint256[] calldata newBorrowCaps) external {\n        require(\n            msg.sender == admin || msg.sender == borrowCapGuardian,\n            \"only admin or borrow cap guardian can set borrow caps\"\n        );\n\n        uint256 numMarkets = jTokens.length;\n        uint256 numBorrowCaps = newBorrowCaps.length;\n\n        require(numMarkets != 0 && numMarkets == numBorrowCaps, \"invalid input\");\n\n        for (uint256 i = 0; i < numMarkets; i++) {\n            borrowCaps[address(jTokens[i])] = newBorrowCaps[i];\n            emit NewBorrowCap(jTokens[i], newBorrowCaps[i]);\n        }\n    }\n\n    /**\n     * @notice Admin function to change the Borrow Cap Guardian\n     * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian\n     */\n    function _setBorrowCapGuardian(address newBorrowCapGuardian) external {\n        require(msg.sender == admin, \"only admin can set borrow cap guardian\");\n\n        // Save current value for inclusion in log\n        address oldBorrowCapGuardian = borrowCapGuardian;\n\n        // Store borrowCapGuardian with value newBorrowCapGuardian\n        borrowCapGuardian = newBorrowCapGuardian;\n\n        // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)\n        emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);\n    }\n\n    /**\n     * @notice Admin function to change the Pause Guardian\n     * @param newPauseGuardian The address of the new Pause Guardian\n     * @return uint 0=success, otherwise a failure. (See enum Error for details)\n     */\n    function _setPauseGuardian(address newPauseGuardian) public returns (uint256) {\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);\n        }\n\n        // Save current value for inclusion in log\n        address oldPauseGuardian = pauseGuardian;\n\n        // Store pauseGuardian with value newPauseGuardian\n        pauseGuardian = newPauseGuardian;\n\n        // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)\n        emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    function _setMintPaused(JToken jToken, bool state) public returns (bool) {\n        require(isMarketListed(address(jToken)), \"cannot pause a market that is not listed\");\n        require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\n        require(msg.sender == admin || state == true, \"only admin can unpause\");\n\n        mintGuardianPaused[address(jToken)] = state;\n        emit ActionPaused(jToken, \"Mint\", state);\n        return state;\n    }\n\n    function _setBorrowPaused(JToken jToken, bool state) public returns (bool) {\n        require(isMarketListed(address(jToken)), \"cannot pause a market that is not listed\");\n        require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\n        require(msg.sender == admin || state == true, \"only admin can unpause\");\n\n        borrowGuardianPaused[address(jToken)] = state;\n        emit ActionPaused(jToken, \"Borrow\", state);\n        return state;\n    }\n\n    function _setFlashloanPaused(JToken jToken, bool state) public returns (bool) {\n        require(isMarketListed(address(jToken)), \"cannot pause a market that is not listed\");\n        require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\n        require(msg.sender == admin || state == true, \"only admin can unpause\");\n\n        flashloanGuardianPaused[address(jToken)] = state;\n        emit ActionPaused(jToken, \"Flashloan\", state);\n        return state;\n    }\n\n    function _setTransferPaused(bool state) public returns (bool) {\n        require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\n        require(msg.sender == admin || state == true, \"only admin can unpause\");\n\n        transferGuardianPaused = state;\n        emit ActionPaused(\"Transfer\", state);\n        return state;\n    }\n\n    function _setSeizePaused(bool state) public returns (bool) {\n        require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\n        require(msg.sender == admin || state == true, \"only admin can unpause\");\n\n        seizeGuardianPaused = state;\n        emit ActionPaused(\"Seize\", state);\n        return state;\n    }\n\n    function _become(Unitroller unitroller) public {\n        require(msg.sender == unitroller.admin(), \"only unitroller admin can change brains\");\n        require(unitroller._acceptImplementation() == 0, \"change not authorized\");\n    }\n\n    /**\n     * @notice Sets whitelisted protocol's credit limit\n     * @param protocol The address of the protocol\n     * @param creditLimit The credit limit\n     */\n    function _setCreditLimit(address protocol, uint256 creditLimit) public {\n        require(msg.sender == admin, \"only admin can set protocol credit limit\");\n\n        creditLimits[protocol] = creditLimit;\n        emit CreditLimitChanged(protocol, creditLimit);\n    }\n\n    /**\n     * @notice Checks caller is admin, or this contract is becoming the new implementation\n     */\n    function adminOrInitializing() internal view returns (bool) {\n        return msg.sender == admin || msg.sender == implementation;\n    }\n\n    /*** Reward distribution functions ***/\n\n    /**\n     * @notice Claim all the JOE/AVAX accrued by holder in all markets\n     * @param holder The address to claim JOE/AVAX for\n     */\n    function claimReward(uint8 rewardType, address payable holder) public {\n        RewardDistributor(rewardDistributor).claimReward(rewardType, holder);\n    }\n\n    /**\n     * @notice Claim all the JOE/AVAX accrued by holder in the specified markets\n     * @param holder The address to claim JOE/AVAX for\n     * @param jTokens The list of markets to claim JOE/AVAX in\n     */\n    function claimReward(\n        uint8 rewardType,\n        address payable holder,\n        JToken[] memory jTokens\n    ) public {\n        RewardDistributor(rewardDistributor).claimReward(rewardType, holder, jTokens);\n    }\n\n    /**\n     * @notice Claim all JOE/AVAX  accrued by the holders\n     * @param rewardType  0 = JOE, 1 = AVAX\n     * @param holders The addresses to claim JOE/AVAX for\n     * @param jTokens The list of markets to claim JOE/AVAX in\n     * @param borrowers Whether or not to claim JOE/AVAX earned by borrowing\n     * @param suppliers Whether or not to claim JOE/AVAX earned by supplying\n     */\n    function claimReward(\n        uint8 rewardType,\n        address payable[] memory holders,\n        JToken[] memory jTokens,\n        bool borrowers,\n        bool suppliers\n    ) public payable {\n        RewardDistributor(rewardDistributor).claimReward(rewardType, holders, jTokens, borrowers, suppliers);\n    }\n}\n"
    },
    "contracts/RewardDistributor.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\npragma experimental ABIEncoderV2;\n\nimport \"./EIP20Interface.sol\";\nimport \"./Joetroller.sol\";\nimport \"./JToken.sol\";\n\ncontract RewardDistributorStorage {\n    /**\n     * @notice Administrator for this contract\n     */\n    address public admin;\n\n    /**\n     * @notice Active brains of Unitroller\n     */\n    Joetroller public joetroller;\n\n    struct RewardMarketState {\n        /// @notice The market's last updated joeBorrowIndex or joeSupplyIndex\n        uint224 index;\n        /// @notice The timestamp number the index was last updated at\n        uint32 timestamp;\n    }\n\n    /// @notice The portion of reward rate that each market currently receives\n    mapping(uint8 => mapping(address => uint256)) public rewardSpeeds;\n\n    /// @notice The JOE/AVAX market supply state for each market\n    mapping(uint8 => mapping(address => RewardMarketState)) public rewardSupplyState;\n\n    /// @notice The JOE/AVAX market borrow state for each market\n    mapping(uint8 => mapping(address => RewardMarketState)) public rewardBorrowState;\n\n    /// @notice The JOE/AVAX borrow index for each market for each supplier as of the last time they accrued reward\n    mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardSupplierIndex;\n\n    /// @notice The JOE/AVAX borrow index for each market for each borrower as of the last time they accrued reward\n    mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardBorrowerIndex;\n\n    /// @notice The JOE/AVAX accrued but not yet transferred to each user\n    mapping(uint8 => mapping(address => uint256)) public rewardAccrued;\n\n    /// @notice The initial reward index for a market\n    uint224 public constant rewardInitialIndex = 1e36;\n\n    /// @notice JOE token contract address\n    address public joeAddress;\n}\n\ncontract RewardDistributor is RewardDistributorStorage, Exponential {\n    /// @notice Emitted when a new reward speed is calculated for a market\n    event RewardSpeedUpdated(uint8 rewardType, JToken indexed jToken, uint256 newSpeed);\n\n    /// @notice Emitted when JOE/AVAX is distributed to a supplier\n    event DistributedSupplierReward(\n        uint8 rewardType,\n        JToken indexed jToken,\n        address indexed supplier,\n        uint256 rewardDelta,\n        uint256 rewardSupplyIndex\n    );\n\n    /// @notice Emitted when JOE/AVAX is distributed to a borrower\n    event DistributedBorrowerReward(\n        uint8 rewardType,\n        JToken indexed jToken,\n        address indexed borrower,\n        uint256 rewardDelta,\n        uint256 rewardBorrowIndex\n    );\n\n    /// @notice Emitted when JOE is granted by admin\n    event RewardGranted(uint8 rewardType, address recipient, uint256 amount);\n\n    bool private initialized;\n\n    constructor() public {\n        admin = msg.sender;\n    }\n\n    function initialize() public {\n        require(!initialized, \"RewardDistributor already initialized\");\n        joetroller = Joetroller(msg.sender);\n        initialized = true;\n    }\n\n    /**\n     * @notice Checks caller is admin, or this contract is becoming the new implementation\n     */\n    function adminOrInitializing() internal view returns (bool) {\n        return msg.sender == admin || msg.sender == address(joetroller);\n    }\n\n    /**\n     * @notice Set JOE/AVAX speed for a single market\n     * @param rewardType 0 = QI, 1 = AVAX\n     * @param jToken The market whose reward speed to update\n     * @param rewardSpeed New reward speed for market\n     */\n    function _setRewardSpeed(\n        uint8 rewardType,\n        JToken jToken,\n        uint256 rewardSpeed\n    ) public {\n        require(rewardType <= 1, \"rewardType is invalid\");\n        require(adminOrInitializing(), \"only admin can set reward speed\");\n        setRewardSpeedInternal(rewardType, jToken, rewardSpeed);\n    }\n\n    /**\n     * @notice Set JOE/AVAX speed for a single market\n     * @param rewardType  0: JOE, 1: AVAX\n     * @param jToken The market whose speed to update\n     * @param newSpeed New JOE or AVAX speed for market\n     */\n    function setRewardSpeedInternal(\n        uint8 rewardType,\n        JToken jToken,\n        uint256 newSpeed\n    ) internal {\n        uint256 currentRewardSpeed = rewardSpeeds[rewardType][address(jToken)];\n        if (currentRewardSpeed != 0) {\n            // note that JOE speed could be set to 0 to halt liquidity rewards for a market\n            Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()});\n            updateRewardSupplyIndex(rewardType, address(jToken));\n            updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex);\n        } else if (newSpeed != 0) {\n            // Add the JOE market\n            require(joetroller.isMarketListed(address(jToken)), \"reward market is not listed\");\n\n            if (\n                rewardSupplyState[rewardType][address(jToken)].index == 0 &&\n                rewardSupplyState[rewardType][address(jToken)].timestamp == 0\n            ) {\n                rewardSupplyState[rewardType][address(jToken)] = RewardMarketState({\n                    index: rewardInitialIndex,\n                    timestamp: safe32(getBlockTimestamp(), \"block timestamp exceeds 32 bits\")\n                });\n            }\n\n            if (\n                rewardBorrowState[rewardType][address(jToken)].index == 0 &&\n                rewardBorrowState[rewardType][address(jToken)].timestamp == 0\n            ) {\n                rewardBorrowState[rewardType][address(jToken)] = RewardMarketState({\n                    index: rewardInitialIndex,\n                    timestamp: safe32(getBlockTimestamp(), \"block timestamp exceeds 32 bits\")\n                });\n            }\n        }\n\n        if (currentRewardSpeed != newSpeed) {\n            rewardSpeeds[rewardType][address(jToken)] = newSpeed;\n            emit RewardSpeedUpdated(rewardType, jToken, newSpeed);\n        }\n    }\n\n    /**\n     * @notice Accrue JOE/AVAX to the market by updating the supply index\n     * @param rewardType  0: JOE, 1: AVAX\n     * @param jToken The market whose supply index to update\n     */\n    function updateRewardSupplyIndex(uint8 rewardType, address jToken) public {\n        require(rewardType <= 1, \"rewardType is invalid\");\n        RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken];\n        uint256 supplySpeed = rewardSpeeds[rewardType][jToken];\n        uint256 blockTimestamp = getBlockTimestamp();\n        uint256 deltaTimestamps = sub_(blockTimestamp, uint256(supplyState.timestamp));\n        if (deltaTimestamps > 0 && supplySpeed > 0) {\n            uint256 supplyTokens = JToken(jToken).totalSupply();\n            uint256 rewardAccrued = mul_(deltaTimestamps, supplySpeed);\n            Double memory ratio = supplyTokens > 0 ? fraction(rewardAccrued, supplyTokens) : Double({mantissa: 0});\n            Double memory index = add_(Double({mantissa: supplyState.index}), ratio);\n            rewardSupplyState[rewardType][jToken] = RewardMarketState({\n                index: safe224(index.mantissa, \"new index exceeds 224 bits\"),\n                timestamp: safe32(blockTimestamp, \"block timestamp exceeds 32 bits\")\n            });\n        } else if (deltaTimestamps > 0) {\n            supplyState.timestamp = safe32(blockTimestamp, \"block timestamp exceeds 32 bits\");\n        }\n    }\n\n    /**\n     * @notice Accrue JOE/AVAX to the market by updating the borrow index\n     * @param rewardType  0: JOE, 1: AVAX\n     * @param jToken The market whose borrow index to update\n     */\n    function updateRewardBorrowIndex(\n        uint8 rewardType,\n        address jToken,\n        Exp memory marketBorrowIndex\n    ) internal {\n        require(rewardType <= 1, \"rewardType is invalid\");\n        RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken];\n        uint256 borrowSpeed = rewardSpeeds[rewardType][jToken];\n        uint256 blockTimestamp = getBlockTimestamp();\n        uint256 deltaTimestamps = sub_(blockTimestamp, uint256(borrowState.timestamp));\n        if (deltaTimestamps > 0 && borrowSpeed > 0) {\n            uint256 borrowAmount = div_(JToken(jToken).totalBorrows(), marketBorrowIndex);\n            uint256 rewardAccrued = mul_(deltaTimestamps, borrowSpeed);\n            Double memory ratio = borrowAmount > 0 ? fraction(rewardAccrued, borrowAmount) : Double({mantissa: 0});\n            Double memory index = add_(Double({mantissa: borrowState.index}), ratio);\n            rewardBorrowState[rewardType][jToken] = RewardMarketState({\n                index: safe224(index.mantissa, \"new index exceeds 224 bits\"),\n                timestamp: safe32(blockTimestamp, \"block timestamp exceeds 32 bits\")\n            });\n        } else if (deltaTimestamps > 0) {\n            borrowState.timestamp = safe32(blockTimestamp, \"block timestamp exceeds 32 bits\");\n        }\n    }\n\n    /**\n     * @notice Calculate JOE/AVAX accrued by a supplier and possibly transfer it to them\n     * @param rewardType  0: JOE, 1: AVAX\n     * @param jToken The market in which the supplier is interacting\n     * @param supplier The address of the supplier to distribute JOE/AVAX to\n     */\n    function distributeSupplierReward(\n        uint8 rewardType,\n        address jToken,\n        address supplier\n    ) public {\n        require(rewardType <= 1, \"rewardType is invalid\");\n        RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken];\n        Double memory supplyIndex = Double({mantissa: supplyState.index});\n        Double memory supplierIndex = Double({mantissa: rewardSupplierIndex[rewardType][jToken][supplier]});\n        rewardSupplierIndex[rewardType][jToken][supplier] = supplyIndex.mantissa;\n\n        if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {\n            supplierIndex.mantissa = rewardInitialIndex;\n        }\n\n        Double memory deltaIndex = sub_(supplyIndex, supplierIndex);\n        uint256 supplierTokens = JToken(jToken).balanceOf(supplier);\n        uint256 supplierDelta = mul_(supplierTokens, deltaIndex);\n        uint256 supplierAccrued = add_(rewardAccrued[rewardType][supplier], supplierDelta);\n        rewardAccrued[rewardType][supplier] = supplierAccrued;\n        emit DistributedSupplierReward(rewardType, JToken(jToken), supplier, supplierDelta, supplyIndex.mantissa);\n    }\n\n    /**\n     * @notice Calculate JOE/AVAX accrued by a borrower and possibly transfer it to them\n     * @dev Borrowers will not begin to accrue until after the first interaction with the protocol.\n     * @param rewardType  0: JOE, 1: AVAX\n     * @param jToken The market in which the borrower is interacting\n     * @param borrower The address of the borrower to distribute JOE/AVAX to\n     */\n    function distributeBorrowerReward(\n        uint8 rewardType,\n        address jToken,\n        address borrower,\n        Exp memory marketBorrowIndex\n    ) public {\n        require(rewardType <= 1, \"rewardType is invalid\");\n        RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken];\n        Double memory borrowIndex = Double({mantissa: borrowState.index});\n        Double memory borrowerIndex = Double({mantissa: rewardBorrowerIndex[rewardType][jToken][borrower]});\n        rewardBorrowerIndex[rewardType][jToken][borrower] = borrowIndex.mantissa;\n\n        if (borrowerIndex.mantissa > 0) {\n            Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);\n            uint256 borrowerAmount = div_(JToken(jToken).borrowBalanceStored(borrower), marketBorrowIndex);\n            uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex);\n            uint256 borrowerAccrued = add_(rewardAccrued[rewardType][borrower], borrowerDelta);\n            rewardAccrued[rewardType][borrower] = borrowerAccrued;\n            emit DistributedBorrowerReward(rewardType, JToken(jToken), borrower, borrowerDelta, borrowIndex.mantissa);\n        }\n    }\n\n    /**\n     * @notice Refactored function to calc and rewards accounts supplier rewards\n     * @param jToken The market to verify the mint against\n     * @param supplier The supplier to be rewarded\n     */\n    function updateAndDistributeSupplierRewardsForToken(address jToken, address supplier) external {\n        require(adminOrInitializing(), \"only admin can update and distribute supplier rewards\");\n        for (uint8 rewardType = 0; rewardType <= 1; rewardType++) {\n            updateRewardSupplyIndex(rewardType, jToken);\n            distributeSupplierReward(rewardType, jToken, supplier);\n        }\n    }\n\n    /**\n     * @notice Refactored function to calc and rewards accounts supplier rewards\n     * @param jToken The market to verify the mint against\n     * @param borrower Borrower to be rewarded\n     */\n    function updateAndDistributeBorrowerRewardsForToken(\n        address jToken,\n        address borrower,\n        Exp calldata marketBorrowIndex\n    ) external {\n        require(adminOrInitializing(), \"only admin can update and distribute borrower rewards\");\n        for (uint8 rewardType = 0; rewardType <= 1; rewardType++) {\n            updateRewardBorrowIndex(rewardType, jToken, marketBorrowIndex);\n            distributeBorrowerReward(rewardType, jToken, borrower, marketBorrowIndex);\n        }\n    }\n\n    /*** User functions ***/\n\n    /**\n     * @notice Claim all the JOE/AVAX accrued by holder in all markets\n     * @param holder The address to claim JOE/AVAX for\n     */\n    function claimReward(uint8 rewardType, address payable holder) public {\n        return claimReward(rewardType, holder, joetroller.getAllMarkets());\n    }\n\n    /**\n     * @notice Claim all the JOE/AVAX accrued by holder in the specified markets\n     * @param holder The address to claim JOE/AVAX for\n     * @param jTokens The list of markets to claim JOE/AVAX in\n     */\n    function claimReward(\n        uint8 rewardType,\n        address payable holder,\n        JToken[] memory jTokens\n    ) public {\n        address payable[] memory holders = new address payable[](1);\n        holders[0] = holder;\n        claimReward(rewardType, holders, jTokens, true, true);\n    }\n\n    /**\n     * @notice Claim all JOE/AVAX  accrued by the holders\n     * @param rewardType  0 = JOE, 1 = AVAX\n     * @param holders The addresses to claim JOE/AVAX for\n     * @param jTokens The list of markets to claim JOE/AVAX in\n     * @param borrowers Whether or not to claim JOE/AVAX earned by borrowing\n     * @param suppliers Whether or not to claim JOE/AVAX earned by supplying\n     */\n    function claimReward(\n        uint8 rewardType,\n        address payable[] memory holders,\n        JToken[] memory jTokens,\n        bool borrowers,\n        bool suppliers\n    ) public payable {\n        require(rewardType <= 1, \"rewardType is invalid\");\n        for (uint256 i = 0; i < jTokens.length; i++) {\n            JToken jToken = jTokens[i];\n            require(joetroller.isMarketListed(address(jToken)), \"market must be listed\");\n            if (borrowers == true) {\n                Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()});\n                updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex);\n                for (uint256 j = 0; j < holders.length; j++) {\n                    distributeBorrowerReward(rewardType, address(jToken), holders[j], borrowIndex);\n                    rewardAccrued[rewardType][holders[j]] = grantRewardInternal(\n                        rewardType,\n                        holders[j],\n                        rewardAccrued[rewardType][holders[j]]\n                    );\n                }\n            }\n            if (suppliers == true) {\n                updateRewardSupplyIndex(rewardType, address(jToken));\n                for (uint256 j = 0; j < holders.length; j++) {\n                    distributeSupplierReward(rewardType, address(jToken), holders[j]);\n                    rewardAccrued[rewardType][holders[j]] = grantRewardInternal(\n                        rewardType,\n                        holders[j],\n                        rewardAccrued[rewardType][holders[j]]\n                    );\n                }\n            }\n        }\n    }\n\n    /**\n     * @notice Transfer JOE/AVAX to the user\n     * @dev Note: If there is not enough JOE/AVAX, we do not perform the transfer all.\n     * @param user The address of the user to transfer JOE/AVAX to\n     * @param amount The amount of JOE/AVAX to (possibly) transfer\n     * @return The amount of JOE/AVAX which was NOT transferred to the user\n     */\n    function grantRewardInternal(\n        uint256 rewardType,\n        address payable user,\n        uint256 amount\n    ) public returns (uint256) {\n        if (rewardType == 0) {\n            EIP20Interface joe = EIP20Interface(joeAddress);\n            uint256 joeRemaining = joe.balanceOf(address(this));\n            if (amount > 0 && amount <= joeRemaining) {\n                joe.transfer(user, amount);\n                return 0;\n            }\n        } else if (rewardType == 1) {\n            uint256 avaxRemaining = address(this).balance;\n            if (amount > 0 && amount <= avaxRemaining) {\n                user.transfer(amount);\n                return 0;\n            }\n        }\n        return amount;\n    }\n\n    /*** Joe Distribution Admin ***/\n\n    /**\n     * @notice Transfer JOE to the recipient\n     * @dev Note: If there is not enough JOE, we do not perform the transfer all.\n     * @param recipient The address of the recipient to transfer JOE to\n     * @param amount The amount of JOE to (possibly) transfer\n     */\n    function _grantReward(\n        uint8 rewardType,\n        address payable recipient,\n        uint256 amount\n    ) public {\n        require(adminOrInitializing(), \"only admin can grant joe\");\n        uint256 amountLeft = grantRewardInternal(rewardType, recipient, amount);\n        require(amountLeft == 0, \"insufficient joe for grant\");\n        emit RewardGranted(rewardType, recipient, amount);\n    }\n\n    /**\n     * @notice Set the JOE token address\n     */\n    function setJoeAddress(address newJoeAddress) public {\n        require(msg.sender == admin, \"only admin can set JOE\");\n        joeAddress = newJoeAddress;\n    }\n\n    /**\n     * @notice Set the Joetroller address\n     */\n    function setJoetroller(address _joetroller) public {\n        require(msg.sender == admin, \"only admin can set Joetroller\");\n        joetroller = Joetroller(_joetroller);\n    }\n\n    /**\n     * @notice Set the admin\n     */\n    function setAdmin(address _newAdmin) public {\n        require(msg.sender == admin, \"only admin can set admin\");\n        admin = _newAdmin;\n    }\n\n    /**\n     * @notice payable function needed to receive AVAX\n     */\n    function() external payable {}\n\n    function getBlockTimestamp() public view returns (uint256) {\n        return block.timestamp;\n    }\n}\n"
    },
    "contracts/Unitroller.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./ErrorReporter.sol\";\nimport \"./JoetrollerStorage.sol\";\n\n/**\n * @title JoetrollerCore\n * @dev Storage for the joetroller is at this address, while execution is delegated to the `implementation`.\n * JTokens should reference this contract as their joetroller.\n */\ncontract Unitroller is UnitrollerAdminStorage, JoetrollerErrorReporter {\n    /**\n     * @notice Emitted when pendingImplementation is changed\n     */\n    event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);\n\n    /**\n     * @notice Emitted when pendingImplementation is accepted, which means joetroller implementation is updated\n     */\n    event NewImplementation(address oldImplementation, address newImplementation);\n\n    /**\n     * @notice Emitted when pendingAdmin is changed\n     */\n    event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);\n\n    /**\n     * @notice Emitted when pendingAdmin is accepted, which means admin is updated\n     */\n    event NewAdmin(address oldAdmin, address newAdmin);\n\n    constructor() public {\n        // Set admin to caller\n        admin = msg.sender;\n    }\n\n    /*** Admin Functions ***/\n    function _setPendingImplementation(address newPendingImplementation) public returns (uint256) {\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);\n        }\n\n        address oldPendingImplementation = pendingImplementation;\n\n        pendingImplementation = newPendingImplementation;\n\n        emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Accepts new implementation of joetroller. msg.sender must be pendingImplementation\n     * @dev Admin function for new implementation to accept it's role as implementation\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _acceptImplementation() public returns (uint256) {\n        // Check caller is pendingImplementation and pendingImplementation ≠ address(0)\n        if (msg.sender != pendingImplementation || pendingImplementation == address(0)) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);\n        }\n\n        // Save current values for inclusion in log\n        address oldImplementation = implementation;\n        address oldPendingImplementation = pendingImplementation;\n\n        implementation = pendingImplementation;\n\n        pendingImplementation = address(0);\n\n        emit NewImplementation(oldImplementation, implementation);\n        emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @param newPendingAdmin New pending admin.\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setPendingAdmin(address newPendingAdmin) public returns (uint256) {\n        // Check caller = admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);\n        }\n\n        // Save current value, if any, for inclusion in log\n        address oldPendingAdmin = pendingAdmin;\n\n        // Store pendingAdmin with value newPendingAdmin\n        pendingAdmin = newPendingAdmin;\n\n        // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)\n        emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\n     * @dev Admin function for pending admin to accept role and update admin\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _acceptAdmin() public returns (uint256) {\n        // Check caller is pendingAdmin\n        if (msg.sender != pendingAdmin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);\n        }\n\n        // Save current values for inclusion in log\n        address oldAdmin = admin;\n        address oldPendingAdmin = pendingAdmin;\n\n        // Store admin with value pendingAdmin\n        admin = pendingAdmin;\n\n        // Clear the pending value\n        pendingAdmin = address(0);\n\n        emit NewAdmin(oldAdmin, admin);\n        emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @dev Delegates execution to an implementation contract.\n     * It returns to the external caller whatever the implementation returns\n     * or forwards reverts.\n     */\n    function() external payable {\n        // delegate all other functions to current implementation\n        (bool success, ) = implementation.delegatecall(msg.data);\n\n        assembly {\n            let free_mem_ptr := mload(0x40)\n            returndatacopy(free_mem_ptr, 0, returndatasize)\n\n            switch success\n            case 0 {\n                revert(free_mem_ptr, returndatasize)\n            }\n            default {\n                return(free_mem_ptr, returndatasize)\n            }\n        }\n    }\n}\n"
    },
    "contracts/PriceOracle/SimplePriceOracle.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./PriceOracle.sol\";\nimport \"../JErc20.sol\";\n\ncontract SimplePriceOracle is PriceOracle {\n    mapping(address => uint256) prices;\n    event PricePosted(\n        address asset,\n        uint256 previousPriceMantissa,\n        uint256 requestedPriceMantissa,\n        uint256 newPriceMantissa\n    );\n\n    function getUnderlyingPrice(JToken jToken) public view returns (uint256) {\n        if (compareStrings(jToken.symbol(), \"jAVAX\")) {\n            return 1e18;\n        } else {\n            return prices[address(JErc20(address(jToken)).underlying())];\n        }\n    }\n\n    function setUnderlyingPrice(JToken jToken, uint256 underlyingPriceMantissa) public {\n        address asset = address(JErc20(address(jToken)).underlying());\n        emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);\n        prices[asset] = underlyingPriceMantissa;\n    }\n\n    function setDirectPrice(address asset, uint256 price) public {\n        emit PricePosted(asset, prices[asset], price, price);\n        prices[asset] = price;\n    }\n\n    // v1 price oracle interface for use as backing of proxy\n    function assetPrices(address asset) external view returns (uint256) {\n        return prices[asset];\n    }\n\n    function compareStrings(string memory a, string memory b) internal pure returns (bool) {\n        return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));\n    }\n}\n"
    },
    "contracts/Lens/JoeLens.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\npragma experimental ABIEncoderV2;\n\nimport \"../JErc20.sol\";\nimport \"../Joetroller.sol\";\nimport \"../JToken.sol\";\nimport \"../PriceOracle/PriceOracle.sol\";\nimport \"../EIP20Interface.sol\";\nimport \"../Exponential.sol\";\n\ninterface JJLPInterface {\n    function claimJoe(address) external returns (uint256);\n}\n\ninterface JJTokenInterface {\n    function claimJoe(address) external returns (uint256);\n}\n\n/**\n * @notice This is a version of JoeLens that contains write transactions.\n * @dev Call these functions as dry-run transactions for the frontend.\n */\ncontract JoeLens is Exponential {\n    string public nativeSymbol;\n\n    constructor(string memory _nativeSymbol) public {\n        nativeSymbol = _nativeSymbol;\n    }\n\n    /*** Market info functions ***/\n    struct JTokenMetadata {\n        address jToken;\n        uint256 exchangeRateCurrent;\n        uint256 supplyRatePerSecond;\n        uint256 borrowRatePerSecond;\n        uint256 reserveFactorMantissa;\n        uint256 totalBorrows;\n        uint256 totalReserves;\n        uint256 totalSupply;\n        uint256 totalCash;\n        uint256 totalCollateralTokens;\n        bool isListed;\n        uint256 collateralFactorMantissa;\n        address underlyingAssetAddress;\n        uint256 jTokenDecimals;\n        uint256 underlyingDecimals;\n        JoetrollerV1Storage.Version version;\n        uint256 collateralCap;\n        uint256 underlyingPrice;\n        bool supplyPaused;\n        bool borrowPaused;\n        uint256 supplyCap;\n        uint256 borrowCap;\n    }\n\n    function jTokenMetadataAll(JToken[] calldata jTokens) external returns (JTokenMetadata[] memory) {\n        uint256 jTokenCount = jTokens.length;\n        require(jTokenCount > 0, \"invalid input\");\n        JTokenMetadata[] memory res = new JTokenMetadata[](jTokenCount);\n        Joetroller joetroller = Joetroller(address(jTokens[0].joetroller()));\n        PriceOracle priceOracle = joetroller.oracle();\n        for (uint256 i = 0; i < jTokenCount; i++) {\n            require(address(joetroller) == address(jTokens[i].joetroller()), \"mismatch joetroller\");\n            res[i] = jTokenMetadataInternal(jTokens[i], joetroller, priceOracle);\n        }\n        return res;\n    }\n\n    function jTokenMetadata(JToken jToken) public returns (JTokenMetadata memory) {\n        Joetroller joetroller = Joetroller(address(jToken.joetroller()));\n        PriceOracle priceOracle = joetroller.oracle();\n        return jTokenMetadataInternal(jToken, joetroller, priceOracle);\n    }\n\n    function jTokenMetadataInternal(\n        JToken jToken,\n        Joetroller joetroller,\n        PriceOracle priceOracle\n    ) internal returns (JTokenMetadata memory) {\n        uint256 exchangeRateCurrent = jToken.exchangeRateCurrent();\n        (bool isListed, uint256 collateralFactorMantissa, JoetrollerV1Storage.Version version) = joetroller.markets(\n            address(jToken)\n        );\n        address underlyingAssetAddress;\n        uint256 underlyingDecimals;\n        uint256 collateralCap;\n        uint256 totalCollateralTokens;\n\n        if (compareStrings(jToken.symbol(), nativeSymbol)) {\n            underlyingAssetAddress = address(0);\n            underlyingDecimals = 18;\n        } else {\n            JErc20 jErc20 = JErc20(address(jToken));\n            underlyingAssetAddress = jErc20.underlying();\n            underlyingDecimals = EIP20Interface(jErc20.underlying()).decimals();\n        }\n\n        if (version == JoetrollerV1Storage.Version.COLLATERALCAP) {\n            collateralCap = JCollateralCapErc20Interface(address(jToken)).collateralCap();\n            totalCollateralTokens = JCollateralCapErc20Interface(address(jToken)).totalCollateralTokens();\n        }\n\n        return\n            JTokenMetadata({\n                jToken: address(jToken),\n                exchangeRateCurrent: exchangeRateCurrent,\n                supplyRatePerSecond: jToken.supplyRatePerSecond(),\n                borrowRatePerSecond: jToken.borrowRatePerSecond(),\n                reserveFactorMantissa: jToken.reserveFactorMantissa(),\n                totalBorrows: jToken.totalBorrows(),\n                totalReserves: jToken.totalReserves(),\n                totalSupply: jToken.totalSupply(),\n                totalCash: jToken.getCash(),\n                totalCollateralTokens: totalCollateralTokens,\n                isListed: isListed,\n                collateralFactorMantissa: collateralFactorMantissa,\n                underlyingAssetAddress: underlyingAssetAddress,\n                jTokenDecimals: jToken.decimals(),\n                underlyingDecimals: underlyingDecimals,\n                version: version,\n                collateralCap: collateralCap,\n                underlyingPrice: priceOracle.getUnderlyingPrice(jToken),\n                supplyPaused: joetroller.mintGuardianPaused(address(jToken)),\n                borrowPaused: joetroller.borrowGuardianPaused(address(jToken)),\n                supplyCap: joetroller.supplyCaps(address(jToken)),\n                borrowCap: joetroller.borrowCaps(address(jToken))\n            });\n    }\n\n    /*** Account JToken info functions ***/\n\n    struct JTokenBalances {\n        address jToken;\n        uint256 jTokenBalance; // Same as collateral balance - the number of jTokens held\n        uint256 balanceOfUnderlyingCurrent; // Balance of underlying asset supplied by. Accrue interest is not called.\n        uint256 supplyValueUSD;\n        uint256 collateralValueUSD; // This is supplyValueUSD multiplied by collateral factor\n        uint256 borrowBalanceCurrent; // Borrow balance without accruing interest\n        uint256 borrowValueUSD;\n        uint256 underlyingTokenBalance; // Underlying balance current held in user's wallet\n        uint256 underlyingTokenAllowance;\n        bool collateralEnabled;\n    }\n\n    function jTokenBalancesAll(JToken[] memory jTokens, address account) public returns (JTokenBalances[] memory) {\n        uint256 jTokenCount = jTokens.length;\n        JTokenBalances[] memory res = new JTokenBalances[](jTokenCount);\n        for (uint256 i = 0; i < jTokenCount; i++) {\n            res[i] = jTokenBalances(jTokens[i], account);\n        }\n        return res;\n    }\n\n    function jTokenBalances(JToken jToken, address account) public returns (JTokenBalances memory) {\n        JTokenBalances memory vars;\n        Joetroller joetroller = Joetroller(address(jToken.joetroller()));\n\n        vars.jToken = address(jToken);\n        vars.collateralEnabled = joetroller.checkMembership(account, jToken);\n\n        if (compareStrings(jToken.symbol(), nativeSymbol)) {\n            vars.underlyingTokenBalance = account.balance;\n            vars.underlyingTokenAllowance = account.balance;\n        } else {\n            JErc20 jErc20 = JErc20(address(jToken));\n            EIP20Interface underlying = EIP20Interface(jErc20.underlying());\n            vars.underlyingTokenBalance = underlying.balanceOf(account);\n            vars.underlyingTokenAllowance = underlying.allowance(account, address(jToken));\n        }\n\n        vars.jTokenBalance = jToken.balanceOf(account);\n        vars.borrowBalanceCurrent = jToken.borrowBalanceCurrent(account);\n\n        vars.balanceOfUnderlyingCurrent = jToken.balanceOfUnderlying(account);\n        PriceOracle priceOracle = joetroller.oracle();\n        uint256 underlyingPrice = priceOracle.getUnderlyingPrice(jToken);\n\n        (, uint256 collateralFactorMantissa, ) = joetroller.markets(address(jToken));\n\n        Exp memory supplyValueInUnderlying = Exp({mantissa: vars.balanceOfUnderlyingCurrent});\n        vars.supplyValueUSD = mul_ScalarTruncate(supplyValueInUnderlying, underlyingPrice);\n\n        Exp memory collateralFactor = Exp({mantissa: collateralFactorMantissa});\n        vars.collateralValueUSD = mul_ScalarTruncate(collateralFactor, vars.supplyValueUSD);\n\n        Exp memory borrowBalance = Exp({mantissa: vars.borrowBalanceCurrent});\n        vars.borrowValueUSD = mul_ScalarTruncate(borrowBalance, underlyingPrice);\n\n        return vars;\n    }\n\n    struct AccountLimits {\n        JToken[] markets;\n        uint256 liquidity;\n        uint256 shortfall;\n        uint256 totalCollateralValueUSD;\n        uint256 totalBorrowValueUSD;\n        uint256 healthFactor;\n    }\n\n    function getAccountLimits(Joetroller joetroller, address account) public returns (AccountLimits memory) {\n        AccountLimits memory vars;\n        uint256 errorCode;\n\n        (errorCode, vars.liquidity, vars.shortfall) = joetroller.getAccountLiquidity(account);\n        require(errorCode == 0, \"Can't get account liquidity\");\n\n        vars.markets = joetroller.getAssetsIn(account);\n        JTokenBalances[] memory jTokenBalancesList = jTokenBalancesAll(vars.markets, account);\n        for (uint256 i = 0; i < jTokenBalancesList.length; i++) {\n            vars.totalCollateralValueUSD = add_(vars.totalCollateralValueUSD, jTokenBalancesList[i].collateralValueUSD);\n            vars.totalBorrowValueUSD = add_(vars.totalBorrowValueUSD, jTokenBalancesList[i].borrowValueUSD);\n        }\n\n        Exp memory totalBorrows = Exp({mantissa: vars.totalBorrowValueUSD});\n\n        vars.healthFactor = vars.totalCollateralValueUSD == 0 ? 0 : vars.totalBorrowValueUSD > 0\n            ? div_(vars.totalCollateralValueUSD, totalBorrows)\n            : 100;\n\n        return vars;\n    }\n\n    function getClaimableRewards(\n        uint8 rewardType,\n        address joetroller,\n        address joe,\n        address payable account\n    ) external returns (uint256) {\n        require(rewardType <= 1, \"rewardType is invalid\");\n        if (rewardType == 0) {\n            uint256 balanceBefore = EIP20Interface(joe).balanceOf(account);\n            Joetroller(joetroller).claimReward(0, account);\n            uint256 balanceAfter = EIP20Interface(joe).balanceOf(account);\n            return sub_(balanceAfter, balanceBefore);\n        } else if (rewardType == 1) {\n            uint256 balanceBefore = account.balance;\n            Joetroller(joetroller).claimReward(1, account);\n            uint256 balanceAfter = account.balance;\n            return sub_(balanceAfter, balanceBefore);\n        }\n    }\n\n    function compareStrings(string memory a, string memory b) internal pure returns (bool) {\n        return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));\n    }\n}\n"
    },
    "contracts/JWrappedNative.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JToken.sol\";\nimport \"./ERC3156FlashBorrowerInterface.sol\";\nimport \"./ERC3156FlashLenderInterface.sol\";\n\n/**\n * @title Wrapped native token interface\n */\ninterface WrappedNativeInterface {\n    function deposit() external payable;\n\n    function withdraw(uint256 wad) external;\n}\n\n/**\n * @title Cream's JWrappedNative Contract\n * @notice JTokens which wrap the native token\n * @author Cream\n */\ncontract JWrappedNative is JToken, JWrappedNativeInterface, JProtocolSeizeShareStorage {\n    /**\n     * @notice Initialize the new money market\n     * @param underlying_ The address of the underlying asset\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ ERC-20 name of this token\n     * @param symbol_ ERC-20 symbol of this token\n     * @param decimals_ ERC-20 decimal precision of this token\n     */\n    function initialize(\n        address underlying_,\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_\n    ) public {\n        // JToken initialize does the bulk of the work\n        super.initialize(joetroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);\n\n        // Set underlying and sanity check it\n        underlying = underlying_;\n        EIP20Interface(underlying).totalSupply();\n        WrappedNativeInterface(underlying);\n    }\n\n    /*** User Interface ***/\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for backward joeatibility\n     * @param mintAmount The amount of the underlying asset to supply\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function mint(uint256 mintAmount) external returns (uint256) {\n        (uint256 err, ) = mintInternal(mintAmount, false);\n        require(err == 0, \"mint failed\");\n    }\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for consistency\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function mintNative() external payable returns (uint256) {\n        (uint256 err, ) = mintInternal(msg.value, true);\n        require(err == 0, \"mint native failed\");\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for backward joeatibility\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeem(uint256 redeemTokens) external returns (uint256) {\n        require(redeemInternal(redeemTokens, false) == 0, \"redeem failed\");\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for consistency\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemNative(uint256 redeemTokens) external returns (uint256) {\n        require(redeemInternal(redeemTokens, true) == 0, \"redeem native failed\");\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for backward joeatibility\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {\n        require(redeemUnderlyingInternal(redeemAmount, false) == 0, \"redeem underlying failed\");\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for consistency\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256) {\n        require(redeemUnderlyingInternal(redeemAmount, true) == 0, \"redeem underlying native failed\");\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for backward joeatibility\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrow(uint256 borrowAmount) external returns (uint256) {\n        require(borrowInternal(borrowAmount, false) == 0, \"borrow failed\");\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for consistency\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrowNative(uint256 borrowAmount) external returns (uint256) {\n        require(borrowInternal(borrowAmount, true) == 0, \"borrow native failed\");\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for backward joeatibility\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrow(uint256 repayAmount) external returns (uint256) {\n        (uint256 err, ) = repayBorrowInternal(repayAmount, false);\n        require(err == 0, \"repay failed\");\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for consistency\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowNative() external payable returns (uint256) {\n        (uint256 err, ) = repayBorrowInternal(msg.value, true);\n        require(err == 0, \"repay native failed\");\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) {\n        (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount, false);\n        require(err == 0, \"repay behalf failed\");\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowBehalfNative(address borrower) external payable returns (uint256) {\n        (uint256 err, ) = repayBorrowBehalfInternal(borrower, msg.value, true);\n        require(err == 0, \"repay behalf native failed\");\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for backward joeatibility\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function liquidateBorrow(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) external returns (uint256) {\n        (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, jTokenCollateral, false);\n        require(err == 0, \"liquidate borrow failed\");\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for consistency\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function liquidateBorrowNative(address borrower, JTokenInterface jTokenCollateral)\n        external\n        payable\n        returns (uint256)\n    {\n        (uint256 err, ) = liquidateBorrowInternal(borrower, msg.value, jTokenCollateral, true);\n        require(err == 0, \"liquidate borrow native failed\");\n    }\n\n    /**\n     * @notice Get the max flash loan amount\n     */\n    function maxFlashLoan() external view returns (uint256) {\n        uint256 amount = 0;\n        if (JoetrollerInterfaceExtension(address(joetroller)).flashloanAllowed(address(this), address(0), amount, \"\")) {\n            amount = getCashPrior();\n        }\n        return amount;\n    }\n\n    /**\n     * @notice Get the flash loan fees\n     * @param amount amount of token to borrow\n     */\n    function flashFee(uint256 amount) external view returns (uint256) {\n        require(\n            JoetrollerInterfaceExtension(address(joetroller)).flashloanAllowed(address(this), address(0), amount, \"\"),\n            \"flashloan is paused\"\n        );\n        return div_(mul_(amount, flashFeeBips), 10000);\n    }\n\n    /**\n     * @notice Flash loan funds to a given account.\n     * @param receiver The receiver address for the funds\n     * @param initiator flash loan initiator\n     * @param amount The amount of the funds to be loaned\n     * @param data The other data\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function flashLoan(\n        ERC3156FlashBorrowerInterface receiver,\n        address initiator,\n        uint256 amount,\n        bytes calldata data\n    ) external nonReentrant returns (bool) {\n        require(amount > 0, \"flashLoan amount should be greater than zero\");\n        require(accrueInterest() == uint256(Error.NO_ERROR), \"accrue interest failed\");\n        require(\n            JoetrollerInterfaceExtension(address(joetroller)).flashloanAllowed(\n                address(this),\n                address(receiver),\n                amount,\n                data\n            ),\n            \"flashloan is paused\"\n        );\n        uint256 cashBefore = getCashPrior();\n        require(cashBefore >= amount, \"INSUFFICIENT_LIQUIDITY\");\n\n        // 1. calculate fee, 1 bips = 1/10000\n        uint256 totalFee = this.flashFee(amount);\n\n        // 2. transfer fund to receiver\n        doTransferOut(address(uint160(address(receiver))), amount, false);\n\n        // 3. update totalBorrows\n        totalBorrows = add_(totalBorrows, amount);\n\n        // 4. execute receiver's callback function\n        require(\n            receiver.onFlashLoan(initiator, underlying, amount, totalFee, data) ==\n                keccak256(\"ERC3156FlashBorrowerInterface.onFlashLoan\"),\n            \"IERC3156: Callback failed\"\n        );\n\n        // 5. take amount + fee from receiver, then check balance\n        uint256 repaymentAmount = add_(amount, totalFee);\n\n        doTransferIn(address(receiver), repaymentAmount, false);\n\n        uint256 cashAfter = getCashPrior();\n        require(cashAfter == add_(cashBefore, totalFee), \"BALANCE_INCONSISTENT\");\n\n        // 6. update totalReserves and totalBorrows\n        uint256 reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee);\n        totalReserves = add_(totalReserves, reservesFee);\n        totalBorrows = sub_(totalBorrows, amount);\n\n        emit Flashloan(address(receiver), amount, totalFee, reservesFee);\n        return true;\n    }\n\n    function() external payable {\n        require(msg.sender == underlying, \"only wrapped native contract could send native token\");\n    }\n\n    /**\n     * @notice The sender adds to reserves.\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for backward joeatibility\n     * @param addAmount The amount fo underlying token to add as reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReserves(uint256 addAmount) external returns (uint256) {\n        require(_addReservesInternal(addAmount, false) == 0, \"add reserves failed\");\n    }\n\n    /**\n     * @notice The sender adds to reserves.\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     *  Keep return in the function signature for consistency\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReservesNative() external payable returns (uint256) {\n        require(_addReservesInternal(msg.value, true) == 0, \"add reserves failed\");\n    }\n\n    /*** Safe Token ***/\n\n    /**\n     * @notice Gets balance of this contract in terms of the underlying\n     * @dev This excludes the value of the current message, if any\n     * @return The quantity of underlying tokens owned by this contract\n     */\n    function getCashPrior() internal view returns (uint256) {\n        EIP20Interface token = EIP20Interface(underlying);\n        return token.balanceOf(address(this));\n    }\n\n    /**\n     * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.\n     *      This will revert due to insufficient balance or insufficient allowance.\n     *      This function returns the actual amount received,\n     *      which may be less than `amount` if there is a fee attached to the transfer.\n     *\n     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n     */\n    function doTransferIn(\n        address from,\n        uint256 amount,\n        bool isNative\n    ) internal returns (uint256) {\n        if (isNative) {\n            // Sanity checks\n            require(msg.sender == from, \"sender mismatch\");\n            require(msg.value == amount, \"value mismatch\");\n\n            // Convert received native token to wrapped token\n            WrappedNativeInterface(underlying).deposit.value(amount)();\n            return amount;\n        } else {\n            EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n            uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this));\n            token.transferFrom(from, address(this), amount);\n\n            bool success;\n            assembly {\n                switch returndatasize()\n                case 0 {\n                    // This is a non-standard ERC-20\n                    success := not(0) // set success to true\n                }\n                case 32 {\n                    // This is a compliant ERC-20\n                    returndatacopy(0, 0, 32)\n                    success := mload(0) // Set `success = returndata` of external call\n                }\n                default {\n                    // This is an excessively non-compliant ERC-20, revert.\n                    revert(0, 0)\n                }\n            }\n            require(success, \"TOKEN_TRANSFER_IN_FAILED\");\n\n            // Calculate the amount that was *actually* transferred\n            uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this));\n            return sub_(balanceAfter, balanceBefore);\n        }\n    }\n\n    /**\n     * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory\n     *      error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to\n     *      insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified\n     *      it is >= amount, this should not revert in normal conditions.\n     *\n     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n     */\n    function doTransferOut(\n        address payable to,\n        uint256 amount,\n        bool isNative\n    ) internal {\n        if (isNative) {\n            // Convert wrapped token to native token\n            WrappedNativeInterface(underlying).withdraw(amount);\n            /* Send the Ether, with minimal gas and revert on failure */\n            to.transfer(amount);\n        } else {\n            EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n            token.transfer(to, amount);\n\n            bool success;\n            assembly {\n                switch returndatasize()\n                case 0 {\n                    // This is a non-standard ERC-20\n                    success := not(0) // set success to true\n                }\n                case 32 {\n                    // This is a joelaint ERC-20\n                    returndatacopy(0, 0, 32)\n                    success := mload(0) // Set `success = returndata` of external call\n                }\n                default {\n                    // This is an excessively non-compliant ERC-20, revert.\n                    revert(0, 0)\n                }\n            }\n            require(success, \"TOKEN_TRANSFER_OUT_FAILED\");\n        }\n    }\n\n    /**\n     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n     * @dev Called by both `transfer` and `transferFrom` internally\n     * @param spender The address of the account performing the transfer\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param tokens The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferTokens(\n        address spender,\n        address src,\n        address dst,\n        uint256 tokens\n    ) internal returns (uint256) {\n        /* Fail if transfer not allowed */\n        uint256 allowed = joetroller.transferAllowed(address(this), src, dst, tokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.TRANSFER_JOETROLLER_REJECTION, allowed);\n        }\n\n        /* Do not allow self-transfers */\n        if (src == dst) {\n            return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);\n        }\n\n        /* Get the allowance, infinite for the account owner */\n        uint256 startingAllowance = 0;\n        if (spender == src) {\n            startingAllowance = uint256(-1);\n        } else {\n            startingAllowance = transferAllowances[src][spender];\n        }\n\n        /* Do the calculations, checking for {under,over}flow */\n        accountTokens[src] = sub_(accountTokens[src], tokens);\n        accountTokens[dst] = add_(accountTokens[dst], tokens);\n\n        /* Eat some of the allowance (if necessary) */\n        if (startingAllowance != uint256(-1)) {\n            transferAllowances[src][spender] = sub_(startingAllowance, tokens);\n        }\n\n        /* We emit a Transfer event */\n        emit Transfer(src, dst, tokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Get the account's jToken balances\n     * @param account The address of the account\n     */\n    function getJTokenBalanceInternal(address account) internal view returns (uint256) {\n        return accountTokens[account];\n    }\n\n    struct MintLocalVars {\n        uint256 exchangeRateMantissa;\n        uint256 mintTokens;\n        uint256 actualMintAmount;\n    }\n\n    /**\n     * @notice User supplies assets into the market and receives jTokens in exchange\n     * @dev Assumes interest has already been accrued up to the current timestamp\n     * @param minter The address of the account which is supplying the assets\n     * @param mintAmount The amount of the underlying asset to supply\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n     */\n    function mintFresh(\n        address minter,\n        uint256 mintAmount,\n        bool isNative\n    ) internal returns (uint256, uint256) {\n        /* Fail if mint not allowed */\n        uint256 allowed = joetroller.mintAllowed(address(this), minter, mintAmount);\n        if (allowed != 0) {\n            return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.MINT_JOETROLLER_REJECTION, allowed), 0);\n        }\n\n        /*\n         * Return if mintAmount is zero.\n         * Put behind `mintAllowed` for accuring potential JOE rewards.\n         */\n        if (mintAmount == 0) {\n            return (uint256(Error.NO_ERROR), 0);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);\n        }\n\n        MintLocalVars memory vars;\n\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         *  We call `doTransferIn` for the minter and the mintAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  `doTransferIn` reverts if anything goes wrong, since we can't be sure if\n         *  side-effects occurred. The function returns the amount actually transferred,\n         *  in case of a fee. On success, the jToken holds an additional `actualMintAmount`\n         *  of cash.\n         */\n        vars.actualMintAmount = doTransferIn(minter, mintAmount, isNative);\n\n        /*\n         * We get the current exchange rate and calculate the number of jTokens to be minted:\n         *  mintTokens = actualMintAmount / exchangeRate\n         */\n        vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));\n\n        /*\n         * We calculate the new total supply of jTokens and minter token balance, checking for overflow:\n         *  totalSupply = totalSupply + mintTokens\n         *  accountTokens[minter] = accountTokens[minter] + mintTokens\n         */\n        totalSupply = add_(totalSupply, vars.mintTokens);\n        accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens);\n\n        /* We emit a Mint event, and a Transfer event */\n        emit Mint(minter, vars.actualMintAmount, vars.mintTokens);\n        emit Transfer(address(this), minter, vars.mintTokens);\n\n        return (uint256(Error.NO_ERROR), vars.actualMintAmount);\n    }\n\n    struct RedeemLocalVars {\n        uint256 exchangeRateMantissa;\n        uint256 redeemTokens;\n        uint256 redeemAmount;\n        uint256 totalSupplyNew;\n        uint256 accountTokensNew;\n    }\n\n    /**\n     * @notice User redeems jTokens in exchange for the underlying asset\n     * @dev Assumes interest has already been accrued up to the current timestamp. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero.\n     * @param redeemer The address of the account which is redeeming the tokens\n     * @param redeemTokensIn The number of jTokens to redeem into underlying\n     * @param redeemAmountIn The number of underlying tokens to receive from redeeming jTokens\n     * @param isNative The amount is in native or not\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemFresh(\n        address payable redeemer,\n        uint256 redeemTokensIn,\n        uint256 redeemAmountIn,\n        bool isNative\n    ) internal returns (uint256) {\n        require(redeemTokensIn == 0 || redeemAmountIn == 0, \"one of redeemTokensIn or redeemAmountIn must be zero\");\n\n        RedeemLocalVars memory vars;\n\n        /* exchangeRate = invoke Exchange Rate Stored() */\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /* If redeemTokensIn > 0: */\n        if (redeemTokensIn > 0) {\n            /*\n             * We calculate the exchange rate and the amount of underlying to be redeemed:\n             *  redeemTokens = redeemTokensIn\n             *  redeemAmount = redeemTokensIn x exchangeRateCurrent\n             */\n            vars.redeemTokens = redeemTokensIn;\n            vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);\n        } else {\n            /*\n             * We get the current exchange rate and calculate the amount to be redeemed:\n             *  redeemTokens = redeemAmountIn / exchangeRate\n             *  redeemAmount = redeemAmountIn\n             */\n            vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));\n            vars.redeemAmount = redeemAmountIn;\n        }\n\n        /* Fail if redeem not allowed */\n        uint256 allowed = joetroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REDEEM_JOETROLLER_REJECTION, allowed);\n        }\n\n        /*\n         * Return if redeemTokensIn and redeemAmountIn are zero.\n         * Put behind `redeemAllowed` for accuring potential JOE rewards.\n         */\n        if (redeemTokensIn == 0 && redeemAmountIn == 0) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);\n        }\n\n        /*\n         * We calculate the new total supply and redeemer balance, checking for underflow:\n         *  totalSupplyNew = totalSupply - redeemTokens\n         *  accountTokensNew = accountTokens[redeemer] - redeemTokens\n         */\n        vars.totalSupplyNew = sub_(totalSupply, vars.redeemTokens);\n        vars.accountTokensNew = sub_(accountTokens[redeemer], vars.redeemTokens);\n\n        /* Fail gracefully if protocol has insufficient cash */\n        if (getCashPrior() < vars.redeemAmount) {\n            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We invoke doTransferOut for the redeemer and the redeemAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken has redeemAmount less of cash.\n         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         */\n        doTransferOut(redeemer, vars.redeemAmount, isNative);\n\n        /* We write previously calculated values into storage */\n        totalSupply = vars.totalSupplyNew;\n        accountTokens[redeemer] = vars.accountTokensNew;\n\n        /* We emit a Transfer event, and a Redeem event */\n        emit Transfer(redeemer, address(this), vars.redeemTokens);\n        emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        /* We call the defense hook */\n        joetroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another JToken.\n     *  Its absolutely critical to use msg.sender as the seizer jToken and not a parameter.\n     * @param seizerToken The contract seizing the collateral (i.e. borrowed jToken)\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seizeInternal(\n        address seizerToken,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) internal returns (uint256) {\n        /* Fail if seize not allowed */\n        uint256 allowed = joetroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_JOETROLLER_REJECTION, allowed);\n        }\n\n        /*\n         * Return if seizeTokens is zero.\n         * Put behind `seizeAllowed` for accuring potential JOE rewards.\n         */\n        if (seizeTokens == 0) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Fail if borrower = liquidator */\n        if (borrower == liquidator) {\n            return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);\n        }\n\n        uint256 protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}));\n        uint256 liquidatorSeizeTokens = sub_(seizeTokens, protocolSeizeTokens);\n\n        uint256 exchangeRateMantissa = exchangeRateStoredInternal();\n        uint256 protocolSeizeAmount = mul_ScalarTruncate(Exp({mantissa: exchangeRateMantissa}), protocolSeizeTokens);\n\n        /*\n         * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:\n         *  borrowerTokensNew = accountTokens[borrower] - seizeTokens\n         *  liquidatorTokensNew = accountTokens[liquidator] + seizeTokens\n         */\n        accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens);\n        accountTokens[liquidator] = add_(accountTokens[liquidator], liquidatorSeizeTokens);\n        totalReserves = add_(totalReserves, protocolSeizeAmount);\n        totalSupply = sub_(totalSupply, protocolSeizeTokens);\n\n        /* Emit a Transfer event */\n        emit Transfer(borrower, liquidator, seizeTokens);\n        emit ReservesAdded(address(this), protocolSeizeAmount, totalReserves);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /*** Admin Functions ***/\n\n    /**\n     * @notice Accrues interest and sets a new collateral seize share for the protocol using _setProtocolSeizeShareFresh\n     * @dev Admin function to accrue interest and set a new collateral seize share\n     * @return uint256 0=success, otherwise a failure (see ErrorReport.sol for details)\n     */\n    function _setProtocolSeizeShare(uint256 newProtocolSeizeShareMantissa) external nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            return fail(Error(error), FailureInfo.SET_PROTOCOL_SEIZE_SHARE_ACCRUE_INTEREST_FAILED);\n        }\n        return _setProtocolSeizeShareFresh(newProtocolSeizeShareMantissa);\n    }\n\n    function _setProtocolSeizeShareFresh(uint256 newProtocolSeizeShareMantissa) internal returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PROTOCOL_SEIZE_SHARE_ADMIN_CHECK);\n        }\n\n        // Verify market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_PROTOCOL_SEIZE_SHARE_FRESH_CHECK);\n        }\n\n        if (newProtocolSeizeShareMantissa > protocolSeizeShareMaxMantissa) {\n            return fail(Error.BAD_INPUT, FailureInfo.SET_PROTOCOL_SEIZE_SHARE_BOUNDS_CHECK);\n        }\n\n        uint256 oldProtocolSeizeShareMantissa = protocolSeizeShareMantissa;\n        protocolSeizeShareMantissa = newProtocolSeizeShareMantissa;\n\n        emit NewProtocolSeizeShare(oldProtocolSeizeShareMantissa, newProtocolSeizeShareMantissa);\n\n        return uint256(Error.NO_ERROR);\n    }\n}\n"
    },
    "contracts/ERC3156FlashLenderInterface.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\nimport \"./ERC3156FlashBorrowerInterface.sol\";\n\ninterface ERC3156FlashLenderInterface {\n    /**\n     * @dev The amount of currency available to be lent.\n     * @param token The loan currency.\n     * @return The amount of `token` that can be borrowed.\n     */\n    function maxFlashLoan(address token) external view returns (uint256);\n\n    /**\n     * @dev The fee to be charged for a given loan.\n     * @param token The loan currency.\n     * @param amount The amount of tokens lent.\n     * @return The amount of `token` to be charged for the loan, on top of the returned principal.\n     */\n    function flashFee(address token, uint256 amount) external view returns (uint256);\n\n    /**\n     * @dev Initiate a flash loan.\n     * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.\n     * @param token The loan currency.\n     * @param amount The amount of tokens lent.\n     * @param data Arbitrary data structure, intended to contain user-defined parameters.\n     */\n    function flashLoan(\n        ERC3156FlashBorrowerInterface receiver,\n        address token,\n        uint256 amount,\n        bytes calldata data\n    ) external returns (bool);\n}\n"
    },
    "contracts/Maximillion.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JWrappedNative.sol\";\n\n/**\n * @title Compound's Maximillion Contract\n * @author Compound\n */\ncontract Maximillion {\n    /**\n     * @notice The default jAvax market to repay in\n     */\n    JWrappedNative public jAvax;\n\n    /**\n     * @notice Construct a Maximillion to repay max in a JWrappedNative market\n     */\n    constructor(JWrappedNative jAvax_) public {\n        jAvax = jAvax_;\n    }\n\n    /**\n     * @notice msg.sender sends Ether to repay an account's borrow in the jAvax market\n     * @dev The provided Ether is applied towards the borrow balance, any excess is refunded\n     * @param borrower The address of the borrower account to repay on behalf of\n     */\n    function repayBehalf(address borrower) public payable {\n        repayBehalfExplicit(borrower, jAvax);\n    }\n\n    /**\n     * @notice msg.sender sends Ether to repay an account's borrow in a jAvax market\n     * @dev The provided Ether is applied towards the borrow balance, any excess is refunded\n     * @param borrower The address of the borrower account to repay on behalf of\n     * @param jAvax_ The address of the jAvax contract to repay in\n     */\n    function repayBehalfExplicit(address borrower, JWrappedNative jAvax_) public payable {\n        uint256 received = msg.value;\n        uint256 borrows = jAvax_.borrowBalanceCurrent(borrower);\n        if (received > borrows) {\n            jAvax_.repayBorrowBehalfNative.value(borrows)(borrower);\n            msg.sender.transfer(received - borrows);\n        } else {\n            jAvax_.repayBorrowBehalfNative.value(received)(borrower);\n        }\n    }\n}\n"
    },
    "contracts/JWrappedNativeDelegate.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JWrappedNative.sol\";\n\n/**\n * @title Cream's JWrappedNativeDelegate Contract\n * @notice JTokens which wrap an EIP-20 underlying and are delegated to\n * @author Cream\n */\ncontract JWrappedNativeDelegate is JWrappedNative {\n    /**\n     * @notice Construct an empty delegate\n     */\n    constructor() public {}\n\n    /**\n     * @notice Called by the delegator on a delegate to initialize it for duty\n     * @param data The encoded bytes data for any initialization\n     */\n    function _becomeImplementation(bytes memory data) public {\n        // Shh -- currently unused\n        data;\n\n        // Shh -- we don't ever want this hook to be marked pure\n        if (false) {\n            implementation = address(0);\n        }\n\n        require(msg.sender == admin, \"only the admin may call _becomeImplementation\");\n\n        // Set JToken version in joetroller and convert native token to wrapped token.\n        JoetrollerInterfaceExtension(address(joetroller)).updateJTokenVersion(\n            address(this),\n            JoetrollerV1Storage.Version.WRAPPEDNATIVE\n        );\n        uint256 balance = address(this).balance;\n        if (balance > 0) {\n            WrappedNativeInterface(underlying).deposit.value(balance)();\n        }\n    }\n\n    /**\n     * @notice Called by the delegator on a delegate to forfeit its responsibility\n     */\n    function _resignImplementation() public {\n        // Shh -- we don't ever want this hook to be marked pure\n        if (false) {\n            implementation = address(0);\n        }\n\n        require(msg.sender == admin, \"only the admin may call _resignImplementation\");\n    }\n}\n"
    },
    "contracts/JCollateralCapErc20.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JToken.sol\";\nimport \"./ERC3156FlashLenderInterface.sol\";\nimport \"./ERC3156FlashBorrowerInterface.sol\";\n\n/**\n * @title Cream's JCollateralCapErc20 Contract\n * @notice JTokens which wrap an EIP-20 underlying with collateral cap\n * @author Cream\n */\ncontract JCollateralCapErc20 is JToken, JCollateralCapErc20Interface, JProtocolSeizeShareStorage {\n    /**\n     * @notice Initialize the new money market\n     * @param underlying_ The address of the underlying asset\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ ERC-20 name of this token\n     * @param symbol_ ERC-20 symbol of this token\n     * @param decimals_ ERC-20 decimal precision of this token\n     */\n    function initialize(\n        address underlying_,\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_\n    ) public {\n        // JToken initialize does the bulk of the work\n        super.initialize(joetroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);\n\n        // Set underlying and sanity check it\n        underlying = underlying_;\n        EIP20Interface(underlying).totalSupply();\n    }\n\n    /*** User Interface ***/\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param mintAmount The amount of the underlying asset to supply\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function mint(uint256 mintAmount) external returns (uint256) {\n        (uint256 err, ) = mintInternal(mintAmount, false);\n        return err;\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeem(uint256 redeemTokens) external returns (uint256) {\n        return redeemInternal(redeemTokens, false);\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {\n        return redeemUnderlyingInternal(redeemAmount, false);\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrow(uint256 borrowAmount) external returns (uint256) {\n        return borrowInternal(borrowAmount, false);\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrow(uint256 repayAmount) external returns (uint256) {\n        (uint256 err, ) = repayBorrowInternal(repayAmount, false);\n        return err;\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) {\n        (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount, false);\n        return err;\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function liquidateBorrow(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) external returns (uint256) {\n        (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, jTokenCollateral, false);\n        return err;\n    }\n\n    /**\n     * @notice The sender adds to reserves.\n     * @param addAmount The amount fo underlying token to add as reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReserves(uint256 addAmount) external returns (uint256) {\n        return _addReservesInternal(addAmount, false);\n    }\n\n    /**\n     * @notice Set the given collateral cap for the market.\n     * @param newCollateralCap New collateral cap for this market. A value of 0 corresponds to no cap.\n     */\n    function _setCollateralCap(uint256 newCollateralCap) external {\n        require(msg.sender == admin, \"only admin can set collateral cap\");\n\n        collateralCap = newCollateralCap;\n        emit NewCollateralCap(address(this), newCollateralCap);\n    }\n\n    /**\n     * @notice Absorb excess cash into reserves.\n     */\n    function gulp() external nonReentrant {\n        uint256 cashOnChain = getCashOnChain();\n        uint256 cashPrior = getCashPrior();\n\n        uint256 excessCash = sub_(cashOnChain, cashPrior);\n        totalReserves = add_(totalReserves, excessCash);\n        internalCash = cashOnChain;\n    }\n\n    /**\n     * @notice Get the max flash loan amount\n     */\n    function maxFlashLoan() external view returns (uint256) {\n        uint256 amount = 0;\n        if (JoetrollerInterfaceExtension(address(joetroller)).flashloanAllowed(address(this), address(0), amount, \"\")) {\n            amount = getCashPrior();\n        }\n        return amount;\n    }\n\n    /**\n     * @notice Get the flash loan fees\n     * @param amount amount of token to borrow\n     */\n    function flashFee(uint256 amount) external view returns (uint256) {\n        require(\n            JoetrollerInterfaceExtension(address(joetroller)).flashloanAllowed(address(this), address(0), amount, \"\"),\n            \"flashloan is paused\"\n        );\n        return div_(mul_(amount, flashFeeBips), 10000);\n    }\n\n    /**\n     * @notice Flash loan funds to a given account.\n     * @param receiver The receiver address for the funds\n     * @param initiator flash loan initiator\n     * @param amount The amount of the funds to be loaned\n     * @param data The other data\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function flashLoan(\n        ERC3156FlashBorrowerInterface receiver,\n        address initiator,\n        uint256 amount,\n        bytes calldata data\n    ) external nonReentrant returns (bool) {\n        require(amount > 0, \"flashLoan amount should be greater than zero\");\n        require(accrueInterest() == uint256(Error.NO_ERROR), \"accrue interest failed\");\n        require(\n            JoetrollerInterfaceExtension(address(joetroller)).flashloanAllowed(\n                address(this),\n                address(receiver),\n                amount,\n                data\n            ),\n            \"flashloan is paused\"\n        );\n        uint256 cashOnChainBefore = getCashOnChain();\n        uint256 cashBefore = getCashPrior();\n        require(cashBefore >= amount, \"INSUFFICIENT_LIQUIDITY\");\n\n        // 1. calculate fee, 1 bips = 1/10000\n        uint256 totalFee = this.flashFee(amount);\n\n        // 2. transfer fund to receiver\n        doTransferOut(address(uint160(address(receiver))), amount, false);\n\n        // 3. update totalBorrows\n        totalBorrows = add_(totalBorrows, amount);\n\n        // 4. execute receiver's callback function\n\n        require(\n            receiver.onFlashLoan(initiator, underlying, amount, totalFee, data) ==\n                keccak256(\"ERC3156FlashBorrowerInterface.onFlashLoan\"),\n            \"IERC3156: Callback failed\"\n        );\n\n        // 5. take amount + fee from receiver, then check balance\n        uint256 repaymentAmount = add_(amount, totalFee);\n        doTransferIn(address(receiver), repaymentAmount, false);\n\n        uint256 cashOnChainAfter = getCashOnChain();\n\n        require(cashOnChainAfter == add_(cashOnChainBefore, totalFee), \"BALANCE_INCONSISTENT\");\n\n        // 6. update reserves and internal cash and totalBorrows\n        uint256 reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee);\n        totalReserves = add_(totalReserves, reservesFee);\n        internalCash = add_(cashBefore, totalFee);\n        totalBorrows = sub_(totalBorrows, amount);\n\n        emit Flashloan(address(receiver), amount, totalFee, reservesFee);\n        return true;\n    }\n\n    /**\n     * @notice Register account collateral tokens if there is space.\n     * @param account The account to register\n     * @dev This function could only be called by joetroller.\n     * @return The actual registered amount of collateral\n     */\n    function registerCollateral(address account) external returns (uint256) {\n        // Make sure accountCollateralTokens of `account` is initialized.\n        initializeAccountCollateralTokens(account);\n\n        require(msg.sender == address(joetroller), \"only joetroller may register collateral for user\");\n\n        uint256 amount = sub_(accountTokens[account], accountCollateralTokens[account]);\n        return increaseUserCollateralInternal(account, amount);\n    }\n\n    /**\n     * @notice Unregister account collateral tokens if the account still has enough collateral.\n     * @dev This function could only be called by joetroller.\n     * @param account The account to unregister\n     */\n    function unregisterCollateral(address account) external {\n        // Make sure accountCollateralTokens of `account` is initialized.\n        initializeAccountCollateralTokens(account);\n\n        require(msg.sender == address(joetroller), \"only joetroller may unregister collateral for user\");\n\n        decreaseUserCollateralInternal(account, accountCollateralTokens[account]);\n    }\n\n    /*** Safe Token ***/\n\n    /**\n     * @notice Gets internal balance of this contract in terms of the underlying.\n     *  It excludes balance from direct transfer.\n     * @dev This excludes the value of the current message, if any\n     * @return The quantity of underlying tokens owned by this contract\n     */\n    function getCashPrior() internal view returns (uint256) {\n        return internalCash;\n    }\n\n    /**\n     * @notice Gets total balance of this contract in terms of the underlying\n     * @dev This excludes the value of the current message, if any\n     * @return The quantity of underlying tokens owned by this contract\n     */\n    function getCashOnChain() internal view returns (uint256) {\n        EIP20Interface token = EIP20Interface(underlying);\n        return token.balanceOf(address(this));\n    }\n\n    /**\n     * @notice Initialize the account's collateral tokens. This function should be called in the beginning of every function\n     *  that accesses accountCollateralTokens or accountTokens.\n     * @param account The account of accountCollateralTokens that needs to be updated\n     */\n    function initializeAccountCollateralTokens(address account) internal {\n        /**\n         * If isCollateralTokenInit is false, it means accountCollateralTokens was not initialized yet.\n         * This case will only happen once and must be the very beginning. accountCollateralTokens is a new structure and its\n         * initial value should be equal to accountTokens if user has entered the market. However, it's almost impossible to\n         * check every user's value when the implementation becomes active. Therefore, it must rely on every action which will\n         * access accountTokens to call this function to check if accountCollateralTokens needed to be initialized.\n         */\n        if (!isCollateralTokenInit[account]) {\n            if (JoetrollerInterfaceExtension(address(joetroller)).checkMembership(account, JToken(this))) {\n                accountCollateralTokens[account] = accountTokens[account];\n                totalCollateralTokens = add_(totalCollateralTokens, accountTokens[account]);\n\n                emit UserCollateralChanged(account, accountCollateralTokens[account]);\n            }\n            isCollateralTokenInit[account] = true;\n        }\n    }\n\n    /**\n     * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.\n     *      This will revert due to insufficient balance or insufficient allowance.\n     *      This function returns the actual amount received,\n     *      which may be less than `amount` if there is a fee attached to the transfer.\n     *\n     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n     */\n    function doTransferIn(\n        address from,\n        uint256 amount,\n        bool isNative\n    ) internal returns (uint256) {\n        isNative; // unused\n\n        EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n        uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this));\n        token.transferFrom(from, address(this), amount);\n\n        bool success;\n        assembly {\n            switch returndatasize()\n            case 0 {\n                // This is a non-standard ERC-20\n                success := not(0) // set success to true\n            }\n            case 32 {\n                // This is a joeliant ERC-20\n                returndatacopy(0, 0, 32)\n                success := mload(0) // Set `success = returndata` of external call\n            }\n            default {\n                // This is an excessively non-joeliant ERC-20, revert.\n                revert(0, 0)\n            }\n        }\n        require(success, \"TOKEN_TRANSFER_IN_FAILED\");\n\n        // Calculate the amount that was *actually* transferred\n        uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this));\n        uint256 transferredIn = sub_(balanceAfter, balanceBefore);\n        internalCash = add_(internalCash, transferredIn);\n        return transferredIn;\n    }\n\n    /**\n     * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory\n     *      error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to\n     *      insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified\n     *      it is >= amount, this should not revert in normal conditions.\n     *\n     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n     */\n    function doTransferOut(\n        address payable to,\n        uint256 amount,\n        bool isNative\n    ) internal {\n        isNative; // unused\n\n        EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n        token.transfer(to, amount);\n\n        bool success;\n        assembly {\n            switch returndatasize()\n            case 0 {\n                // This is a non-standard ERC-20\n                success := not(0) // set success to true\n            }\n            case 32 {\n                // This is a joelaint ERC-20\n                returndatacopy(0, 0, 32)\n                success := mload(0) // Set `success = returndata` of external call\n            }\n            default {\n                // This is an excessively non-joeliant ERC-20, revert.\n                revert(0, 0)\n            }\n        }\n        require(success, \"TOKEN_TRANSFER_OUT_FAILED\");\n        internalCash = sub_(internalCash, amount);\n    }\n\n    /**\n     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n     * @dev Called by both `transfer` and `transferFrom` internally\n     * @param spender The address of the account performing the transfer\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param tokens The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferTokens(\n        address spender,\n        address src,\n        address dst,\n        uint256 tokens\n    ) internal returns (uint256) {\n        // Make sure accountCollateralTokens of `src` and `dst` are initialized.\n        initializeAccountCollateralTokens(src);\n        initializeAccountCollateralTokens(dst);\n\n        /**\n         * For every user, accountTokens must be greater than or equal to accountCollateralTokens.\n         * The buffer between the two values will be transferred first.\n         * bufferTokens = accountTokens[src] - accountCollateralTokens[src]\n         * collateralTokens = tokens - bufferTokens\n         */\n        uint256 bufferTokens = sub_(accountTokens[src], accountCollateralTokens[src]);\n        uint256 collateralTokens = 0;\n        if (tokens > bufferTokens) {\n            collateralTokens = tokens - bufferTokens;\n        }\n\n        /**\n         * Since bufferTokens are not collateralized and can be transferred freely, we only check with joetroller\n         * whether collateralized tokens can be transferred.\n         */\n        uint256 allowed = joetroller.transferAllowed(address(this), src, dst, collateralTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.TRANSFER_JOETROLLER_REJECTION, allowed);\n        }\n\n        /* Do not allow self-transfers */\n        if (src == dst) {\n            return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);\n        }\n\n        /* Get the allowance, infinite for the account owner */\n        uint256 startingAllowance = 0;\n        if (spender == src) {\n            startingAllowance = uint256(-1);\n        } else {\n            startingAllowance = transferAllowances[src][spender];\n        }\n\n        /* Do the calculations, checking for {under,over}flow */\n        accountTokens[src] = sub_(accountTokens[src], tokens);\n        accountTokens[dst] = add_(accountTokens[dst], tokens);\n        if (collateralTokens > 0) {\n            accountCollateralTokens[src] = sub_(accountCollateralTokens[src], collateralTokens);\n            accountCollateralTokens[dst] = add_(accountCollateralTokens[dst], collateralTokens);\n\n            emit UserCollateralChanged(src, accountCollateralTokens[src]);\n            emit UserCollateralChanged(dst, accountCollateralTokens[dst]);\n        }\n\n        /* Eat some of the allowance (if necessary) */\n        if (startingAllowance != uint256(-1)) {\n            transferAllowances[src][spender] = sub_(startingAllowance, tokens);\n        }\n\n        /* We emit a Transfer event */\n        emit Transfer(src, dst, tokens);\n\n        // unused function\n        // joetroller.transferVerify(address(this), src, dst, tokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Get the account's jToken balances\n     * @param account The address of the account\n     */\n    function getJTokenBalanceInternal(address account) internal view returns (uint256) {\n        if (isCollateralTokenInit[account]) {\n            return accountCollateralTokens[account];\n        } else {\n            /**\n             * If the value of accountCollateralTokens was not initialized, we should return the value of accountTokens.\n             */\n            return accountTokens[account];\n        }\n    }\n\n    /**\n     * @notice Increase user's collateral. Increase as much as we can.\n     * @param account The address of the account\n     * @param amount The amount of collateral user wants to increase\n     * @return The actual increased amount of collateral\n     */\n    function increaseUserCollateralInternal(address account, uint256 amount) internal returns (uint256) {\n        uint256 totalCollateralTokensNew = add_(totalCollateralTokens, amount);\n        if (collateralCap == 0 || (collateralCap != 0 && totalCollateralTokensNew <= collateralCap)) {\n            // 1. If collateral cap is not set,\n            // 2. If collateral cap is set but has enough space for this user,\n            // give all the user needs.\n            totalCollateralTokens = totalCollateralTokensNew;\n            accountCollateralTokens[account] = add_(accountCollateralTokens[account], amount);\n\n            emit UserCollateralChanged(account, accountCollateralTokens[account]);\n            return amount;\n        } else if (collateralCap > totalCollateralTokens) {\n            // If the collateral cap is set but the remaining cap is not enough for this user,\n            // give the remaining parts to the user.\n            uint256 gap = sub_(collateralCap, totalCollateralTokens);\n            totalCollateralTokens = collateralCap;\n            accountCollateralTokens[account] = add_(accountCollateralTokens[account], gap);\n\n            emit UserCollateralChanged(account, accountCollateralTokens[account]);\n            return gap;\n        }\n        return 0;\n    }\n\n    /**\n     * @notice Decrease user's collateral. Reject if the amount can't be fully decrease.\n     * @param account The address of the account\n     * @param amount The amount of collateral user wants to decrease\n     */\n    function decreaseUserCollateralInternal(address account, uint256 amount) internal {\n        require(joetroller.redeemAllowed(address(this), account, amount) == 0, \"joetroller rejection\");\n\n        /*\n         * Return if amount is zero.\n         * Put behind `redeemAllowed` for accuring potential JOE rewards.\n         */\n        if (amount == 0) {\n            return;\n        }\n\n        totalCollateralTokens = sub_(totalCollateralTokens, amount);\n        accountCollateralTokens[account] = sub_(accountCollateralTokens[account], amount);\n\n        emit UserCollateralChanged(account, accountCollateralTokens[account]);\n    }\n\n    struct MintLocalVars {\n        uint256 exchangeRateMantissa;\n        uint256 mintTokens;\n        uint256 actualMintAmount;\n    }\n\n    /**\n     * @notice User supplies assets into the market and receives jTokens in exchange\n     * @dev Assumes interest has already been accrued up to the current timestamp\n     * @param minter The address of the account which is supplying the assets\n     * @param mintAmount The amount of the underlying asset to supply\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n     */\n    function mintFresh(\n        address minter,\n        uint256 mintAmount,\n        bool isNative\n    ) internal returns (uint256, uint256) {\n        // Make sure accountCollateralTokens of `minter` is initialized.\n        initializeAccountCollateralTokens(minter);\n\n        /* Fail if mint not allowed */\n        uint256 allowed = joetroller.mintAllowed(address(this), minter, mintAmount);\n        if (allowed != 0) {\n            return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.MINT_JOETROLLER_REJECTION, allowed), 0);\n        }\n\n        /*\n         * Return if mintAmount is zero.\n         * Put behind `mintAllowed` for accuring potential JOE rewards.\n         */\n        if (mintAmount == 0) {\n            return (uint256(Error.NO_ERROR), 0);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);\n        }\n\n        MintLocalVars memory vars;\n\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         *  We call `doTransferIn` for the minter and the mintAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  `doTransferIn` reverts if anything goes wrong, since we can't be sure if\n         *  side-effects occurred. The function returns the amount actually transferred,\n         *  in case of a fee. On success, the jToken holds an additional `actualMintAmount`\n         *  of cash.\n         */\n        vars.actualMintAmount = doTransferIn(minter, mintAmount, isNative);\n\n        /*\n         * We get the current exchange rate and calculate the number of jTokens to be minted:\n         *  mintTokens = actualMintAmount / exchangeRate\n         */\n        vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));\n\n        /*\n         * We calculate the new total supply of jTokens and minter token balance, checking for overflow:\n         *  totalSupply = totalSupply + mintTokens\n         *  accountTokens[minter] = accountTokens[minter] + mintTokens\n         */\n        totalSupply = add_(totalSupply, vars.mintTokens);\n        accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens);\n\n        /*\n         * We only allocate collateral tokens if the minter has entered the market.\n         */\n        if (JoetrollerInterfaceExtension(address(joetroller)).checkMembership(minter, JToken(this))) {\n            increaseUserCollateralInternal(minter, vars.mintTokens);\n        }\n\n        /* We emit a Mint event, and a Transfer event */\n        emit Mint(minter, vars.actualMintAmount, vars.mintTokens);\n        emit Transfer(address(this), minter, vars.mintTokens);\n\n        /* We call the defense hook */\n        // unused function\n        // joetroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);\n\n        return (uint256(Error.NO_ERROR), vars.actualMintAmount);\n    }\n\n    struct RedeemLocalVars {\n        uint256 exchangeRateMantissa;\n        uint256 redeemTokens;\n        uint256 redeemAmount;\n    }\n\n    /**\n     * @notice User redeems jTokens in exchange for the underlying asset\n     * @dev Assumes interest has already been accrued up to the current timestamp. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero.\n     * @param redeemer The address of the account which is redeeming the tokens\n     * @param redeemTokensIn The number of jTokens to redeem into underlying\n     * @param redeemAmountIn The number of underlying tokens to receive from redeeming jTokens\n     * @param isNative The amount is in native or not\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemFresh(\n        address payable redeemer,\n        uint256 redeemTokensIn,\n        uint256 redeemAmountIn,\n        bool isNative\n    ) internal returns (uint256) {\n        // Make sure accountCollateralTokens of `redeemer` is initialized.\n        initializeAccountCollateralTokens(redeemer);\n\n        require(redeemTokensIn == 0 || redeemAmountIn == 0, \"one of redeemTokensIn or redeemAmountIn must be zero\");\n\n        RedeemLocalVars memory vars;\n\n        /* exchangeRate = invoke Exchange Rate Stored() */\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /* If redeemTokensIn > 0: */\n        if (redeemTokensIn > 0) {\n            /*\n             * We calculate the exchange rate and the amount of underlying to be redeemed:\n             *  redeemTokens = redeemTokensIn\n             *  redeemAmount = redeemTokensIn x exchangeRateCurrent\n             */\n            vars.redeemTokens = redeemTokensIn;\n            vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);\n        } else {\n            /*\n             * We get the current exchange rate and calculate the amount to be redeemed:\n             *  redeemTokens = redeemAmountIn / exchangeRate\n             *  redeemAmount = redeemAmountIn\n             */\n            vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));\n            vars.redeemAmount = redeemAmountIn;\n        }\n\n        /**\n         * For every user, accountTokens must be greater than or equal to accountCollateralTokens.\n         * The buffer between the two values will be redeemed first.\n         * bufferTokens = accountTokens[redeemer] - accountCollateralTokens[redeemer]\n         * collateralTokens = redeemTokens - bufferTokens\n         */\n        uint256 bufferTokens = sub_(accountTokens[redeemer], accountCollateralTokens[redeemer]);\n        uint256 collateralTokens = 0;\n        if (vars.redeemTokens > bufferTokens) {\n            collateralTokens = vars.redeemTokens - bufferTokens;\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);\n        }\n\n        /* Fail gracefully if protocol has insufficient cash */\n        if (getCashPrior() < vars.redeemAmount) {\n            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We invoke doTransferOut for the redeemer and the redeemAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken has redeemAmount less of cash.\n         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         */\n        doTransferOut(redeemer, vars.redeemAmount, isNative);\n\n        /*\n         * We calculate the new total supply and redeemer balance, checking for underflow:\n         *  totalSupplyNew = totalSupply - redeemTokens\n         *  accountTokensNew = accountTokens[redeemer] - redeemTokens\n         */\n        totalSupply = sub_(totalSupply, vars.redeemTokens);\n        accountTokens[redeemer] = sub_(accountTokens[redeemer], vars.redeemTokens);\n\n        /*\n         * We only deallocate collateral tokens if the redeemer needs to redeem them.\n         */\n        decreaseUserCollateralInternal(redeemer, collateralTokens);\n\n        /* We emit a Transfer event, and a Redeem event */\n        emit Transfer(redeemer, address(this), vars.redeemTokens);\n        emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        /* We call the defense hook */\n        joetroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another JToken.\n     *  Its absolutely critical to use msg.sender as the seizer jToken and not a parameter.\n     * @param seizerToken The contract seizing the collateral (i.e. borrowed jToken)\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seizeInternal(\n        address seizerToken,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) internal returns (uint256) {\n        // Make sure accountCollateralTokens of `liquidator` and `borrower` are initialized.\n        initializeAccountCollateralTokens(liquidator);\n        initializeAccountCollateralTokens(borrower);\n\n        /* Fail if seize not allowed */\n        uint256 allowed = joetroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_JOETROLLER_REJECTION, allowed);\n        }\n\n        /*\n         * Return if seizeTokens is zero.\n         * Put behind `seizeAllowed` for accuring potential JOE rewards.\n         */\n        if (seizeTokens == 0) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Fail if borrower = liquidator */\n        if (borrower == liquidator) {\n            return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);\n        }\n\n        uint256 protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}));\n        uint256 liquidatorSeizeTokens = sub_(seizeTokens, protocolSeizeTokens);\n\n        uint256 exchangeRateMantissa = exchangeRateStoredInternal();\n        uint256 protocolSeizeAmount = mul_ScalarTruncate(Exp({mantissa: exchangeRateMantissa}), protocolSeizeTokens);\n\n        /*\n         * We calculate the new borrower and liquidator token balances and token collateral balances, failing on underflow/overflow:\n         *  accountTokens[borrower] = accountTokens[borrower] - seizeTokens\n         *  accountTokens[liquidator] = accountTokens[liquidator] + seizeTokens\n         *  accountCollateralTokens[borrower] = accountCollateralTokens[borrower] - seizeTokens\n         *  accountCollateralTokens[liquidator] = accountCollateralTokens[liquidator] + seizeTokens\n         */\n        accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens);\n        accountTokens[liquidator] = add_(accountTokens[liquidator], liquidatorSeizeTokens);\n        accountCollateralTokens[borrower] = sub_(accountCollateralTokens[borrower], seizeTokens);\n        accountCollateralTokens[liquidator] = add_(accountCollateralTokens[liquidator], liquidatorSeizeTokens);\n        totalReserves = add_(totalReserves, protocolSeizeAmount);\n        totalSupply = sub_(totalSupply, protocolSeizeTokens);\n\n        /* Emit a Transfer, UserCollateralChanged and ReservesAdded events */\n        emit Transfer(borrower, liquidator, seizeTokens);\n        emit UserCollateralChanged(borrower, accountCollateralTokens[borrower]);\n        emit UserCollateralChanged(liquidator, accountCollateralTokens[liquidator]);\n        emit ReservesAdded(address(this), protocolSeizeAmount, totalReserves);\n\n        /* We call the defense hook */\n        // unused function\n        // joetroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /*** Admin Functions ***/\n\n    /**\n     * @notice Accrues interest and sets a new collateral seize share for the protocol using _setProtocolSeizeShareFresh\n     * @dev Admin function to accrue interest and set a new collateral seize share\n     * @return uint256 0=success, otherwise a failure (see ErrorReport.sol for details)\n     */\n    function _setProtocolSeizeShare(uint256 newProtocolSeizeShareMantissa) external nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            return fail(Error(error), FailureInfo.SET_PROTOCOL_SEIZE_SHARE_ACCRUE_INTEREST_FAILED);\n        }\n        return _setProtocolSeizeShareFresh(newProtocolSeizeShareMantissa);\n    }\n\n    function _setProtocolSeizeShareFresh(uint256 newProtocolSeizeShareMantissa) internal returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PROTOCOL_SEIZE_SHARE_ADMIN_CHECK);\n        }\n\n        // Verify market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_PROTOCOL_SEIZE_SHARE_FRESH_CHECK);\n        }\n\n        if (newProtocolSeizeShareMantissa > protocolSeizeShareMaxMantissa) {\n            return fail(Error.BAD_INPUT, FailureInfo.SET_PROTOCOL_SEIZE_SHARE_BOUNDS_CHECK);\n        }\n\n        uint256 oldProtocolSeizeShareMantissa = protocolSeizeShareMantissa;\n        protocolSeizeShareMantissa = newProtocolSeizeShareMantissa;\n\n        emit NewProtocolSeizeShare(oldProtocolSeizeShareMantissa, newProtocolSeizeShareMantissa);\n\n        return uint256(Error.NO_ERROR);\n    }\n}\n"
    },
    "contracts/JCollateralCapErc20Delegate.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JCollateralCapErc20.sol\";\n\n/**\n * @title Cream's JCollateralCapErc20Delegate Contract\n * @notice JTokens which wrap an EIP-20 underlying and are delegated to\n * @author Cream\n */\ncontract JCollateralCapErc20Delegate is JCollateralCapErc20 {\n    /**\n     * @notice Construct an empty delegate\n     */\n    constructor() public {}\n\n    /**\n     * @notice Called by the delegator on a delegate to initialize it for duty\n     * @param data The encoded bytes data for any initialization\n     */\n    function _becomeImplementation(bytes memory data) public {\n        // Shh -- currently unused\n        data;\n\n        // Shh -- we don't ever want this hook to be marked pure\n        if (false) {\n            implementation = address(0);\n        }\n\n        require(msg.sender == admin, \"only the admin may call _becomeImplementation\");\n\n        // Set internal cash when becoming implementation\n        internalCash = getCashOnChain();\n\n        // Set JToken version in joetroller\n        JoetrollerInterfaceExtension(address(joetroller)).updateJTokenVersion(\n            address(this),\n            JoetrollerV1Storage.Version.COLLATERALCAP\n        );\n    }\n\n    /**\n     * @notice Called by the delegator on a delegate to forfeit its responsibility\n     */\n    function _resignImplementation() public {\n        // Shh -- we don't ever want this hook to be marked pure\n        if (false) {\n            implementation = address(0);\n        }\n\n        require(msg.sender == admin, \"only the admin may call _resignImplementation\");\n    }\n}\n"
    },
    "contracts/JWrappedNativeDelegator.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JTokenInterfaces.sol\";\n\n/**\n * @title Compound's JWrappedNativeDelegator Contract\n * @notice JTokens which wrap an EIP-20 underlying and delegate to an implementation\n * @author Compound\n */\ncontract JWrappedNativeDelegator is JTokenInterface, JWrappedNativeInterface, JDelegatorInterface {\n    /**\n     * @notice Construct a new money market\n     * @param underlying_ The address of the underlying asset\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ ERC-20 name of this token\n     * @param symbol_ ERC-20 symbol of this token\n     * @param decimals_ ERC-20 decimal precision of this token\n     * @param admin_ Address of the administrator of this token\n     * @param implementation_ The address of the implementation the contract delegates to\n     * @param becomeImplementationData The encoded args for becomeImplementation\n     */\n    constructor(\n        address underlying_,\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_,\n        address payable admin_,\n        address implementation_,\n        bytes memory becomeImplementationData\n    ) public {\n        // Creator of the contract is admin during initialization\n        admin = msg.sender;\n\n        // First delegate gets to initialize the delegator (i.e. storage contract)\n        delegateTo(\n            implementation_,\n            abi.encodeWithSignature(\n                \"initialize(address,address,address,uint256,string,string,uint8)\",\n                underlying_,\n                joetroller_,\n                interestRateModel_,\n                initialExchangeRateMantissa_,\n                name_,\n                symbol_,\n                decimals_\n            )\n        );\n\n        // New implementations always get set via the settor (post-initialize)\n        _setImplementation(implementation_, false, becomeImplementationData);\n\n        // Set the proper admin now that initialization is done\n        admin = admin_;\n    }\n\n    /**\n     * @notice Called by the admin to update the implementation of the delegator\n     * @param implementation_ The address of the new implementation for delegation\n     * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation\n     * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n     */\n    function _setImplementation(\n        address implementation_,\n        bool allowResign,\n        bytes memory becomeImplementationData\n    ) public {\n        require(msg.sender == admin, \"JWrappedNativeDelegator::_setImplementation: Caller must be admin\");\n\n        if (allowResign) {\n            delegateToImplementation(abi.encodeWithSignature(\"_resignImplementation()\"));\n        }\n\n        address oldImplementation = implementation;\n        implementation = implementation_;\n\n        delegateToImplementation(abi.encodeWithSignature(\"_becomeImplementation(bytes)\", becomeImplementationData));\n\n        emit NewImplementation(oldImplementation, implementation);\n    }\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param mintAmount The amount of the underlying asset to supply\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function mint(uint256 mintAmount) external returns (uint256) {\n        mintAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function mintNative() external payable returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeem(uint256 redeemTokens) external returns (uint256) {\n        redeemTokens; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemNative(uint256 redeemTokens) external returns (uint256) {\n        redeemTokens; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {\n        redeemAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256) {\n        redeemAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrow(uint256 borrowAmount) external returns (uint256) {\n        borrowAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrowNative(uint256 borrowAmount) external returns (uint256) {\n        borrowAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrow(uint256 repayAmount) external returns (uint256) {\n        repayAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowNative() external payable returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) {\n        borrower;\n        repayAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowBehalfNative(address borrower) external payable returns (uint256) {\n        borrower; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function liquidateBorrow(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) external returns (uint256) {\n        borrower;\n        repayAmount;\n        jTokenCollateral; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function liquidateBorrowNative(address borrower, JTokenInterface jTokenCollateral)\n        external\n        payable\n        returns (uint256)\n    {\n        borrower;\n        jTokenCollateral; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Flash loan funds to a given account.\n     * @param receiver The receiver address for the funds\n     * @param amount The amount of the funds to be loaned\n     * @param data The other data\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n\n    function flashLoan(\n        ERC3156FlashBorrowerInterface receiver,\n        address initiator,\n        uint256 amount,\n        bytes calldata data\n    ) external returns (bool) {\n        receiver;\n        amount;\n        data; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transfer(address dst, uint256 amount) external returns (bool) {\n        dst;\n        amount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `src` to `dst`\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferFrom(\n        address src,\n        address dst,\n        uint256 amount\n    ) external returns (bool) {\n        src;\n        dst;\n        amount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Approve `spender` to transfer up to `amount` from `src`\n     * @dev This will overwrite the approval amount for `spender`\n     *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n     * @param spender The address of the account which may transfer tokens\n     * @param amount The number of tokens that are approved (-1 means infinite)\n     * @return Whether or not the approval succeeded\n     */\n    function approve(address spender, uint256 amount) external returns (bool) {\n        spender;\n        amount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Get the current allowance from `owner` for `spender`\n     * @param owner The address of the account which owns the tokens to be spent\n     * @param spender The address of the account which may transfer tokens\n     * @return The number of tokens allowed to be spent (-1 means infinite)\n     */\n    function allowance(address owner, address spender) external view returns (uint256) {\n        owner;\n        spender; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Get the token balance of the `owner`\n     * @param owner The address of the account to query\n     * @return The number of tokens owned by `owner`\n     */\n    function balanceOf(address owner) external view returns (uint256) {\n        owner; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Get the underlying balance of the `owner`\n     * @dev This also accrues interest in a transaction\n     * @param owner The address of the account to query\n     * @return The amount of underlying owned by `owner`\n     */\n    function balanceOfUnderlying(address owner) external returns (uint256) {\n        owner; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Get a snapshot of the account's balances, and the cached exchange rate\n     * @dev This is used by joetroller to more efficiently perform liquidity checks.\n     * @param account Address of the account to snapshot\n     * @return (possible error, token balance, borrow balance, exchange rate mantissa)\n     */\n    function getAccountSnapshot(address account)\n        external\n        view\n        returns (\n            uint256,\n            uint256,\n            uint256,\n            uint256\n        )\n    {\n        account; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Returns the current per-sec borrow interest rate for this jToken\n     * @return The borrow interest rate per sec, scaled by 1e18\n     */\n    function borrowRatePerSecond() external view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Returns the current per-sec supply interest rate for this jToken\n     * @return The supply interest rate per sec, scaled by 1e18\n     */\n    function supplyRatePerSecond() external view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Returns the current total borrows plus accrued interest\n     * @return The total borrows with interest\n     */\n    function totalBorrowsCurrent() external returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex\n     * @param account The address whose balance should be calculated after updating borrowIndex\n     * @return The calculated balance\n     */\n    function borrowBalanceCurrent(address account) external returns (uint256) {\n        account; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Return the borrow balance of account based on stored data\n     * @param account The address whose balance should be calculated\n     * @return The calculated balance\n     */\n    function borrowBalanceStored(address account) public view returns (uint256) {\n        account; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Accrue interest then return the up-to-date exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateCurrent() public returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Calculates the exchange rate from the underlying to the JToken\n     * @dev This function does not accrue interest before calculating the exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateStored() public view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Get cash balance of this jToken in the underlying asset\n     * @return The quantity of underlying asset owned by this contract\n     */\n    function getCash() external view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Applies accrued interest to total borrows and reserves.\n     * @dev This calculates interest accrued from the last checkpointed timestamp\n     *      up to the current timestamp and writes new checkpoint to storage.\n     */\n    function accrueInterest() public returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Will fail unless called by another jToken during the process of liquidation.\n     *  Its absolutely critical to use msg.sender as the borrowed jToken and not a parameter.\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seize(\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external returns (uint256) {\n        liquidator;\n        borrower;\n        seizeTokens; // Shh\n        delegateAndReturn();\n    }\n\n    /*** Admin Functions ***/\n\n    /**\n     * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @param newPendingAdmin New pending admin.\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) {\n        newPendingAdmin; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sets a new joetroller for the market\n     * @dev Admin function to set a new joetroller\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256) {\n        newJoetroller; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh\n     * @dev Admin function to accrue interest and set a new reserve factor\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256) {\n        newReserveFactorMantissa; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\n     * @dev Admin function for pending admin to accept role and update admin\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _acceptAdmin() external returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and adds reserves by transferring from admin\n     * @param addAmount Amount of reserves to add\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReserves(uint256 addAmount) external returns (uint256) {\n        addAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and adds reserves by transferring from admin\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReservesNative() external payable returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and reduces reserves by transferring to admin\n     * @param reduceAmount Amount of reduction to reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _reduceReserves(uint256 reduceAmount) external returns (uint256) {\n        reduceAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh\n     * @dev Admin function to accrue interest and update the interest rate model\n     * @param newInterestRateModel the new interest rate model to use\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) {\n        newInterestRateModel; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Internal method to delegate execution to another contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     * @param callee The contract to delegatecall\n     * @param data The raw data to delegatecall\n     * @return The returned bytes from the delegatecall\n     */\n    function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returnData) = callee.delegatecall(data);\n        assembly {\n            if eq(success, 0) {\n                revert(add(returnData, 0x20), returndatasize)\n            }\n        }\n        return returnData;\n    }\n\n    /**\n     * @notice Delegates execution to the implementation contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     * @param data The raw data to delegatecall\n     * @return The returned bytes from the delegatecall\n     */\n    function delegateToImplementation(bytes memory data) public returns (bytes memory) {\n        return delegateTo(implementation, data);\n    }\n\n    /**\n     * @notice Delegates execution to an implementation contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     *  There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.\n     * @param data The raw data to delegatecall\n     * @return The returned bytes from the delegatecall\n     */\n    function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {\n        (bool success, bytes memory returnData) = address(this).staticcall(\n            abi.encodeWithSignature(\"delegateToImplementation(bytes)\", data)\n        );\n        assembly {\n            if eq(success, 0) {\n                revert(add(returnData, 0x20), returndatasize)\n            }\n        }\n        return abi.decode(returnData, (bytes));\n    }\n\n    function delegateToViewAndReturn() private view returns (bytes memory) {\n        (bool success, ) = address(this).staticcall(\n            abi.encodeWithSignature(\"delegateToImplementation(bytes)\", msg.data)\n        );\n\n        assembly {\n            let free_mem_ptr := mload(0x40)\n            returndatacopy(free_mem_ptr, 0, returndatasize)\n\n            switch success\n            case 0 {\n                revert(free_mem_ptr, returndatasize)\n            }\n            default {\n                return(add(free_mem_ptr, 0x40), returndatasize)\n            }\n        }\n    }\n\n    function delegateAndReturn() private returns (bytes memory) {\n        (bool success, ) = implementation.delegatecall(msg.data);\n\n        assembly {\n            let free_mem_ptr := mload(0x40)\n            returndatacopy(free_mem_ptr, 0, returndatasize)\n\n            switch success\n            case 0 {\n                revert(free_mem_ptr, returndatasize)\n            }\n            default {\n                return(free_mem_ptr, returndatasize)\n            }\n        }\n    }\n\n    /**\n     * @notice Delegates execution to an implementation contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     */\n    function() external payable {\n        // delegate all other functions to current implementation\n        delegateAndReturn();\n    }\n}\n"
    },
    "contracts/JErc20Delegator.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JTokenInterfaces.sol\";\n\n/**\n * @title Compound's JErc20Delegator Contract\n * @notice JTokens which wrap an EIP-20 underlying and delegate to an implementation\n * @author Compound\n */\ncontract JErc20Delegator is JTokenInterface, JErc20Interface, JDelegatorInterface {\n    /**\n     * @notice Construct a new money market\n     * @param underlying_ The address of the underlying asset\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ ERC-20 name of this token\n     * @param symbol_ ERC-20 symbol of this token\n     * @param decimals_ ERC-20 decimal precision of this token\n     * @param admin_ Address of the administrator of this token\n     * @param implementation_ The address of the implementation the contract delegates to\n     * @param becomeImplementationData The encoded args for becomeImplementation\n     */\n    constructor(\n        address underlying_,\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_,\n        address payable admin_,\n        address implementation_,\n        bytes memory becomeImplementationData\n    ) public {\n        // Creator of the contract is admin during initialization\n        admin = msg.sender;\n\n        // First delegate gets to initialize the delegator (i.e. storage contract)\n        delegateTo(\n            implementation_,\n            abi.encodeWithSignature(\n                \"initialize(address,address,address,uint256,string,string,uint8)\",\n                underlying_,\n                joetroller_,\n                interestRateModel_,\n                initialExchangeRateMantissa_,\n                name_,\n                symbol_,\n                decimals_\n            )\n        );\n\n        // New implementations always get set via the settor (post-initialize)\n        _setImplementation(implementation_, false, becomeImplementationData);\n\n        // Set the proper admin now that initialization is done\n        admin = admin_;\n    }\n\n    /**\n     * @notice Called by the admin to update the implementation of the delegator\n     * @param implementation_ The address of the new implementation for delegation\n     * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation\n     * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n     */\n    function _setImplementation(\n        address implementation_,\n        bool allowResign,\n        bytes memory becomeImplementationData\n    ) public {\n        require(msg.sender == admin, \"JErc20Delegator::_setImplementation: Caller must be admin\");\n\n        if (allowResign) {\n            delegateToImplementation(abi.encodeWithSignature(\"_resignImplementation()\"));\n        }\n\n        address oldImplementation = implementation;\n        implementation = implementation_;\n\n        delegateToImplementation(abi.encodeWithSignature(\"_becomeImplementation(bytes)\", becomeImplementationData));\n\n        emit NewImplementation(oldImplementation, implementation);\n    }\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param mintAmount The amount of the underlying asset to supply\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function mint(uint256 mintAmount) external returns (uint256) {\n        mintAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeem(uint256 redeemTokens) external returns (uint256) {\n        redeemTokens; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {\n        redeemAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrow(uint256 borrowAmount) external returns (uint256) {\n        borrowAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrow(uint256 repayAmount) external returns (uint256) {\n        repayAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) {\n        borrower;\n        repayAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function liquidateBorrow(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) external returns (uint256) {\n        borrower;\n        repayAmount;\n        jTokenCollateral; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transfer(address dst, uint256 amount) external returns (bool) {\n        dst;\n        amount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `src` to `dst`\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferFrom(\n        address src,\n        address dst,\n        uint256 amount\n    ) external returns (bool) {\n        src;\n        dst;\n        amount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Approve `spender` to transfer up to `amount` from `src`\n     * @dev This will overwrite the approval amount for `spender`\n     *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n     * @param spender The address of the account which may transfer tokens\n     * @param amount The number of tokens that are approved (-1 means infinite)\n     * @return Whether or not the approval succeeded\n     */\n    function approve(address spender, uint256 amount) external returns (bool) {\n        spender;\n        amount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Get the current allowance from `owner` for `spender`\n     * @param owner The address of the account which owns the tokens to be spent\n     * @param spender The address of the account which may transfer tokens\n     * @return The number of tokens allowed to be spent (-1 means infinite)\n     */\n    function allowance(address owner, address spender) external view returns (uint256) {\n        owner;\n        spender; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Get the token balance of the `owner`\n     * @param owner The address of the account to query\n     * @return The number of tokens owned by `owner`\n     */\n    function balanceOf(address owner) external view returns (uint256) {\n        owner; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Get the underlying balance of the `owner`\n     * @dev This also accrues interest in a transaction\n     * @param owner The address of the account to query\n     * @return The amount of underlying owned by `owner`\n     */\n    function balanceOfUnderlying(address owner) external returns (uint256) {\n        owner; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Get a snapshot of the account's balances, and the cached exchange rate\n     * @dev This is used by joetroller to more efficiently perform liquidity checks.\n     * @param account Address of the account to snapshot\n     * @return (possible error, token balance, borrow balance, exchange rate mantissa)\n     */\n    function getAccountSnapshot(address account)\n        external\n        view\n        returns (\n            uint256,\n            uint256,\n            uint256,\n            uint256\n        )\n    {\n        account; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Returns the current per-sec borrow interest rate for this jToken\n     * @return The borrow interest rate per sec, scaled by 1e18\n     */\n    function borrowRatePerSecond() external view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Returns the current per-sec supply interest rate for this jToken\n     * @return The supply interest rate per sec, scaled by 1e18\n     */\n    function supplyRatePerSecond() external view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Returns the current total borrows plus accrued interest\n     * @return The total borrows with interest\n     */\n    function totalBorrowsCurrent() external returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex\n     * @param account The address whose balance should be calculated after updating borrowIndex\n     * @return The calculated balance\n     */\n    function borrowBalanceCurrent(address account) external returns (uint256) {\n        account; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Return the borrow balance of account based on stored data\n     * @param account The address whose balance should be calculated\n     * @return The calculated balance\n     */\n    function borrowBalanceStored(address account) public view returns (uint256) {\n        account; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Accrue interest then return the up-to-date exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateCurrent() public returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Calculates the exchange rate from the underlying to the JToken\n     * @dev This function does not accrue interest before calculating the exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateStored() public view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Get cash balance of this jToken in the underlying asset\n     * @return The quantity of underlying asset owned by this contract\n     */\n    function getCash() external view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Applies accrued interest to total borrows and reserves.\n     * @dev This calculates interest accrued from the last checkpointed timestamp\n     *      up to the current timestamp and writes new checkpoint to storage.\n     */\n    function accrueInterest() public returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Will fail unless called by another jToken during the process of liquidation.\n     *  Its absolutely critical to use msg.sender as the borrowed jToken and not a parameter.\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seize(\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external returns (uint256) {\n        liquidator;\n        borrower;\n        seizeTokens; // Shh\n        delegateAndReturn();\n    }\n\n    /*** Admin Functions ***/\n\n    /**\n     * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @param newPendingAdmin New pending admin.\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) {\n        newPendingAdmin; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sets a new joetroller for the market\n     * @dev Admin function to set a new joetroller\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256) {\n        newJoetroller; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh\n     * @dev Admin function to accrue interest and set a new reserve factor\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256) {\n        newReserveFactorMantissa; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\n     * @dev Admin function for pending admin to accept role and update admin\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _acceptAdmin() external returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and adds reserves by transferring from admin\n     * @param addAmount Amount of reserves to add\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReserves(uint256 addAmount) external returns (uint256) {\n        addAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and reduces reserves by transferring to admin\n     * @param reduceAmount Amount of reduction to reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _reduceReserves(uint256 reduceAmount) external returns (uint256) {\n        reduceAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh\n     * @dev Admin function to accrue interest and update the interest rate model\n     * @param newInterestRateModel the new interest rate model to use\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) {\n        newInterestRateModel; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Internal method to delegate execution to another contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     * @param callee The contract to delegatecall\n     * @param data The raw data to delegatecall\n     * @return The returned bytes from the delegatecall\n     */\n    function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returnData) = callee.delegatecall(data);\n        assembly {\n            if eq(success, 0) {\n                revert(add(returnData, 0x20), returndatasize)\n            }\n        }\n        return returnData;\n    }\n\n    /**\n     * @notice Delegates execution to the implementation contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     * @param data The raw data to delegatecall\n     * @return The returned bytes from the delegatecall\n     */\n    function delegateToImplementation(bytes memory data) public returns (bytes memory) {\n        return delegateTo(implementation, data);\n    }\n\n    /**\n     * @notice Delegates execution to an implementation contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     *  There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.\n     * @param data The raw data to delegatecall\n     * @return The returned bytes from the delegatecall\n     */\n    function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {\n        (bool success, bytes memory returnData) = address(this).staticcall(\n            abi.encodeWithSignature(\"delegateToImplementation(bytes)\", data)\n        );\n        assembly {\n            if eq(success, 0) {\n                revert(add(returnData, 0x20), returndatasize)\n            }\n        }\n        return abi.decode(returnData, (bytes));\n    }\n\n    function delegateToViewAndReturn() private view returns (bytes memory) {\n        (bool success, ) = address(this).staticcall(\n            abi.encodeWithSignature(\"delegateToImplementation(bytes)\", msg.data)\n        );\n\n        assembly {\n            let free_mem_ptr := mload(0x40)\n            returndatacopy(free_mem_ptr, 0, returndatasize)\n\n            switch success\n            case 0 {\n                revert(free_mem_ptr, returndatasize)\n            }\n            default {\n                return(add(free_mem_ptr, 0x40), returndatasize)\n            }\n        }\n    }\n\n    function delegateAndReturn() private returns (bytes memory) {\n        (bool success, ) = implementation.delegatecall(msg.data);\n\n        assembly {\n            let free_mem_ptr := mload(0x40)\n            returndatacopy(free_mem_ptr, 0, returndatasize)\n\n            switch success\n            case 0 {\n                revert(free_mem_ptr, returndatasize)\n            }\n            default {\n                return(free_mem_ptr, returndatasize)\n            }\n        }\n    }\n\n    /**\n     * @notice Delegates execution to an implementation contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     */\n    function() external payable {\n        require(msg.value == 0, \"JErc20Delegator:fallback: cannot send value to fallback\");\n\n        // delegate all other functions to current implementation\n        delegateAndReturn();\n    }\n}\n"
    },
    "contracts/JCollateralCapErc20Delegator.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JTokenInterfaces.sol\";\n\n/**\n * @title Cream's JCollateralCapErc20Delegator Contract\n * @notice JTokens which wrap an EIP-20 underlying and delegate to an implementation\n * @author Cream\n */\ncontract JCollateralCapErc20Delegator is JTokenInterface, JCollateralCapErc20Interface, JDelegatorInterface {\n    /**\n     * @notice Construct a new money market\n     * @param underlying_ The address of the underlying asset\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ ERC-20 name of this token\n     * @param symbol_ ERC-20 symbol of this token\n     * @param decimals_ ERC-20 decimal precision of this token\n     * @param admin_ Address of the administrator of this token\n     * @param implementation_ The address of the implementation the contract delegates to\n     * @param becomeImplementationData The encoded args for becomeImplementation\n     */\n    constructor(\n        address underlying_,\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_,\n        address payable admin_,\n        address implementation_,\n        bytes memory becomeImplementationData\n    ) public {\n        // Creator of the contract is admin during initialization\n        admin = msg.sender;\n\n        // First delegate gets to initialize the delegator (i.e. storage contract)\n        delegateTo(\n            implementation_,\n            abi.encodeWithSignature(\n                \"initialize(address,address,address,uint256,string,string,uint8)\",\n                underlying_,\n                joetroller_,\n                interestRateModel_,\n                initialExchangeRateMantissa_,\n                name_,\n                symbol_,\n                decimals_\n            )\n        );\n\n        // New implementations always get set via the settor (post-initialize)\n        _setImplementation(implementation_, false, becomeImplementationData);\n\n        // Set the proper admin now that initialization is done\n        admin = admin_;\n    }\n\n    /**\n     * @notice Called by the admin to update the implementation of the delegator\n     * @param implementation_ The address of the new implementation for delegation\n     * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation\n     * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n     */\n    function _setImplementation(\n        address implementation_,\n        bool allowResign,\n        bytes memory becomeImplementationData\n    ) public {\n        require(msg.sender == admin, \"CErc20Delegator::_setImplementation: Caller must be admin\");\n\n        if (allowResign) {\n            delegateToImplementation(abi.encodeWithSignature(\"_resignImplementation()\"));\n        }\n\n        address oldImplementation = implementation;\n        implementation = implementation_;\n\n        delegateToImplementation(abi.encodeWithSignature(\"_becomeImplementation(bytes)\", becomeImplementationData));\n\n        emit NewImplementation(oldImplementation, implementation);\n    }\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param mintAmount The amount of the underlying asset to supply\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function mint(uint256 mintAmount) external returns (uint256) {\n        mintAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeem(uint256 redeemTokens) external returns (uint256) {\n        redeemTokens; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {\n        redeemAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrow(uint256 borrowAmount) external returns (uint256) {\n        borrowAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrow(uint256 repayAmount) external returns (uint256) {\n        repayAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) {\n        borrower;\n        repayAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function liquidateBorrow(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) external returns (uint256) {\n        borrower;\n        repayAmount;\n        jTokenCollateral; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transfer(address dst, uint256 amount) external returns (bool) {\n        dst;\n        amount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `src` to `dst`\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferFrom(\n        address src,\n        address dst,\n        uint256 amount\n    ) external returns (bool) {\n        src;\n        dst;\n        amount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Approve `spender` to transfer up to `amount` from `src`\n     * @dev This will overwrite the approval amount for `spender`\n     *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n     * @param spender The address of the account which may transfer tokens\n     * @param amount The number of tokens that are approved (-1 means infinite)\n     * @return Whether or not the approval succeeded\n     */\n    function approve(address spender, uint256 amount) external returns (bool) {\n        spender;\n        amount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Gulps excess contract cash to reserves\n     * @dev This function calculates excess ERC20 gained from a ERC20.transfer() call and adds the excess to reserves.\n     */\n    function gulp() external {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Flash loan funds to a given account.\n     * @param receiver The receiver address for the funds\n     * @param initiator flash loan initiator\n     * @param amount The amount of the funds to be loaned\n     * @param data The other data\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function flashLoan(\n        ERC3156FlashBorrowerInterface receiver,\n        address initiator,\n        uint256 amount,\n        bytes calldata data\n    ) external returns (bool) {\n        receiver;\n        initiator;\n        amount;\n        data; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Register account collateral tokens if there is space.\n     * @param account The account to register\n     * @dev This function could only be called by joetroller.\n     * @return The actual registered amount of collateral\n     */\n    function registerCollateral(address account) external returns (uint256) {\n        account; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Unregister account collateral tokens if the account still has enough collateral.\n     * @dev This function could only be called by joetroller.\n     * @param account The account to unregister\n     */\n    function unregisterCollateral(address account) external {\n        account; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Get the current allowance from `owner` for `spender`\n     * @param owner The address of the account which owns the tokens to be spent\n     * @param spender The address of the account which may transfer tokens\n     * @return The number of tokens allowed to be spent (-1 means infinite)\n     */\n    function allowance(address owner, address spender) external view returns (uint256) {\n        owner;\n        spender; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Get the token balance of the `owner`\n     * @param owner The address of the account to query\n     * @return The number of tokens owned by `owner`\n     */\n    function balanceOf(address owner) external view returns (uint256) {\n        owner; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Get the underlying balance of the `owner`\n     * @dev This also accrues interest in a transaction\n     * @param owner The address of the account to query\n     * @return The amount of underlying owned by `owner`\n     */\n    function balanceOfUnderlying(address owner) external returns (uint256) {\n        owner; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Get a snapshot of the account's balances, and the cached exchange rate\n     * @dev This is used by joetroller to more efficiently perform liquidity checks.\n     * @param account Address of the account to snapshot\n     * @return (possible error, token balance, borrow balance, exchange rate mantissa)\n     */\n    function getAccountSnapshot(address account)\n        external\n        view\n        returns (\n            uint256,\n            uint256,\n            uint256,\n            uint256\n        )\n    {\n        account; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Returns the current per-sec borrow interest rate for this jToken\n     * @return The borrow interest rate per sec, scaled by 1e18\n     */\n    function borrowRatePerSecond() external view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Returns the current per-sec supply interest rate for this jToken\n     * @return The supply interest rate per sec, scaled by 1e18\n     */\n    function supplyRatePerSecond() external view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Returns the current total borrows plus accrued interest\n     * @return The total borrows with interest\n     */\n    function totalBorrowsCurrent() external returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex\n     * @param account The address whose balance should be calculated after updating borrowIndex\n     * @return The calculated balance\n     */\n    function borrowBalanceCurrent(address account) external returns (uint256) {\n        account; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Return the borrow balance of account based on stored data\n     * @param account The address whose balance should be calculated\n     * @return The calculated balance\n     */\n    function borrowBalanceStored(address account) public view returns (uint256) {\n        account; // Shh\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Accrue interest then return the up-to-date exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateCurrent() public returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Calculates the exchange rate from the underlying to the JToken\n     * @dev This function does not accrue interest before calculating the exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateStored() public view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Get cash balance of this jToken in the underlying asset\n     * @return The quantity of underlying asset owned by this contract\n     */\n    function getCash() external view returns (uint256) {\n        delegateToViewAndReturn();\n    }\n\n    /**\n     * @notice Applies accrued interest to total borrows and reserves.\n     * @dev This calculates interest accrued from the last checkpointed timestamp\n     *      up to the current timestamp and writes new checkpoint to storage.\n     */\n    function accrueInterest() public returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Will fail unless called by another jToken during the process of liquidation.\n     *  Its absolutely critical to use msg.sender as the borrowed jToken and not a parameter.\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seize(\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external returns (uint256) {\n        liquidator;\n        borrower;\n        seizeTokens; // Shh\n        delegateAndReturn();\n    }\n\n    /*** Admin Functions ***/\n\n    /**\n     * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @param newPendingAdmin New pending admin.\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) {\n        newPendingAdmin; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Sets a new joetroller for the market\n     * @dev Admin function to set a new joetroller\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256) {\n        newJoetroller; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh\n     * @dev Admin function to accrue interest and set a new reserve factor\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256) {\n        newReserveFactorMantissa; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\n     * @dev Admin function for pending admin to accept role and update admin\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _acceptAdmin() external returns (uint256) {\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and adds reserves by transferring from admin\n     * @param addAmount Amount of reserves to add\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReserves(uint256 addAmount) external returns (uint256) {\n        addAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and reduces reserves by transferring to admin\n     * @param reduceAmount Amount of reduction to reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _reduceReserves(uint256 reduceAmount) external returns (uint256) {\n        reduceAmount; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh\n     * @dev Admin function to accrue interest and update the interest rate model\n     * @param newInterestRateModel the new interest rate model to use\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) {\n        newInterestRateModel; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Set collateral cap of this market, 0 for no cap\n     * @param newCollateralCap The new collateral cap\n     */\n    function _setCollateralCap(uint256 newCollateralCap) external {\n        newCollateralCap; // Shh\n        delegateAndReturn();\n    }\n\n    /**\n     * @notice Internal method to delegate execution to another contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     * @param callee The contract to delegatecall\n     * @param data The raw data to delegatecall\n     * @return The returned bytes from the delegatecall\n     */\n    function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returnData) = callee.delegatecall(data);\n        assembly {\n            if eq(success, 0) {\n                revert(add(returnData, 0x20), returndatasize)\n            }\n        }\n        return returnData;\n    }\n\n    /**\n     * @notice Delegates execution to the implementation contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     * @param data The raw data to delegatecall\n     * @return The returned bytes from the delegatecall\n     */\n    function delegateToImplementation(bytes memory data) public returns (bytes memory) {\n        return delegateTo(implementation, data);\n    }\n\n    /**\n     * @notice Delegates execution to an implementation contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     *  There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.\n     * @param data The raw data to delegatecall\n     * @return The returned bytes from the delegatecall\n     */\n    function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {\n        (bool success, bytes memory returnData) = address(this).staticcall(\n            abi.encodeWithSignature(\"delegateToImplementation(bytes)\", data)\n        );\n        assembly {\n            if eq(success, 0) {\n                revert(add(returnData, 0x20), returndatasize)\n            }\n        }\n        return abi.decode(returnData, (bytes));\n    }\n\n    function delegateToViewAndReturn() private view returns (bytes memory) {\n        (bool success, ) = address(this).staticcall(\n            abi.encodeWithSignature(\"delegateToImplementation(bytes)\", msg.data)\n        );\n\n        assembly {\n            let free_mem_ptr := mload(0x40)\n            returndatacopy(free_mem_ptr, 0, returndatasize)\n\n            switch success\n            case 0 {\n                revert(free_mem_ptr, returndatasize)\n            }\n            default {\n                return(add(free_mem_ptr, 0x40), returndatasize)\n            }\n        }\n    }\n\n    function delegateAndReturn() private returns (bytes memory) {\n        (bool success, ) = implementation.delegatecall(msg.data);\n\n        assembly {\n            let free_mem_ptr := mload(0x40)\n            returndatacopy(free_mem_ptr, 0, returndatasize)\n\n            switch success\n            case 0 {\n                revert(free_mem_ptr, returndatasize)\n            }\n            default {\n                return(free_mem_ptr, returndatasize)\n            }\n        }\n    }\n\n    /**\n     * @notice Delegates execution to an implementation contract\n     * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n     */\n    function() external payable {\n        require(msg.value == 0, \"CErc20Delegator:fallback: cannot send value to fallback\");\n\n        // delegate all other functions to current implementation\n        delegateAndReturn();\n    }\n}\n"
    },
    "contracts/JTokenDeprecated.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JoetrollerInterface.sol\";\nimport \"./JTokenInterfaces.sol\";\nimport \"./ErrorReporter.sol\";\nimport \"./Exponential.sol\";\nimport \"./EIP20Interface.sol\";\nimport \"./EIP20NonStandardInterface.sol\";\nimport \"./InterestRateModel.sol\";\n\n/**\n * @title Deprecated JToken Contract only for JAvax.\n * @dev JAvax will not be used anymore and existing JAvax can't be upgraded.\n * @author Cream\n */\ncontract JTokenDeprecated is JTokenInterface, Exponential, TokenErrorReporter {\n    /**\n     * @notice Initialize the money market\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ EIP-20 name of this token\n     * @param symbol_ EIP-20 symbol of this token\n     * @param decimals_ EIP-20 decimal precision of this token\n     */\n    function initialize(\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_\n    ) public {\n        require(msg.sender == admin, \"only admin may initialize the market\");\n        require(accrualBlockTimestamp == 0 && borrowIndex == 0, \"market may only be initialized once\");\n\n        // Set initial exchange rate\n        initialExchangeRateMantissa = initialExchangeRateMantissa_;\n        require(initialExchangeRateMantissa > 0, \"initial exchange rate must be greater than zero.\");\n\n        // Set the joetroller\n        uint256 err = _setJoetroller(joetroller_);\n        require(err == uint256(Error.NO_ERROR), \"setting joetroller failed\");\n\n        // Initialize block timestamp and borrow index (block timestamp mocks depend on joetroller being set)\n        accrualBlockTimestamp = getBlockTimestamp();\n        borrowIndex = mantissaOne;\n\n        // Set the interest rate model (depends on block timestamp / borrow index)\n        err = _setInterestRateModelFresh(interestRateModel_);\n        require(err == uint256(Error.NO_ERROR), \"setting interest rate model failed\");\n\n        name = name_;\n        symbol = symbol_;\n        decimals = decimals_;\n\n        // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)\n        _notEntered = true;\n    }\n\n    /**\n     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n     * @dev Called by both `transfer` and `transferFrom` internally\n     * @param spender The address of the account performing the transfer\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param tokens The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferTokens(\n        address spender,\n        address src,\n        address dst,\n        uint256 tokens\n    ) internal returns (uint256) {\n        /* Fail if transfer not allowed */\n        uint256 allowed = joetroller.transferAllowed(address(this), src, dst, tokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.TRANSFER_JOETROLLER_REJECTION, allowed);\n        }\n\n        /* Do not allow self-transfers */\n        if (src == dst) {\n            return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);\n        }\n\n        /* Get the allowance, infinite for the account owner */\n        uint256 startingAllowance = 0;\n        if (spender == src) {\n            startingAllowance = uint256(-1);\n        } else {\n            startingAllowance = transferAllowances[src][spender];\n        }\n\n        /* Do the calculations, checking for {under,over}flow */\n        uint256 allowanceNew = sub_(startingAllowance, tokens);\n        uint256 srjTokensNew = sub_(accountTokens[src], tokens);\n        uint256 dstTokensNew = add_(accountTokens[dst], tokens);\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        accountTokens[src] = srjTokensNew;\n        accountTokens[dst] = dstTokensNew;\n\n        /* Eat some of the allowance (if necessary) */\n        if (startingAllowance != uint256(-1)) {\n            transferAllowances[src][spender] = allowanceNew;\n        }\n\n        /* We emit a Transfer event */\n        emit Transfer(src, dst, tokens);\n\n        joetroller.transferVerify(address(this), src, dst, tokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {\n        return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Transfer `amount` tokens from `src` to `dst`\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param amount The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferFrom(\n        address src,\n        address dst,\n        uint256 amount\n    ) external nonReentrant returns (bool) {\n        return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Approve `spender` to transfer up to `amount` from `src`\n     * @dev This will overwrite the approval amount for `spender`\n     *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n     * @param spender The address of the account which may transfer tokens\n     * @param amount The number of tokens that are approved (-1 means infinite)\n     * @return Whether or not the approval succeeded\n     */\n    function approve(address spender, uint256 amount) external returns (bool) {\n        address src = msg.sender;\n        transferAllowances[src][spender] = amount;\n        emit Approval(src, spender, amount);\n        return true;\n    }\n\n    /**\n     * @notice Get the current allowance from `owner` for `spender`\n     * @param owner The address of the account which owns the tokens to be spent\n     * @param spender The address of the account which may transfer tokens\n     * @return The number of tokens allowed to be spent (-1 means infinite)\n     */\n    function allowance(address owner, address spender) external view returns (uint256) {\n        return transferAllowances[owner][spender];\n    }\n\n    /**\n     * @notice Get the token balance of the `owner`\n     * @param owner The address of the account to query\n     * @return The number of tokens owned by `owner`\n     */\n    function balanceOf(address owner) external view returns (uint256) {\n        return accountTokens[owner];\n    }\n\n    /**\n     * @notice Get the underlying balance of the `owner`\n     * @dev This also accrues interest in a transaction\n     * @param owner The address of the account to query\n     * @return The amount of underlying owned by `owner`\n     */\n    function balanceOfUnderlying(address owner) external returns (uint256) {\n        Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});\n        return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);\n    }\n\n    /**\n     * @notice Get a snapshot of the account's balances, and the cached exchange rate\n     * @dev This is used by joetroller to more efficiently perform liquidity checks.\n     * @param account Address of the account to snapshot\n     * @return (possible error, token balance, borrow balance, exchange rate mantissa)\n     */\n    function getAccountSnapshot(address account)\n        external\n        view\n        returns (\n            uint256,\n            uint256,\n            uint256,\n            uint256\n        )\n    {\n        uint256 jTokenBalance = accountTokens[account];\n        uint256 borrowBalance = borrowBalanceStoredInternal(account);\n        uint256 exchangeRateMantissa = exchangeRateStoredInternal();\n\n        return (uint256(Error.NO_ERROR), jTokenBalance, borrowBalance, exchangeRateMantissa);\n    }\n\n    /**\n     * @dev Function to simply retrieve block timestamp \n     *  This exists mainly for inheriting test contracts to stub this result.\n     */\n    function getBlockTimestamp() internal view returns (uint256) {\n        return block.timestamp;\n    }\n\n    /**\n     * @notice Returns the current per-sec borrow interest rate for this jToken\n     * @return The borrow interest rate per sec, scaled by 1e18\n     */\n    function borrowRatePerSecond() external view returns (uint256) {\n        return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);\n    }\n\n    /**\n     * @notice Returns the current per-sec supply interest rate for this jToken\n     * @return The supply interest rate per sec, scaled by 1e18\n     */\n    function supplyRatePerSecond() external view returns (uint256) {\n        return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);\n    }\n\n    /**\n     * @notice Returns the current total borrows plus accrued interest\n     * @return The total borrows with interest\n     */\n    function totalBorrowsCurrent() external nonReentrant returns (uint256) {\n        require(accrueInterest() == uint256(Error.NO_ERROR), \"accrue interest failed\");\n        return totalBorrows;\n    }\n\n    /**\n     * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex\n     * @param account The address whose balance should be calculated after updating borrowIndex\n     * @return The calculated balance\n     */\n    function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) {\n        require(accrueInterest() == uint256(Error.NO_ERROR), \"accrue interest failed\");\n        return borrowBalanceStored(account);\n    }\n\n    /**\n     * @notice Return the borrow balance of account based on stored data\n     * @param account The address whose balance should be calculated\n     * @return The calculated balance\n     */\n    function borrowBalanceStored(address account) public view returns (uint256) {\n        return borrowBalanceStoredInternal(account);\n    }\n\n    /**\n     * @notice Return the borrow balance of account based on stored data\n     * @param account The address whose balance should be calculated\n     * @return the calculated balance or 0 if error code is non-zero\n     */\n    function borrowBalanceStoredInternal(address account) internal view returns (uint256) {\n        /* Get borrowBalance and borrowIndex */\n        BorrowSnapshot storage borrowSnapshot = accountBorrows[account];\n\n        /* If borrowBalance = 0 then borrowIndex is likely also 0.\n         * Rather than failing the calculation with a division by 0, we immediately return 0 in this case.\n         */\n        if (borrowSnapshot.principal == 0) {\n            return 0;\n        }\n\n        /* Calculate new borrow balance using the interest index:\n         *  recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex\n         */\n        uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex);\n        uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex);\n        return result;\n    }\n\n    /**\n     * @notice Accrue interest then return the up-to-date exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateCurrent() public nonReentrant returns (uint256) {\n        require(accrueInterest() == uint256(Error.NO_ERROR), \"accrue interest failed\");\n        return exchangeRateStored();\n    }\n\n    /**\n     * @notice Calculates the exchange rate from the underlying to the JToken\n     * @dev This function does not accrue interest before calculating the exchange rate\n     * @return Calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateStored() public view returns (uint256) {\n        return exchangeRateStoredInternal();\n    }\n\n    /**\n     * @notice Calculates the exchange rate from the underlying to the JToken\n     * @dev This function does not accrue interest before calculating the exchange rate\n     * @return calculated exchange rate scaled by 1e18\n     */\n    function exchangeRateStoredInternal() internal view returns (uint256) {\n        uint256 _totalSupply = totalSupply;\n        if (_totalSupply == 0) {\n            /*\n             * If there are no tokens minted:\n             *  exchangeRate = initialExchangeRate\n             */\n            return initialExchangeRateMantissa;\n        } else {\n            /*\n             * Otherwise:\n             *  exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply\n             */\n            uint256 totalCash = getCashPrior();\n            uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves);\n            uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply}));\n            return exchangeRate;\n        }\n    }\n\n    /**\n     * @notice Get cash balance of this jToken in the underlying asset\n     * @return The quantity of underlying asset owned by this contract\n     */\n    function getCash() external view returns (uint256) {\n        return getCashPrior();\n    }\n\n    /**\n     * @notice Applies accrued interest to total borrows and reserves\n     * @dev This calculates interest accrued from the last checkpointed timestamp \n     *   up to the current timestamp and writes new checkpoint to storage.\n     */\n    function accrueInterest() public returns (uint256) {\n        /* Remember the initial block timestamp */\n        uint256 currentBlockTimestamp = getBlockTimestamp();\n        uint256 accrualBlockTimestampPrior = accrualBlockTimestamp;\n\n        /* Short-circuit accumulating 0 interest */\n        if (accrualBlockTimestampPrior == currentBlockTimestamp) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Read the previous values out of storage */\n        uint256 cashPrior = getCashPrior();\n        uint256 borrowsPrior = totalBorrows;\n        uint256 reservesPrior = totalReserves;\n        uint256 borrowIndexPrior = borrowIndex;\n\n        /* Calculate the current borrow interest rate */\n        uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);\n        require(borrowRateMantissa <= borrowRateMaxMantissa, \"borrow rate is absurdly high\");\n\n        /* Calculate the number of seconds elapsed since the last accrual */\n        uint256 timestampDelta = sub_(currentBlockTimestamp, accrualBlockTimestampPrior);\n\n        /*\n         * Calculate the interest accumulated into borrows and reserves and the new index:\n         *  simpleInterestFactor = borrowRate * timestampDelta\n         *  interestAccumulated = simpleInterestFactor * totalBorrows\n         *  totalBorrowsNew = interestAccumulated + totalBorrows\n         *  totalReservesNew = interestAccumulated * reserveFactor + totalReserves\n         *  borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex\n         */\n\n        Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), timestampDelta);\n        uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);\n        uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior);\n        uint256 totalReservesNew = mul_ScalarTruncateAddUInt(\n            Exp({mantissa: reserveFactorMantissa}),\n            interestAccumulated,\n            reservesPrior\n        );\n        uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /* We write the previously calculated values into storage */\n        accrualBlockTimestamp = currentBlockTimestamp;\n        borrowIndex = borrowIndexNew;\n        totalBorrows = totalBorrowsNew;\n        totalReserves = totalReservesNew;\n\n        /* We emit an AccrueInterest event */\n        emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param mintAmount The amount of the underlying asset to supply\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n     */\n    function mintInternal(uint256 mintAmount) internal nonReentrant returns (uint256, uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n            return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);\n        }\n        // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to\n        return mintFresh(msg.sender, mintAmount);\n    }\n\n    struct MintLocalVars {\n        Error err;\n        MathError mathErr;\n        uint256 exchangeRateMantissa;\n        uint256 mintTokens;\n        uint256 totalSupplyNew;\n        uint256 accountTokensNew;\n        uint256 actualMintAmount;\n    }\n\n    /**\n     * @notice User supplies assets into the market and receives jTokens in exchange\n     * @dev Assumes interest has already been accrued up to the current timestamp \n     * @param minter The address of the account which is supplying the assets\n     * @param mintAmount The amount of the underlying asset to supply\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n     */\n    function mintFresh(address minter, uint256 mintAmount) internal returns (uint256, uint256) {\n        /* Fail if mint not allowed */\n        uint256 allowed = joetroller.mintAllowed(address(this), minter, mintAmount);\n        if (allowed != 0) {\n            return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.MINT_JOETROLLER_REJECTION, allowed), 0);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);\n        }\n\n        MintLocalVars memory vars;\n\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         *  We call `doTransferIn` for the minter and the mintAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  `doTransferIn` reverts if anything goes wrong, since we can't be sure if\n         *  side-effects occurred. The function returns the amount actually transferred,\n         *  in case of a fee. On success, the jToken holds an additional `actualMintAmount`\n         *  of cash.\n         */\n        vars.actualMintAmount = doTransferIn(minter, mintAmount);\n\n        /*\n         * We get the current exchange rate and calculate the number of jTokens to be minted:\n         *  mintTokens = actualMintAmount / exchangeRate\n         */\n\n        vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));\n\n        /*\n         * We calculate the new total supply of jTokens and minter token balance, checking for overflow:\n         *  totalSupplyNew = totalSupply + mintTokens\n         *  accountTokensNew = accountTokens[minter] + mintTokens\n         */\n        vars.totalSupplyNew = add_(totalSupply, vars.mintTokens);\n        vars.accountTokensNew = add_(accountTokens[minter], vars.mintTokens);\n\n        /* We write previously calculated values into storage */\n        totalSupply = vars.totalSupplyNew;\n        accountTokens[minter] = vars.accountTokensNew;\n\n        /* We emit a Mint event, and a Transfer event */\n        emit Mint(minter, vars.actualMintAmount, vars.mintTokens);\n        emit Transfer(address(this), minter, vars.mintTokens);\n\n        /* We call the defense hook */\n        joetroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);\n\n        return (uint256(Error.NO_ERROR), vars.actualMintAmount);\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemInternal(uint256 redeemTokens) internal nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed\n            return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);\n        }\n        // redeemFresh emits redeem-specific logs on errors, so we don't need to\n        return redeemFresh(msg.sender, redeemTokens, 0);\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to receive from redeeming jTokens\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlyingInternal(uint256 redeemAmount) internal nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed\n            return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);\n        }\n        // redeemFresh emits redeem-specific logs on errors, so we don't need to\n        return redeemFresh(msg.sender, 0, redeemAmount);\n    }\n\n    struct RedeemLocalVars {\n        Error err;\n        MathError mathErr;\n        uint256 exchangeRateMantissa;\n        uint256 redeemTokens;\n        uint256 redeemAmount;\n        uint256 totalSupplyNew;\n        uint256 accountTokensNew;\n    }\n\n    /**\n     * @notice User redeems jTokens in exchange for the underlying asset\n     * @dev Assumes interest has already been accrued up to the current timestamp \n     * @param redeemer The address of the account which is redeeming the tokens\n     * @param redeemTokensIn The number of jTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)\n     * @param redeemAmountIn The number of underlying tokens to receive from redeeming jTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemFresh(\n        address payable redeemer,\n        uint256 redeemTokensIn,\n        uint256 redeemAmountIn\n    ) internal returns (uint256) {\n        require(redeemTokensIn == 0 || redeemAmountIn == 0, \"one of redeemTokensIn or redeemAmountIn must be zero\");\n\n        RedeemLocalVars memory vars;\n\n        /* exchangeRate = invoke Exchange Rate Stored() */\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /* If redeemTokensIn > 0: */\n        if (redeemTokensIn > 0) {\n            /*\n             * We calculate the exchange rate and the amount of underlying to be redeemed:\n             *  redeemTokens = redeemTokensIn\n             *  redeemAmount = redeemTokensIn x exchangeRateCurrent\n             */\n            vars.redeemTokens = redeemTokensIn;\n            vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);\n        } else {\n            /*\n             * We get the current exchange rate and calculate the amount to be redeemed:\n             *  redeemTokens = redeemAmountIn / exchangeRate\n             *  redeemAmount = redeemAmountIn\n             */\n            vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));\n            vars.redeemAmount = redeemAmountIn;\n        }\n\n        /* Fail if redeem not allowed */\n        uint256 allowed = joetroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REDEEM_JOETROLLER_REJECTION, allowed);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);\n        }\n\n        /*\n         * We calculate the new total supply and redeemer balance, checking for underflow:\n         *  totalSupplyNew = totalSupply - redeemTokens\n         *  accountTokensNew = accountTokens[redeemer] - redeemTokens\n         */\n        vars.totalSupplyNew = sub_(totalSupply, vars.redeemTokens);\n        vars.accountTokensNew = sub_(accountTokens[redeemer], vars.redeemTokens);\n\n        /* Fail gracefully if protocol has insufficient cash */\n        if (getCashPrior() < vars.redeemAmount) {\n            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We invoke doTransferOut for the redeemer and the redeemAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken has redeemAmount less of cash.\n         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         */\n        doTransferOut(redeemer, vars.redeemAmount);\n\n        /* We write previously calculated values into storage */\n        totalSupply = vars.totalSupplyNew;\n        accountTokens[redeemer] = vars.accountTokensNew;\n\n        /* We emit a Transfer event, and a Redeem event */\n        emit Transfer(redeemer, address(this), vars.redeemTokens);\n        emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        /* We call the defense hook */\n        joetroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrowInternal(uint256 borrowAmount) internal nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n            return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);\n        }\n        // borrowFresh emits borrow-specific logs on errors, so we don't need to\n        return borrowFresh(msg.sender, borrowAmount);\n    }\n\n    struct BorrowLocalVars {\n        MathError mathErr;\n        uint256 accountBorrows;\n        uint256 accountBorrowsNew;\n        uint256 totalBorrowsNew;\n    }\n\n    /**\n     * @notice Users borrow assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrowFresh(address payable borrower, uint256 borrowAmount) internal returns (uint256) {\n        /* Fail if borrow not allowed */\n        uint256 allowed = joetroller.borrowAllowed(address(this), borrower, borrowAmount);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.BORROW_JOETROLLER_REJECTION, allowed);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);\n        }\n\n        /* Fail gracefully if protocol has insufficient underlying cash */\n        if (getCashPrior() < borrowAmount) {\n            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);\n        }\n\n        BorrowLocalVars memory vars;\n\n        /*\n         * We calculate the new borrower and total borrow balances, failing on overflow:\n         *  accountBorrowsNew = accountBorrows + borrowAmount\n         *  totalBorrowsNew = totalBorrows + borrowAmount\n         */\n        vars.accountBorrows = borrowBalanceStoredInternal(borrower);\n        vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount);\n        vars.totalBorrowsNew = add_(totalBorrows, borrowAmount);\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We invoke doTransferOut for the borrower and the borrowAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken borrowAmount less of cash.\n         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         */\n        doTransferOut(borrower, borrowAmount);\n\n        /* We write the previously calculated values into storage */\n        accountBorrows[borrower].principal = vars.accountBorrowsNew;\n        accountBorrows[borrower].interestIndex = borrowIndex;\n        totalBorrows = vars.totalBorrowsNew;\n\n        /* We emit a Borrow event */\n        emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);\n\n        /* We call the defense hook */\n        joetroller.borrowVerify(address(this), borrower, borrowAmount);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @param repayAmount The amount to repay\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n     */\n    function repayBorrowInternal(uint256 repayAmount) internal nonReentrant returns (uint256, uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n            return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);\n        }\n        // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to\n        return repayBorrowFresh(msg.sender, msg.sender, repayAmount);\n    }\n\n    struct RepayBorrowLocalVars {\n        Error err;\n        MathError mathErr;\n        uint256 repayAmount;\n        uint256 borrowerIndex;\n        uint256 accountBorrows;\n        uint256 accountBorrowsNew;\n        uint256 totalBorrowsNew;\n        uint256 actualRepayAmount;\n    }\n\n    /**\n     * @notice Borrows are repaid by another user (possibly the borrower).\n     * @param payer the account paying off the borrow\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount the amount of undelrying tokens being returned\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n     */\n    function repayBorrowFresh(\n        address payer,\n        address borrower,\n        uint256 repayAmount\n    ) internal returns (uint256, uint256) {\n        /* Fail if repayBorrow not allowed */\n        uint256 allowed = joetroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);\n        if (allowed != 0) {\n            return (\n                failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REPAY_BORROW_JOETROLLER_REJECTION, allowed),\n                0\n            );\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);\n        }\n\n        RepayBorrowLocalVars memory vars;\n\n        /* We remember the original borrowerIndex for verification purposes */\n        vars.borrowerIndex = accountBorrows[borrower].interestIndex;\n\n        /* We fetch the amount the borrower owes, with accumulated interest */\n        vars.accountBorrows = borrowBalanceStoredInternal(borrower);\n\n        /* If repayAmount == -1, repayAmount = accountBorrows */\n        if (repayAmount == uint256(-1)) {\n            vars.repayAmount = vars.accountBorrows;\n        } else {\n            vars.repayAmount = repayAmount;\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We call doTransferIn for the payer and the repayAmount\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken holds an additional repayAmount of cash.\n         *  doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         *   it returns the amount actually transferred, in case of a fee.\n         */\n        vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);\n\n        /*\n         * We calculate the new borrower and total borrow balances, failing on underflow:\n         *  accountBorrowsNew = accountBorrows - actualRepayAmount\n         *  totalBorrowsNew = totalBorrows - actualRepayAmount\n         */\n        vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount);\n        vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount);\n\n        /* We write the previously calculated values into storage */\n        accountBorrows[borrower].principal = vars.accountBorrowsNew;\n        accountBorrows[borrower].interestIndex = borrowIndex;\n        totalBorrows = vars.totalBorrowsNew;\n\n        /* We emit a RepayBorrow event */\n        emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);\n\n        /* We call the defense hook */\n        joetroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);\n\n        return (uint256(Error.NO_ERROR), vars.actualRepayAmount);\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n     */\n    function liquidateBorrowInternal(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) internal nonReentrant returns (uint256, uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\n            return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);\n        }\n\n        error = jTokenCollateral.accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\n            return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);\n        }\n\n        // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to\n        return liquidateBorrowFresh(msg.sender, borrower, repayAmount, jTokenCollateral);\n    }\n\n    /**\n     * @notice The liquidator liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param liquidator The address repaying the borrow and seizing collateral\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n     */\n    function liquidateBorrowFresh(\n        address liquidator,\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) internal returns (uint256, uint256) {\n        /* Fail if liquidate not allowed */\n        uint256 allowed = joetroller.liquidateBorrowAllowed(\n            address(this),\n            address(jTokenCollateral),\n            liquidator,\n            borrower,\n            repayAmount\n        );\n        if (allowed != 0) {\n            return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_JOETROLLER_REJECTION, allowed), 0);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);\n        }\n\n        /* Verify jTokenCollateral market's block timestamp equals current block timestamp */\n        if (jTokenCollateral.accrualBlockTimestamp() != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);\n        }\n\n        /* Fail if borrower = liquidator */\n        if (borrower == liquidator) {\n            return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);\n        }\n\n        /* Fail if repayAmount = 0 */\n        if (repayAmount == 0) {\n            return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);\n        }\n\n        /* Fail if repayAmount = -1 */\n        if (repayAmount == uint256(-1)) {\n            return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);\n        }\n\n        /* Fail if repayBorrow fails */\n        (uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);\n        if (repayBorrowError != uint256(Error.NO_ERROR)) {\n            return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /* We calculate the number of collateral tokens that will be seized */\n        (uint256 amountSeizeError, uint256 seizeTokens) = joetroller.liquidateCalculateSeizeTokens(\n            address(this),\n            address(jTokenCollateral),\n            actualRepayAmount\n        );\n        require(amountSeizeError == uint256(Error.NO_ERROR), \"LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED\");\n\n        /* Revert if borrower collateral token balance < seizeTokens */\n        require(jTokenCollateral.balanceOf(borrower) >= seizeTokens, \"LIQUIDATE_SEIZE_TOO_MUCH\");\n\n        // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call\n        uint256 seizeError;\n        if (address(jTokenCollateral) == address(this)) {\n            seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);\n        } else {\n            seizeError = jTokenCollateral.seize(liquidator, borrower, seizeTokens);\n        }\n\n        /* Revert if seize tokens fails (since we cannot be sure of side effects) */\n        require(seizeError == uint256(Error.NO_ERROR), \"token seizure failed\");\n\n        /* We emit a LiquidateBorrow event */\n        emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(jTokenCollateral), seizeTokens);\n\n        /* We call the defense hook */\n        joetroller.liquidateBorrowVerify(\n            address(this),\n            address(jTokenCollateral),\n            liquidator,\n            borrower,\n            actualRepayAmount,\n            seizeTokens\n        );\n\n        return (uint256(Error.NO_ERROR), actualRepayAmount);\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Will fail unless called by another jToken during the process of liquidation.\n     *  Its absolutely critical to use msg.sender as the borrowed jToken and not a parameter.\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seize(\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) external nonReentrant returns (uint256) {\n        return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another JToken.\n     *  Its absolutely critical to use msg.sender as the seizer jToken and not a parameter.\n     * @param seizerToken The contract seizing the collateral (i.e. borrowed jToken)\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seizeInternal(\n        address seizerToken,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) internal returns (uint256) {\n        /* Fail if seize not allowed */\n        uint256 allowed = joetroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_JOETROLLER_REJECTION, allowed);\n        }\n\n        /* Fail if borrower = liquidator */\n        if (borrower == liquidator) {\n            return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);\n        }\n\n        /*\n         * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:\n         *  borrowerTokensNew = accountTokens[borrower] - seizeTokens\n         *  liquidatorTokensNew = accountTokens[liquidator] + seizeTokens\n         */\n        uint256 borrowerTokensNew = sub_(accountTokens[borrower], seizeTokens);\n        uint256 liquidatorTokensNew = add_(accountTokens[liquidator], seizeTokens);\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /* We write the previously calculated values into storage */\n        accountTokens[borrower] = borrowerTokensNew;\n        accountTokens[liquidator] = liquidatorTokensNew;\n\n        /* Emit a Transfer event */\n        emit Transfer(borrower, liquidator, seizeTokens);\n\n        /* We call the defense hook */\n        joetroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /*** Admin Functions ***/\n\n    /**\n     * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n     * @param newPendingAdmin New pending admin.\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) {\n        // Check caller = admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);\n        }\n\n        // Save current value, if any, for inclusion in log\n        address oldPendingAdmin = pendingAdmin;\n\n        // Store pendingAdmin with value newPendingAdmin\n        pendingAdmin = newPendingAdmin;\n\n        // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)\n        emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\n     * @dev Admin function for pending admin to accept role and update admin\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _acceptAdmin() external returns (uint256) {\n        // Check caller is pendingAdmin and pendingAdmin ≠ address(0)\n        if (msg.sender != pendingAdmin || msg.sender == address(0)) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);\n        }\n\n        // Save current values for inclusion in log\n        address oldAdmin = admin;\n        address oldPendingAdmin = pendingAdmin;\n\n        // Store admin with value pendingAdmin\n        admin = pendingAdmin;\n\n        // Clear the pending value\n        pendingAdmin = address(0);\n\n        emit NewAdmin(oldAdmin, admin);\n        emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Sets a new joetroller for the market\n     * @dev Admin function to set a new joetroller\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_JOETROLLER_OWNER_CHECK);\n        }\n\n        JoetrollerInterface oldJoetroller = joetroller;\n        // Ensure invoke joetroller.isJoetroller() returns true\n        require(newJoetroller.isJoetroller(), \"marker method returned false\");\n\n        // Set market's joetroller to newJoetroller\n        joetroller = newJoetroller;\n\n        // Emit NewJoetroller(oldJoetroller, newJoetroller)\n        emit NewJoetroller(oldJoetroller, newJoetroller);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh\n     * @dev Admin function to accrue interest and set a new reserve factor\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.\n            return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);\n        }\n        // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.\n        return _setReserveFactorFresh(newReserveFactorMantissa);\n    }\n\n    /**\n     * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)\n     * @dev Admin function to set a new reserve factor\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) {\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);\n        }\n\n        // Verify market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);\n        }\n\n        // Check newReserveFactor ≤ maxReserveFactor\n        if (newReserveFactorMantissa > reserveFactorMaxMantissa) {\n            return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);\n        }\n\n        uint256 oldReserveFactorMantissa = reserveFactorMantissa;\n        reserveFactorMantissa = newReserveFactorMantissa;\n\n        emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Accrues interest and reduces reserves by transferring from msg.sender\n     * @param addAmount Amount of addition to reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReservesInternal(uint256 addAmount) internal nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.\n            return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);\n        }\n\n        // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.\n        (error, ) = _addReservesFresh(addAmount);\n        return error;\n    }\n\n    /**\n     * @notice Add reserves by transferring from caller\n     * @dev Requires fresh interest accrual\n     * @param addAmount Amount of addition to reserves\n     * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees\n     */\n    function _addReservesFresh(uint256 addAmount) internal returns (uint256, uint256) {\n        // totalReserves + actualAddAmount\n        uint256 totalReservesNew;\n        uint256 actualAddAmount;\n\n        // We fail gracefully unless market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We call doTransferIn for the caller and the addAmount\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken holds an additional addAmount of cash.\n         *  doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         *  it returns the amount actually transferred, in case of a fee.\n         */\n\n        actualAddAmount = doTransferIn(msg.sender, addAmount);\n\n        totalReservesNew = add_(totalReserves, actualAddAmount);\n\n        // Store reserves[n+1] = reserves[n] + actualAddAmount\n        totalReserves = totalReservesNew;\n\n        /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */\n        emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);\n\n        /* Return (NO_ERROR, actualAddAmount) */\n        return (uint256(Error.NO_ERROR), actualAddAmount);\n    }\n\n    /**\n     * @notice Accrues interest and reduces reserves by transferring to admin\n     * @param reduceAmount Amount of reduction to reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.\n            return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);\n        }\n        // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.\n        return _reduceReservesFresh(reduceAmount);\n    }\n\n    /**\n     * @notice Reduces reserves by transferring to admin\n     * @dev Requires fresh interest accrual\n     * @param reduceAmount Amount of reduction to reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) {\n        // totalReserves - reduceAmount\n        uint256 totalReservesNew;\n\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);\n        }\n\n        // We fail gracefully unless market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);\n        }\n\n        // Fail gracefully if protocol has insufficient underlying cash\n        if (getCashPrior() < reduceAmount) {\n            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);\n        }\n\n        // Check reduceAmount ≤ reserves[n] (totalReserves)\n        if (reduceAmount > totalReserves) {\n            return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        totalReservesNew = sub_(totalReserves, reduceAmount);\n\n        // Store reserves[n+1] = reserves[n] - reduceAmount\n        totalReserves = totalReservesNew;\n\n        // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n        doTransferOut(admin, reduceAmount);\n\n        emit ReservesReduced(admin, reduceAmount, totalReservesNew);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh\n     * @dev Admin function to accrue interest and update the interest rate model\n     * @param newInterestRateModel the new interest rate model to use\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) {\n        uint256 error = accrueInterest();\n        if (error != uint256(Error.NO_ERROR)) {\n            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed\n            return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);\n        }\n        // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.\n        return _setInterestRateModelFresh(newInterestRateModel);\n    }\n\n    /**\n     * @notice updates the interest rate model (*requires fresh interest accrual)\n     * @dev Admin function to update the interest rate model\n     * @param newInterestRateModel the new interest rate model to use\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) {\n        // Used to store old model for use in the event that is emitted on success\n        InterestRateModel oldInterestRateModel;\n\n        // Check caller is admin\n        if (msg.sender != admin) {\n            return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);\n        }\n\n        // We fail gracefully unless market's block timestamp equals current block timestamp\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);\n        }\n\n        // Track the market's current interest rate model\n        oldInterestRateModel = interestRateModel;\n\n        // Ensure invoke newInterestRateModel.isInterestRateModel() returns true\n        require(newInterestRateModel.isInterestRateModel(), \"marker method returned false\");\n\n        // Set the interest rate model to newInterestRateModel\n        interestRateModel = newInterestRateModel;\n\n        // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)\n        emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /*** Safe Token ***/\n\n    /**\n     * @notice Gets balance of this contract in terms of the underlying\n     * @dev This excludes the value of the current message, if any\n     * @return The quantity of underlying owned by this contract\n     */\n    function getCashPrior() internal view returns (uint256);\n\n    /**\n     * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.\n     *  This may revert due to insufficient balance or insufficient allowance.\n     */\n    function doTransferIn(address from, uint256 amount) internal returns (uint256);\n\n    /**\n     * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.\n     *  If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.\n     *  If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.\n     */\n    function doTransferOut(address payable to, uint256 amount) internal;\n\n    /*** Reentrancy Guard ***/\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     */\n    modifier nonReentrant() {\n        require(_notEntered, \"re-entered\");\n        _notEntered = false;\n        _;\n        _notEntered = true; // get a gas-refund post-Istanbul\n    }\n}\n"
    },
    "contracts/TripleSlopeRateModel.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./InterestRateModel.sol\";\nimport \"./SafeMath.sol\";\n\n/**\n * @title CREAM's TripleSlopeRateModel Contract\n * @author C.R.E.A.M. Finance\n */\ncontract TripleSlopeRateModel is InterestRateModel {\n    using SafeMath for uint256;\n\n    event NewInterestParams(\n        uint256 baseRatePerSecond,\n        uint256 multiplierPerSecond,\n        uint256 jumpMultiplierPerSecond,\n        uint256 kink1,\n        uint256 kink2,\n        uint256 roof\n    );\n\n    /**\n     * @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly\n     */\n    address public owner;\n\n    /**\n     * @notice The approximate number of seconds per year that is assumed by the interest rate model\n     */\n    uint256 public constant secondsPerYear = 31536000;\n\n    /**\n     * @notice The minimum roof value used for calculating borrow rate.\n     */\n    uint256 internal constant minRoofValue = 1e18;\n\n    /**\n     * @notice The multiplier of utilization rate that gives the slope of the interest rate\n     */\n    uint256 public multiplierPerSecond;\n\n    /**\n     * @notice The base interest rate which is the y-intercept when utilization rate is 0\n     */\n    uint256 public baseRatePerSecond;\n\n    /**\n     * @notice The multiplierPerSecond after hitting a specified utilization point\n     */\n    uint256 public jumpMultiplierPerSecond;\n\n    /**\n     * @notice The utilization point at which the interest rate is fixed\n     */\n    uint256 public kink1;\n\n    /**\n     * @notice The utilization point at which the jump multiplier is applied\n     */\n    uint256 public kink2;\n\n    /**\n     * @notice The utilization point at which the rate is fixed\n     */\n    uint256 public roof;\n\n    /**\n     * @notice Construct an interest rate model\n     * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)\n     * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)\n     * @param jumpMultiplierPerYear The multiplierPerSecond after hitting a specified utilization point\n     * @param kink1_ The utilization point at which the interest rate is fixed\n     * @param kink2_ The utilization point at which the jump multiplier is applied\n     * @param roof_ The utilization point at which the borrow rate is fixed\n     * @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly)\n     */\n    constructor(\n        uint256 baseRatePerYear,\n        uint256 multiplierPerYear,\n        uint256 jumpMultiplierPerYear,\n        uint256 kink1_,\n        uint256 kink2_,\n        uint256 roof_,\n        address owner_\n    ) public {\n        owner = owner_;\n\n        updateTripleRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink1_, kink2_, roof_);\n    }\n\n    /**\n     * @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock)\n     * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)\n     * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)\n     * @param jumpMultiplierPerYear The multiplierPerSecond after hitting a specified utilization point\n     * @param kink1_ The utilization point at which the interest rate is fixed\n     * @param kink2_ The utilization point at which the jump multiplier is applied\n     * @param roof_ The utilization point at which the borrow rate is fixed\n     */\n    function updateTripleRateModel(\n        uint256 baseRatePerYear,\n        uint256 multiplierPerYear,\n        uint256 jumpMultiplierPerYear,\n        uint256 kink1_,\n        uint256 kink2_,\n        uint256 roof_\n    ) external {\n        require(msg.sender == owner, \"only the owner may call this function.\");\n\n        updateTripleRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink1_, kink2_, roof_);\n    }\n\n    /**\n     * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`\n     * @param cash The amount of cash in the market\n     * @param borrows The amount of borrows in the market\n     * @param reserves The amount of reserves in the market (currently unused)\n     * @return The utilization rate as a mantissa between [0, 1e18]\n     */\n    function utilizationRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves\n    ) public view returns (uint256) {\n        // Utilization rate is 0 when there are no borrows\n        if (borrows == 0) {\n            return 0;\n        }\n\n        uint256 util = borrows.mul(1e18).div(cash.add(borrows).sub(reserves));\n        // If the utilization is above the roof, cap it.\n        if (util > roof) {\n            util = roof;\n        }\n        return util;\n    }\n\n    /**\n     * @notice Calculates the current borrow rate per second, with the error code expected by the market\n     * @param cash The amount of cash in the market\n     * @param borrows The amount of borrows in the market\n     * @param reserves The amount of reserves in the market\n     * @return The borrow rate percentage per second as a mantissa (scaled by 1e18)\n     */\n    function getBorrowRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves\n    ) public view returns (uint256) {\n        uint256 util = utilizationRate(cash, borrows, reserves);\n\n        if (util <= kink1) {\n            return util.mul(multiplierPerSecond).div(1e18).add(baseRatePerSecond);\n        } else if (util <= kink2) {\n            return kink1.mul(multiplierPerSecond).div(1e18).add(baseRatePerSecond);\n        } else {\n            uint256 normalRate = kink1.mul(multiplierPerSecond).div(1e18).add(baseRatePerSecond);\n            uint256 excessUtil = util.sub(kink2);\n            return excessUtil.mul(jumpMultiplierPerSecond).div(1e18).add(normalRate);\n        }\n    }\n\n    /**\n     * @notice Calculates the current supply rate per second\n     * @param cash The amount of cash in the market\n     * @param borrows The amount of borrows in the market\n     * @param reserves The amount of reserves in the market\n     * @param reserveFactorMantissa The current reserve factor for the market\n     * @return The supply rate percentage per second as a mantissa (scaled by 1e18)\n     */\n    function getSupplyRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves,\n        uint256 reserveFactorMantissa\n    ) public view returns (uint256) {\n        uint256 oneMinusReserveFactor = uint256(1e18).sub(reserveFactorMantissa);\n        uint256 borrowRate = getBorrowRate(cash, borrows, reserves);\n        uint256 rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);\n        return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18);\n    }\n\n    /**\n     * @notice Internal function to update the parameters of the interest rate model\n     * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)\n     * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)\n     * @param jumpMultiplierPerYear The multiplierPerSecond after hitting a specified utilization point\n     * @param kink1_ The utilization point at which the interest rate is fixed\n     * @param kink2_ The utilization point at which the jump multiplier is applied\n     * @param roof_ The utilization point at which the borrow rate is fixed\n     */\n    function updateTripleRateModelInternal(\n        uint256 baseRatePerYear,\n        uint256 multiplierPerYear,\n        uint256 jumpMultiplierPerYear,\n        uint256 kink1_,\n        uint256 kink2_,\n        uint256 roof_\n    ) internal {\n        require(kink1_ <= kink2_, \"kink1 must less than or equal to kink2\");\n        require(roof_ >= minRoofValue, \"invalid roof value\");\n\n        baseRatePerSecond = baseRatePerYear.div(secondsPerYear);\n        multiplierPerSecond = (multiplierPerYear.mul(1e18)).div(secondsPerYear.mul(kink1_));\n        jumpMultiplierPerSecond = jumpMultiplierPerYear.div(secondsPerYear);\n        kink1 = kink1_;\n        kink2 = kink2_;\n        roof = roof_;\n\n        emit NewInterestParams(baseRatePerSecond, multiplierPerSecond, jumpMultiplierPerSecond, kink1, kink2, roof);\n    }\n}\n"
    },
    "contracts/SafeMath.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\n// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol\n// Subject to the MIT license.\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c >= a, \"SafeMath: addition overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     * - Addition cannot overflow.\n     */\n    function add(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c >= a, errorMessage);\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot underflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        return sub(a, b, \"SafeMath: subtraction underflow\");\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot underflow.\n     */\n    function sub(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        require(b <= a, errorMessage);\n        uint256 c = a - b;\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n        // benefit is lost if 'b' is also tested.\n        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n        if (a == 0) {\n            return 0;\n        }\n\n        uint256 c = a * b;\n        require(c / a == b, \"SafeMath: multiplication overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     * - Multiplication cannot overflow.\n     */\n    function mul(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n        // benefit is lost if 'b' is also tested.\n        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n        if (a == 0) {\n            return 0;\n        }\n\n        uint256 c = a * b;\n        require(c / a == b, errorMessage);\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers.\n     * Reverts on division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        return div(a, b, \"SafeMath: division by zero\");\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers.\n     * Reverts with custom message on division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function div(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        // Solidity only automatically asserts when dividing by 0\n        require(b > 0, errorMessage);\n        uint256 c = a / b;\n        // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        return mod(a, b, \"SafeMath: modulo by zero\");\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts with custom message when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function mod(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        require(b != 0, errorMessage);\n        return a % b;\n    }\n}\n"
    },
    "contracts/JumpRateModelV2.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./InterestRateModel.sol\";\nimport \"./SafeMath.sol\";\n\n/**\n * @title Compound's JumpRateModel Contract V2\n * @author Compound (modified by Dharma Labs)\n * @notice Version 2 modifies Version 1 by enabling updateable parameters.\n */\ncontract JumpRateModelV2 is InterestRateModel {\n    using SafeMath for uint256;\n\n    event NewInterestParams(\n        uint256 baseRatePerSecond,\n        uint256 multiplierPerSecond,\n        uint256 jumpMultiplierPerSecond,\n        uint256 kink,\n        uint256 roof\n    );\n\n    /**\n     * @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly\n     */\n    address public owner;\n\n    /**\n     * @notice The approximate number of seconds per year that is assumed by the interest rate model\n     */\n    uint256 public constant secondsPerYear = 31536000;\n\n    /**\n     * @notice The minimum roof value used for calculating borrow rate.\n     */\n    uint256 internal constant minRoofValue = 1e18;\n\n    /**\n     * @notice The multiplier of utilization rate that gives the slope of the interest rate\n     */\n    uint256 public multiplierPerSecond;\n\n    /**\n     * @notice The base interest rate which is the y-intercept when utilization rate is 0\n     */\n    uint256 public baseRatePerSecond;\n\n    /**\n     * @notice The multiplierPerSecond after hitting a specified utilization point\n     */\n    uint256 public jumpMultiplierPerSecond;\n\n    /**\n     * @notice The utilization point at which the jump multiplier is applied\n     */\n    uint256 public kink;\n\n    /**\n     * @notice The utilization point at which the rate is fixed\n     */\n    uint256 public roof;\n\n    /**\n     * @notice Construct an interest rate model\n     * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)\n     * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)\n     * @param jumpMultiplierPerYear The multiplierPerSecond after hitting a specified utilization point\n     * @param kink_ The utilization point at which the jump multiplier is applied\n     * @param roof_ The utilization point at which the borrow rate is fixed\n     * @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly)\n     */\n    constructor(\n        uint256 baseRatePerYear,\n        uint256 multiplierPerYear,\n        uint256 jumpMultiplierPerYear,\n        uint256 kink_,\n        uint256 roof_,\n        address owner_\n    ) public {\n        owner = owner_;\n\n        updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_, roof_);\n    }\n\n    /**\n     * @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock)\n     * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)\n     * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)\n     * @param jumpMultiplierPerYear The multiplierPerSecond after hitting a specified utilization point\n     * @param kink_ The utilization point at which the jump multiplier is applied\n     * @param roof_ The utilization point at which the borrow rate is fixed\n     */\n    function updateJumpRateModel(\n        uint256 baseRatePerYear,\n        uint256 multiplierPerYear,\n        uint256 jumpMultiplierPerYear,\n        uint256 kink_,\n        uint256 roof_\n    ) external {\n        require(msg.sender == owner, \"only the owner may call this function.\");\n\n        updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_, roof_);\n    }\n\n    /**\n     * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`\n     * @param cash The amount of cash in the market\n     * @param borrows The amount of borrows in the market\n     * @param reserves The amount of reserves in the market (currently unused)\n     * @return The utilization rate as a mantissa between [0, 1e18]\n     */\n    function utilizationRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves\n    ) public view returns (uint256) {\n        // Utilization rate is 0 when there are no borrows\n        if (borrows == 0) {\n            return 0;\n        }\n\n        uint256 util = borrows.mul(1e18).div(cash.add(borrows).sub(reserves));\n        // If the utilization is above the roof, cap it.\n        if (util > roof) {\n            util = roof;\n        }\n        return util;\n    }\n\n    /**\n     * @notice Calculates the current borrow rate per second, with the error code expected by the market\n     * @param cash The amount of cash in the market\n     * @param borrows The amount of borrows in the market\n     * @param reserves The amount of reserves in the market\n     * @return The borrow rate percentage per second as a mantissa (scaled by 1e18)\n     */\n    function getBorrowRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves\n    ) public view returns (uint256) {\n        uint256 util = utilizationRate(cash, borrows, reserves);\n\n        if (util <= kink) {\n            return util.mul(multiplierPerSecond).div(1e18).add(baseRatePerSecond);\n        } else {\n            uint256 normalRate = kink.mul(multiplierPerSecond).div(1e18).add(baseRatePerSecond);\n            uint256 excessUtil = util.sub(kink);\n            return excessUtil.mul(jumpMultiplierPerSecond).div(1e18).add(normalRate);\n        }\n    }\n\n    /**\n     * @notice Calculates the current supply rate per second\n     * @param cash The amount of cash in the market\n     * @param borrows The amount of borrows in the market\n     * @param reserves The amount of reserves in the market\n     * @param reserveFactorMantissa The current reserve factor for the market\n     * @return The supply rate percentage per second as a mantissa (scaled by 1e18)\n     */\n    function getSupplyRate(\n        uint256 cash,\n        uint256 borrows,\n        uint256 reserves,\n        uint256 reserveFactorMantissa\n    ) public view returns (uint256) {\n        uint256 oneMinusReserveFactor = uint256(1e18).sub(reserveFactorMantissa);\n        uint256 borrowRate = getBorrowRate(cash, borrows, reserves);\n        uint256 rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);\n        return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18);\n    }\n\n    /**\n     * @notice Internal function to update the parameters of the interest rate model\n     * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)\n     * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)\n     * @param jumpMultiplierPerYear The multiplierPerSecond after hitting a specified utilization point\n     * @param kink_ The utilization point at which the jump multiplier is applied\n     * @param roof_ The utilization point at which the borrow rate is fixed\n     */\n    function updateJumpRateModelInternal(\n        uint256 baseRatePerYear,\n        uint256 multiplierPerYear,\n        uint256 jumpMultiplierPerYear,\n        uint256 kink_,\n        uint256 roof_\n    ) internal {\n        require(roof_ >= minRoofValue, \"invalid roof value\");\n\n        baseRatePerSecond = baseRatePerYear.div(secondsPerYear);\n        multiplierPerSecond = (multiplierPerYear.mul(1e18)).div(secondsPerYear.mul(kink_));\n        jumpMultiplierPerSecond = jumpMultiplierPerYear.div(secondsPerYear);\n        kink = kink_;\n        roof = roof_;\n\n        emit NewInterestParams(baseRatePerSecond, multiplierPerSecond, jumpMultiplierPerSecond, kink, roof);\n    }\n}\n"
    },
    "contracts/JTokenAdmin.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JErc20.sol\";\nimport \"./JToken.sol\";\nimport \"./EIP20NonStandardInterface.sol\";\n\ncontract JTokenAdmin {\n    /// @notice Admin address\n    address payable public admin;\n\n    /// @notice Reserve manager address\n    address payable public reserveManager;\n\n    /// @notice Emits when a new admin is assigned\n    event SetAdmin(address indexed oldAdmin, address indexed newAdmin);\n\n    /// @notice Emits when a new reserve manager is assigned\n    event SetReserveManager(address indexed oldReserveManager, address indexed newAdmin);\n\n    /**\n     * @dev Throws if called by any account other than the admin.\n     */\n    modifier onlyAdmin() {\n        require(msg.sender == admin, \"only the admin may call this function\");\n        _;\n    }\n\n    /**\n     * @dev Throws if called by any account other than the reserve manager.\n     */\n    modifier onlyReserveManager() {\n        require(msg.sender == reserveManager, \"only the reserve manager may call this function\");\n        _;\n    }\n\n    constructor(address payable _admin) public {\n        _setAdmin(_admin);\n    }\n\n    /**\n     * @notice Get jToken admin\n     * @param jToken The jToken address\n     */\n    function getJTokenAdmin(address jToken) public view returns (address) {\n        return JToken(jToken).admin();\n    }\n\n    /**\n     * @notice Set jToken pending admin\n     * @param jToken The jToken address\n     * @param newPendingAdmin The new pending admin\n     */\n    function _setPendingAdmin(address jToken, address payable newPendingAdmin) external onlyAdmin returns (uint256) {\n        return JTokenInterface(jToken)._setPendingAdmin(newPendingAdmin);\n    }\n\n    /**\n     * @notice Accept jToken admin\n     * @param jToken The jToken address\n     */\n    function _acceptAdmin(address jToken) external onlyAdmin returns (uint256) {\n        return JTokenInterface(jToken)._acceptAdmin();\n    }\n\n    /**\n     * @notice Set jToken joetroller\n     * @param jToken The jToken address\n     * @param newJoetroller The new joetroller address\n     */\n    function _setJoetroller(address jToken, JoetrollerInterface newJoetroller) external onlyAdmin returns (uint256) {\n        return JTokenInterface(jToken)._setJoetroller(newJoetroller);\n    }\n\n    /**\n     * @notice Set jToken reserve factor\n     * @param jToken The jToken address\n     * @param newReserveFactorMantissa The new reserve factor\n     */\n    function _setReserveFactor(address jToken, uint256 newReserveFactorMantissa) external onlyAdmin returns (uint256) {\n        return JTokenInterface(jToken)._setReserveFactor(newReserveFactorMantissa);\n    }\n\n    /**\n     * @notice Reduce jToken reserve\n     * @param jToken The jToken address\n     * @param reduceAmount The amount of reduction\n     */\n    function _reduceReserves(address jToken, uint256 reduceAmount) external onlyAdmin returns (uint256) {\n        return JTokenInterface(jToken)._reduceReserves(reduceAmount);\n    }\n\n    /**\n     * @notice Set jToken IRM\n     * @param jToken The jToken address\n     * @param newInterestRateModel The new IRM address\n     */\n    function _setInterestRateModel(address jToken, InterestRateModel newInterestRateModel)\n        external\n        onlyAdmin\n        returns (uint256)\n    {\n        return JTokenInterface(jToken)._setInterestRateModel(newInterestRateModel);\n    }\n\n    /**\n     * @notice Set jToken collateral cap\n     * @dev It will revert if the jToken is not JCollateralCap.\n     * @param jToken The jToken address\n     * @param newCollateralCap The new collateral cap\n     */\n    function _setCollateralCap(address jToken, uint256 newCollateralCap) external onlyAdmin {\n        JCollateralCapErc20Interface(jToken)._setCollateralCap(newCollateralCap);\n    }\n\n    /**\n     * @notice Set jToken new implementation\n     * @param jToken The jToken address\n     * @param implementation The new implementation\n     * @param becomeImplementationData The payload data\n     */\n    function _setImplementation(\n        address jToken,\n        address implementation,\n        bool allowResign,\n        bytes calldata becomeImplementationData\n    ) external onlyAdmin {\n        JDelegatorInterface(jToken)._setImplementation(implementation, allowResign, becomeImplementationData);\n    }\n\n    /**\n     * @notice Extract reserves by the reserve manager\n     * @param jToken The jToken address\n     * @param reduceAmount The amount of reduction\n     */\n    function extractReserves(address jToken, uint256 reduceAmount) external onlyReserveManager {\n        require(JTokenInterface(jToken)._reduceReserves(reduceAmount) == 0, \"failed to reduce reserves\");\n\n        address underlying = JErc20(jToken).underlying();\n        _transferToken(underlying, reserveManager, reduceAmount);\n    }\n\n    /**\n     * @notice Seize the stock assets\n     * @param token The token address\n     */\n    function seize(address token) external onlyAdmin {\n        uint256 amount = EIP20NonStandardInterface(token).balanceOf(address(this));\n        if (amount > 0) {\n            _transferToken(token, admin, amount);\n        }\n    }\n\n    /**\n     * @notice Set the admin\n     * @param newAdmin The new admin\n     */\n    function setAdmin(address payable newAdmin) external onlyAdmin {\n        _setAdmin(newAdmin);\n    }\n\n    /**\n     * @notice Set the reserve manager\n     * @param newReserveManager The new reserve manager\n     */\n    function setReserveManager(address payable newReserveManager) external onlyAdmin {\n        address oldReserveManager = reserveManager;\n        reserveManager = newReserveManager;\n\n        emit SetReserveManager(oldReserveManager, newReserveManager);\n    }\n\n    /* Internal functions */\n\n    function _setAdmin(address payable newAdmin) private {\n        require(newAdmin != address(0), \"new admin cannot be zero address\");\n        address oldAdmin = admin;\n        admin = newAdmin;\n        emit SetAdmin(oldAdmin, newAdmin);\n    }\n\n    function _transferToken(\n        address token,\n        address payable to,\n        uint256 amount\n    ) private {\n        require(to != address(0), \"receiver cannot be zero address\");\n\n        EIP20NonStandardInterface(token).transfer(to, amount);\n\n        bool success;\n        assembly {\n            switch returndatasize()\n            case 0 {\n                // This is a non-standard ERC-20\n                success := not(0) // set success to true\n            }\n            case 32 {\n                // This is a joelaint ERC-20\n                returndatacopy(0, 0, 32)\n                success := mload(0) // Set `success = returndata` of external call\n            }\n            default {\n                if lt(returndatasize(), 32) {\n                    revert(0, 0) // This is a non-compliant ERC-20, revert.\n                }\n                returndatacopy(0, 0, 32) // Vyper joeiler before 0.2.8 will not truncate RETURNDATASIZE.\n                success := mload(0) // See here: https://github.com/vyperlang/vyper/security/advisories/GHSA-375m-5fvv-xq23\n            }\n        }\n        require(success, \"TOKEN_TRANSFER_OUT_FAILED\");\n    }\n\n    function compareStrings(string memory a, string memory b) private pure returns (bool) {\n        return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));\n    }\n\n    function() external payable {}\n}\n"
    },
    "contracts/FlashloanLender.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\nimport \"./JCollateralCapErc20.sol\";\nimport \"./JErc20.sol\";\nimport \"./Joetroller.sol\";\n\ninterface CERC20Interface {\n    function underlying() external view returns (address);\n}\n\ncontract FlashloanLender is ERC3156FlashLenderInterface {\n    /**\n     * @notice underlying token to jToken mapping\n     */\n    mapping(address => address) public underlyingToJToken;\n\n    /**\n     * @notice C.R.E.A.M. joetroller address\n     */\n    address payable public joetroller;\n\n    address public owner;\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        require(msg.sender == owner, \"not owner\");\n        _;\n    }\n\n    constructor(address payable _joetroller, address _owner) public {\n        joetroller = _joetroller;\n        owner = _owner;\n        initialiseUnderlyingMapping();\n    }\n\n    function maxFlashLoan(address token) external view returns (uint256) {\n        address jToken = underlyingToJToken[token];\n        uint256 amount = 0;\n        if (jToken != address(0)) {\n            amount = JCollateralCapErc20(jToken).maxFlashLoan();\n        }\n        return amount;\n    }\n\n    function flashFee(address token, uint256 amount) external view returns (uint256) {\n        address jToken = underlyingToJToken[token];\n        require(jToken != address(0), \"cannot find jToken of this underlying in the mapping\");\n        return JCollateralCapErc20(jToken).flashFee(amount);\n    }\n\n    function flashLoan(\n        ERC3156FlashBorrowerInterface receiver,\n        address token,\n        uint256 amount,\n        bytes calldata data\n    ) external returns (bool) {\n        address jToken = underlyingToJToken[token];\n        require(jToken != address(0), \"cannot find jToken of this underlying in the mapping\");\n        return JCollateralCapErc20(jToken).flashLoan(receiver, msg.sender, amount, data);\n    }\n\n    function updateUnderlyingMapping(JToken[] calldata jTokens) external onlyOwner returns (bool) {\n        uint256 jTokenLength = jTokens.length;\n        for (uint256 i = 0; i < jTokenLength; i++) {\n            JToken jToken = jTokens[i];\n            address underlying = JErc20(address(jToken)).underlying();\n            underlyingToJToken[underlying] = address(jToken);\n        }\n        return true;\n    }\n\n    function removeUnderlyingMapping(JToken[] calldata jTokens) external onlyOwner returns (bool) {\n        uint256 jTokenLength = jTokens.length;\n        for (uint256 i = 0; i < jTokenLength; i++) {\n            JToken jToken = jTokens[i];\n            address underlying = JErc20(address(jToken)).underlying();\n            underlyingToJToken[underlying] = address(0);\n        }\n        return true;\n    }\n\n    /*** Internal Functions ***/\n\n    function compareStrings(string memory a, string memory b) private pure returns (bool) {\n        return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));\n    }\n\n    function initialiseUnderlyingMapping() internal {\n        JToken[] memory jTokens = Joetroller(joetroller).getAllMarkets();\n        uint256 jTokenLength = jTokens.length;\n        for (uint256 i = 0; i < jTokenLength; i++) {\n            JToken jToken = jTokens[i];\n            if (compareStrings(jToken.symbol(), \"crETH\")) {\n                continue;\n            }\n            address underlying = JErc20(address(jToken)).underlying();\n            underlyingToJToken[underlying] = address(jToken);\n        }\n    }\n}\n"
    },
    "contracts/JAvax.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JTokenDeprecated.sol\";\n\n/**\n * @title Compound's JAvax Contract\n * @notice JToken which wraps Ether\n * @author Compound\n */\ncontract JAvax is JTokenDeprecated {\n    /**\n     * @notice Construct a new JAvax money market\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ ERC-20 name of this token\n     * @param symbol_ ERC-20 symbol of this token\n     * @param decimals_ ERC-20 decimal precision of this token\n     * @param admin_ Address of the administrator of this token\n     */\n    constructor(\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_,\n        address payable admin_\n    ) public {\n        // Creator of the contract is admin during initialization\n        admin = msg.sender;\n\n        initialize(joetroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);\n\n        // Set the proper admin now that initialization is done\n        admin = admin_;\n    }\n\n    /*** User Interface ***/\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Reverts upon any failure\n     */\n    function mint() external payable {\n        (uint256 err, ) = mintInternal(msg.value);\n        requireNoError(err, \"mint failed\");\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeem(uint256 redeemTokens) external returns (uint256) {\n        return redeemInternal(redeemTokens);\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {\n        return redeemUnderlyingInternal(redeemAmount);\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrow(uint256 borrowAmount) external returns (uint256) {\n        return borrowInternal(borrowAmount);\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @dev Reverts upon any failure\n     */\n    function repayBorrow() external payable {\n        (uint256 err, ) = repayBorrowInternal(msg.value);\n        requireNoError(err, \"repayBorrow failed\");\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @dev Reverts upon any failure\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     */\n    function liquidateBorrow(address borrower, JTokenDeprecated jTokenCollateral) external payable {\n        (uint256 err, ) = liquidateBorrowInternal(borrower, msg.value, jTokenCollateral);\n        requireNoError(err, \"liquidateBorrow failed\");\n    }\n\n    /**\n     * @notice Send Ether to JAvax to mint\n     */\n    function() external payable {\n        (uint256 err, ) = mintInternal(msg.value);\n        requireNoError(err, \"mint failed\");\n    }\n\n    /*** Safe Token ***/\n\n    /**\n     * @notice Gets balance of this contract in terms of Ether, before this message\n     * @dev This excludes the value of the current message, if any\n     * @return The quantity of Ether owned by this contract\n     */\n    function getCashPrior() internal view returns (uint256) {\n        (MathError err, uint256 startingBalance) = subUInt(address(this).balance, msg.value);\n        require(err == MathError.NO_ERROR);\n        return startingBalance;\n    }\n\n    /**\n     * @notice Perform the actual transfer in, which is a no-op\n     * @param from Address sending the Ether\n     * @param amount Amount of Ether being sent\n     * @return The actual amount of Ether transferred\n     */\n    function doTransferIn(address from, uint256 amount) internal returns (uint256) {\n        // Sanity checks\n        require(msg.sender == from, \"sender mismatch\");\n        require(msg.value == amount, \"value mismatch\");\n        return amount;\n    }\n\n    function doTransferOut(address payable to, uint256 amount) internal {\n        /* Send the Ether, with minimal gas and revert on failure */\n        to.transfer(amount);\n    }\n\n    function requireNoError(uint256 errCode, string memory message) internal pure {\n        if (errCode == uint256(Error.NO_ERROR)) {\n            return;\n        }\n\n        bytes memory fullMessage = new bytes(bytes(message).length + 5);\n        uint256 i;\n\n        for (i = 0; i < bytes(message).length; i++) {\n            fullMessage[i] = bytes(message)[i];\n        }\n\n        fullMessage[i + 0] = bytes1(uint8(32));\n        fullMessage[i + 1] = bytes1(uint8(40));\n        fullMessage[i + 2] = bytes1(uint8(48 + (errCode / 10)));\n        fullMessage[i + 3] = bytes1(uint8(48 + (errCode % 10)));\n        fullMessage[i + 4] = bytes1(uint8(41));\n\n        require(errCode == uint256(Error.NO_ERROR), string(fullMessage));\n    }\n}\n"
    },
    "contracts/JCapableErc20.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JToken.sol\";\n\n/**\n * @title Deprecated Cream's JCapableErc20 Contract\n * @notice JTokens which wrap an EIP-20 underlying\n * @author Cream\n */\ncontract JCapableErc20 is JToken, JCapableErc20Interface, JProtocolSeizeShareStorage {\n    /**\n     * @notice Initialize the new money market\n     * @param underlying_ The address of the underlying asset\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ ERC-20 name of this token\n     * @param symbol_ ERC-20 symbol of this token\n     * @param decimals_ ERC-20 decimal precision of this token\n     */\n    function initialize(\n        address underlying_,\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_\n    ) public {\n        // JToken initialize does the bulk of the work\n        super.initialize(joetroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);\n\n        // Set underlying and sanity check it\n        underlying = underlying_;\n        EIP20Interface(underlying).totalSupply();\n    }\n\n    /*** User Interface ***/\n\n    /**\n     * @notice Sender supplies assets into the market and receives jTokens in exchange\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param mintAmount The amount of the underlying asset to supply\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function mint(uint256 mintAmount) external returns (uint256) {\n        (uint256 err, ) = mintInternal(mintAmount, false);\n        return err;\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for the underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemTokens The number of jTokens to redeem into underlying\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeem(uint256 redeemTokens) external returns (uint256) {\n        return redeemInternal(redeemTokens, false);\n    }\n\n    /**\n     * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset\n     * @dev Accrues interest whether or not the operation succeeds, unless reverted\n     * @param redeemAmount The amount of underlying to redeem\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {\n        return redeemUnderlyingInternal(redeemAmount, false);\n    }\n\n    /**\n     * @notice Sender borrows assets from the protocol to their own address\n     * @param borrowAmount The amount of the underlying asset to borrow\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function borrow(uint256 borrowAmount) external returns (uint256) {\n        return borrowInternal(borrowAmount, false);\n    }\n\n    /**\n     * @notice Sender repays their own borrow\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrow(uint256 repayAmount) external returns (uint256) {\n        (uint256 err, ) = repayBorrowInternal(repayAmount, false);\n        return err;\n    }\n\n    /**\n     * @notice Sender repays a borrow belonging to borrower\n     * @param borrower the account with the debt being payed off\n     * @param repayAmount The amount to repay\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) {\n        (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount, false);\n        return err;\n    }\n\n    /**\n     * @notice The sender liquidates the borrowers collateral.\n     *  The collateral seized is transferred to the liquidator.\n     * @param borrower The borrower of this jToken to be liquidated\n     * @param repayAmount The amount of the underlying borrowed asset to repay\n     * @param jTokenCollateral The market in which to seize collateral from the borrower\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function liquidateBorrow(\n        address borrower,\n        uint256 repayAmount,\n        JTokenInterface jTokenCollateral\n    ) external returns (uint256) {\n        (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, jTokenCollateral, false);\n        return err;\n    }\n\n    /**\n     * @notice The sender adds to reserves.\n     * @param addAmount The amount fo underlying token to add as reserves\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function _addReserves(uint256 addAmount) external returns (uint256) {\n        return _addReservesInternal(addAmount, false);\n    }\n\n    /**\n     * @notice Absorb excess cash into reserves.\n     */\n    function gulp() external nonReentrant {\n        uint256 cashOnChain = getCashOnChain();\n        uint256 cashPrior = getCashPrior();\n\n        uint256 excessCash = sub_(cashOnChain, cashPrior);\n        totalReserves = add_(totalReserves, excessCash);\n        internalCash = cashOnChain;\n    }\n\n    /**\n     * @notice Flash loan funds to a given account.\n     * @param receiver The receiver address for the funds\n     * @param amount The amount of the funds to be loaned\n     * @param params The other parameters\n     */\n    function flashLoan(\n        address receiver,\n        uint256 amount,\n        bytes calldata params\n    ) external nonReentrant {\n        require(amount > 0, \"flashLoan amount should be greater than zero\");\n        require(accrueInterest() == uint256(Error.NO_ERROR), \"accrue interest failed\");\n\n        uint256 cashOnChainBefore = getCashOnChain();\n        uint256 cashBefore = getCashPrior();\n        require(cashBefore >= amount, \"INSUFFICIENT_LIQUIDITY\");\n\n        // 1. calculate fee, 1 bips = 1/10000\n        uint256 totalFee = div_(mul_(amount, flashFeeBips), 10000);\n\n        // 2. transfer fund to receiver\n        doTransferOut(address(uint160(receiver)), amount, false);\n\n        // 3. update totalBorrows\n        totalBorrows = add_(totalBorrows, amount);\n\n        // 4. execute receiver's callback function\n        IFlashloanReceiver(receiver).executeOperation(msg.sender, underlying, amount, totalFee, params);\n\n        // 5. check balance\n        uint256 cashOnChainAfter = getCashOnChain();\n        require(cashOnChainAfter == add_(cashOnChainBefore, totalFee), \"BALANCE_INCONSISTENT\");\n\n        // 6. update reserves and internal cash and totalBorrows\n        uint256 reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee);\n        totalReserves = add_(totalReserves, reservesFee);\n        internalCash = add_(cashBefore, totalFee);\n        totalBorrows = sub_(totalBorrows, amount);\n\n        emit Flashloan(receiver, amount, totalFee, reservesFee);\n    }\n\n    /*** Safe Token ***/\n\n    /**\n     * @notice Gets internal balance of this contract in terms of the underlying.\n     *  It excludes balance from direct transfer.\n     * @dev This excludes the value of the current message, if any\n     * @return The quantity of underlying tokens owned by this contract\n     */\n    function getCashPrior() internal view returns (uint256) {\n        return internalCash;\n    }\n\n    /**\n     * @notice Gets total balance of this contract in terms of the underlying\n     * @dev This excludes the value of the current message, if any\n     * @return The quantity of underlying tokens owned by this contract\n     */\n    function getCashOnChain() internal view returns (uint256) {\n        EIP20Interface token = EIP20Interface(underlying);\n        return token.balanceOf(address(this));\n    }\n\n    /**\n     * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.\n     *      This will revert due to insufficient balance or insufficient allowance.\n     *      This function returns the actual amount received,\n     *      which may be less than `amount` if there is a fee attached to the transfer.\n     *\n     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n     */\n    function doTransferIn(\n        address from,\n        uint256 amount,\n        bool isNative\n    ) internal returns (uint256) {\n        isNative; // unused\n\n        EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n        uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this));\n        token.transferFrom(from, address(this), amount);\n\n        bool success;\n        assembly {\n            switch returndatasize()\n            case 0 {\n                // This is a non-standard ERC-20\n                success := not(0) // set success to true\n            }\n            case 32 {\n                // This is a joeliant ERC-20\n                returndatacopy(0, 0, 32)\n                success := mload(0) // Set `success = returndata` of external call\n            }\n            default {\n                // This is an excessively non-joeliant ERC-20, revert.\n                revert(0, 0)\n            }\n        }\n        require(success, \"TOKEN_TRANSFER_IN_FAILED\");\n\n        // Calculate the amount that was *actually* transferred\n        uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this));\n        uint256 transferredIn = sub_(balanceAfter, balanceBefore);\n        internalCash = add_(internalCash, transferredIn);\n        return transferredIn;\n    }\n\n    /**\n     * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory\n     *      error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to\n     *      insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified\n     *      it is >= amount, this should not revert in normal conditions.\n     *\n     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n     */\n    function doTransferOut(\n        address payable to,\n        uint256 amount,\n        bool isNative\n    ) internal {\n        isNative; // unused\n\n        EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n        token.transfer(to, amount);\n\n        bool success;\n        assembly {\n            switch returndatasize()\n            case 0 {\n                // This is a non-standard ERC-20\n                success := not(0) // set success to true\n            }\n            case 32 {\n                // This is a joelaint ERC-20\n                returndatacopy(0, 0, 32)\n                success := mload(0) // Set `success = returndata` of external call\n            }\n            default {\n                // This is an excessively non-joeliant ERC-20, revert.\n                revert(0, 0)\n            }\n        }\n        require(success, \"TOKEN_TRANSFER_OUT_FAILED\");\n        internalCash = sub_(internalCash, amount);\n    }\n\n    /**\n     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n     * @dev Called by both `transfer` and `transferFrom` internally\n     * @param spender The address of the account performing the transfer\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param tokens The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferTokens(\n        address spender,\n        address src,\n        address dst,\n        uint256 tokens\n    ) internal returns (uint256) {\n        /* Fail if transfer not allowed */\n        uint256 allowed = joetroller.transferAllowed(address(this), src, dst, tokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.TRANSFER_JOETROLLER_REJECTION, allowed);\n        }\n\n        /* Do not allow self-transfers */\n        if (src == dst) {\n            return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);\n        }\n\n        /* Get the allowance, infinite for the account owner */\n        uint256 startingAllowance = 0;\n        if (spender == src) {\n            startingAllowance = uint256(-1);\n        } else {\n            startingAllowance = transferAllowances[src][spender];\n        }\n\n        /* Do the calculations, checking for {under,over}flow */\n        accountTokens[src] = sub_(accountTokens[src], tokens);\n        accountTokens[dst] = add_(accountTokens[dst], tokens);\n\n        /* Eat some of the allowance (if necessary) */\n        if (startingAllowance != uint256(-1)) {\n            transferAllowances[src][spender] = sub_(startingAllowance, tokens);\n        }\n\n        /* We emit a Transfer event */\n        emit Transfer(src, dst, tokens);\n\n        // unused function\n        // joetroller.transferVerify(address(this), src, dst, tokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Get the account's jToken balances\n     * @param account The address of the account\n     */\n    function getJTokenBalanceInternal(address account) internal view returns (uint256) {\n        return accountTokens[account];\n    }\n\n    struct MintLocalVars {\n        uint256 exchangeRateMantissa;\n        uint256 mintTokens;\n        uint256 actualMintAmount;\n    }\n\n    /**\n     * @notice User supplies assets into the market and receives jTokens in exchange\n     * @dev Assumes interest has already been accrued up to the current timestamp\n     * @param minter The address of the account which is supplying the assets\n     * @param mintAmount The amount of the underlying asset to supply\n     * @param isNative The amount is in native or not\n     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n     */\n    function mintFresh(\n        address minter,\n        uint256 mintAmount,\n        bool isNative\n    ) internal returns (uint256, uint256) {\n        /* Fail if mint not allowed */\n        uint256 allowed = joetroller.mintAllowed(address(this), minter, mintAmount);\n        if (allowed != 0) {\n            return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.MINT_JOETROLLER_REJECTION, allowed), 0);\n        }\n\n        /*\n         * Return if mintAmount is zero.\n         * Put behind `mintAllowed` for accuring potential JOE rewards.\n         */\n        if (mintAmount == 0) {\n            return (uint256(Error.NO_ERROR), 0);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);\n        }\n\n        MintLocalVars memory vars;\n\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         *  We call `doTransferIn` for the minter and the mintAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  `doTransferIn` reverts if anything goes wrong, since we can't be sure if\n         *  side-effects occurred. The function returns the amount actually transferred,\n         *  in case of a fee. On success, the jToken holds an additional `actualMintAmount`\n         *  of cash.\n         */\n        vars.actualMintAmount = doTransferIn(minter, mintAmount, isNative);\n\n        /*\n         * We get the current exchange rate and calculate the number of jTokens to be minted:\n         *  mintTokens = actualMintAmount / exchangeRate\n         */\n        vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));\n\n        /*\n         * We calculate the new total supply of jTokens and minter token balance, checking for overflow:\n         *  totalSupply = totalSupply + mintTokens\n         *  accountTokens[minter] = accountTokens[minter] + mintTokens\n         */\n        totalSupply = add_(totalSupply, vars.mintTokens);\n        accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens);\n\n        /* We emit a Mint event, and a Transfer event */\n        emit Mint(minter, vars.actualMintAmount, vars.mintTokens);\n        emit Transfer(address(this), minter, vars.mintTokens);\n\n        /* We call the defense hook */\n        // unused function\n        // joetroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);\n\n        return (uint256(Error.NO_ERROR), vars.actualMintAmount);\n    }\n\n    struct RedeemLocalVars {\n        uint256 exchangeRateMantissa;\n        uint256 redeemTokens;\n        uint256 redeemAmount;\n        uint256 totalSupplyNew;\n        uint256 accountTokensNew;\n    }\n\n    /**\n     * @notice User redeems jTokens in exchange for the underlying asset\n     * @dev Assumes interest has already been accrued up to the current timestamp. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero.\n     * @param redeemer The address of the account which is redeeming the tokens\n     * @param redeemTokensIn The number of jTokens to redeem into underlying\n     * @param redeemAmountIn The number of underlying tokens to receive from redeeming jTokens\n     * @param isNative The amount is in native or not\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function redeemFresh(\n        address payable redeemer,\n        uint256 redeemTokensIn,\n        uint256 redeemAmountIn,\n        bool isNative\n    ) internal returns (uint256) {\n        require(redeemTokensIn == 0 || redeemAmountIn == 0, \"one of redeemTokensIn or redeemAmountIn must be zero\");\n\n        RedeemLocalVars memory vars;\n\n        /* exchangeRate = invoke Exchange Rate Stored() */\n        vars.exchangeRateMantissa = exchangeRateStoredInternal();\n\n        /* If redeemTokensIn > 0: */\n        if (redeemTokensIn > 0) {\n            /*\n             * We calculate the exchange rate and the amount of underlying to be redeemed:\n             *  redeemTokens = redeemTokensIn\n             *  redeemAmount = redeemTokensIn x exchangeRateCurrent\n             */\n            vars.redeemTokens = redeemTokensIn;\n            vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);\n        } else {\n            /*\n             * We get the current exchange rate and calculate the amount to be redeemed:\n             *  redeemTokens = redeemAmountIn / exchangeRate\n             *  redeemAmount = redeemAmountIn\n             */\n            vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));\n            vars.redeemAmount = redeemAmountIn;\n        }\n\n        /* Fail if redeem not allowed */\n        uint256 allowed = joetroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REDEEM_JOETROLLER_REJECTION, allowed);\n        }\n\n        /*\n         * Return if redeemTokensIn and redeemAmountIn are zero.\n         * Put behind `redeemAllowed` for accuring potential JOE rewards.\n         */\n        if (redeemTokensIn == 0 && redeemAmountIn == 0) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Verify market's block timestamp equals current block timestamp */\n        if (accrualBlockTimestamp != getBlockTimestamp()) {\n            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);\n        }\n\n        /*\n         * We calculate the new total supply and redeemer balance, checking for underflow:\n         *  totalSupplyNew = totalSupply - redeemTokens\n         *  accountTokensNew = accountTokens[redeemer] - redeemTokens\n         */\n        vars.totalSupplyNew = sub_(totalSupply, vars.redeemTokens);\n        vars.accountTokensNew = sub_(accountTokens[redeemer], vars.redeemTokens);\n\n        /* Fail gracefully if protocol has insufficient cash */\n        if (getCashPrior() < vars.redeemAmount) {\n            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);\n        }\n\n        /////////////////////////\n        // EFFECTS & INTERACTIONS\n        // (No safe failures beyond this point)\n\n        /*\n         * We invoke doTransferOut for the redeemer and the redeemAmount.\n         *  Note: The jToken must handle variations between ERC-20 and ETH underlying.\n         *  On success, the jToken has redeemAmount less of cash.\n         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n         */\n        doTransferOut(redeemer, vars.redeemAmount, isNative);\n\n        /* We write previously calculated values into storage */\n        totalSupply = vars.totalSupplyNew;\n        accountTokens[redeemer] = vars.accountTokensNew;\n\n        /* We emit a Transfer event, and a Redeem event */\n        emit Transfer(redeemer, address(this), vars.redeemTokens);\n        emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        /* We call the defense hook */\n        joetroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n\n    /**\n     * @notice Transfers collateral tokens (this market) to the liquidator.\n     * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another JToken.\n     *  Its absolutely critical to use msg.sender as the seizer jToken and not a parameter.\n     * @param seizerToken The contract seizing the collateral (i.e. borrowed jToken)\n     * @param liquidator The account receiving seized collateral\n     * @param borrower The account having collateral seized\n     * @param seizeTokens The number of jTokens to seize\n     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n     */\n    function seizeInternal(\n        address seizerToken,\n        address liquidator,\n        address borrower,\n        uint256 seizeTokens\n    ) internal returns (uint256) {\n        /* Fail if seize not allowed */\n        uint256 allowed = joetroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);\n        if (allowed != 0) {\n            return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_JOETROLLER_REJECTION, allowed);\n        }\n\n        /*\n         * Return if seizeTokens is zero.\n         * Put behind `seizeAllowed` for accuring potential JOE rewards.\n         */\n        if (seizeTokens == 0) {\n            return uint256(Error.NO_ERROR);\n        }\n\n        /* Fail if borrower = liquidator */\n        if (borrower == liquidator) {\n            return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);\n        }\n\n        uint256 protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}));\n        uint256 liquidatorSeizeTokens = sub_(seizeTokens, protocolSeizeTokens);\n\n        uint256 exchangeRateMantissa = exchangeRateStoredInternal();\n        uint256 protocolSeizeAmount = mul_ScalarTruncate(Exp({mantissa: exchangeRateMantissa}), protocolSeizeTokens);\n\n        /*\n         * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:\n         *  borrowerTokensNew = accountTokens[borrower] - seizeTokens\n         *  liquidatorTokensNew = accountTokens[liquidator] + seizeTokens\n         */\n        accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens);\n        accountTokens[liquidator] = add_(accountTokens[liquidator], liquidatorSeizeTokens);\n        totalReserves = add_(totalReserves, protocolSeizeAmount);\n        totalSupply = sub_(totalSupply, protocolSeizeTokens);\n\n        /* Emit a Transfer event */\n        emit Transfer(borrower, liquidator, seizeTokens);\n        emit ReservesAdded(address(this), protocolSeizeAmount, totalReserves);\n\n        /* We call the defense hook */\n        // unused function\n        // joetroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);\n\n        return uint256(Error.NO_ERROR);\n    }\n}\n"
    },
    "contracts/JCapableErc20Delegate.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JCapableErc20.sol\";\n\n/**\n * @title Joeound's JCapableErc20Delegate Contract\n * @notice JTokens which wrap an EIP-20 underlying and are delegated to\n * @author Joeound\n */\ncontract JCapableErc20Delegate is JCapableErc20 {\n    /**\n     * @notice Construct an empty delegate\n     */\n    constructor() public {}\n\n    /**\n     * @notice Called by the delegator on a delegate to initialize it for duty\n     * @param data The encoded bytes data for any initialization\n     */\n    function _becomeImplementation(bytes memory data) public {\n        // Shh -- currently unused\n        data;\n\n        // Shh -- we don't ever want this hook to be marked pure\n        if (false) {\n            implementation = address(0);\n        }\n\n        require(msg.sender == admin, \"only the admin may call _becomeImplementation\");\n\n        // Set internal cash when becoming implementation\n        internalCash = getCashOnChain();\n    }\n\n    /**\n     * @notice Called by the delegator on a delegate to forfeit its responsibility\n     */\n    function _resignImplementation() public {\n        // Shh -- we don't ever want this hook to be marked pure\n        if (false) {\n            implementation = address(0);\n        }\n\n        require(msg.sender == admin, \"only the admin may call _resignImplementation\");\n    }\n}\n"
    },
    "contracts/JJTokenDelegate.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JCapableErc20Delegate.sol\";\nimport \"./EIP20Interface.sol\";\n\n/**\n * @notice Compound's Joetroller interface to get Joe address\n */\ninterface IJoetroller {\n    function getJoeAddress() external view returns (address);\n\n    function claimJoe(\n        address[] calldata holders,\n        JToken[] calldata jTokens,\n        bool borrowers,\n        bool suppliers\n    ) external;\n}\n\n/**\n * @title Cream's JJToken's Contract\n * @notice JToken which wraps Compound's Ctoken\n * @author Cream\n */\ncontract JJTokenDelegate is JCapableErc20Delegate {\n    /**\n     * @notice The joetroller of Compound's JToken\n     */\n    address public underlyingJoetroller;\n\n    /**\n     * @notice Joe token address\n     */\n    address public joe;\n\n    /**\n     * @notice Container for joe rewards state\n     * @member balance The balance of joe\n     * @member index The last updated index\n     */\n    struct RewardState {\n        uint256 balance;\n        uint256 index;\n    }\n\n    /**\n     * @notice The state of Compound's JToken supply\n     */\n    RewardState public supplyState;\n\n    /**\n     * @notice The index of every Compound's JToken supplier\n     */\n    mapping(address => uint256) public supplierState;\n\n    /**\n     * @notice The joe amount of every user\n     */\n    mapping(address => uint256) public joeUserAccrued;\n\n    /**\n     * @notice Delegate interface to become the implementation\n     * @param data The encoded arguments for becoming\n     */\n    function _becomeImplementation(bytes memory data) public {\n        super._becomeImplementation(data);\n\n        underlyingJoetroller = address(JToken(underlying).joetroller());\n        joe = IJoetroller(underlyingJoetroller).getJoeAddress();\n    }\n\n    /**\n     * @notice Manually claim joe rewards by user\n     * @return The amount of joe rewards user claims\n     */\n    function claimJoe(address account) public returns (uint256) {\n        harvestJoe();\n\n        updateSupplyIndex();\n        updateSupplierIndex(account);\n\n        uint256 joeBalance = joeUserAccrued[account];\n        if (joeBalance > 0) {\n            // Transfer user joe and subtract the balance in supplyState\n            EIP20Interface(joe).transfer(account, joeBalance);\n            supplyState.balance = sub_(supplyState.balance, joeBalance);\n\n            // Clear user's joe accrued.\n            joeUserAccrued[account] = 0;\n\n            return joeBalance;\n        }\n        return 0;\n    }\n\n    /*** JToken Overrides ***/\n\n    /**\n     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n     * @param spender The address of the account performing the transfer\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param tokens The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferTokens(\n        address spender,\n        address src,\n        address dst,\n        uint256 tokens\n    ) internal returns (uint256) {\n        harvestJoe();\n\n        updateSupplyIndex();\n        updateSupplierIndex(src);\n        updateSupplierIndex(dst);\n\n        return super.transferTokens(spender, src, dst, tokens);\n    }\n\n    /*** Safe Token ***/\n\n    /**\n     * @notice Transfer the underlying to this contract\n     * @param from Address to transfer funds from\n     * @param amount Amount of underlying to transfer\n     * @param isNative The amount is in native or not\n     * @return The actual amount that is transferred\n     */\n    function doTransferIn(\n        address from,\n        uint256 amount,\n        bool isNative\n    ) internal returns (uint256) {\n        uint256 transferredIn = super.doTransferIn(from, amount, isNative);\n\n        harvestJoe();\n        updateSupplyIndex();\n        updateSupplierIndex(from);\n\n        return transferredIn;\n    }\n\n    /**\n     * @notice Transfer the underlying from this contract\n     * @param to Address to transfer funds to\n     * @param amount Amount of underlying to transfer\n     * @param isNative The amount is in native or not\n     */\n    function doTransferOut(\n        address payable to,\n        uint256 amount,\n        bool isNative\n    ) internal {\n        harvestJoe();\n        updateSupplyIndex();\n        updateSupplierIndex(to);\n\n        super.doTransferOut(to, amount, isNative);\n    }\n\n    /*** Internal functions ***/\n\n    function harvestJoe() internal {\n        address[] memory holders = new address[](1);\n        holders[0] = address(this);\n        JToken[] memory jTokens = new JToken[](1);\n        jTokens[0] = JToken(underlying);\n\n        // JJToken contract will never borrow assets from Compound.\n        IJoetroller(underlyingJoetroller).claimJoe(holders, jTokens, false, true);\n    }\n\n    function updateSupplyIndex() internal {\n        uint256 joeAccrued = sub_(joeBalance(), supplyState.balance);\n        uint256 supplyTokens = JToken(address(this)).totalSupply();\n        Double memory ratio = supplyTokens > 0 ? fraction(joeAccrued, supplyTokens) : Double({mantissa: 0});\n        Double memory index = add_(Double({mantissa: supplyState.index}), ratio);\n\n        // Update supplyState.\n        supplyState.index = index.mantissa;\n        supplyState.balance = joeBalance();\n    }\n\n    function updateSupplierIndex(address supplier) internal {\n        Double memory supplyIndex = Double({mantissa: supplyState.index});\n        Double memory supplierIndex = Double({mantissa: supplierState[supplier]});\n        Double memory deltaIndex = sub_(supplyIndex, supplierIndex);\n        if (deltaIndex.mantissa > 0) {\n            uint256 supplierTokens = JToken(address(this)).balanceOf(supplier);\n            uint256 supplierDelta = mul_(supplierTokens, deltaIndex);\n            joeUserAccrued[supplier] = add_(joeUserAccrued[supplier], supplierDelta);\n            supplierState[supplier] = supplyIndex.mantissa;\n        }\n    }\n\n    function joeBalance() internal view returns (uint256) {\n        return EIP20Interface(joe).balanceOf(address(this));\n    }\n}\n"
    },
    "contracts/JJLPDelegate.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\npragma experimental ABIEncoderV2;\n\nimport \"./JCapableErc20Delegate.sol\";\nimport \"./EIP20Interface.sol\";\n\n// Ref: https://etherscan.io/address/0xc2edad668740f1aa35e4d8f227fb8e17dca888cd#code\ninterface IMasterChef {\n    struct PoolInfo {\n        address lpToken;\n    }\n\n    struct UserInfo {\n        uint256 amount;\n    }\n\n    function deposit(uint256, uint256) external;\n\n    function withdraw(uint256, uint256) external;\n\n    function joe() external view returns (address);\n\n    function poolInfo(uint256) external view returns (PoolInfo memory);\n\n    function userInfo(uint256, address) external view returns (UserInfo memory);\n\n    function pendingJoe(uint256, address) external view returns (uint256);\n}\n\n// Ref: https://etherscan.io/address/0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272#code\ninterface IJoeBar {\n    function enter(uint256 _amount) external;\n\n    function leave(uint256 _share) external;\n}\n\n/**\n * @title Cream's JJoeLP's Contract\n * @notice JToken which wraps Joe's LP token\n * @author Cream\n */\ncontract JJLPDelegate is JCapableErc20Delegate {\n    /**\n     * @notice MasterChef address\n     */\n    address public masterChef;\n\n    /**\n     * @notice JoeBar address\n     */\n    address public joeBar;\n\n    /**\n     * @notice Joe token address\n     */\n    address public joe;\n\n    /**\n     * @notice Pool ID of this LP in MasterChef\n     */\n    uint256 public pid;\n\n    /**\n     * @notice Container for joe rewards state\n     * @member balance The balance of xJoe\n     * @member index The last updated index\n     */\n    struct JoeRewardState {\n        uint256 balance;\n        uint256 index;\n    }\n\n    /**\n     * @notice The state of JLP supply\n     */\n    JoeRewardState public jlpSupplyState;\n\n    /**\n     * @notice The index of every JLP supplier\n     */\n    mapping(address => uint256) public jlpSupplierIndex;\n\n    /**\n     * @notice The xJoe amount of every user\n     */\n    mapping(address => uint256) public xJoeUserAccrued;\n\n    /**\n     * @notice Delegate interface to become the implementation\n     * @param data The encoded arguments for becoming\n     */\n    function _becomeImplementation(bytes memory data) public {\n        super._becomeImplementation(data);\n\n        (address masterChefAddress_, address joeBarAddress_, uint256 pid_) = abi.decode(\n            data,\n            (address, address, uint256)\n        );\n        masterChef = masterChefAddress_;\n        joeBar = joeBarAddress_;\n        joe = IMasterChef(masterChef).joe();\n\n        IMasterChef.PoolInfo memory poolInfo = IMasterChef(masterChef).poolInfo(pid_);\n        require(poolInfo.lpToken == underlying, \"mismatch underlying token\");\n        pid = pid_;\n\n        // Approve moving our JLP into the master chef contract.\n        EIP20Interface(underlying).approve(masterChefAddress_, uint256(-1));\n\n        // Approve moving joe rewards into the joe bar contract.\n        EIP20Interface(joe).approve(joeBarAddress_, uint256(-1));\n    }\n\n    /**\n     * @notice Manually claim joe rewards by user\n     * @return The amount of joe rewards user claims\n     */\n    function claimJoe(address account) public returns (uint256) {\n        claimAndStakeJoe();\n\n        updateJLPSupplyIndex();\n        updateSupplierIndex(account);\n\n        // Get user's xJoe accrued.\n        uint256 xJoeBalance = xJoeUserAccrued[account];\n        if (xJoeBalance > 0) {\n            // Withdraw user xJoe balance and subtract the amount in jlpSupplyState\n            IJoeBar(joeBar).leave(xJoeBalance);\n            jlpSupplyState.balance = sub_(jlpSupplyState.balance, xJoeBalance);\n\n            uint256 balance = joeBalance();\n            EIP20Interface(joe).transfer(account, balance);\n\n            // Clear user's xJoe accrued.\n            xJoeUserAccrued[account] = 0;\n\n            return balance;\n        }\n        return 0;\n    }\n\n    /*** JToken Overrides ***/\n\n    /**\n     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n     * @param spender The address of the account performing the transfer\n     * @param src The address of the source account\n     * @param dst The address of the destination account\n     * @param tokens The number of tokens to transfer\n     * @return Whether or not the transfer succeeded\n     */\n    function transferTokens(\n        address spender,\n        address src,\n        address dst,\n        uint256 tokens\n    ) internal returns (uint256) {\n        claimAndStakeJoe();\n\n        updateJLPSupplyIndex();\n        updateSupplierIndex(src);\n        updateSupplierIndex(dst);\n\n        return super.transferTokens(spender, src, dst, tokens);\n    }\n\n    /*** Safe Token ***/\n\n    /**\n     * @notice Gets balance of this contract in terms of the underlying\n     * @return The quantity of underlying tokens owned by this contract\n     */\n    function getCashPrior() internal view returns (uint256) {\n        IMasterChef.UserInfo memory userInfo = IMasterChef(masterChef).userInfo(pid, address(this));\n        return userInfo.amount;\n    }\n\n    /**\n     * @notice Transfer the underlying to this contract and sweep into master chef\n     * @param from Address to transfer funds from\n     * @param amount Amount of underlying to transfer\n     * @param isNative The amount is in native or not\n     * @return The actual amount that is transferred\n     */\n    function doTransferIn(\n        address from,\n        uint256 amount,\n        bool isNative\n    ) internal returns (uint256) {\n        isNative; // unused\n\n        // Perform the EIP-20 transfer in\n        EIP20Interface token = EIP20Interface(underlying);\n        require(token.transferFrom(from, address(this), amount), \"unexpected EIP-20 transfer in return\");\n\n        // Deposit to masterChef.\n        IMasterChef(masterChef).deposit(pid, amount);\n\n        if (joeBalance() > 0) {\n            // Send joe rewards to JoeBar.\n            IJoeBar(joeBar).enter(joeBalance());\n        }\n\n        updateJLPSupplyIndex();\n        updateSupplierIndex(from);\n\n        return amount;\n    }\n\n    /**\n     * @notice Transfer the underlying from this contract, after sweeping out of master chef\n     * @param to Address to transfer funds to\n     * @param amount Amount of underlying to transfer\n     * @param isNative The amount is in native or not\n     */\n    function doTransferOut(\n        address payable to,\n        uint256 amount,\n        bool isNative\n    ) internal {\n        isNative; // unused\n\n        // Withdraw the underlying tokens from masterChef.\n        IMasterChef(masterChef).withdraw(pid, amount);\n\n        if (joeBalance() > 0) {\n            // Send joe rewards to JoeBar.\n            IJoeBar(joeBar).enter(joeBalance());\n        }\n\n        updateJLPSupplyIndex();\n        updateSupplierIndex(to);\n\n        EIP20Interface token = EIP20Interface(underlying);\n        require(token.transfer(to, amount), \"unexpected EIP-20 transfer out return\");\n    }\n\n    /*** Internal functions ***/\n\n    function claimAndStakeJoe() internal {\n        // Deposit 0 JLP into MasterChef to claim joe rewards.\n        IMasterChef(masterChef).deposit(pid, 0);\n\n        if (joeBalance() > 0) {\n            // Send joe rewards to JoeBar.\n            IJoeBar(joeBar).enter(joeBalance());\n        }\n    }\n\n    function updateJLPSupplyIndex() internal {\n        uint256 xJoeBalance = xJoeBalance();\n        uint256 xJoeAccrued = sub_(xJoeBalance, jlpSupplyState.balance);\n        uint256 supplyTokens = JToken(address(this)).totalSupply();\n        Double memory ratio = supplyTokens > 0 ? fraction(xJoeAccrued, supplyTokens) : Double({mantissa: 0});\n        Double memory index = add_(Double({mantissa: jlpSupplyState.index}), ratio);\n\n        // Update jlpSupplyState.\n        jlpSupplyState.index = index.mantissa;\n        jlpSupplyState.balance = xJoeBalance;\n    }\n\n    function updateSupplierIndex(address supplier) internal {\n        Double memory supplyIndex = Double({mantissa: jlpSupplyState.index});\n        Double memory supplierIndex = Double({mantissa: jlpSupplierIndex[supplier]});\n        Double memory deltaIndex = sub_(supplyIndex, supplierIndex);\n        if (deltaIndex.mantissa > 0) {\n            uint256 supplierTokens = JToken(address(this)).balanceOf(supplier);\n            uint256 supplierDelta = mul_(supplierTokens, deltaIndex);\n            xJoeUserAccrued[supplier] = add_(xJoeUserAccrued[supplier], supplierDelta);\n            jlpSupplierIndex[supplier] = supplyIndex.mantissa;\n        }\n    }\n\n    function joeBalance() internal view returns (uint256) {\n        return EIP20Interface(joe).balanceOf(address(this));\n    }\n\n    function xJoeBalance() internal view returns (uint256) {\n        return EIP20Interface(joeBar).balanceOf(address(this));\n    }\n}\n"
    },
    "contracts/JErc20Immutable.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JErc20.sol\";\n\n/**\n * @title Joeound's JErc20Immutable Contract\n * @notice JTokens which wrap an EIP-20 underlying and are immutable\n * @author Joeound\n */\ncontract JErc20Immutable is JErc20 {\n    /**\n     * @notice Construct a new money market\n     * @param underlying_ The address of the underlying asset\n     * @param joetroller_ The address of the Joetroller\n     * @param interestRateModel_ The address of the interest rate model\n     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n     * @param name_ ERC-20 name of this token\n     * @param symbol_ ERC-20 symbol of this token\n     * @param decimals_ ERC-20 decimal precision of this token\n     * @param admin_ Address of the administrator of this token\n     */\n    constructor(\n        address underlying_,\n        JoetrollerInterface joetroller_,\n        InterestRateModel interestRateModel_,\n        uint256 initialExchangeRateMantissa_,\n        string memory name_,\n        string memory symbol_,\n        uint8 decimals_,\n        address payable admin_\n    ) public {\n        // Creator of the contract is admin during initialization\n        admin = msg.sender;\n\n        // Initialize the market\n        initialize(\n            underlying_,\n            joetroller_,\n            interestRateModel_,\n            initialExchangeRateMantissa_,\n            name_,\n            symbol_,\n            decimals_\n        );\n\n        // Set the proper admin now that initialization is done\n        admin = admin_;\n    }\n}\n"
    },
    "contracts/JErc20Delegate.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.5.16;\n\nimport \"./JErc20.sol\";\n\n/**\n * @title Compound's JErc20Delegate Contract\n * @notice JTokens which wrap an EIP-20 underlying and are delegated to\n * @author Compound\n */\ncontract JErc20Delegate is JErc20, JDelegateInterface {\n    /**\n     * @notice Construct an empty delegate\n     */\n    constructor() public {}\n\n    /**\n     * @notice Called by the delegator on a delegate to initialize it for duty\n     * @param data The encoded bytes data for any initialization\n     */\n    function _becomeImplementation(bytes memory data) public {\n        // Shh -- currently unused\n        data;\n\n        // Shh -- we don't ever want this hook to be marked pure\n        if (false) {\n            implementation = address(0);\n        }\n\n        require(msg.sender == admin, \"only the admin may call _becomeImplementation\");\n    }\n\n    /**\n     * @notice Called by the delegator on a delegate to forfeit its responsibility\n     */\n    function _resignImplementation() public {\n        // Shh -- we don't ever want this hook to be marked pure\n        if (false) {\n            implementation = address(0);\n        }\n\n        require(msg.sender == admin, \"only the admin may call _resignImplementation\");\n    }\n}\n"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "outputSelection": {
      "*": {
        "*": [
          "abi",
          "evm.bytecode",
          "evm.deployedBytecode",
          "evm.methodIdentifiers",
          "metadata",
          "devdoc",
          "userdoc",
          "storageLayout",
          "evm.gasEstimates"
        ],
        "": [
          "ast"
        ]
      }
    },
    "metadata": {
      "useLiteralContent": true
    },
    "libraries": {
      "": {
        "__CACHE_BREAKER__": "0x00000000d41867734bbee4c6863d9255b2b06ac1"
      }
    }
  }
}