Contract 0xC11c339a1B24b3a10f81a309A1d271DE141908dA

 
 
Txn Hash Method
Block
From
To
Value [Txn Fee]
0x84e2513472ea45126c76784a278eb28d72135937779241028bc6dd321303a7ff_become78245042021-05-29 7:08:57112 days 9 hrs ago0x17d04113a3651e79e7d40a40e47aae23046f7761 IN  0xc11c339a1b24b3a10f81a309a1d271de141908da0 BNB0.000215125
0x3868f1cbbdf9926143fd7b4abe36a11f3f6501d1fccb2d13d0f5834a5fd0f4a80x6080604078243622021-05-29 7:01:51112 days 9 hrs ago0x17d04113a3651e79e7d40a40e47aae23046f7761 IN  Contract Creation0 BNB0.01970627
[ Download CSV Export 
Parent Txn Hash Block From To Value
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
Controller

Compiler Version
v0.5.16+commit.9c3226ce

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 15 : Controller.sol
pragma solidity ^0.5.16;

import "./KToken.sol";
import "./KMCD.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./KineControllerInterface.sol";
import "./ControllerStorage.sol";
import "./Unitroller.sol";
import "./KineOracleInterface.sol";
import "./KineSafeMath.sol";
import "./Math.sol";

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol
* Modified to work in the Kine system.
* Main modifications:
*   1. removed Comp token related logics.
*   2. removed interest rate model related logics.
*   3. simplified calculations in mint, redeem, liquidity check, seize due to we don't use interest model/exchange rate.
*   4. user can only supply kTokens (see KToken) and borrow Kine MCDs (see KMCD). Kine MCD's underlying can be considered as itself.
*   5. removed error code propagation mechanism, using revert to fail fast and loudly.
*/

/**
 * @title Kine's Controller Contract
 * @author Kine
 */
contract Controller is ControllerStorage, KineControllerInterface, Exponential, ControllerErrorReporter {
    /// @notice Emitted when an admin supports a market
    event MarketListed(KToken kToken);

    /// @notice Emitted when an account enters a market
    event MarketEntered(KToken kToken, address account);

    /// @notice Emitted when an account exits a market
    event MarketExited(KToken kToken, address account);

    /// @notice Emitted when close factor is changed by admin
    event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);

    /// @notice Emitted when a collateral factor is changed by admin
    event NewCollateralFactor(KToken kToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);

    /// @notice Emitted when liquidation incentive is changed by admin
    event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);

    /// @notice Emitted when redemption params is changed by admin
    event NewRedemptionInitialPunishment(uint oldRedemptionInitialPunishmentMantissa, uint newRedemptionInitialPunishmentMantissa);

    /// @notice Emitted when price oracle is changed
    event NewPriceOracle(KineOracleInterface oldPriceOracle, KineOracleInterface newPriceOracle);

    /// @notice Emitted when pause guardian is changed
    event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);

    /// @notice Emitted when an action is paused globally
    event ActionPaused(string action, bool pauseState);

    /// @notice Emitted when an action is paused on a market
    event ActionPaused(KToken kToken, string action, bool pauseState);

    /// @notice Emitted when borrow cap for a kToken is changed
    event NewBorrowCap(KToken indexed kToken, uint newBorrowCap);

    /// @notice Emitted when supply cap for a kToken is changed
    event NewSupplyCap(KToken indexed kToken, uint newSupplyCap);

    /// @notice Emitted when borrow/supply cap guardian is changed
    event NewCapGuardian(address oldCapGuardian, address newCapGuardian);

    // closeFactorMantissa must be strictly greater than this value
    uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05

    // closeFactorMantissa must not exceed this value
    uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9

    // liquidationIncentiveMantissa must be no less than this value
    uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0

    // liquidationIncentiveMantissa must be no greater than this value
    uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5

    // No collateralFactorMantissa may exceed this value
    uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9

    constructor() public {
        admin = msg.sender;
    }

    modifier onlyAdmin() {
        require(msg.sender == admin, "only admin can call this function");
        _;
    }

    /*** Assets You Are In ***/

    /**
     * @notice Returns the assets an account has entered
     * @param account The address of the account to pull assets for
     * @return A dynamic list with the assets the account has entered
     */
    function getAssetsIn(address account) external view returns (KToken[] memory) {
        KToken[] memory assetsIn = accountAssets[account];

        return assetsIn;
    }

    /**
     * @notice Returns whether the given account is entered in the given asset
     * @param account The address of the account to check
     * @param kToken The kToken to check
     * @return True if the account is in the asset, otherwise false.
     */
    function checkMembership(address account, KToken kToken) external view returns (bool) {
        return markets[address(kToken)].accountMembership[account];
    }

    /**
     * @notice Add assets to be included in account liquidity calculation
     * @param kTokens The list of addresses of the kToken markets to be enabled
     * @dev will revert if any market entering failed
     */
    function enterMarkets(address[] memory kTokens) public {
        uint len = kTokens.length;
        for (uint i = 0; i < len; i++) {
            KToken kToken = KToken(kTokens[i]);
            addToMarketInternal(kToken, msg.sender);
        }
    }

    /**
     * @notice Add the market to the borrower's "assets in" for liquidity calculations
     * @param kToken The market to enter
     * @param borrower The address of the account to modify
     */
    function addToMarketInternal(KToken kToken, address borrower) internal {
        Market storage marketToJoin = markets[address(kToken)];

        require(marketToJoin.isListed, MARKET_NOT_LISTED);

        if (marketToJoin.accountMembership[borrower] == true) {
            // already joined
            return;
        }

        // survived the gauntlet, add to list
        // NOTE: we store these somewhat redundantly as a significant optimization
        //  this avoids having to iterate through the list for the most common use cases
        //  that is, only when we need to perform liquidity checks
        //  and not whenever we want to check if an account is in a particular market
        marketToJoin.accountMembership[borrower] = true;
        accountAssets[borrower].push(kToken);

        emit MarketEntered(kToken, borrower);
    }

    /**
     * @notice Removes asset from sender's account liquidity calculation
     * @dev Sender must not have an outstanding borrow balance in the asset,
     *  or be providing necessary collateral for an outstanding borrow.
     * @param kTokenAddress The address of the asset to be removed
     */
    function exitMarket(address kTokenAddress) external {
        KToken kToken = KToken(kTokenAddress);
        /* Get sender tokensHeld and amountOwed underlying from the kToken */
        (uint tokensHeld, uint amountOwed) = kToken.getAccountSnapshot(msg.sender);

        /* Fail if the sender has a borrow balance */
        require(amountOwed == 0, EXIT_MARKET_BALANCE_OWED);

        /* Fail if the sender is not permitted to redeem all of their tokens */
        (bool allowed,) = redeemAllowedInternal(kTokenAddress, msg.sender, tokensHeld);
        require(allowed, EXIT_MARKET_REJECTION);

        Market storage marketToExit = markets[address(kToken)];

        /* Succeed true if the sender is not already ‘in’ the market */
        if (!marketToExit.accountMembership[msg.sender]) {
            return;
        }

        /* Set kToken account membership to false */
        delete marketToExit.accountMembership[msg.sender];

        /* Delete kToken from the account’s list of assets */
        // load into memory for faster iteration
        KToken[] memory userAssetList = accountAssets[msg.sender];
        uint len = userAssetList.length;
        uint assetIndex = len;
        for (uint i = 0; i < len; i++) {
            if (userAssetList[i] == kToken) {
                assetIndex = i;
                break;
            }
        }

        // We *must* have found the asset in the list or our redundant data structure is broken
        require(assetIndex < len, "accountAssets array broken");

        // copy last item in list to location of item to be removed, reduce length by 1
        KToken[] storage storedList = accountAssets[msg.sender];
        if (assetIndex != storedList.length - 1) {
            storedList[assetIndex] = storedList[storedList.length - 1];
        }
        storedList.length--;

        emit MarketExited(kToken, msg.sender);
    }

    /*** Policy Hooks ***/

    /**
     * @notice Checks if the account should be allowed to mint tokens in the given market
     * @param kToken The market to verify the mint against
     * @param minter The account which would get the minted tokens
     * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
     * @return false and reason if mint not allowed, otherwise return true and empty string
     */
    function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool allowed, string memory reason) {
        if (mintGuardianPaused[kToken]) {
            allowed = false;
            reason = MINT_PAUSED;
            return (allowed, reason);
        }

        uint supplyCap = supplyCaps[kToken];
        // Supply cap of 0 corresponds to unlimited supplying
        if (supplyCap != 0) {
            uint totalSupply = KToken(kToken).totalSupply();
            uint nextTotalSupply = totalSupply.add(mintAmount);
            if (nextTotalSupply > supplyCap) {
                allowed = false;
                reason = MARKET_SUPPLY_CAP_REACHED;
                return (allowed, reason);
            }
        }

        // Shh - currently unused
        minter;

        if (!markets[kToken].isListed) {
            allowed = false;
            reason = MARKET_NOT_LISTED;
            return (allowed, reason);
        }

        allowed = true;
        return (allowed, reason);
    }

    /**
     * @notice Validates mint and reverts on rejection. May emit logs.
     * @param kToken Asset being minted
     * @param minter The address minting the tokens
     * @param actualMintAmount The amount of the underlying asset being minted
     * @param mintTokens The number of tokens being minted
     */
    function mintVerify(address kToken, address minter, uint actualMintAmount, uint mintTokens) external {
        // Shh - currently unused
        kToken;
        minter;
        actualMintAmount;
        mintTokens;

        // Shh - we don't ever want this hook to be marked pure
        if (false) {
            maxAssets = maxAssets;
        }
    }

    /**
     * @notice Checks if the account should be allowed to redeem tokens in the given market
     * @param kToken The market to verify the redeem against
     * @param redeemer The account which would redeem the tokens
     * @param redeemTokens The number of kTokens to exchange for the underlying asset in the market
     * @return false and reason if redeem not allowed, otherwise return true and empty string
     */
    function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool allowed, string memory reason) {
        return redeemAllowedInternal(kToken, redeemer, redeemTokens);
    }

    /**
     * @param kToken The market to verify the redeem against
     * @param redeemer The account which would redeem the tokens
     * @param redeemTokens The number of kTokens to exchange for the underlying asset in the market
     * @return false and reason if redeem not allowed, otherwise return true and empty string
     */
    function redeemAllowedInternal(address kToken, address redeemer, uint redeemTokens) internal view returns (bool allowed, string memory reason) {
        if (!markets[kToken].isListed) {
            allowed = false;
            reason = MARKET_NOT_LISTED;
            return (allowed, reason);
        }

        /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
        if (!markets[kToken].accountMembership[redeemer]) {
            allowed = true;
            return (allowed, reason);
        }

        /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
        (, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(redeemer, KToken(kToken), redeemTokens, 0);
        if (shortfall > 0) {
            allowed = false;
            reason = INSUFFICIENT_LIQUIDITY;
            return (allowed, reason);
        }

        allowed = true;
        return (allowed, reason);
    }

    /**
     * @notice Validates redeem and reverts on rejection. May emit logs.
     * @param kToken Asset being redeemed
     * @param redeemer The address redeeming the tokens
     * @param redeemTokens The number of tokens being redeemed
     */
    function redeemVerify(address kToken, address redeemer, uint redeemTokens) external {
        // Shh - currently unused
        kToken;
        redeemer;

        require(redeemTokens != 0, REDEEM_TOKENS_ZERO);
    }

    /**
     * @notice Checks if the account should be allowed to borrow the underlying asset of the given market
     * @param kToken The market to verify the borrow against
     * @param borrower The account which would borrow the asset
     * @param borrowAmount The amount of underlying the account would borrow
     * @return false and reason if borrow not allowed, otherwise return true and empty string
     */
    function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool allowed, string memory reason) {
        if (borrowGuardianPaused[kToken]) {
            allowed = false;
            reason = BORROW_PAUSED;
            return (allowed, reason);
        }

        if (!markets[kToken].isListed) {
            allowed = false;
            reason = MARKET_NOT_LISTED;
            return (allowed, reason);
        }

        if (!markets[kToken].accountMembership[borrower]) {
            // only kTokens may call borrowAllowed if borrower not in market
            require(msg.sender == kToken, "sender must be kToken");

            // attempt to add borrower to the market
            addToMarketInternal(KToken(msg.sender), borrower);

            // it should be impossible to break the important invariant
            assert(markets[kToken].accountMembership[borrower]);
        }

        require(oracle.getUnderlyingPrice(kToken) != 0, "price error");

        uint borrowCap = borrowCaps[kToken];
        // Borrow cap of 0 corresponds to unlimited borrowing
        if (borrowCap != 0) {
            uint totalBorrows = KMCD(kToken).totalBorrows();
            uint nextTotalBorrows = totalBorrows.add(borrowAmount);
            if (nextTotalBorrows > borrowCap) {
                allowed = false;
                reason = MARKET_BORROW_CAP_REACHED;
                return (allowed, reason);
            }
        }

        (, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(borrower, KToken(kToken), 0, borrowAmount);
        if (shortfall > 0) {
            allowed = false;
            reason = INSUFFICIENT_LIQUIDITY;
            return (allowed, reason);
        }

        allowed = true;
        return (allowed, reason);
    }

    /**
     * @notice Validates borrow and reverts on rejection. May emit logs.
     * @param kToken Asset whose underlying is being borrowed
     * @param borrower The address borrowing the underlying
     * @param borrowAmount The amount of the underlying asset requested to borrow
     */
    function borrowVerify(address kToken, address borrower, uint borrowAmount) external {
        // Shh - currently unused
        kToken;
        borrower;
        borrowAmount;

        // Shh - we don't ever want this hook to be marked pure
        if (false) {
            maxAssets = maxAssets;
        }
    }

    /**
     * @notice Checks if the account should be allowed to repay a borrow in the given market
     * @param kToken The market to verify the repay against
     * @param payer The account which would repay the asset
     * @param borrower The account which would borrowed the asset
     * @param repayAmount The amount of the underlying asset the account would repay
     * @return false and reason if repay borrow not allowed, otherwise return true and empty string
     */
    function repayBorrowAllowed(
        address kToken,
        address payer,
        address borrower,
        uint repayAmount) external returns (bool allowed, string memory reason) {
        // Shh - currently unused
        payer;
        borrower;
        repayAmount;

        if (!markets[kToken].isListed) {
            allowed = false;
            reason = MARKET_NOT_LISTED;
        }

        allowed = true;
        return (allowed, reason);
    }

    /**
     * @notice Validates repayBorrow and reverts on rejection. May emit logs.
     * @param kToken Asset being repaid
     * @param payer The address repaying the borrow
     * @param borrower The address of the borrower
     * @param actualRepayAmount The amount of underlying being repaid
     */
    function repayBorrowVerify(
        address kToken,
        address payer,
        address borrower,
        uint actualRepayAmount) external {
        // Shh - currently unused
        kToken;
        payer;
        borrower;
        actualRepayAmount;

        // Shh - we don't ever want this hook to be marked pure
        if (false) {
            maxAssets = maxAssets;
        }
    }

    /**
     * @notice Checks if the liquidation should be allowed to occur
     * @param kTokenBorrowed Asset which was borrowed by the borrower
     * @param kTokenCollateral Asset which was used as collateral and will be seized
     * @param liquidator The address repaying the borrow and seizing the collateral
     * @param borrower The address of the borrower
     * @param repayAmount The amount of underlying being repaid
     * @return false and reason if liquidate borrow not allowed, otherwise return true and empty string
     */
    function liquidateBorrowAllowed(
        address kTokenBorrowed,
        address kTokenCollateral,
        address liquidator,
        address borrower,
        uint repayAmount) external returns (bool allowed, string memory reason) {
        // Shh - currently unused
        liquidator;

        if (!markets[kTokenBorrowed].isListed || !markets[kTokenCollateral].isListed) {
            allowed = false;
            reason = MARKET_NOT_LISTED;
            return (allowed, reason);
        }

        if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) {
            allowed = false;
            reason = CONTROLLER_MISMATCH;
            return (allowed, reason);
        }

        /* The liquidator may not repay more than what is allowed by the closeFactor */
        /* Only KMCD has borrow related logics */
        uint borrowBalance = KMCD(kTokenBorrowed).borrowBalance(borrower);
        uint maxClose = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance);
        if (repayAmount > maxClose) {
            allowed = false;
            reason = TOO_MUCH_REPAY;
            return (allowed, reason);
        }

        allowed = true;
        return (allowed, reason);
    }

    /**
     * @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
     * @param kTokenBorrowed Asset which was borrowed by the borrower
     * @param kTokenCollateral Asset which was used as collateral and will be seized
     * @param liquidator The address repaying the borrow and seizing the collateral
     * @param borrower The address of the borrower
     * @param actualRepayAmount The amount of underlying being repaid
     */
    function liquidateBorrowVerify(
        address kTokenBorrowed,
        address kTokenCollateral,
        address liquidator,
        address borrower,
        uint actualRepayAmount,
        uint seizeTokens) external {
        // Shh - currently unused
        kTokenBorrowed;
        kTokenCollateral;
        liquidator;
        borrower;
        actualRepayAmount;
        seizeTokens;

        // Shh - we don't ever want this hook to be marked pure
        if (false) {
            maxAssets = maxAssets;
        }
    }

    /**
     * @notice Checks if the seizing of assets should be allowed to occur
     * @param kTokenCollateral Asset which was used as collateral and will be seized
     * @param kTokenBorrowed Asset which was borrowed by the borrower
     * @param liquidator The address repaying the borrow and seizing the collateral
     * @param borrower The address of the borrower
     * @param seizeTokens The number of collateral tokens to seize
     * @return false and reason if seize not allowed, otherwise return true and empty string
     */
    function seizeAllowed(
        address kTokenCollateral,
        address kTokenBorrowed,
        address liquidator,
        address borrower,
        uint seizeTokens) external returns (bool allowed, string memory reason) {
        if (seizeGuardianPaused) {
            allowed = false;
            reason = SEIZE_PAUSED;
            return (allowed, reason);
        }

        // Shh - currently unused
        seizeTokens;
        liquidator;
        borrower;

        if (!markets[kTokenCollateral].isListed || !markets[kTokenBorrowed].isListed) {
            allowed = false;
            reason = MARKET_NOT_LISTED;
            return (allowed, reason);
        }

        if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) {
            allowed = false;
            reason = CONTROLLER_MISMATCH;
            return (allowed, reason);
        }

        allowed = true;
        return (allowed, reason);
    }

    /**
     * @notice Validates seize and reverts on rejection. May emit logs.
     * @param kTokenCollateral Asset which was used as collateral and will be seized
     * @param kTokenBorrowed Asset which was borrowed by the borrower
     * @param liquidator The address repaying the borrow and seizing the collateral
     * @param borrower The address of the borrower
     * @param seizeTokens The number of collateral tokens to seize
     */
    function seizeVerify(
        address kTokenCollateral,
        address kTokenBorrowed,
        address liquidator,
        address borrower,
        uint seizeTokens) external {
        // Shh - currently unused
        kTokenCollateral;
        kTokenBorrowed;
        liquidator;
        borrower;
        seizeTokens;

        // Shh - we don't ever want this hook to be marked pure
        if (false) {
            maxAssets = maxAssets;
        }
    }

    /**
     * @notice Checks if the account should be allowed to transfer tokens in the given market
     * @param kToken The market to verify the transfer against
     * @param src The account which sources the tokens
     * @param dst The account which receives the tokens
     * @param transferTokens The number of kTokens to transfer
     * @return false and reason if seize not allowed, otherwise return true and empty string
     */
    function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool allowed, string memory reason) {
        if (transferGuardianPaused) {
            allowed = false;
            reason = TRANSFER_PAUSED;
            return (allowed, reason);
        }

        // not used currently
        dst;

        // Currently the only consideration is whether or not
        //  the src is allowed to redeem this many tokens
        return redeemAllowedInternal(kToken, src, transferTokens);
    }

    /**
     * @notice Validates transfer and reverts on rejection. May emit logs.
     * @param kToken Asset being transferred
     * @param src The account which sources the tokens
     * @param dst The account which receives the tokens
     * @param transferTokens The number of kTokens to transfer
     */
    function transferVerify(address kToken, address src, address dst, uint transferTokens) external {
        // Shh - currently unused
        kToken;
        src;
        dst;
        transferTokens;

        // Shh - we don't ever want this hook to be marked pure
        if (false) {
            maxAssets = maxAssets;
        }
    }

    /*** Liquidity/Liquidation Calculations ***/

    /**
     * @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
     *  Note that `kTokenBalance` is the number of kTokens the account owns in the market,
     *  whereas `borrowBalance` is the amount of underlying that the account has borrowed.
     *  In Kine system, user can only borrow Kine MCD, the `borrowBalance` is the amount of Kine MCD account has borrowed.
     */
    struct AccountLiquidityLocalVars {
        uint sumStaking;
        uint sumCollateral;
        uint sumBorrowPlusEffects;
        uint kTokenBalance;
        uint borrowBalance;
        uint oraclePriceMantissa;
        Exp collateralFactor;
        Exp oraclePrice;
        Exp tokensToDenom;
    }

    /**
     * @notice Determine the current account liquidity wrt collateral requirements
     * @return (account liquidity in excess of collateral requirements,
     *          account shortfall below collateral requirements,
     *          account staking asset value,
     *          account collateral value)
     */
    function getAccountLiquidity(address account) public view returns (uint, uint, uint, uint) {
        return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0);
    }

    /**
     * @notice Determine the current account liquidity wrt collateral requirements
     * @return (account liquidity in excess of collateral requirements,
     *          account shortfall below collateral requirements
     *          account staking asset value,
     *          account collateral value)
     */
    function getAccountLiquidityInternal(address account) internal view returns (uint, uint, uint, uint) {
        return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0);
    }

    /**
     * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
     * @param kTokenModify The market to hypothetically redeem/borrow in
     * @param account The account to determine liquidity for
     * @param redeemTokens The number of tokens to hypothetically redeem
     * @param borrowAmount The amount of underlying to hypothetically borrow
     * @return (hypothetical account liquidity in excess of collateral requirements,
     *          hypothetical account shortfall below collateral requirements)
     */
    function getHypotheticalAccountLiquidity(
        address account,
        address kTokenModify,
        uint redeemTokens,
        uint borrowAmount) public view returns (uint, uint) {
        (uint liquidity, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(account, KToken(kTokenModify), redeemTokens, borrowAmount);
        return (liquidity, shortfall);
    }

    /**
     * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
     * @param kTokenModify The market to hypothetically redeem/borrow in
     * @param account The account to determine liquidity for
     * @param redeemTokens The number of tokens to hypothetically redeem
     * @param borrowAmount The amount of underlying to hypothetically borrow
     * @return (hypothetical account liquidity in excess of collateral requirements,
     *          hypothetical account shortfall below collateral requirements)
     */
    function getHypotheticalAccountLiquidityInternal(
        address account,
        KToken kTokenModify,
        uint redeemTokens,
        uint borrowAmount) internal view returns (uint, uint, uint, uint) {

        AccountLiquidityLocalVars memory vars;

        // For each asset the account is in
        KToken[] memory assets = accountAssets[account];
        for (uint i = 0; i < assets.length; i++) {
            KToken asset = assets[i];

            // Read the balances from the kToken
            (vars.kTokenBalance, vars.borrowBalance) = asset.getAccountSnapshot(account);
            vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa});

            // Get the normalized price of the asset
            vars.oraclePriceMantissa = oracle.getUnderlyingPrice(address(asset));
            require(vars.oraclePriceMantissa != 0, "price error");
            vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa});

            // Pre-compute a conversion factor
            vars.tokensToDenom = mulExp(vars.collateralFactor, vars.oraclePrice);

            // sumStaking += oraclePrice * kTokenBalance
            vars.sumStaking = mulScalarTruncateAddUInt(vars.oraclePrice, vars.kTokenBalance, vars.sumStaking);

            // sumCollateral += tokensToDenom * kTokenBalance
            vars.sumCollateral = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.kTokenBalance, vars.sumCollateral);

            // sumBorrowPlusEffects += oraclePrice * borrowBalance
            vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);

            // Calculate effects of interacting with kTokenModify
            if (asset == kTokenModify) {
                // redeem effect
                // sumBorrowPlusEffects += tokensToDenom * redeemTokens
                vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);

                // borrow effect
                // sumBorrowPlusEffects += oraclePrice * borrowAmount
                vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
            }
        }

        // These are safe, as the underflow condition is checked first
        if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
            return (vars.sumCollateral - vars.sumBorrowPlusEffects, 0, vars.sumStaking, vars.sumCollateral);
        } else {
            return (0, vars.sumBorrowPlusEffects - vars.sumCollateral, vars.sumStaking, vars.sumCollateral);
        }
    }

    /**
     * @notice Calculate number of tokens of collateral asset to seize given an underlying amount
     * @dev Used in liquidation (called in kMCD.liquidateBorrowFresh)
     * @param kTokenBorrowed The address of the borrowed kToken
     * @param kTokenCollateral The address of the collateral kToken
     * @param actualRepayAmount The amount of kTokenBorrowed underlying to convert into kTokenCollateral tokens
     * @return number of kTokenCollateral tokens to be seized in a liquidation
     */
    function liquidateCalculateSeizeTokens(address target, address kTokenBorrowed, address kTokenCollateral, uint actualRepayAmount) external view returns (uint) {
        /* Read oracle prices for borrowed and collateral markets */
        uint priceBorrowedMantissa = oracle.getUnderlyingPrice(kTokenBorrowed);
        uint priceCollateralMantissa = oracle.getUnderlyingPrice(kTokenCollateral);
        require(priceBorrowedMantissa != 0 && priceCollateralMantissa != 0, "price error");

        uint cf = markets[address(kTokenCollateral)].collateralFactorMantissa;

        (uint liquidity, uint shortfall, uint stakingValue, uint collateralValue) = getAccountLiquidityInternal(target);

        uint incentiveOrPunishment;
        if (shortfall > 0) {
            // a liquidation occurs, incentive will be adjusted as below
            // adjusted liquidation incentive = min((1-cf)/2 + 100%, (shortfall/collateralValue/cf)^2 + liquidationIncentive)
            uint r = shortfall.mul(expScale).div(collateralValue).mul(expScale).div(cf);
            incentiveOrPunishment = Math.min(mantissaOne.sub(cf).div(2).add(mantissaOne), r.mul(r).div(expScale).add(liquidationIncentiveMantissa));
        } else {
            require(!redemptionPaused, "Redemption paused");
            require(!redemptionPausedPerAsset[kTokenCollateral], "Asset Redemption paused");
            // a redemption occurs, punishment will be adjusted as below
            // adjusted redemption punishment = 1 - (redemptionInitialPunishment + (liquidity/collateralValue*cf)^2)
            uint r = liquidity.mul(expScale).div(collateralValue).mul(cf).div(expScale);
            incentiveOrPunishment = mantissaOne.sub(redemptionInitialPunishmentMantissa.add(r.mul(r).div(expScale)));
        }

        /*
         *  calculate the number of collateral tokens to seize:
         *  seizeTokens = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
        */
        Exp memory ratio = divExp(mulExp(incentiveOrPunishment, priceBorrowedMantissa), Exp({mantissa : priceCollateralMantissa}));
        return mulScalarTruncate(ratio, actualRepayAmount);
    }

    /*** Admin Functions ***/

    /**
      * @notice Sets a new price oracle for the controller
      * @dev Admin function to set a new price oracle
      */
    function _setPriceOracle(KineOracleInterface newOracle) external onlyAdmin() {
        KineOracleInterface oldOracle = oracle;
        oracle = newOracle;
        emit NewPriceOracle(oldOracle, newOracle);
    }

    /**
      * @notice Sets the closeFactor used when liquidating borrows
      * @dev Admin function to set closeFactor
      * @param newCloseFactorMantissa New close factor, scaled by 1e18
      */
    function _setCloseFactor(uint newCloseFactorMantissa) external onlyAdmin() {
        require(newCloseFactorMantissa <= closeFactorMaxMantissa, INVALID_CLOSE_FACTOR);
        require(newCloseFactorMantissa >= closeFactorMinMantissa, INVALID_CLOSE_FACTOR);

        uint oldCloseFactorMantissa = closeFactorMantissa;
        closeFactorMantissa = newCloseFactorMantissa;
        emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
    }

    /**
      * @notice Sets the collateralFactor for a market
      * @dev Admin function to set per-market collateralFactor
      * @param kToken The market to set the factor on
      * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
      */
    function _setCollateralFactor(KToken kToken, uint newCollateralFactorMantissa) external onlyAdmin() {
        // Verify market is listed
        Market storage market = markets[address(kToken)];
        require(market.isListed, MARKET_NOT_LISTED);

        Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa});

        // Check collateral factor <= 0.9
        Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa});
        require(!lessThanExp(highLimit, newCollateralFactorExp), INVALID_COLLATERAL_FACTOR);

        // If collateral factor != 0, fail if price == 0
        require(newCollateralFactorMantissa == 0 || oracle.getUnderlyingPrice(address(kToken)) != 0, "price error");

        // Set market's collateral factor to new collateral factor, remember old value
        uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
        market.collateralFactorMantissa = newCollateralFactorMantissa;

        // Emit event with asset, old collateral factor, and new collateral factor
        emit NewCollateralFactor(kToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
    }

    /**
      * @notice Sets liquidationIncentive
      * @dev Admin function to set liquidationIncentive
      * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
      */
    function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyAdmin() {
        require(newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, INVALID_LIQUIDATION_INCENTIVE);
        require(newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa, INVALID_LIQUIDATION_INCENTIVE);

        uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
        liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
        emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
    }

    /**
      * @notice Add the market to the markets mapping and set it as listed
      * @dev Admin function to set isListed and add support for the market
      * @param kToken The address of the market (token) to list
      */
    function _supportMarket(KToken kToken) external onlyAdmin() {
        require(!markets[address(kToken)].isListed, MARKET_ALREADY_LISTED);

        kToken.isKToken();
        // Sanity check to make sure its really a KToken

        markets[address(kToken)] = Market({isListed : true, collateralFactorMantissa : 0});

        _addMarketInternal(address(kToken));

        emit MarketListed(kToken);
    }

    function _addMarketInternal(address kToken) internal {
        for (uint i = 0; i < allMarkets.length; i ++) {
            require(allMarkets[i] != KToken(kToken), MARKET_ALREADY_ADDED);
        }
        allMarkets.push(KToken(kToken));
    }


    /**
      * @notice Set the given borrow caps for the given kToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
      * @dev Admin or capGuardian can call this function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
      * @param kTokens The addresses of the markets (tokens) to change the borrow caps for
      * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
      */
    function _setMarketBorrowCaps(KToken[] calldata kTokens, uint[] calldata newBorrowCaps) external {
        require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set borrow caps");

        uint numMarkets = kTokens.length;
        uint numBorrowCaps = newBorrowCaps.length;

        require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");

        for (uint i = 0; i < numMarkets; i++) {
            borrowCaps[address(kTokens[i])] = newBorrowCaps[i];
            emit NewBorrowCap(kTokens[i], newBorrowCaps[i]);
        }
    }

    /**
      * @notice Set the given supply caps for the given kToken markets. Supplying that brings total supply to or above supply cap will revert.
      * @dev Admin or capGuardian can call this function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying.
      * @param kTokens The addresses of the markets (tokens) to change the supply caps for
      * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
      */
    function _setMarketSupplyCaps(KToken[] calldata kTokens, uint[] calldata newSupplyCaps) external {
        require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set supply caps");

        uint numMarkets = kTokens.length;
        uint numSupplyCaps = newSupplyCaps.length;

        require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input");

        for (uint i = 0; i < numMarkets; i++) {
            supplyCaps[address(kTokens[i])] = newSupplyCaps[i];
            emit NewSupplyCap(kTokens[i], newSupplyCaps[i]);
        }
    }

    /**
     * @notice Admin function to change the Borrow and Supply Cap Guardian
     * @param newCapGuardian The address of the new Cap Guardian
     */
    function _setCapGuardian(address newCapGuardian) external onlyAdmin() {
        address oldCapGuardian = capGuardian;
        capGuardian = newCapGuardian;
        emit NewCapGuardian(oldCapGuardian, newCapGuardian);
    }

    /**
     * @notice Admin function to change the Pause Guardian
     * @param newPauseGuardian The address of the new Pause Guardian
     */
    function _setPauseGuardian(address newPauseGuardian) external onlyAdmin() {
        address oldPauseGuardian = pauseGuardian;
        pauseGuardian = newPauseGuardian;
        emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
    }

    function _setMintPaused(KToken kToken, bool state) public returns (bool) {
        require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
        require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");

        mintGuardianPaused[address(kToken)] = state;
        emit ActionPaused(kToken, "Mint", state);
        return state;
    }

    function _setBorrowPaused(KToken kToken, bool state) public returns (bool) {
        require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
        require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");

        borrowGuardianPaused[address(kToken)] = state;
        emit ActionPaused(kToken, "Borrow", state);
        return state;
    }

    function _setTransferPaused(bool state) public returns (bool) {
        require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");

        transferGuardianPaused = state;
        emit ActionPaused("Transfer", state);
        return state;
    }

    function _setSeizePaused(bool state) public returns (bool) {
        require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");

        seizeGuardianPaused = state;
        emit ActionPaused("Seize", state);
        return state;
    }

    function _setRedemptionPaused(bool state) public returns (bool) {
        require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");

        redemptionPaused = state;
        emit ActionPaused("Redemption", state);
        return state;
    }

    function _setRedemptionPausedPerAsset(KToken kToken, bool state) public returns (bool) {
        require(markets[address(kToken)].isListed, "cannot pause a market that is not listed");
        require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause");

        redemptionPausedPerAsset[address(kToken)] = state;
        emit ActionPaused(kToken, "Redemption", state);
        return state;
    }

    function _setRedemptionInitialPunishment(uint newRedemptionInitialPunishmentMantissa) external onlyAdmin() {
        uint oldRedemptionInitialPunishmentMantissa = redemptionInitialPunishmentMantissa;
        redemptionInitialPunishmentMantissa = newRedemptionInitialPunishmentMantissa;
        emit NewRedemptionInitialPunishment(oldRedemptionInitialPunishmentMantissa, newRedemptionInitialPunishmentMantissa);
    }

    function _become(Unitroller unitroller) public {
        require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
        unitroller._acceptImplementation();
    }

    /**
     * @notice Return all of the markets
     * @dev The automatic getter may be used to access an individual market.
     * @return The list of market addresses
     */
    function getAllMarkets() public view returns (KToken[] memory) {
        return allMarkets;
    }

    function getBlockNumber() public view returns (uint) {
        return block.number;
    }

    function getOracle() external view returns (address) {
        return address(oracle);
    }

}

File 2 of 15 : ControllerStorage.sol
pragma solidity ^0.5.16;

import "./KToken.sol";
import "./KineOracleInterface.sol";

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerStorage.sol
* Modified to work in the Kine system.
* Main modifications:
*   1. removed Comp token related logics.
*   2. removed interest rate model related logics.
*   3. combined different versions storage contracts into one.
*/

contract UnitrollerAdminStorage {
    /**
    * @notice Administrator for this contract
    */
    address public admin;

    /**
    * @notice Pending administrator for this contract
    */
    address public pendingAdmin;

    /**
    * @notice Active brains of Unitroller
    */
    address public controllerImplementation;

    /**
    * @notice Pending brains of Unitroller
    */
    address public pendingControllerImplementation;
}

contract ControllerStorage is UnitrollerAdminStorage {

    struct Market {
        /// @notice Whether or not this market is listed
        bool isListed;

        /**
         * @notice Multiplier representing the most one can borrow against their collateral in this market.
         *  For instance, 0.9 to allow borrowing 90% of collateral value.
         *  Must be between 0 and 1, and stored as a mantissa.
         */
        uint collateralFactorMantissa;

        /// @notice Per-market mapping of "accounts in this asset"
        mapping(address => bool) accountMembership;
    }

    /**
     * @notice Oracle which gives the price of any given asset
     */
    KineOracleInterface public oracle;

    /**
     * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
     */
    uint public closeFactorMantissa;

    /**
     * @notice Multiplier representing the discount on collateral that a liquidator receives
     */
    uint public liquidationIncentiveMantissa;

    /**
     * @notice Max number of assets a single account can participate in (borrow or use as collateral)
     */
    uint public maxAssets;

    /**
     * @notice Per-account mapping of "assets you are in", capped by maxAssets
     */
    mapping(address => KToken[]) public accountAssets;

    /**
     * @notice Official mapping of kTokens -> Market metadata
     * @dev Used e.g. to determine if a market is supported
     */
    mapping(address => Market) public markets;

    /// @notice A list of all markets
    KToken[] public allMarkets;

    /**
     * @notice The Pause Guardian can pause certain actions as a safety mechanism.
     *  Actions which allow users to remove their own assets cannot be paused.
     *  Liquidation / seizing / transfer can only be paused globally, not by market.
     */
    address public pauseGuardian;
    // @notice The capGuardian can set borrowCaps/supplyCaps to any number for any market. Lowering the borrow/supply cap could disable borrowing/supplying on the given market.
    address public capGuardian;
    bool public transferGuardianPaused;
    bool public seizeGuardianPaused;
    mapping(address => bool) public mintGuardianPaused;
    mapping(address => bool) public borrowGuardianPaused;

    // @notice Borrow caps enforced by borrowAllowed for each kToken address. Defaults to zero which corresponds to unlimited borrowing.
    mapping(address => uint) public borrowCaps;
    // @notice Supply caps enforced by mintAllowed for each kToken address. Defaults to zero which corresponds to unlimited supplying.
    mapping(address => uint) public supplyCaps;

    /**
     * @notice Indicator whether redemption is paused
     */
    bool public redemptionPaused;

    /**
     * @notice Percentage of initial punishment when a redemption occur
     */
    uint public redemptionInitialPunishmentMantissa;

    /**
     * @notice Indicator whether redemption is paused per asset
     */
    mapping(address => bool) public redemptionPausedPerAsset;
}

File 3 of 15 : EIP20Interface.sol
pragma solidity ^0.5.16;

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @title ERC 20 Token Standard Interface
 *  https://eips.ethereum.org/EIPS/eip-20
 */
interface EIP20Interface {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);

    /**
      * @notice Get the total number of tokens in circulation
      * @return The supply of tokens
      */
    function totalSupply() external view returns (uint256);

    /**
     * @notice Gets the balance of the specified address
     * @param owner The address from which the balance will be retrieved
     * @return The balance
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
      * @notice Transfer `amount` tokens from `msg.sender` to `dst`
      * @param dst The address of the destination account
      * @param amount The number of tokens to transfer
      * @return Whether or not the transfer succeeded
      */
    function transfer(address dst, uint256 amount) external returns (bool success);

    /**
      * @notice Transfer `amount` tokens from `src` to `dst`
      * @param src The address of the source account
      * @param dst The address of the destination account
      * @param amount The number of tokens to transfer
      * @return Whether or not the transfer succeeded
      */
    function transferFrom(address src, address dst, uint256 amount) external returns (bool success);

    /**
      * @notice Approve `spender` to transfer up to `amount` from `src`
      * @dev This will overwrite the approval amount for `spender`
      *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
      * @param spender The address of the account which may transfer tokens
      * @param amount The number of tokens that are approved (-1 means infinite)
      * @return Whether or not the approval succeeded
      */
    function approve(address spender, uint256 amount) external returns (bool success);

    /**
      * @notice Get the current allowance from `owner` for `spender`
      * @param owner The address of the account which owns the tokens to be spent
      * @param spender The address of the account which may transfer tokens
      * @return The number of tokens allowed to be spent (-1 means infinite)
      */
    function allowance(address owner, address spender) external view returns (uint256 remaining);

    event Transfer(address indexed from, address indexed to, uint256 amount);
    event Approval(address indexed owner, address indexed spender, uint256 amount);
}

File 4 of 15 : EIP20NonStandardInterface.sol
pragma solidity ^0.5.16;

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @title EIP20NonStandardInterface
 * @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
 *  See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
 */
interface EIP20NonStandardInterface {

    /**
     * @notice Get the total number of tokens in circulation
     * @return The supply of tokens
     */
    function totalSupply() external view returns (uint256);

    /**
     * @notice Gets the balance of the specified address
     * @param owner The address from which the balance will be retrieved
     * @return The balance
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    ///
    /// !!!!!!!!!!!!!!
    /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
    /// !!!!!!!!!!!!!!
    ///

    /**
      * @notice Transfer `amount` tokens from `msg.sender` to `dst`
      * @param dst The address of the destination account
      * @param amount The number of tokens to transfer
      */
    function transfer(address dst, uint256 amount) external;

    ///
    /// !!!!!!!!!!!!!!
    /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
    /// !!!!!!!!!!!!!!
    ///

    /**
      * @notice Transfer `amount` tokens from `src` to `dst`
      * @param src The address of the source account
      * @param dst The address of the destination account
      * @param amount The number of tokens to transfer
      */
    function transferFrom(address src, address dst, uint256 amount) external;

    /**
      * @notice Approve `spender` to transfer up to `amount` from `src`
      * @dev This will overwrite the approval amount for `spender`
      *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
      * @param spender The address of the account which may transfer tokens
      * @param amount The number of tokens that are approved
      * @return Whether or not the approval succeeded
      */
    function approve(address spender, uint256 amount) external returns (bool success);

    /**
      * @notice Get the current allowance from `owner` for `spender`
      * @param owner The address of the account which owns the tokens to be spent
      * @param spender The address of the account which may transfer tokens
      * @return The number of tokens allowed to be spent
      */
    function allowance(address owner, address spender) external view returns (uint256 remaining);

    event Transfer(address indexed from, address indexed to, uint256 amount);
    event Approval(address indexed owner, address indexed spender, uint256 amount);
}

File 5 of 15 : ErrorReporter.sol
pragma solidity ^0.5.16;

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ErrorReporter.sol
* Modified to work in the Kine system.
* Main modifications:
*   1. using constant string instead of enums
*/

contract ControllerErrorReporter {
    string internal constant MARKET_NOT_LISTED = "MARKET_NOT_LISTED";
    string internal constant MARKET_ALREADY_LISTED = "MARKET_ALREADY_LISTED";
    string internal constant MARKET_ALREADY_ADDED = "MARKET_ALREADY_ADDED";
    string internal constant EXIT_MARKET_BALANCE_OWED = "EXIT_MARKET_BALANCE_OWED";
    string internal constant EXIT_MARKET_REJECTION = "EXIT_MARKET_REJECTION";
    string internal constant MINT_PAUSED = "MINT_PAUSED";
    string internal constant BORROW_PAUSED = "BORROW_PAUSED";
    string internal constant SEIZE_PAUSED = "SEIZE_PAUSED";
    string internal constant TRANSFER_PAUSED = "TRANSFER_PAUSED";
    string internal constant MARKET_BORROW_CAP_REACHED = "MARKET_BORROW_CAP_REACHED";
    string internal constant MARKET_SUPPLY_CAP_REACHED = "MARKET_SUPPLY_CAP_REACHED";
    string internal constant REDEEM_TOKENS_ZERO = "REDEEM_TOKENS_ZERO";
    string internal constant INSUFFICIENT_LIQUIDITY = "INSUFFICIENT_LIQUIDITY";
    string internal constant INSUFFICIENT_SHORTFALL = "INSUFFICIENT_SHORTFALL";
    string internal constant TOO_MUCH_REPAY = "TOO_MUCH_REPAY";
    string internal constant CONTROLLER_MISMATCH = "CONTROLLER_MISMATCH";
    string internal constant INVALID_COLLATERAL_FACTOR = "INVALID_COLLATERAL_FACTOR";
    string internal constant INVALID_CLOSE_FACTOR = "INVALID_CLOSE_FACTOR";
    string internal constant INVALID_LIQUIDATION_INCENTIVE = "INVALID_LIQUIDATION_INCENTIVE";
}

contract KTokenErrorReporter {
    string internal constant BAD_INPUT = "BAD_INPUT";
    string internal constant TRANSFER_NOT_ALLOWED = "TRANSFER_NOT_ALLOWED";
    string internal constant TRANSFER_NOT_ENOUGH = "TRANSFER_NOT_ENOUGH";
    string internal constant TRANSFER_TOO_MUCH = "TRANSFER_TOO_MUCH";
    string internal constant MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED";
    string internal constant MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED";
    string internal constant REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED = "REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED";
    string internal constant REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED = "REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED";
    string internal constant BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED";
    string internal constant BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED";
    string internal constant REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED";
    string internal constant REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED = "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED";
    string internal constant INVALID_CLOSE_AMOUNT_REQUESTED = "INVALID_CLOSE_AMOUNT_REQUESTED";
    string internal constant LIQUIDATE_SEIZE_TOO_MUCH = "LIQUIDATE_SEIZE_TOO_MUCH";
    string internal constant TOKEN_INSUFFICIENT_CASH = "TOKEN_INSUFFICIENT_CASH";
    string internal constant INVALID_ACCOUNT_PAIR = "INVALID_ACCOUNT_PAIR";
    string internal constant LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED";
    string internal constant LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED = "LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED";
    string internal constant TOKEN_TRANSFER_IN_FAILED = "TOKEN_TRANSFER_IN_FAILED";
    string internal constant TOKEN_TRANSFER_IN_OVERFLOW = "TOKEN_TRANSFER_IN_OVERFLOW";
    string internal constant TOKEN_TRANSFER_OUT_FAILED = "TOKEN_TRANSFER_OUT_FAILED";

}

File 6 of 15 : Exponential.sol
pragma solidity ^0.5.16;

import "./KineSafeMath.sol";

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol
* Modified to work in the Kine system.
* Main modifications:
*   1. use SafeMath instead of CarefulMath to fail fast and loudly
*/

/**
 * @title Exponential module for storing fixed-precision decimals
 * @author Compound
 * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
 *         Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
 *         `Exp({mantissa: 5100000000000000000})`.
 */
contract Exponential {
    using KineSafeMath for uint;
    uint constant expScale = 1e18;
    uint constant doubleScale = 1e36;
    uint constant halfExpScale = expScale / 2;
    uint constant mantissaOne = expScale;

    struct Exp {
        uint mantissa;
    }

    struct Double {
        uint mantissa;
    }

    /**
     * @dev Creates an exponential from numerator and denominator values.
     */
    function getExp(uint num, uint denom) pure internal returns (Exp memory) {
        uint rational = num.mul(expScale).div(denom);
        return Exp({mantissa : rational});
    }

    /**
     * @dev Adds two exponentials, returning a new exponential.
     */
    function addExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
        uint result = a.mantissa.add(b.mantissa);
        return Exp({mantissa : result});
    }

    /**
     * @dev Subtracts two exponentials, returning a new exponential.
     */
    function subExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
        uint result = a.mantissa.sub(b.mantissa);
        return Exp({mantissa : result});
    }

    /**
     * @dev Multiply an Exp by a scalar, returning a new Exp.
     */
    function mulScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) {
        uint scaledMantissa = a.mantissa.mul(scalar);
        return Exp({mantissa : scaledMantissa});
    }

    /**
     * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
     */
    function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
        Exp memory product = mulScalar(a, scalar);
        return truncate(product);
    }

    /**
     * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
     */
    function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
        Exp memory product = mulScalar(a, scalar);
        return truncate(product).add(addend);
    }

    /**
     * @dev Divide an Exp by a scalar, returning a new Exp.
     */
    function divScalar(Exp memory a, uint scalar) pure internal returns (Exp memory) {
        uint descaledMantissa = a.mantissa.div(scalar);
        return Exp({mantissa : descaledMantissa});
    }

    /**
     * @dev Divide a scalar by an Exp, returning a new Exp.
     */
    function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) {
        /*
          We are doing this as:
          getExp(expScale.mul(scalar), divisor.mantissa)

          How it works:
          Exp = a / b;
          Scalar = s;
          `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
        */
        uint numerator = expScale.mul(scalar);
        return getExp(numerator, divisor.mantissa);
    }

    /**
     * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
     */
    function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (uint) {
        Exp memory fraction = divScalarByExp(scalar, divisor);
        return truncate(fraction);
    }

    /**
     * @dev Multiplies two exponentials, returning a new exponential.
     */
    function mulExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
        uint doubleScaledProduct = a.mantissa.mul(b.mantissa);

        // We add half the scale before dividing so that we get rounding instead of truncation.
        //  See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
        // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
        uint doubleScaledProductWithHalfScale = halfExpScale.add(doubleScaledProduct);
        uint product = doubleScaledProductWithHalfScale.div(expScale);
        return Exp({mantissa : product});
    }

    /**
     * @dev Multiplies two exponentials given their mantissas, returning a new exponential.
     */
    function mulExp(uint a, uint b) pure internal returns (Exp memory) {
        return mulExp(Exp({mantissa : a}), Exp({mantissa : b}));
    }

    /**
     * @dev Divides two exponentials, returning a new exponential.
     *     (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
     *  which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
     */
    function divExp(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
        return getExp(a.mantissa, b.mantissa);
    }

    /**
     * @dev Truncates the given exp to a whole number value.
     *      For example, truncate(Exp{mantissa: 15 * expScale}) = 15
     */
    function truncate(Exp memory exp) pure internal returns (uint) {
        // Note: We are not using careful math here as we're performing a division that cannot fail
        return exp.mantissa / expScale;
    }

    /**
     * @dev Checks if first Exp is less than second Exp.
     */
    function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
        return left.mantissa < right.mantissa;
    }

    /**
     * @dev Checks if left Exp <= right Exp.
     */
    function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
        return left.mantissa <= right.mantissa;
    }

    /**
     * @dev Checks if left Exp > right Exp.
     */
    function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
        return left.mantissa > right.mantissa;
    }

    /**
     * @dev returns true if Exp is exactly zero
     */
    function isZeroExp(Exp memory value) pure internal returns (bool) {
        return value.mantissa == 0;
    }

    function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
        require(n < 2 ** 224, errorMessage);
        return uint224(n);
    }

    function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
        require(n < 2 ** 32, errorMessage);
        return uint32(n);
    }

    function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
        return Exp({mantissa : add_(a.mantissa, b.mantissa)});
    }

    function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
        return Double({mantissa : add_(a.mantissa, b.mantissa)});
    }

    function add_(uint a, uint b) pure internal returns (uint) {
        return add_(a, b, "addition overflow");
    }

    function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
        uint c = a + b;
        require(c >= a, errorMessage);
        return c;
    }

    function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
        return Exp({mantissa : sub_(a.mantissa, b.mantissa)});
    }

    function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
        return Double({mantissa : sub_(a.mantissa, b.mantissa)});
    }

    function sub_(uint a, uint b) pure internal returns (uint) {
        return sub_(a, b, "subtraction underflow");
    }

    function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
        require(b <= a, errorMessage);
        return a - b;
    }

    function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
        return Exp({mantissa : mul_(a.mantissa, b.mantissa) / expScale});
    }

    function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
        return Exp({mantissa : mul_(a.mantissa, b)});
    }

    function mul_(uint a, Exp memory b) pure internal returns (uint) {
        return mul_(a, b.mantissa) / expScale;
    }

    function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
        return Double({mantissa : mul_(a.mantissa, b.mantissa) / doubleScale});
    }

    function mul_(Double memory a, uint b) pure internal returns (Double memory) {
        return Double({mantissa : mul_(a.mantissa, b)});
    }

    function mul_(uint a, Double memory b) pure internal returns (uint) {
        return mul_(a, b.mantissa) / doubleScale;
    }

    function mul_(uint a, uint b) pure internal returns (uint) {
        return mul_(a, b, "multiplication overflow");
    }

    function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
        if (a == 0 || b == 0) {
            return 0;
        }
        uint c = a * b;
        require(c / a == b, errorMessage);
        return c;
    }

    function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
        return Exp({mantissa : div_(mul_(a.mantissa, expScale), b.mantissa)});
    }

    function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
        return Exp({mantissa : div_(a.mantissa, b)});
    }

    function div_(uint a, Exp memory b) pure internal returns (uint) {
        return div_(mul_(a, expScale), b.mantissa);
    }

    function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
        return Double({mantissa : div_(mul_(a.mantissa, doubleScale), b.mantissa)});
    }

    function div_(Double memory a, uint b) pure internal returns (Double memory) {
        return Double({mantissa : div_(a.mantissa, b)});
    }

    function div_(uint a, Double memory b) pure internal returns (uint) {
        return div_(mul_(a, doubleScale), b.mantissa);
    }

    function div_(uint a, uint b) pure internal returns (uint) {
        return div_(a, b, "divide by zero");
    }

    function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
        require(b > 0, errorMessage);
        return a / b;
    }

    function fraction(uint a, uint b) pure internal returns (Double memory) {
        return Double({mantissa : div_(mul_(a, doubleScale), b)});
    }
}

File 7 of 15 : KMCD.sol
pragma solidity ^0.5.16;

import "./KineControllerInterface.sol";
import "./KMCDInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./KTokenInterfaces.sol";

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol
* Modified to work in the Kine system.
* Main modifications:
*   1. removed Comp token related logics.
*   2. removed interest rate model related logics.
*   3. removed mint, redeem logics. users can only supply kTokens (see KToken) and borrow Kine MCD.
*   4. removed transfer logics. MCD can't be transferred.
*   5. removed error code propagation mechanism, using revert to fail fast and loudly.
*/

/**
 * @title Kine's KMCD Contract
 * @notice Kine Market Connected Debt (MCD) contract. Users are allowed to call KUSDMinter to borrow Kine MCD and mint KUSD
 * after they supply collaterals in KTokens. One should notice that Kine MCD is not ERC20 token since it can't be transferred by user.
 * @author Kine
 */
contract KMCD is KMCDInterface, Exponential, KTokenErrorReporter {
    modifier onlyAdmin(){
        require(msg.sender == admin, "only admin can call this function");
        _;
    }

    /// @notice Prevent anyone other than minter from borrow/repay Kine MCD
    modifier onlyMinter {
        require(
            msg.sender == minter,
            "Only minter can call this function."
        );
        _;
    }

    /**
     * @notice Initialize the money market
     * @param controller_ The address of the Controller
     * @param name_ Name of this MCD token
     * @param symbol_ Symbol of this MCD token
     * @param decimals_ Decimal precision of this token
     */
    function initialize(KineControllerInterface controller_,
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        address minter_) public {
        require(msg.sender == admin, "only admin may initialize the market");
        require(initialized == false, "market may only be initialized once");

        // Set the controller
        _setController(controller_);

        minter = minter_;
        name = name_;
        symbol = symbol_;
        decimals = decimals_;

        // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
        _notEntered = true;
        initialized = true;
    }

    /*** User Interface ***/

    /**
      * @notice Only minter can borrow Kine MCD on behalf of user from the protocol
      * @param borrowAmount Amount of Kine MCD to borrow on behalf of user
      */
    function borrowBehalf(address payable borrower, uint borrowAmount) onlyMinter external {
        borrowInternal(borrower, borrowAmount);
    }

    /**
     * @notice Only minter can repay Kine MCD on behalf of borrower to the protocol
     * @param borrower Account with the MCD being payed off
     * @param repayAmount The amount to repay
     */
    function repayBorrowBehalf(address borrower, uint repayAmount) onlyMinter external {
        repayBorrowBehalfInternal(borrower, repayAmount);
    }

    /**
     * @notice Only minter can liquidates the borrowers collateral on behalf of user
     *  The collateral seized is transferred to the liquidator
     * @param borrower The borrower of MCD to be liquidated
     * @param repayAmount The amount of the MCD to repay
     * @param kTokenCollateral The market in which to seize collateral from the borrower
     */
    function liquidateBorrowBehalf(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral, uint minSeizeKToken) onlyMinter external {
        liquidateBorrowInternal(liquidator, borrower, repayAmount, kTokenCollateral, minSeizeKToken);
    }

    /**
     * @notice Get a snapshot of the account's balances
     * @dev This is used by controller to more efficiently perform liquidity checks.
     * @param account Address of the account to snapshot
     * @return (token balance, borrow balance)
     */
    function getAccountSnapshot(address account) external view returns (uint, uint) {
        return (0, accountBorrows[account]);
    }

    /**
     * @dev Function to simply retrieve block number
     *  This exists mainly for inheriting test contracts to stub this result.
     */
    function getBlockNumber() internal view returns (uint) {
        return block.number;
    }

    /**
     * @notice get account's borrow balance
     * @param account The address whose balance should be get
     * @return The balance
     */
    function borrowBalance(address account) public view returns (uint) {
        return accountBorrows[account];
    }

    /**
      * @notice Sender borrows MCD from the protocol to their own address
      * @param borrowAmount The amount of MCD to borrow
      */
    function borrowInternal(address payable borrower, uint borrowAmount) internal nonReentrant {
        borrowFresh(borrower, borrowAmount);
    }

    struct BorrowLocalVars {
        uint accountBorrows;
        uint accountBorrowsNew;
        uint totalBorrowsNew;
    }

    /**
      * @notice Sender borrow MCD from the protocol to their own address
      * @param borrowAmount The amount of the MCD to borrow
      */
    function borrowFresh(address payable borrower, uint borrowAmount) internal {
        /* Fail if borrow not allowed */
        (bool allowed, string memory reason) = controller.borrowAllowed(address(this), borrower, borrowAmount);
        require(allowed, reason);

        BorrowLocalVars memory vars;

        /*
         * We calculate the new borrower and total borrow balances, failing on overflow:
         *  accountBorrowsNew = accountBorrows + borrowAmount
         *  totalBorrowsNew = totalBorrows + borrowAmount
         */
        vars.accountBorrows = accountBorrows[borrower];

        vars.accountBorrowsNew = vars.accountBorrows.add(borrowAmount, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED);
        vars.totalBorrowsNew = totalBorrows.add(borrowAmount, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED);

        /* We write the previously calculated values into storage */
        accountBorrows[borrower] = vars.accountBorrowsNew;
        totalBorrows = vars.totalBorrowsNew;

        /* We emit a Borrow event */
        emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);

        /* We call the defense hook */
        controller.borrowVerify(address(this), borrower, borrowAmount);
    }

    /**
     * @notice Sender repays MCD belonging to borrower
     * @param borrower the account with the MCD being payed off
     * @param repayAmount The amount to repay
     * @return the actual repayment amount.
     */
    function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint) {
        return repayBorrowFresh(msg.sender, borrower, repayAmount);
    }

    struct RepayBorrowLocalVars {
        uint accountBorrows;
        uint accountBorrowsNew;
        uint totalBorrowsNew;
    }

    /**
     * @notice Borrows are repaid by another user, should be the minter.
     * @param payer the account paying off the MCD
     * @param borrower the account with the MCD being payed off
     * @param repayAmount the amount of MCD being returned
     * @return the actual repayment amount.
     */
    function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) {
        /* Fail if repayBorrow not allowed */
        (bool allowed, string memory reason) = controller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
        require(allowed, reason);

        RepayBorrowLocalVars memory vars;

        /* We fetch the amount the borrower owes */
        vars.accountBorrows = accountBorrows[borrower];

        /*
         * We calculate the new borrower and total borrow balances, failing on underflow:
         *  accountBorrowsNew = accountBorrows - actualRepayAmount
         *  totalBorrowsNew = totalBorrows - actualRepayAmount
         */
        vars.accountBorrowsNew = vars.accountBorrows.sub(repayAmount, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED);
        vars.totalBorrowsNew = totalBorrows.sub(repayAmount, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED);

        /* We write the previously calculated values into storage */
        accountBorrows[borrower] = vars.accountBorrowsNew;
        totalBorrows = vars.totalBorrowsNew;

        /* We emit a RepayBorrow event */
        emit RepayBorrow(payer, borrower, repayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);

        /* We call the defense hook */
        controller.repayBorrowVerify(address(this), payer, borrower, repayAmount);

        return repayAmount;
    }

    /**
     * @notice The sender liquidates the borrowers collateral.
     *  The collateral seized is transferred to the liquidator.
     * @param borrower The borrower of this MCD to be liquidated
     * @param kTokenCollateral The market in which to seize collateral from the borrower
     * @param repayAmount The amount of the MCD asset to repay
     * @return the actual repayment amount.
     */
    function liquidateBorrowInternal(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral, uint minSeizeKToken) internal nonReentrant returns (uint) {
        return liquidateBorrowFresh(liquidator, borrower, repayAmount, kTokenCollateral, minSeizeKToken);
    }

    /**
     * @notice The liquidator liquidates the borrowers collateral.
     *  The collateral seized is transferred to the liquidator.
     * @param borrower The borrower of this MCD to be liquidated
     * @param liquidator The address repaying the MCD and seizing collateral
     * @param kTokenCollateral The market in which to seize collateral from the borrower
     * @param repayAmount The amount of the borrowed MCD to repay
     * @return the actual repayment amount.
     */
    function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, KTokenInterface kTokenCollateral, uint minSeizeKToken) internal returns (uint) {
        /* Revert if trying to seize MCD */
        require(address(kTokenCollateral) != address(this), "Kine MCD can't be seized");

        /* Fail if liquidate not allowed */
        (bool allowed, string memory reason) = controller.liquidateBorrowAllowed(address(this), address(kTokenCollateral), liquidator, borrower, repayAmount);
        require(allowed, reason);

        /* Fail if borrower = liquidator */
        require(borrower != liquidator, INVALID_ACCOUNT_PAIR);

        /* Fail if repayAmount = 0 */
        require(repayAmount != 0, INVALID_CLOSE_AMOUNT_REQUESTED);

        /* Fail if repayAmount = -1 */
        require(repayAmount != uint(- 1), INVALID_CLOSE_AMOUNT_REQUESTED);

        /////////////////////////
        // EFFECTS & INTERACTIONS

        /* We calculate the number of collateral tokens that will be seized */
        uint seizeTokens = controller.liquidateCalculateSeizeTokens(borrower, address(this), address(kTokenCollateral), repayAmount);

        require(seizeTokens >= minSeizeKToken, "Reach minSeizeKToken limit");

        /* Revert if borrower collateral token balance < seizeTokens */
        require(kTokenCollateral.balanceOf(borrower) >= seizeTokens, LIQUIDATE_SEIZE_TOO_MUCH);

        /* Fail if repayBorrow fails */
        repayBorrowFresh(liquidator, borrower, repayAmount);

        /* Seize borrower tokens to liquidator */
        kTokenCollateral.seize(liquidator, borrower, seizeTokens);

        /* We emit a LiquidateBorrow event */
        emit LiquidateBorrow(liquidator, borrower, repayAmount, address(kTokenCollateral), seizeTokens);

        /* We call the defense hook */
        controller.liquidateBorrowVerify(address(this), address(kTokenCollateral), liquidator, borrower, repayAmount, seizeTokens);

        return repayAmount;
    }

    /*** Admin Functions ***/

    /**
      * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
      * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
      * @param newPendingAdmin New pending admin.
      */
    function _setPendingAdmin(address payable newPendingAdmin) external onlyAdmin() {
        // Save current value, if any, for inclusion in log
        address oldPendingAdmin = pendingAdmin;

        // Store pendingAdmin with value newPendingAdmin
        pendingAdmin = newPendingAdmin;

        // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
        emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
    }

    /**
      * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
      * @dev Admin function for pending admin to accept role and update admin
      */
    function _acceptAdmin() external {
        // Check caller is pendingAdmin and pendingAdmin ≠ address(0)
        require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized");

        // Save current values for inclusion in log
        address oldAdmin = admin;
        address oldPendingAdmin = pendingAdmin;

        // Store admin with value pendingAdmin
        admin = pendingAdmin;

        // Clear the pending value
        pendingAdmin = address(0);

        emit NewAdmin(oldAdmin, admin);
        emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
    }

    /**
      * @notice Sets a new controller for the market
      * @dev Admin function to set a new controller
      */
    function _setController(KineControllerInterface newController) public onlyAdmin() {
        KineControllerInterface oldController = controller;
        // Ensure invoke controller.isController() returns true
        require(newController.isController(), "marker method returned false");

        // Set market's controller to newController
        controller = newController;

        // Emit NewController(oldController, newController)
        emit NewController(oldController, newController);
    }

    function _setMinter(address newMinter) public onlyAdmin() {
        address oldMinter = minter;
        minter = newMinter;

        emit NewMinter(oldMinter, newMinter);
    }

    /*** Reentrancy Guard ***/

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     */
    modifier nonReentrant() {
        require(_notEntered, "re-entered");
        _notEntered = false;
        _;
        _notEntered = true;
        // get a gas-refund post-Istanbul
    }
}

File 8 of 15 : KMCDInterfaces.sol
pragma solidity ^0.5.16;

import "./KineControllerInterface.sol";

contract KMCDStorage {
    /**
     * @dev Guard variable for re-entrancy checks
     */
    bool internal _notEntered;

    /**
    * @notice flag that Kine MCD has been initialized;
    */
    bool public initialized;

    /**
    * @notice Only KUSDMinter can borrow/repay Kine MCD on behalf of users;
    */
    address public minter;

    /**
     * @notice Name for this MCD
     */
    string public name;

    /**
     * @notice Symbol for this MCD
     */
    string public symbol;

    /**
     * @notice Decimals for this MCD
     */
    uint8 public decimals;

    /**
     * @notice Administrator for this contract
     */
    address payable public admin;

    /**
     * @notice Pending administrator for this contract
     */
    address payable public pendingAdmin;

    /**
     * @notice Contract which oversees inter-kToken operations
     */
    KineControllerInterface public controller;

    /**
     * @notice Approved token transfer amounts on behalf of others
     */
    mapping(address => mapping(address => uint)) internal transferAllowances;

    /**
     * @notice Total amount of outstanding borrows of the MCD
     */
    uint public totalBorrows;

    /**
     * @notice Mapping of account addresses to outstanding borrow balances
     */
    mapping(address => uint) internal accountBorrows;
}

contract KMCDInterface is KMCDStorage {
    /**
     * @notice Indicator that this is a KToken contract (for inspection)
     */
    bool public constant isKToken = true;


    /*** Market Events ***/

    /**
     * @notice Event emitted when MCD is borrowed
     */
    event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);

    /**
     * @notice Event emitted when a borrow is repaid
     */
    event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);

    /**
     * @notice Event emitted when a borrow is liquidated
     */
    event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address kTokenCollateral, uint seizeTokens);


    /*** Admin Events ***/

    /**
     * @notice Event emitted when pendingAdmin is changed
     */
    event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);

    /**
     * @notice Event emitted when pendingAdmin is accepted, which means admin is updated
     */
    event NewAdmin(address oldAdmin, address newAdmin);

    /**
     * @notice Event emitted when controller is changed
     */
    event NewController(KineControllerInterface oldController, KineControllerInterface newController);

    /**
     * @notice Event emitted when minter is changed
     */
    event NewMinter(address oldMinter, address newMinter);


    /*** User Interface ***/

    function getAccountSnapshot(address account) external view returns (uint, uint);

    function borrowBalance(address account) public view returns (uint);

    /*** Admin Functions ***/

    function _setPendingAdmin(address payable newPendingAdmin) external;

    function _acceptAdmin() external;

    function _setController(KineControllerInterface newController) public;
}

File 9 of 15 : KToken.sol
pragma solidity ^0.5.16;

import "./KineControllerInterface.sol";
import "./KTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/CToken.sol
* Modified to work in the Kine system.
* Main modifications:
*   1. removed Comp token related logics.
*   2. removed interest rate model related logics.
*   3. removed borrow/repay logics. users can only mint/redeem kTokens and borrow Kine MCD (see KMCD).
*   4. removed error code propagation mechanism, using revert to fail fast and loudly.
*/

/**
 * @title Kine's KToken Contract
 * @notice Abstract base for KTokens
 * @author Kine
 */
contract KToken is KTokenInterface, Exponential, KTokenErrorReporter {
    modifier onlyAdmin(){
        require(msg.sender == admin, "only admin can call this function");
        _;
    }

    /**
     * @notice Initialize the money market
     * @param controller_ The address of the Controller
     * @param name_ EIP-20 name of this token
     * @param symbol_ EIP-20 symbol of this token
     * @param decimals_ EIP-20 decimal precision of this token
     */
    function initialize(KineControllerInterface controller_,
        string memory name_,
        string memory symbol_,
        uint8 decimals_) public {
        require(msg.sender == admin, "only admin may initialize the market");
        require(initialized == false, "market may only be initialized once");

        // Set the controller
        _setController(controller_);

        name = name_;
        symbol = symbol_;
        decimals = decimals_;

        // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
        _notEntered = true;
        initialized = true;
    }

    /**
     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
     * @dev Called by both `transfer` and `transferFrom` internally
     * @param spender The address of the account performing the transfer
     * @param src The address of the source account
     * @param dst The address of the destination account
     * @param tokens The number of tokens to transfer
     */
    function transferTokens(address spender, address src, address dst, uint tokens) internal {
        /* Fail if transfer not allowed */
        (bool allowed, string memory reason) = controller.transferAllowed(address(this), src, dst, tokens);
        require(allowed, reason);

        /* Do not allow self-transfers */
        require(src != dst, BAD_INPUT);

        /* Get the allowance, infinite for the account owner */
        uint startingAllowance = 0;
        if (spender == src) {
            startingAllowance = uint(- 1);
        } else {
            startingAllowance = transferAllowances[src][spender];
        }

        /* Do the calculations, checking for {under,over}flow */
        uint allowanceNew = startingAllowance.sub(tokens, TRANSFER_NOT_ALLOWED);
        uint srcTokensNew = accountTokens[src].sub(tokens, TRANSFER_NOT_ENOUGH);
        uint dstTokensNew = accountTokens[dst].add(tokens, TRANSFER_TOO_MUCH);

        /////////////////////////
        // EFFECTS & INTERACTIONS
        accountTokens[src] = srcTokensNew;
        accountTokens[dst] = dstTokensNew;

        /* Eat some of the allowance (if necessary) */
        if (startingAllowance != uint(- 1)) {
            transferAllowances[src][spender] = allowanceNew;
        }

        /* We emit a Transfer event */
        emit Transfer(src, dst, tokens);

        controller.transferVerify(address(this), src, dst, tokens);
    }

    /**
     * @notice Transfer `amount` tokens from `msg.sender` to `dst`
     * @param dst The address of the destination account
     * @param amount The number of tokens to transfer
     * @return Whether or not the transfer succeeded
     */
    function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
        transferTokens(msg.sender, msg.sender, dst, amount);
        return true;
    }

    /**
     * @notice Transfer `amount` tokens from `src` to `dst`
     * @param src The address of the source account
     * @param dst The address of the destination account
     * @param amount The number of tokens to transfer
     * @return Whether or not the transfer succeeded
     */
    function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
        transferTokens(msg.sender, src, dst, amount);
        return true;
    }

    /**
     * @notice Approve `spender` to transfer up to `amount` from `src`
     * @dev This will overwrite the approval amount for `spender`
     *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
     * @param spender The address of the account which may transfer tokens
     * @param amount The number of tokens that are approved (uint256(-1) means infinite)
     * @return Whether or not the approval succeeded
     */
    function approve(address spender, uint256 amount) external returns (bool) {
        address src = msg.sender;
        transferAllowances[src][spender] = amount;
        emit Approval(src, spender, amount);
        return true;
    }

    /**
     * @notice Get the current allowance from `owner` for `spender`
     * @param owner The address of the account which owns the tokens to be spent
     * @param spender The address of the account which may transfer tokens
     * @return The number of tokens allowed to be spent (-1 means infinite)
     */
    function allowance(address owner, address spender) external view returns (uint256) {
        return transferAllowances[owner][spender];
    }

    /**
     * @notice Get the token balance of the `owner`
     * @param owner The address of the account to query
     * @return The number of tokens owned by `owner`
     */
    function balanceOf(address owner) external view returns (uint256) {
        return accountTokens[owner];
    }


    /**
     * @notice Get a snapshot of the account's balances
     * @dev This is used by controller to more efficiently perform liquidity checks.
     * and for kTokens, there is only token balance, for kMCD, there is only borrow balance
     * @param account Address of the account to snapshot
     * @return (token balance, borrow balance)
     */
    function getAccountSnapshot(address account) external view returns (uint, uint) {
        return (accountTokens[account], 0);
    }

    /**
     * @dev Function to simply retrieve block number
     *  This exists mainly for inheriting test contracts to stub this result.
     */
    function getBlockNumber() internal view returns (uint) {
        return block.number;
    }

    /**
     * @notice Get cash balance of this kToken in the underlying asset
     * @return The quantity of underlying asset owned by this contract
     */
    function getCash() external view returns (uint) {
        return getCashPrior();
    }

    /**
     * @notice Sender supplies assets into the market and receives kTokens in exchange
     * @param mintAmount The amount of the underlying asset to supply
     * @return the actual mint amount.
     */
    function mintInternal(uint mintAmount) internal nonReentrant returns (uint) {
        return mintFresh(msg.sender, mintAmount);
    }

    struct MintLocalVars {
        uint mintTokens;
        uint totalSupplyNew;
        uint accountTokensNew;
        uint actualMintAmount;
    }

    /**
     * @notice User supplies assets into the market and receives kTokens in exchange
     * @param minter The address of the account which is supplying the assets
     * @param mintAmount The amount of the underlying asset to supply
     * @return the actual mint amount.
     */
    function mintFresh(address minter, uint mintAmount) internal returns (uint) {
        /* Fail if mint not allowed */
        (bool allowed, string memory reason) = controller.mintAllowed(address(this), minter, mintAmount);
        require(allowed, reason);

        MintLocalVars memory vars;

        /////////////////////////
        // EFFECTS & INTERACTIONS

        /*
         *  We call `doTransferIn` for the minter and the mintAmount.
         *  Note: The kToken must handle variations between ERC-20 and ETH underlying.
         *  `doTransferIn` reverts if anything goes wrong, since we can't be sure if
         *  side-effects occurred. The function returns the amount actually transferred,
         *  in case of a fee. On success, the kToken holds an additional `actualMintAmount`
         *  of cash.
         */
        vars.actualMintAmount = doTransferIn(minter, mintAmount);

        /*
         *  mintTokens = actualMintAmount
         */
        vars.mintTokens = vars.actualMintAmount;

        /*
         * We calculate the new total supply of kTokens and minter token balance, checking for overflow:
         *  totalSupplyNew = totalSupply + mintTokens
         *  accountTokensNew = accountTokens[minter] + mintTokens
         */
        vars.totalSupplyNew = totalSupply.add(vars.mintTokens, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
        vars.accountTokensNew = accountTokens[minter].add(vars.mintTokens, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED);

        /* We write previously calculated values into storage */
        totalSupply = vars.totalSupplyNew;
        accountTokens[minter] = vars.accountTokensNew;

        /* We emit a Mint event, and a Transfer event */
        emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
        emit Transfer(address(this), minter, vars.mintTokens);

        /* We call the defense hook */
        controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);

        return vars.actualMintAmount;
    }

    /**
     * @notice Sender redeems kTokens in exchange for the underlying asset
     * @param redeemTokens The number of kTokens to redeem into underlying
     */
    function redeemInternal(uint redeemTokens) internal nonReentrant {
        redeemFresh(msg.sender, redeemTokens);
    }

    struct RedeemLocalVars {
        uint totalSupplyNew;
        uint accountTokensNew;
    }

    /**
     * @notice User redeems kTokens in exchange for the underlying asset
     * @param redeemer The address of the account which is redeeming the tokens
     * @param redeemTokensIn The number of kTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
     */
    function redeemFresh(address payable redeemer, uint redeemTokensIn) internal {
        require(redeemTokensIn != 0, "redeemTokensIn must not be zero");

        RedeemLocalVars memory vars;

        /* Fail if redeem not allowed */
        (bool allowed, string memory reason) = controller.redeemAllowed(address(this), redeemer, redeemTokensIn);
        require(allowed, reason);

        /*
         * We calculate the new total supply and redeemer balance, checking for underflow:
         *  totalSupplyNew = totalSupply - redeemTokens
         *  accountTokensNew = accountTokens[redeemer] - redeemTokens
         */
        vars.totalSupplyNew = totalSupply.sub(redeemTokensIn, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);

        vars.accountTokensNew = accountTokens[redeemer].sub(redeemTokensIn, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED);

        /* Fail gracefully if protocol has insufficient cash */
        require(getCashPrior() >= redeemTokensIn, TOKEN_INSUFFICIENT_CASH);

        /////////////////////////
        // EFFECTS & INTERACTIONS

        /* We write previously calculated values into storage */
        totalSupply = vars.totalSupplyNew;
        accountTokens[redeemer] = vars.accountTokensNew;
        /*
         * We invoke doTransferOut for the redeemer and the redeemAmount.
         *  Note: The kToken must handle variations between ERC-20 and ETH underlying.
         *  On success, the kToken has redeemAmount less of cash.
         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
         */
        doTransferOut(redeemer, redeemTokensIn);

        /* We emit a Transfer event, and a Redeem event */
        emit Transfer(redeemer, address(this), redeemTokensIn);
        emit Redeem(redeemer, redeemTokensIn);

        /* We call the defense hook */
        controller.redeemVerify(address(this), redeemer, redeemTokensIn);
    }

    /**
     * @notice Transfers collateral tokens (this market) to the liquidator.
     * @dev Will fail unless called by another kToken during the process of liquidation.
     *  Its absolutely critical to use msg.sender as the borrowed kToken and not a parameter.
     * @param liquidator The account receiving seized collateral
     * @param borrower The account having collateral seized
     * @param seizeTokens The number of kTokens to seize
     */
    function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant {
        seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
    }

    /**
     * @notice Transfers collateral tokens (this market) to the liquidator.
     * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another KToken.
     *  Its absolutely critical to use msg.sender as the seizer kToken and not a parameter.
     * @param seizerToken The contract seizing the collateral (i.e. borrowed kToken)
     * @param liquidator The account receiving seized collateral
     * @param borrower The account having collateral seized
     * @param seizeTokens The number of kTokens to seize
     */
    function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal {
        /* Fail if seize not allowed */
        (bool allowed, string memory reason) = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
        require(allowed, reason);

        /* Fail if borrower = liquidator */
        require(borrower != liquidator, INVALID_ACCOUNT_PAIR);

        /*
         * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
         *  borrowerTokensNew = accountTokens[borrower] - seizeTokens
         *  liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
         */
        uint borrowerTokensNew = accountTokens[borrower].sub(seizeTokens, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED);

        uint liquidatorTokensNew = accountTokens[liquidator].add(seizeTokens, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED);

        /////////////////////////
        // EFFECTS & INTERACTIONS

        /* We write the previously calculated values into storage */
        accountTokens[borrower] = borrowerTokensNew;
        accountTokens[liquidator] = liquidatorTokensNew;

        /* Emit a Transfer event */
        emit Transfer(borrower, liquidator, seizeTokens);

        /* We call the defense hook */
        controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
    }


    /*** Admin Functions ***/

    /**
      * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
      * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
      * @param newPendingAdmin New pending admin.
      */
    function _setPendingAdmin(address payable newPendingAdmin) external onlyAdmin() {
        address oldPendingAdmin = pendingAdmin;
        pendingAdmin = newPendingAdmin;
        emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
    }

    /**
      * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
      * @dev Admin function for pending admin to accept role and update admin
      */
    function _acceptAdmin() external {
        // Check caller is pendingAdmin and pendingAdmin ≠ address(0)
        require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized");

        // Save current values for inclusion in log
        address oldAdmin = admin;
        address oldPendingAdmin = pendingAdmin;

        // Store admin with value pendingAdmin
        admin = pendingAdmin;

        // Clear the pending value
        pendingAdmin = address(0);

        emit NewAdmin(oldAdmin, admin);
        emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
    }

    /**
      * @notice Sets a new controller for the market
      * @dev Admin function to set a new controller
      */
    function _setController(KineControllerInterface newController) public onlyAdmin() {
        KineControllerInterface oldController = controller;
        // Ensure invoke controller.isController() returns true
        require(newController.isController(), "marker method returned false");

        // Set market's controller to newController
        controller = newController;

        // Emit NewController(oldController, newController)
        emit NewController(oldController, newController);
    }

    /**
     * @notice Gets balance of this contract in terms of the underlying
     * @dev This excludes the value of the current message, if any
     * @return The quantity of underlying owned by this contract
     */
    function getCashPrior() internal view returns (uint);

    /**
     * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
     *  This may revert due to insufficient balance or insufficient allowance.
     */
    function doTransferIn(address from, uint amount) internal returns (uint);

    /**
     * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
     *  If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
     *  If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
     */
    function doTransferOut(address payable to, uint amount) internal;


    /*** Reentrancy Guard ***/

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     */
    modifier nonReentrant() {
        require(_notEntered, "re-entered");
        _notEntered = false;
        _;
        _notEntered = true;
        // get a gas-refund post-Istanbul
    }
}

File 10 of 15 : KTokenInterfaces.sol
pragma solidity ^0.5.16;

import "./KineControllerInterface.sol";

contract KTokenStorage {
    /**
     * @dev Guard variable for re-entrancy checks
     */
    bool internal _notEntered;

    /**
    * @notice flag that kToken has been initialized;
    */
    bool public initialized;

    /**
     * @notice EIP-20 token name for this token
     */
    string public name;

    /**
     * @notice EIP-20 token symbol for this token
     */
    string public symbol;

    /**
     * @notice EIP-20 token decimals for this token
     */
    uint8 public decimals;

    /**
     * @notice Administrator for this contract
     */
    address payable public admin;

    /**
     * @notice Pending administrator for this contract
     */
    address payable public pendingAdmin;

    /**
     * @notice Contract which oversees inter-kToken operations
     */
    KineControllerInterface public controller;

    /**
     * @notice Total number of tokens in circulation
     */
    uint public totalSupply;

    /**
     * @notice Official record of token balances for each account
     */
    mapping (address => uint) internal accountTokens;

    /**
     * @notice Approved token transfer amounts on behalf of others
     */
    mapping (address => mapping (address => uint)) internal transferAllowances;

}

contract KTokenInterface is KTokenStorage {
    /**
     * @notice Indicator that this is a KToken contract (for inspection)
     */
    bool public constant isKToken = true;


    /*** Market Events ***/

    /**
     * @notice Event emitted when tokens are minted
     */
    event Mint(address minter, uint mintAmount, uint mintTokens);

    /**
     * @notice Event emitted when tokens are redeemed
     */
    event Redeem(address redeemer, uint redeemTokens);


    /*** Admin Events ***/

    /**
     * @notice Event emitted when pendingAdmin is changed
     */
    event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);

    /**
     * @notice Event emitted when pendingAdmin is accepted, which means admin is updated
     */
    event NewAdmin(address oldAdmin, address newAdmin);

    /**
     * @notice Event emitted when controller is changed
     */
    event NewController(KineControllerInterface oldController, KineControllerInterface newController);

    /**
     * @notice EIP20 Transfer event
     */
    event Transfer(address indexed from, address indexed to, uint amount);

    /**
     * @notice EIP20 Approval event
     */
    event Approval(address indexed owner, address indexed spender, uint amount);


    /*** User Interface ***/

    function transfer(address dst, uint amount) external returns (bool);
    function transferFrom(address src, address dst, uint amount) external returns (bool);
    function approve(address spender, uint amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function getAccountSnapshot(address account) external view returns (uint, uint);
    function getCash() external view returns (uint);
    function seize(address liquidator, address borrower, uint seizeTokens) external;


    /*** Admin Functions ***/

    function _setPendingAdmin(address payable newPendingAdmin) external;
    function _acceptAdmin() external;
    function _setController(KineControllerInterface newController) public;
}

contract KErc20Storage {
    /**
     * @notice Underlying asset for this KToken
     */
    address public underlying;
}

contract KErc20Interface is KErc20Storage {

    /*** User Interface ***/

    function mint(uint mintAmount) external returns (uint);
    function redeem(uint redeemTokens) external;

}

contract KDelegationStorage {
    /**
     * @notice Implementation address for this contract
     */
    address public implementation;
}

contract KDelegatorInterface is KDelegationStorage {
    /**
     * @notice Emitted when implementation is changed
     */
    event NewImplementation(address oldImplementation, address newImplementation);

    /**
     * @notice Called by the admin to update the implementation of the delegator
     * @param implementation_ The address of the new implementation for delegation
     * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
     * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
     */
    function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}

contract KDelegateInterface is KDelegationStorage {
    /**
     * @notice Called by the delegator on a delegate to initialize it for duty
     * @dev Should revert if any issues arise which make it unfit for delegation
     * @param data The encoded bytes data for any initialization
     */
    function _becomeImplementation(bytes memory data) public;

    /**
     * @notice Called by the delegator on a delegate to forfeit its responsibility
     */
    function _resignImplementation() public;
}

File 11 of 15 : KineControllerInterface.sol
pragma solidity ^0.5.16;

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerInterface.sol
* Modified to work in the Kine system.
* Main modifications:
*   1. removed Comp token related logics.
*   2. removed interest rate model related logics.
*   3. removed error code propagation mechanism to fail fast and loudly
*/

contract KineControllerInterface {
    /// @notice Indicator that this is a Controller contract (for inspection)
    bool public constant isController = true;

    /// @notice oracle getter function
    function getOracle() external view returns (address);

    /*** Assets You Are In ***/

    function enterMarkets(address[] calldata kTokens) external;

    function exitMarket(address kToken) external;

    /*** Policy Hooks ***/

    function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool, string memory);

    function mintVerify(address kToken, address minter, uint mintAmount, uint mintTokens) external;

    function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool, string memory);

    function redeemVerify(address kToken, address redeemer, uint redeemTokens) external;

    function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool, string memory);

    function borrowVerify(address kToken, address borrower, uint borrowAmount) external;

    function repayBorrowAllowed(
        address kToken,
        address payer,
        address borrower,
        uint repayAmount) external returns (bool, string memory);

    function repayBorrowVerify(
        address kToken,
        address payer,
        address borrower,
        uint repayAmount) external;

    function liquidateBorrowAllowed(
        address kTokenBorrowed,
        address kTokenCollateral,
        address liquidator,
        address borrower,
        uint repayAmount) external returns (bool, string memory);

    function liquidateBorrowVerify(
        address kTokenBorrowed,
        address kTokenCollateral,
        address liquidator,
        address borrower,
        uint repayAmount,
        uint seizeTokens) external;

    function seizeAllowed(
        address kTokenCollateral,
        address kTokenBorrowed,
        address liquidator,
        address borrower,
        uint seizeTokens) external returns (bool, string memory);

    function seizeVerify(
        address kTokenCollateral,
        address kTokenBorrowed,
        address liquidator,
        address borrower,
        uint seizeTokens) external;

    function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool, string memory);

    function transferVerify(address kToken, address src, address dst, uint transferTokens) external;

    /*** Liquidity/Liquidation Calculations ***/

    function liquidateCalculateSeizeTokens(
        address target,
        address kTokenBorrowed,
        address kTokenCollateral,
        uint repayAmount) external view returns (uint);
}

File 12 of 15 : KineOracleInterface.sol
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;

/**
 * @title KineOracleInterface brief abstraction of Price Oracle
 */
interface KineOracleInterface {

    /**
     * @notice Get the underlying collateral price of given kToken.
     * @dev Returned kToken underlying price is scaled by 1e(36 - underlying token decimals)
     */
    function getUnderlyingPrice(address kToken) external view returns (uint);

    /**
     * @notice Post prices of tokens owned by Kine.
     * @param messages Signed price data of tokens
     * @param signatures Signatures used to recover reporter public key
     * @param symbols Token symbols
     */
    function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external;

    /**
     * @notice Post Kine MCD price.
     */
    function postMcdPrice(uint mcdPrice) external;

    /**
     * @notice Get the reporter address.
     */
    function reporter() external returns (address);
}

File 13 of 15 : KineSafeMath.sol
pragma solidity ^0.5.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */

/**
 * Original work from OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol
 * changes we made:
 * 1. add two methods that take errorMessage as input parameter
 */

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

        return c;
    }

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

        return c;
    }

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

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     * - Subtraction cannot overflow.
     *
     * _Available since v2.4.0._
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

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

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

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

        uint256 c = a * b;
        require(c / a == b, errorMessage);

        return c;
    }

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

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     *
     * _Available since v2.4.0._
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        // Solidity only automatically asserts when dividing by 0
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

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

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     *
     * _Available since v2.4.0._
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

File 14 of 15 : Math.sol
pragma solidity ^0.5.0;

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

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

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

File 15 of 15 : Unitroller.sol
pragma solidity ^0.5.16;

import "./ErrorReporter.sol";
import "./ControllerStorage.sol";

/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @title ControllerCore
 * @dev Storage for the controller is at this address, while execution is delegated to the `controllerImplementation`.
 * KTokens should reference this contract as their controller.
 */
contract Unitroller is UnitrollerAdminStorage {

    /**
      * @notice Emitted when pendingControllerImplementation is changed
      */
    event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);

    /**
      * @notice Emitted when pendingControllerImplementation is accepted, which means controller implementation is updated
      */
    event NewImplementation(address oldImplementation, address newImplementation);

    /**
      * @notice Emitted when pendingAdmin is changed
      */
    event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);

    /**
      * @notice Emitted when pendingAdmin is accepted, which means admin is updated
      */
    event NewAdmin(address oldAdmin, address newAdmin);

    constructor() public {
        // Set admin to caller
        admin = msg.sender;
    }

    /*** Admin Functions ***/
    function _setPendingImplementation(address newPendingImplementation) public {
        require(msg.sender == admin, "unauthorized");

        address oldPendingImplementation = pendingControllerImplementation;

        pendingControllerImplementation = newPendingImplementation;

        emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
    }

    /**
    * @notice Accepts new implementation of controller. msg.sender must be pendingImplementation
    * @dev Admin function for new implementation to accept it's role as implementation
    */
    function _acceptImplementation() public {
        // Check caller is pendingImplementation and pendingImplementation ≠ address(0)
        require(pendingControllerImplementation != address(0) && msg.sender == pendingControllerImplementation, "unauthorized");

        // Save current values for inclusion in log
        address oldImplementation = controllerImplementation;
        address oldPendingImplementation = pendingControllerImplementation;

        controllerImplementation = pendingControllerImplementation;

        pendingControllerImplementation = address(0);

        emit NewImplementation(oldImplementation, controllerImplementation);
        emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
    }


    /**
      * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
      * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
      * @param newPendingAdmin New pending admin.
      */
    function _setPendingAdmin(address newPendingAdmin) public {
        require(msg.sender == admin, "unauthorized");

        // Save current value, if any, for inclusion in log
        address oldPendingAdmin = pendingAdmin;

        // Store pendingAdmin with value newPendingAdmin
        pendingAdmin = newPendingAdmin;

        // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
        emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
    }

    /**
      * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
      * @dev Admin function for pending admin to accept role and update admin
      */
    function _acceptAdmin() public {
        require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized");

        // Save current values for inclusion in log
        address oldAdmin = admin;
        address oldPendingAdmin = pendingAdmin;

        // Store admin with value pendingAdmin
        admin = pendingAdmin;

        // Clear the pending value
        pendingAdmin = address(0);

        emit NewAdmin(oldAdmin, admin);
        emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
    }

    /**
     * @dev Delegates execution to an implementation contract.
     * It returns to the external caller whatever the implementation returns
     * or forwards reverts.
     */
    function () payable external {
        // delegate all other functions to current implementation
        (bool success, ) = controllerImplementation.delegatecall(msg.data);

        assembly {
              let free_mem_ptr := mload(0x40)
              returndatacopy(free_mem_ptr, 0, returndatasize)

              switch success
              case 0 { revert(free_mem_ptr, returndatasize) }
              default { return(free_mem_ptr, returndatasize) }
        }
    }
}

Settings
{
  "remappings": [],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "evmVersion": "istanbul",
  "libraries": {},
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"action","type":"string"},{"indexed":false,"internalType":"bool","name":"pauseState","type":"bool"}],"name":"ActionPaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract KToken","name":"kToken","type":"address"},{"indexed":false,"internalType":"string","name":"action","type":"string"},{"indexed":false,"internalType":"bool","name":"pauseState","type":"bool"}],"name":"ActionPaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract KToken","name":"kToken","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"MarketEntered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract KToken","name":"kToken","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"MarketExited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract KToken","name":"kToken","type":"address"}],"name":"MarketListed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract KToken","name":"kToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"newBorrowCap","type":"uint256"}],"name":"NewBorrowCap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldCapGuardian","type":"address"},{"indexed":false,"internalType":"address","name":"newCapGuardian","type":"address"}],"name":"NewCapGuardian","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldCloseFactorMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newCloseFactorMantissa","type":"uint256"}],"name":"NewCloseFactor","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract KToken","name":"kToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"oldCollateralFactorMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newCollateralFactorMantissa","type":"uint256"}],"name":"NewCollateralFactor","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldLiquidationIncentiveMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newLiquidationIncentiveMantissa","type":"uint256"}],"name":"NewLiquidationIncentive","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldPauseGuardian","type":"address"},{"indexed":false,"internalType":"address","name":"newPauseGuardian","type":"address"}],"name":"NewPauseGuardian","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract KineOracleInterface","name":"oldPriceOracle","type":"address"},{"indexed":false,"internalType":"contract KineOracleInterface","name":"newPriceOracle","type":"address"}],"name":"NewPriceOracle","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldRedemptionInitialPunishmentMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRedemptionInitialPunishmentMantissa","type":"uint256"}],"name":"NewRedemptionInitialPunishment","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract KToken","name":"kToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"newSupplyCap","type":"uint256"}],"name":"NewSupplyCap","type":"event"},{"constant":false,"inputs":[{"internalType":"contract Unitroller","name":"unitroller","type":"address"}],"name":"_become","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract KToken","name":"kToken","type":"address"},{"internalType":"bool","name":"state","type":"bool"}],"name":"_setBorrowPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newCapGuardian","type":"address"}],"name":"_setCapGuardian","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"newCloseFactorMantissa","type":"uint256"}],"name":"_setCloseFactor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract KToken","name":"kToken","type":"address"},{"internalType":"uint256","name":"newCollateralFactorMantissa","type":"uint256"}],"name":"_setCollateralFactor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"newLiquidationIncentiveMantissa","type":"uint256"}],"name":"_setLiquidationIncentive","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract KToken[]","name":"kTokens","type":"address[]"},{"internalType":"uint256[]","name":"newBorrowCaps","type":"uint256[]"}],"name":"_setMarketBorrowCaps","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract KToken[]","name":"kTokens","type":"address[]"},{"internalType":"uint256[]","name":"newSupplyCaps","type":"uint256[]"}],"name":"_setMarketSupplyCaps","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract KToken","name":"kToken","type":"address"},{"internalType":"bool","name":"state","type":"bool"}],"name":"_setMintPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newPauseGuardian","type":"address"}],"name":"_setPauseGuardian","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract KineOracleInterface","name":"newOracle","type":"address"}],"name":"_setPriceOracle","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"newRedemptionInitialPunishmentMantissa","type":"uint256"}],"name":"_setRedemptionInitialPunishment","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bool","name":"state","type":"bool"}],"name":"_setRedemptionPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract KToken","name":"kToken","type":"address"},{"internalType":"bool","name":"state","type":"bool"}],"name":"_setRedemptionPausedPerAsset","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bool","name":"state","type":"bool"}],"name":"_setSeizePaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bool","name":"state","type":"bool"}],"name":"_setTransferPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract KToken","name":"kToken","type":"address"}],"name":"_supportMarket","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"accountAssets","outputs":[{"internalType":"contract KToken","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"allMarkets","outputs":[{"internalType":"contract KToken","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"borrowAllowed","outputs":[{"internalType":"bool","name":"allowed","type":"bool"},{"internalType":"string","name":"reason","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"borrowCaps","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"borrowGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"borrowVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"capGuardian","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract KToken","name":"kToken","type":"address"}],"name":"checkMembership","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"closeFactorMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"controllerImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address[]","name":"kTokens","type":"address[]"}],"name":"enterMarkets","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kTokenAddress","type":"address"}],"name":"exitMarket","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAllMarkets","outputs":[{"internalType":"contract KToken[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAssetsIn","outputs":[{"internalType":"contract KToken[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getBlockNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"kTokenModify","type":"address"},{"internalType":"uint256","name":"redeemTokens","type":"uint256"},{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"getHypotheticalAccountLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOracle","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isController","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kTokenBorrowed","type":"address"},{"internalType":"address","name":"kTokenCollateral","type":"address"},{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"liquidateBorrowAllowed","outputs":[{"internalType":"bool","name":"allowed","type":"bool"},{"internalType":"string","name":"reason","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kTokenBorrowed","type":"address"},{"internalType":"address","name":"kTokenCollateral","type":"address"},{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"actualRepayAmount","type":"uint256"},{"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"liquidateBorrowVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"address","name":"kTokenBorrowed","type":"address"},{"internalType":"address","name":"kTokenCollateral","type":"address"},{"internalType":"uint256","name":"actualRepayAmount","type":"uint256"}],"name":"liquidateCalculateSeizeTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"liquidationIncentiveMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"markets","outputs":[{"internalType":"bool","name":"isListed","type":"bool"},{"internalType":"uint256","name":"collateralFactorMantissa","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maxAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"minter","type":"address"},{"internalType":"uint256","name":"mintAmount","type":"uint256"}],"name":"mintAllowed","outputs":[{"internalType":"bool","name":"allowed","type":"bool"},{"internalType":"string","name":"reason","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"mintGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"minter","type":"address"},{"internalType":"uint256","name":"actualMintAmount","type":"uint256"},{"internalType":"uint256","name":"mintTokens","type":"uint256"}],"name":"mintVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"oracle","outputs":[{"internalType":"contract KineOracleInterface","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"pauseGuardian","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"pendingAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"pendingControllerImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"redeemer","type":"address"},{"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"redeemAllowed","outputs":[{"internalType":"bool","name":"allowed","type":"bool"},{"internalType":"string","name":"reason","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"redeemer","type":"address"},{"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"redeemVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"redemptionInitialPunishmentMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"redemptionPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"redemptionPausedPerAsset","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"payer","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"repayBorrowAllowed","outputs":[{"internalType":"bool","name":"allowed","type":"bool"},{"internalType":"string","name":"reason","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"payer","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"actualRepayAmount","type":"uint256"}],"name":"repayBorrowVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kTokenCollateral","type":"address"},{"internalType":"address","name":"kTokenBorrowed","type":"address"},{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"seizeAllowed","outputs":[{"internalType":"bool","name":"allowed","type":"bool"},{"internalType":"string","name":"reason","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"seizeGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kTokenCollateral","type":"address"},{"internalType":"address","name":"kTokenBorrowed","type":"address"},{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"seizeVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"supplyCaps","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"src","type":"address"},{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"transferTokens","type":"uint256"}],"name":"transferAllowed","outputs":[{"internalType":"bool","name":"allowed","type":"bool"},{"internalType":"string","name":"reason","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"transferGuardianPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"kToken","type":"address"},{"internalType":"address","name":"src","type":"address"},{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"transferTokens","type":"uint256"}],"name":"transferVerify","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]

608060405234801561001057600080fd5b50600080546001600160a01b031916331790556145f3806100326000396000f3fe608060405234801561001057600080fd5b50600436106103d05760003560e01c80636d154ea5116101ff578063a76b3fda1161011a578063dce15449116100ad578063ede4edd01161007c578063ede4edd014610f28578063efcb03dd14610a96578063f13df66e14610f4e578063f851a44014610f74576103d0565b8063dce1544914610e92578063e4028eee14610ebe578063e875544614610eea578063eabe7d9114610ef2576103d0565b8063bdcdc258116100e9578063bdcdc25814610d39578063c299823814610d75578063d02f735114610e16578063da3d454c14610e5c576103d0565b8063a76b3fda14610c8d578063abfceffc14610cb3578063ac0b0bb714610d29578063b0772d0b14610d31576103d0565b806388824a6111610192578063929fe9a111610161578063929fe9a114610c4757806394b2294b14610c755780639788e73114610c7d57806399a8761614610c85576103d0565b806388824a6114610bc25780638e6c095914610bdf5780638e8f294b14610be75780638ebf636414610c28576103d0565b806373a95ddd116101ce57806373a95ddd14610ba25780637dc0d1d014610baa578063833b1fce14610bb257806387f7630314610bba576103d0565b80636d154ea514610b085780636d35bf9114610b2e578063731f0c2b14610b74578063738ec42214610b9a576103d0565b80634ada90af116102ef5780635682992e116102825780635fc7e71e116102515780635fc7e71e14610992578063607ef6c1146109d85780636a56947e14610a965780636c8bb09814610ad2576103d0565b80635682992e146108c45780635c778605146108ea5780635ec88c79146109205780635f5af1aa1461096c576103d0565b80634fd42e17116102be5780634fd42e17146107a657806351a485e4146107c357806352d84d1e1461088157806355ee1fe11461089e576103d0565b80634ada90af1461070b5780634e1647fb146107135780634e79238f1461071b5780634ef4c3e114610770576103d0565b8063267822471161036757806341c728b91161033657806341c728b91461065557806342cbb15c1461069157806347ef3b3b146106995780634a584432146106e5576103d0565b806326782247146105e35780632d70db78146105eb578063317b0b771461060a5780633bcf7ec114610627576103d0565b80631d504dc6116103a35780631d504dc6146104aa5780631d787d09146104d257806324008a621461050057806324a3d622146105bf576103d0565b806302c3bcbb146103d55780630636962c1461040d5780630ef332ca1461044057806318c882a51461047c575b600080fd5b6103fb600480360360208110156103eb57600080fd5b50356001600160a01b0316610f7c565b60408051918252519081900360200190f35b61042c6004803603602081101561042357600080fd5b50351515610f8e565b604080519115158252519081900360200190f35b6103fb6004803603608081101561045657600080fd5b506001600160a01b03813581169160208101358216916040820135169060600135611058565b61042c6004803603604081101561049257600080fd5b506001600160a01b03813516906020013515156113f2565b6104d0600480360360208110156104c057600080fd5b50356001600160a01b031661152d565b005b61042c600480360360408110156104e857600080fd5b506001600160a01b038135169060200135151561162e565b61053c6004803603608081101561051657600080fd5b506001600160a01b0381358116916020810135821691604082013516906060013561176a565b604051808315151515815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561058357818101518382015260200161056b565b50505050905090810190601f1680156105b05780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b6105c76117c9565b604080516001600160a01b039092168252519081900360200190f35b6105c76117d8565b61042c6004803603602081101561060157600080fd5b503515156117e7565b6104d06004803603602081101561062057600080fd5b50356118b8565b61042c6004803603604081101561063d57600080fd5b506001600160a01b0381351690602001351515611a8a565b6104d06004803603608081101561066b57600080fd5b506001600160a01b03813581169160208101359091169060408101359060600135611bc0565b6103fb611bc6565b6104d0600480360360c08110156106af57600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060808101359060a00135611bcb565b6103fb600480360360208110156106fb57600080fd5b50356001600160a01b0316611bd3565b6103fb611be5565b61042c611beb565b6107576004803603608081101561073157600080fd5b506001600160a01b03813581169160208101359091169060408101359060600135611bf0565b6040805192835260208301919091528051918290030190f35b61053c6004803603606081101561078657600080fd5b506001600160a01b03813581169160208101359091169060400135611c13565b6104d0600480360360208110156107bc57600080fd5b5035611dae565b6104d0600480360360408110156107d957600080fd5b810190602081018135600160201b8111156107f357600080fd5b82018360208201111561080557600080fd5b803590602001918460208302840111600160201b8311171561082657600080fd5b919390929091602081019035600160201b81111561084357600080fd5b82018360208201111561085557600080fd5b803590602001918460208302840111600160201b8311171561087657600080fd5b509092509050611f56565b6105c76004803603602081101561089757600080fd5b50356120e6565b6104d0600480360360208110156108b457600080fd5b50356001600160a01b031661210d565b61042c600480360360208110156108da57600080fd5b50356001600160a01b03166121b9565b6104d06004803603606081101561090057600080fd5b506001600160a01b038135811691602081013590911690604001356121ce565b6109466004803603602081101561093657600080fd5b50356001600160a01b03166121d3565b604080519485526020850193909352838301919091526060830152519081900360800190f35b6104d06004803603602081101561098257600080fd5b50356001600160a01b03166121f6565b61053c600480360360a08110156109a857600080fd5b506001600160a01b03813581169160208101358216916040820135811691606081013590911690608001356122a1565b6104d0600480360360408110156109ee57600080fd5b810190602081018135600160201b811115610a0857600080fd5b820183602082011115610a1a57600080fd5b803590602001918460208302840111600160201b83111715610a3b57600080fd5b919390929091602081019035600160201b811115610a5857600080fd5b820183602082011115610a6a57600080fd5b803590602001918460208302840111600160201b83111715610a8b57600080fd5b509092509050612524565b6104d060048036036080811015610aac57600080fd5b506001600160a01b03813581169160208101358216916040820135169060600135611bc0565b6104d060048036036060811015610ae857600080fd5b506001600160a01b038135811691602081013590911690604001356126ab565b61042c60048036036020811015610b1e57600080fd5b50356001600160a01b0316612720565b6104d0600480360360a0811015610b4457600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060800135612735565b61042c60048036036020811015610b8a57600080fd5b50356001600160a01b031661273a565b6105c761274f565b61042c61275e565b6105c7612767565b6105c7612776565b61042c612785565b6104d060048036036020811015610bd857600080fd5b5035612795565b6105c7612825565b610c0d60048036036020811015610bfd57600080fd5b50356001600160a01b0316612834565b60408051921515835260208301919091528051918290030190f35b61042c60048036036020811015610c3e57600080fd5b50351515612853565b61042c60048036036040811015610c5d57600080fd5b506001600160a01b0381358116916020013516612927565b6103fb61295a565b6105c7612960565b6103fb61296f565b6104d060048036036020811015610ca357600080fd5b50356001600160a01b0316612975565b610cd960048036036020811015610cc957600080fd5b50356001600160a01b0316612b43565b60408051602080825283518183015283519192839290830191858101910280838360005b83811015610d15578181015183820152602001610cfd565b505050509050019250505060405180910390f35b61042c612bcc565b610cd9612bdc565b61053c60048036036080811015610d4f57600080fd5b506001600160a01b03813581169160208101358216916040820135169060600135612c3e565b6104d060048036036020811015610d8b57600080fd5b810190602081018135600160201b811115610da557600080fd5b820183602082011115610db757600080fd5b803590602001918460208302840111600160201b83111715610dd857600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612c9e945050505050565b61053c600480360360a0811015610e2c57600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060800135612cd6565b61053c60048036036060811015610e7257600080fd5b506001600160a01b03813581169160208101359091169060400135612eb8565b6105c760048036036040811015610ea857600080fd5b506001600160a01b03813516906020013561322a565b6104d060048036036040811015610ed457600080fd5b506001600160a01b03813516906020013561325f565b6103fb613525565b61053c60048036036060811015610f0857600080fd5b506001600160a01b0381358116916020810135909116906040013561352b565b6104d060048036036020811015610f3e57600080fd5b50356001600160a01b0316613546565b6104d060048036036020811015610f6457600080fd5b50356001600160a01b0316613914565b6105c76139c0565b60106020526000908152604090205481565b600b546000906001600160a01b0316331480610fb457506000546001600160a01b031633145b610fef5760405162461bcd60e51b815260040180806020018281038252602f8152602001806144a3602f913960400191505060405180910390fd5b6011805483151560ff199091168117909155604080516020810192909252808252600a82820152692932b232b6b83a34b7b760b11b6060830152517fef159d9a32b2472e32b098f954f3ce62d232939f1c207070b584df1814de2de09181900360800190a15090565b600480546040805163fc57d4df60e01b81526001600160a01b038781169482019490945290516000938493169163fc57d4df916024808301926020929190829003018186803b1580156110aa57600080fd5b505afa1580156110be573d6000803e3d6000fd5b505050506040513d60208110156110d457600080fd5b5051600480546040805163fc57d4df60e01b81526001600160a01b03898116948201949094529051939450600093929091169163fc57d4df91602480820192602092909190829003018186803b15801561112d57600080fd5b505afa158015611141573d6000803e3d6000fd5b505050506040513d602081101561115757600080fd5b50519050811580159061116957508015155b6111a8576040805162461bcd60e51b815260206004820152600b60248201526a383934b1b29032b93937b960a91b604482015290519081900360640190fd5b6001600160a01b038516600090815260096020526040812060010154908080806111d18c6121d3565b935093509350935060008084111561128157600061121f87611207670de0b6b3a764000061121387838b8463ffffffff6139cf16565b9063ffffffff613a2f16565b9063ffffffff6139cf16565b9050611279611251670de0b6b3a76400006112456002611207838d63ffffffff613a7116565b9063ffffffff613ab316565b60065461127490611245670de0b6b3a7640000611207878063ffffffff6139cf16565b613b0d565b9150506113ab565b60115460ff16156112cd576040805162461bcd60e51b8152602060048201526011602482015270149959195b5c1d1a5bdb881c185d5cd959607a1b604482015290519081900360640190fd5b6001600160a01b038b1660009081526013602052604090205460ff161561133b576040805162461bcd60e51b815260206004820152601760248201527f417373657420526564656d7074696f6e20706175736564000000000000000000604482015290519081900360640190fd5b600061135f670de0b6b3a76400006112078961121387838c8663ffffffff6139cf16565b90506113a7611392611383670de0b6b3a7640000611207858063ffffffff6139cf16565b6012549063ffffffff613ab316565b670de0b6b3a76400009063ffffffff613a7116565b9150505b6113b36143f0565b6113d46113c0838b613b23565b60405180602001604052808b815250613b51565b90506113e0818c613b67565b9e9d5050505050505050505050505050565b6001600160a01b03821660009081526009602052604081205460ff166114495760405162461bcd60e51b81526004018080602001828103825260288152602001806144d26028913960400191505060405180910390fd5b600b546001600160a01b031633148061146c57506000546001600160a01b031633145b6114a75760405162461bcd60e51b815260040180806020018281038252602f8152602001806144a3602f913960400191505060405180910390fd5b6001600160a01b0383166000818152600e6020908152604091829020805486151560ff199091168117909155825193845283830152606090830181905260069083015265426f72726f7760d01b6080830152517f71aec636243f9709bb0007ae15e9afb8150ab01716d75fd7573be5cc096e03b09181900360a00190a150805b92915050565b806001600160a01b031663f851a4406040518163ffffffff1660e01b815260040160206040518083038186803b15801561156657600080fd5b505afa15801561157a573d6000803e3d6000fd5b505050506040513d602081101561159057600080fd5b50516001600160a01b031633146115d85760405162461bcd60e51b81526004018080602001828103825260278152602001806145986027913960400191505060405180910390fd5b806001600160a01b031663c1e803346040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561161357600080fd5b505af1158015611627573d6000803e3d6000fd5b5050505050565b6001600160a01b03821660009081526009602052604081205460ff166116855760405162461bcd60e51b81526004018080602001828103825260288152602001806144d26028913960400191505060405180910390fd5b600b546001600160a01b03163314806116a857506000546001600160a01b031633145b6116e35760405162461bcd60e51b815260040180806020018281038252602f8152602001806144a3602f913960400191505060405180910390fd5b6001600160a01b038316600081815260136020908152604091829020805486151560ff1990911681179091558251938452838301526060908301819052600a90830152692932b232b6b83a34b7b760b11b6080830152517f71aec636243f9709bb0007ae15e9afb8150ab01716d75fd7573be5cc096e03b09181900360a00190a150919050565b6001600160a01b03841660009081526009602052604081205460609060ff166117bb57505060408051808201909152601181527013505492d15517d393d517d31254d51151607a1b60208201526000905b600191505b94509492505050565b600b546001600160a01b031681565b6001546001600160a01b031681565b600b546000906001600160a01b031633148061180d57506000546001600160a01b031633145b6118485760405162461bcd60e51b815260040180806020018281038252602f8152602001806144a3602f913960400191505060405180910390fd5b600c8054831515600160a81b810260ff60a81b1990921691909117909155604080516020810192909252808252600582820152645365697a6560d81b6060830152517fef159d9a32b2472e32b098f954f3ce62d232939f1c207070b584df1814de2de09181900360800190a15090565b6000546001600160a01b031633146119015760405162461bcd60e51b81526004018080602001828103825260218152602001806144fa6021913960400191505060405180910390fd5b60408051808201909152601481527324a72b20a624a22fa1a627a9a2afa320a1aa27a960611b6020820152670c7d713b49da00008211156119c05760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561198557818101518382015260200161196d565b50505050905090810190601f1680156119b25780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060408051808201909152601481527324a72b20a624a22fa1a627a9a2afa320a1aa27a960611b602082015266b1a2bc2ec50000821015611a425760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b506005805490829055604080518281526020810184905281517f3b9670cf975d26958e754b57098eaa2ac914d8d2a31b83257997b9f346110fd9929181900390910190a15050565b6001600160a01b03821660009081526009602052604081205460ff16611ae15760405162461bcd60e51b81526004018080602001828103825260288152602001806144d26028913960400191505060405180910390fd5b600b546001600160a01b0316331480611b0457506000546001600160a01b031633145b611b3f5760405162461bcd60e51b815260040180806020018281038252602f8152602001806144a3602f913960400191505060405180910390fd5b6001600160a01b0383166000818152600d6020908152604091829020805486151560ff199091168117909155825193845283830152606090830181905260049083015263135a5b9d60e21b6080830152517f71aec636243f9709bb0007ae15e9afb8150ab01716d75fd7573be5cc096e03b09181900360a00190a150919050565b50505050565b435b90565b505050505050565b600f6020526000908152604090205481565b60065481565b600181565b600080600080611c0288888888613b8e565b50919a909950975050505050505050565b6001600160a01b0383166000908152600d602052604081205460609060ff1615611c6357505060408051808201909152600b81526a1352539517d4105554d15160aa1b6020820152600090611da6565b6001600160a01b0385166000908152601060205260409020548015611d4d576000866001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015611cbd57600080fd5b505afa158015611cd1573d6000803e3d6000fd5b505050506040513d6020811015611ce757600080fd5b505190506000611cfd828763ffffffff613ab316565b905082811115611d4a57505060408051808201909152601981527f4d41524b45545f535550504c595f4341505f52454143484544000000000000006020820152600093509150611da69050565b50505b6001600160a01b03861660009081526009602052604090205460ff16611da057505060408051808201909152601181527013505492d15517d393d517d31254d51151607a1b602082015260009150611da6565b50600191505b935093915050565b6000546001600160a01b03163314611df75760405162461bcd60e51b81526004018080602001828103825260218152602001806144fa6021913960400191505060405180910390fd5b60408051808201909152601d81527f494e56414c49445f4c49515549444154494f4e5f494e43454e5449564500000060208201526714d1120d7b160000821115611e825760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b5060408051808201909152601d81527f494e56414c49445f4c49515549444154494f4e5f494e43454e544956450000006020820152670de0b6b3a7640000821015611f0e5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b506006805490829055604080518281526020810184905281517faeba5a6c40a8ac138134bff1aaa65debf25971188a58804bad717f82f0ec1316929181900390910190a15050565b6000546001600160a01b0316331480611f795750600c546001600160a01b031633145b611fb45760405162461bcd60e51b815260040180806020018281038252602e81526020018061451b602e913960400191505060405180910390fd5b82818115801590611fc457508082145b612005576040805162461bcd60e51b815260206004820152600d60248201526c1a5b9d985b1a59081a5b9c1d5d609a1b604482015290519081900360640190fd5b60005b828110156120dd5784848281811061201c57fe5b905060200201356010600089898581811061203357fe5b905060200201356001600160a01b03166001600160a01b03166001600160a01b031681526020019081526020016000208190555086868281811061207357fe5b905060200201356001600160a01b03166001600160a01b03167f9e0ad9cee10bdf36b7fbd38910c0bdff0f275ace679b45b922381c2723d676f88686848181106120b957fe5b905060200201356040518082815260200191505060405180910390a2600101612008565b50505050505050565b600a81815481106120f357fe5b6000918252602090912001546001600160a01b0316905081565b6000546001600160a01b031633146121565760405162461bcd60e51b81526004018080602001828103825260218152602001806144fa6021913960400191505060405180910390fd5b600480546001600160a01b038381166001600160a01b0319831681179093556040805191909216808252602082019390935281517fd52b2b9b7e9ee655fcb95d2e5b9e0c9f69e7ef2b8e9d2d0ea78402d576d22e22929181900390910190a15050565b60136020526000908152604090205460ff1681565b505050565b6000806000806121e7856000806000613b8e565b93509350935093509193509193565b6000546001600160a01b0316331461223f5760405162461bcd60e51b81526004018080602001828103825260218152602001806144fa6021913960400191505060405180910390fd5b600b80546001600160a01b038381166001600160a01b0319831617928390556040805192821680845293909116602083015280517f0613b6ee6a04f0d09f390e4d9318894b9f6ac7fd83897cd8d18896ba579c401e9281900390910190a15050565b6001600160a01b03851660009081526009602052604081205460609060ff1615806122e557506001600160a01b03861660009081526009602052604090205460ff16155b1561231c57505060408051808201909152601181527013505492d15517d393d517d31254d51151607a1b602082015260009061251a565b866001600160a01b031663f77c47916040518163ffffffff1660e01b815260040160206040518083038186803b15801561235557600080fd5b505afa158015612369573d6000803e3d6000fd5b505050506040513d602081101561237f57600080fd5b50516040805163f77c479160e01b815290516001600160a01b039283169289169163f77c4791916004808301926020929190829003018186803b1580156123c557600080fd5b505afa1580156123d9573d6000803e3d6000fd5b505050506040513d60208110156123ef57600080fd5b50516001600160a01b0316146124335750506040805180820190915260138152720869e9ca8a49e98988aa4be9a92a69a82a8869606b1b602082015260009061251a565b6000876001600160a01b0316634d73e9ba866040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561248b57600080fd5b505afa15801561249f573d6000803e3d6000fd5b505050506040513d60208110156124b557600080fd5b5051604080516020810190915260055481529091506000906124d79083613b67565b90508085111561251357505060408051808201909152600e81526d544f4f5f4d5543485f524550415960901b602082015260009250905061251a565b5060019250505b9550959350505050565b6000546001600160a01b03163314806125475750600c546001600160a01b031633145b6125825760405162461bcd60e51b815260040180806020018281038252602e81526020018061456a602e913960400191505060405180910390fd5b8281811580159061259257508082145b6125d3576040805162461bcd60e51b815260206004820152600d60248201526c1a5b9d985b1a59081a5b9c1d5d609a1b604482015290519081900360640190fd5b60005b828110156120dd578484828181106125ea57fe5b90506020020135600f600089898581811061260157fe5b905060200201356001600160a01b03166001600160a01b03166001600160a01b031681526020019081526020016000208190555086868281811061264157fe5b905060200201356001600160a01b03166001600160a01b03167f6f1951b2aad10f3fc81b86d91105b413a5b3f847a34bbc5ce1904201b14438f686868481811061268757fe5b905060200201356040518082815260200191505060405180910390a26001016125d6565b60408051808201909152601281527152454445454d5f544f4b454e535f5a45524f60701b602082015281611bc05760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b600e6020526000908152604090205460ff1681565b611627565b600d6020526000908152604090205460ff1681565b600c546001600160a01b031681565b60115460ff1681565b6004546001600160a01b031681565b6004546001600160a01b031690565b600c54600160a01b900460ff1681565b6000546001600160a01b031633146127de5760405162461bcd60e51b81526004018080602001828103825260218152602001806144fa6021913960400191505060405180910390fd5b6012805490829055604080518281526020810184905281517fd2c030cde2165ef6603444b268837adc2a1110f5a0590ec238d7723068708040929181900390910190a15050565b6002546001600160a01b031681565b6009602052600090815260409020805460019091015460ff9091169082565b600b546000906001600160a01b031633148061287957506000546001600160a01b031633145b6128b45760405162461bcd60e51b815260040180806020018281038252602f8152602001806144a3602f913960400191505060405180910390fd5b600c8054831515600160a01b810260ff60a01b1990921691909117909155604080516020810192909252808252600882820152672a3930b739b332b960c11b6060830152517fef159d9a32b2472e32b098f954f3ce62d232939f1c207070b584df1814de2de09181900360800190a15090565b6001600160a01b038082166000908152600960209081526040808320938616835260029093019052205460ff1692915050565b60075481565b6003546001600160a01b031681565b60125481565b6000546001600160a01b031633146129be5760405162461bcd60e51b81526004018080602001828103825260218152602001806144fa6021913960400191505060405180910390fd5b6001600160a01b038116600090815260096020908152604091829020548251808401909352601583527413505492d15517d053149150511657d31254d51151605a1b9183019190915260ff1615612a565760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b50806001600160a01b03166329d9109c6040518163ffffffff1660e01b815260040160206040518083038186803b158015612a9057600080fd5b505afa158015612aa4573d6000803e3d6000fd5b505050506040513d6020811015612aba57600080fd5b50506040805180820182526001808252600060208084018281526001600160a01b038716835260099091529390209151825460ff19169015151782559151910155612b0481613ecd565b604080516001600160a01b038316815290517fcf583bb0c569eb967f806b11601c4cb93c10310485c67add5f8362c2f212321f9181900360200190a150565b60608060086000846001600160a01b03166001600160a01b03168152602001908152602001600020805480602002602001604051908101604052809291908181526020018280548015612bbf57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311612ba1575b5093979650505050505050565b600c54600160a81b900460ff1681565b6060600a805480602002602001604051908101604052809291908181526020018280548015612c3457602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311612c16575b5050505050905090565b600c54600090606090600160a01b900460ff1615612c8657505060408051808201909152600f81526e1514905394d1915497d4105554d151608a1b60208201526000906117c0565b612c91868685613fef565b9150915094509492505050565b805160005b818110156121ce576000838281518110612cb957fe5b60200260200101519050612ccd81336140d3565b50600101612ca3565b600c54600090606090600160a81b900460ff1615612d1b57505060408051808201909152600c81526b14d152569157d4105554d15160a21b602082015260009061251a565b6001600160a01b03871660009081526009602052604090205460ff161580612d5c57506001600160a01b03861660009081526009602052604090205460ff16155b15612d9357505060408051808201909152601181527013505492d15517d393d517d31254d51151607a1b602082015260009061251a565b856001600160a01b031663f77c47916040518163ffffffff1660e01b815260040160206040518083038186803b158015612dcc57600080fd5b505afa158015612de0573d6000803e3d6000fd5b505050506040513d6020811015612df657600080fd5b50516040805163f77c479160e01b815290516001600160a01b03928316928a169163f77c4791916004808301926020929190829003018186803b158015612e3c57600080fd5b505afa158015612e50573d6000803e3d6000fd5b505050506040513d6020811015612e6657600080fd5b50516001600160a01b031614612eaa5750506040805180820190915260138152720869e9ca8a49e98988aa4be9a92a69a82a8869606b1b602082015260009061251a565b600191509550959350505050565b6001600160a01b0383166000908152600e602052604081205460609060ff1615612f0a57505060408051808201909152600d81526c1093d49493d5d7d4105554d151609a1b6020820152600090611da6565b6001600160a01b03851660009081526009602052604090205460ff16612f5c57505060408051808201909152601181527013505492d15517d393d517d31254d51151607a1b6020820152600090611da6565b6001600160a01b038086166000908152600960209081526040808320938816835260029093019052205460ff1661301f57336001600160a01b03861614612fe2576040805162461bcd60e51b815260206004820152601560248201527439b2b73232b91036bab9ba1031329035aa37b5b2b760591b604482015290519081900360640190fd5b612fec33856140d3565b6001600160a01b038086166000908152600960209081526040808320938816835260029093019052205460ff1661301f57fe5b600480546040805163fc57d4df60e01b81526001600160a01b03898116948201949094529051929091169163fc57d4df91602480820192602092909190829003018186803b15801561307057600080fd5b505afa158015613084573d6000803e3d6000fd5b505050506040513d602081101561309a57600080fd5b50516130db576040805162461bcd60e51b815260206004820152600b60248201526a383934b1b29032b93937b960a91b604482015290519081900360640190fd5b6001600160a01b0385166000908152600f602052604090205480156131c5576000866001600160a01b03166347bd37186040518163ffffffff1660e01b815260040160206040518083038186803b15801561313557600080fd5b505afa158015613149573d6000803e3d6000fd5b505050506040513d602081101561315f57600080fd5b505190506000613175828763ffffffff613ab316565b9050828111156131c257505060408051808201909152601981527f4d41524b45545f424f52524f575f4341505f52454143484544000000000000006020820152600093509150611da69050565b50505b60006131d48688600088613b8e565b5050915050600081111561321c575050604080518082019091526016815275494e53554646494349454e545f4c495155494449545960501b6020820152600092509050611da6565b506001925050935093915050565b6008602052816000526040600020818154811061324357fe5b6000918252602090912001546001600160a01b03169150829050565b6000546001600160a01b031633146132a85760405162461bcd60e51b81526004018080602001828103825260218152602001806144fa6021913960400191505060405180910390fd5b6001600160a01b03821660009081526009602090815260409182902080548351808501909452601184527013505492d15517d393d517d31254d51151607a1b92840192909252919060ff1661333e5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b506133476143f0565b50604080516020810190915282815261335e6143f0565b506040805160208101909152670c7d713b49da0000815261337f818361422d565b156040518060400160405280601981526020017f494e56414c49445f434f4c4c41544552414c5f464143544f5200000000000000815250906134025760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b5083158061348b5750600480546040805163fc57d4df60e01b81526001600160a01b03898116948201949094529051929091169163fc57d4df91602480820192602092909190829003018186803b15801561345c57600080fd5b505afa158015613470573d6000803e3d6000fd5b505050506040513d602081101561348657600080fd5b505115155b6134ca576040805162461bcd60e51b815260206004820152600b60248201526a383934b1b29032b93937b960a91b604482015290519081900360640190fd5b60018301805490859055604080516001600160a01b03881681526020810183905280820187905290517f70483e6592cd5182d45ac970e05bc62cdcc90e9d8ef2c2dbe686cf383bcd7fc59181900360600190a1505050505050565b60055481565b6000606061353a858585613fef565b91509150935093915050565b604080516361bfb47160e11b81523360048201528151839260009283926001600160a01b0386169263c37f68e29260248082019391829003018186803b15801561358f57600080fd5b505afa1580156135a3573d6000803e3d6000fd5b505050506040513d60408110156135b957600080fd5b50805160209182015160408051808201909152601881527f455849545f4d41524b45545f42414c414e43455f4f5745440000000000000000938101939093529093509150811561364a5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b506000613658853385613fef565b509050806040518060400160405280601581526020017422ac24aa2fa6a0a925a2aa2fa922a522a1aa24a7a760591b815250906136d65760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b506001600160a01b0384166000908152600960209081526040808320338452600281019092529091205460ff16613711575050505050613911565b3360009081526002820160209081526040808320805460ff19169055600882529182902080548351818402810184019094528084526060939283018282801561378357602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613765575b5050835193945083925060009150505b828110156137d857886001600160a01b03168482815181106137b157fe5b60200260200101516001600160a01b031614156137d0578091506137d8565b600101613793565b5081811061382d576040805162461bcd60e51b815260206004820152601a60248201527f6163636f756e744173736574732061727261792062726f6b656e000000000000604482015290519081900360640190fd5b33600090815260086020526040902080546000190182146138b35780548190600019810190811061385a57fe5b9060005260206000200160009054906101000a90046001600160a01b031681838154811061388457fe5b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b031602179055505b80546138c3826000198301614403565b50604080516001600160a01b038b16815233602082015281517fe699a64c18b07ac5b7301aa273f36a2287239eb9501d81950672794afba29a0d929181900390910190a15050505050505050505b50565b6000546001600160a01b0316331461395d5760405162461bcd60e51b81526004018080602001828103825260218152602001806144fa6021913960400191505060405180910390fd5b600c80546001600160a01b038381166001600160a01b0319831681179093556040805191909216808252602082019390935281517f2f6501e926584583e839a91203ea2e7077edc47c2b928f1f6da8d7dddcaad423929181900390910190a15050565b6000546001600160a01b031681565b6000826139de57506000611527565b828202828482816139eb57fe5b0414613a285760405162461bcd60e51b81526004018080602001828103825260218152602001806145496021913960400191505060405180910390fd5b9392505050565b6000613a2883836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250614234565b6000613a2883836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250614299565b600082820183811015613a28576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b6000818310613b1c5781613a28565b5090919050565b613b2b6143f0565b613a286040518060200160405280858152506040518060200160405280858152506142f3565b613b596143f0565b82518251613a28919061435c565b6000613b716143f0565b613b7b8484614398565b9050613b86816143b5565b949350505050565b600080600080613b9c614427565b6001600160a01b038916600090815260086020908152604091829020805483518184028101840190945280845260609392830182828015613c0657602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613be8575b50939450600093505050505b8151811015613e75576000828281518110613c2957fe5b60200260200101519050806001600160a01b031663c37f68e28d6040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b03168152602001915050604080518083038186803b158015613c8857600080fd5b505afa158015613c9c573d6000803e3d6000fd5b505050506040513d6040811015613cb257600080fd5b508051602091820151608087015260608601526040805180830182526001600160a01b0380851660008181526009865284902060010154835260c089019290925260048054845163fc57d4df60e01b815291820193909352925191169263fc57d4df9260248082019391829003018186803b158015613d3057600080fd5b505afa158015613d44573d6000803e3d6000fd5b505050506040513d6020811015613d5a57600080fd5b505160a08501819052613da2576040805162461bcd60e51b815260206004820152600b60248201526a383934b1b29032b93937b960a91b604482015290519081900360640190fd5b604080516020810190915260a0850151815260e0850181905260c0850151613dc9916142f3565b61010085015260e084015160608501518551613de69291906143c4565b845261010084015160608501516020860151613e039291906143c4565b602085015260e084015160808501516040860151613e229291906143c4565b60408501526001600160a01b03818116908c161415613e6c57613e4f8461010001518b86604001516143c4565b6040850181905260e0850151613e66918b906143c4565b60408501525b50600101613c12565b50816040015182602001511115613ea5575060408101516020820151915190820395506000945092509050613ec2565b506020810151604082015191516000965091819003945090925090505b945094509450949050565b60005b600a54811015613f9c57816001600160a01b0316600a8281548110613ef157fe5b9060005260206000200160009054906101000a90046001600160a01b03166001600160a01b031614156040518060400160405280601481526020017313505492d15517d053149150511657d05111115160621b81525090613f935760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b50600101613ed0565b50600a80546001810182556000919091527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a80180546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b03831660009081526009602052604081205460609060ff1661404457505060408051808201909152601181527013505492d15517d393d517d31254d51151607a1b6020820152600090611da6565b6001600160a01b038086166000908152600960209081526040808320938816835260029093019052205460ff1661407e5760019150611da6565b600061408d8587866000613b8e565b50509150506000811115611da0575050604080518082019091526016815275494e53554646494349454e545f4c495155494449545960501b602082015260009150611da6565b6001600160a01b03821660009081526009602090815260409182902080548351808501909452601184527013505492d15517d393d517d31254d51151607a1b92840192909252919060ff166141695760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b506001600160a01b038216600090815260028201602052604090205460ff161515600114156141985750614229565b6001600160a01b0380831660008181526002840160209081526040808320805460ff19166001908117909155600883528184208054918201815584529282902090920180549488166001600160a01b031990951685179055815193845283019190915280517f3ab23ab0d51cccc0c3085aec51f99228625aa1a922b3a8ca89a26b0f2027a1a59281900390910190a1505b5050565b5190511090565b600081836142835760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b50600083858161428f57fe5b0495945050505050565b600081848411156142eb5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561198557818101518382015260200161196d565b505050900390565b6142fb6143f0565b81518351600091614312919063ffffffff6139cf16565b905060006143286706f05b59d3b2000083613ab3565b9050600061434482670de0b6b3a764000063ffffffff613a2f16565b60408051602081019091529081529695505050505050565b6143646143f0565b60006143828361120786670de0b6b3a764000063ffffffff6139cf16565b6040805160208101909152908152949350505050565b6143a06143f0565b8251600090614382908463ffffffff6139cf16565b51670de0b6b3a7640000900490565b60006143ce6143f0565b6143d88585614398565b90506143e783611245836143b5565b95945050505050565b6040518060200160405280600081525090565b8154818355818111156121ce576000838152602090206121ce918101908301614484565b6040518061012001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016144656143f0565b81526020016144726143f0565b815260200161447f6143f0565b905290565b611bc891905b8082111561449e576000815560010161448a565b509056fe6f6e6c7920706175736520677561726469616e20616e642061646d696e2063616e2070617573652f756e706175736563616e6e6f742070617573652061206d61726b65742074686174206973206e6f74206c69737465646f6e6c792061646d696e2063616e2063616c6c20746869732066756e6374696f6e6f6e6c792061646d696e206f722063617020677561726469616e2063616e2073657420737570706c792063617073536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f776f6e6c792061646d696e206f722063617020677561726469616e2063616e2073657420626f72726f7720636170736f6e6c7920756e6974726f6c6c65722061646d696e2063616e206368616e676520627261696e73a265627a7a72315820e2879c23b9b2c54fe7ce71782928f91617e25d8fbffdbdb9e32b26f98d08778564736f6c63430005100032

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