Contract

0xB6C1b4DEF5Cdce350194816BD9b6C1770F08487D

Overview

S Balance

Sonic LogoSonic LogoSonic Logo0 S

S Value

-

Token Holdings

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
_add Emission Co...14157762024-12-24 3:47:085 days ago1735012028IN
0xB6C1b4DE...70F08487D
0 S0.000247121.1
_add Emission Co...14156902024-12-24 3:45:455 days ago1735011945IN
0xB6C1b4DE...70F08487D
0 S0.000247121.1
Initialize8193802024-12-20 6:15:189 days ago1734675318IN
0xB6C1b4DE...70F08487D
0 S0.000152941.1

Parent Transaction Hash Block From To
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MultiRewardDistributor

Compiler Version
v0.8.19+commit.7dd6d404

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
File 1 of 24 : MultiRewardDistributor.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

import {ReentrancyGuard} from "@openzeppelin-contracts/contracts/security/ReentrancyGuard.sol";
import {Initializable} from "@openzeppelin-contracts/contracts/proxy/utils/Initializable.sol";
import {SafeERC20} from "@openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {Pausable} from "@openzeppelin-contracts/contracts/security/Pausable.sol";
import {IERC20} from "@openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";

import {MToken} from "../MToken.sol";
import {Comptroller} from "../Comptroller.sol";
import {MTokenInterface} from "../MTokenInterfaces.sol";
import {ExponentialNoError} from "../ExponentialNoError.sol";
import {MultiRewardDistributorCommon} from "./MultiRewardDistributorCommon.sol";

/**
    @title A multi-asset distributor that tracks mTokens supply/borrows
    @author Octavius - [email protected]

    This contract integrates with the Moonwell Comptroller and manages all reward disbursal and index
    calculations both for the global market indices as well as individual user indices on those markets.
    It is largely the same logic that compound uses, just generalized (meaning that transfers will not
    fail if things can't be sent out, but the excess is accrued on the books to be sent later).

    Each market has an array of configs, each with a unique emission token owned by a specific team/user.
    That owner can adjust supply and borrow emissions, end times, and

    This emitter also supports native assets, but keep in mind that things get complicated with multiple
    owners managing a native asset emitter - one owner can drain the contract by increasing their own

    Delegates admin control to the comptroller's admin (no internal admin controls).

    There is a hard rule that each market should only have 1 config with a specific emission token.

    Emission configs are non-removable because they hold the supplier/borrower indices and that would
    cause rewards to not be disbursed properly when a config is removed.

    There is a pause guardian in this contract that can immediately stop all token emissions. Accruals
    still happen but no tokens will be sent out when the circuit breaker is popped. Much like the pause
    guardians on the Comptroller, only the comptroller's admin can actually unpause things.
*/

contract MultiRewardDistributor is
    Pausable,
    ReentrancyGuard,
    Initializable,
    MultiRewardDistributorCommon,
    ExponentialNoError
{
    using SafeERC20 for IERC20;

    /// @notice The main data storage for this contract, holds a mapping of mToken to array
    //          of market configs
    mapping(address => MarketEmissionConfig[]) public marketConfigs;

    /// @notice Comptroller this distributor is bound to
    Comptroller public comptroller; /// we can't make this immutable because we are using proxies

    /// @notice The pause guardian for this contract
    address public pauseGuardian;

    /// @notice The initialIndexConstant, used to initialize indexes, and taken from the Comptroller
    uint224 public constant initialIndexConstant = 1e36;

    /// @notice The emission cap dictates an upper limit for reward speed emission speed configs
    /// @dev By default, is set to 100 1e18 token emissions / sec to avoid unbounded
    ///  computation/multiplication overflows
    uint256 public emissionCap;

    // Some structs we can't move to the interface
    struct CurrentMarketData {
        uint256 totalMTokens;
        uint256 totalBorrows;
        Exp marketBorrowIndex;
    }

    struct CalculatedData {
        CurrentMarketData marketData;
        MTokenData mTokenInfo;
    }

    /// construct the logic contract and initialize so that the initialize function is uncallable
    /// from the implementation and only callable from the proxy
    constructor() {
        // _disableInitializers();
    }

    function initialize(
        address _comptroller,
        address _pauseGuardian
    ) external initializer {
        // Sanity check the params
        require(
            _comptroller != address(0),
            "Comptroller can't be the 0 address!"
        );
        require(
            _pauseGuardian != address(0),
            "Pause Guardian can't be the 0 address!"
        );

        comptroller = Comptroller(payable(_comptroller));

        require(
            comptroller.isComptroller(),
            "Can't bind to something that's not a comptroller!"
        );

        pauseGuardian = _pauseGuardian;
        emissionCap = 100e18;
    }

    /*
    ====================================================================================================
     ACL Modifiers

     all modifiers allow for the admin to call in to take actions within this contract, the idea being that
     the timelock can act like an owner of the config to set parameters, and act like the comptroller to
     kick the reward index updates, and act like a pause guardian to pause things.
    ====================================================================================================
    */

    /// @notice Only allow the comptroller's admin to take an action, usually the timelock
    modifier onlyComptrollersAdmin() {
        require(
            msg.sender == address(comptroller.admin()),
            "Only the comptroller's administrator can do this!"
        );
        _;
    }

    /// @notice Only allow the comptroller OR the comptroller's admin to take an action
    modifier onlyComptrollerOrAdmin() {
        require(
            msg.sender == address(comptroller) ||
                msg.sender == comptroller.admin(),
            "Only the comptroller or comptroller admin can call this function"
        );
        _;
    }

    /// @notice Only allow the emission config owner OR the comptroller's admin to take an action
    modifier onlyEmissionConfigOwnerOrAdmin(
        MToken _mToken,
        address emissionToken
    ) {
        MarketEmissionConfig
            storage emissionConfig = fetchConfigByEmissionToken(
                _mToken,
                emissionToken
            );
        require(
            msg.sender == emissionConfig.config.owner ||
                msg.sender == comptroller.admin(),
            "Only the config owner or comptroller admin can call this function"
        );
        _;
    }

    /// @notice Only allow the pause guardian OR the comptroller's admin to take an action
    modifier onlyPauseGuardianOrAdmin() {
        require(
            msg.sender == pauseGuardian || msg.sender == comptroller.admin(),
            "Only the pause guardian or comptroller admin can call this function"
        );
        _;
    }

    /*
    ====================================================================================================
     External/publicly accessible API

     The main public API for the contract, generally focused on getting a user's outstanding rewards or
     pulling down specific configs. Users should call `claimRewards` on the comptroller as usual to recv
     their rewards.
    ====================================================================================================
    */

    /**
     * @notice Get the current owner of a config
     * @param _mToken The market to get a config for
     * @param _emissionToken The reward token address
     */
    function getCurrentOwner(
        MToken _mToken,
        address _emissionToken
    ) external view returns (address) {
        MarketEmissionConfig
            storage emissionConfig = fetchConfigByEmissionToken(
                _mToken,
                _emissionToken
            );
        return emissionConfig.config.owner;
    }

    /// @notice A view to enumerate all configs for a given market, does not include index data
    function getAllMarketConfigs(
        MToken _mToken
    ) external view returns (MarketConfig[] memory) {
        MarketEmissionConfig[] storage configs = marketConfigs[
            address(_mToken)
        ];

        MarketConfig[] memory outputMarketConfigs = new MarketConfig[](
            configs.length
        );

        // Pop out the MarketConfigs to return them
        for (uint256 index = 0; index < configs.length; index++) {
            MarketEmissionConfig storage emissionConfig = configs[index];
            outputMarketConfigs[index] = emissionConfig.config;
        }

        return outputMarketConfigs;
    }

    /// @notice A view to get a config for a specific market/emission token pair
    function getConfigForMarket(
        MToken _mToken,
        address _emissionToken
    ) external view returns (MarketConfig memory) {
        MarketEmissionConfig
            storage emissionConfig = fetchConfigByEmissionToken(
                _mToken,
                _emissionToken
            );
        return emissionConfig.config;
    }

    /// @notice A view to enumerate a user's rewards across all markets and all emission tokens
    function getOutstandingRewardsForUser(
        address _user
    ) external view returns (RewardWithMToken[] memory) {
        MToken[] memory markets = comptroller.getAllMarkets();

        RewardWithMToken[] memory outputData = new RewardWithMToken[](
            markets.length
        );

        for (uint256 index = 0; index < markets.length; index++) {
            RewardInfo[] memory rewardInfo = getOutstandingRewardsForUser(
                markets[index],
                _user
            );

            outputData[index] = RewardWithMToken(
                address(markets[index]),
                rewardInfo
            );
        }

        return outputData;
    }

    /// @notice A view to enumerate a user's rewards across a specified market and all emission tokens for that market
    function getOutstandingRewardsForUser(
        MToken _mToken,
        address _user
    ) public view returns (RewardInfo[] memory) {
        // Global config for this mToken
        MarketEmissionConfig[] storage configs = marketConfigs[
            address(_mToken)
        ];

        // Output var
        RewardInfo[] memory outputRewardData = new RewardInfo[](configs.length);

        // Code golf to avoid too many local vars :rolling-eyes:
        CalculatedData memory calcData = CalculatedData({
            marketData: CurrentMarketData({
                totalMTokens: _mToken.totalSupply(),
                totalBorrows: _mToken.totalBorrows(),
                marketBorrowIndex: Exp({mantissa: _mToken.borrowIndex()})
            }),
            mTokenInfo: MTokenData({
                mTokenBalance: _mToken.balanceOf(_user),
                borrowBalanceStored: _mToken.borrowBalanceStored(_user)
            })
        });

        for (uint256 index = 0; index < configs.length; index++) {
            MarketEmissionConfig storage emissionConfig = configs[index];

            // Calculate our new global supply index
            IndexUpdate memory supplyUpdate = calculateNewIndex(
                emissionConfig.config.supplyEmissionsPerSec,
                emissionConfig.config.supplyGlobalTimestamp,
                emissionConfig.config.supplyGlobalIndex,
                emissionConfig.config.endTime,
                calcData.marketData.totalMTokens
            );

            // Calculate our new global borrow index
            IndexUpdate memory borrowUpdate = calculateNewIndex(
                emissionConfig.config.borrowEmissionsPerSec,
                emissionConfig.config.borrowGlobalTimestamp,
                emissionConfig.config.borrowGlobalIndex,
                emissionConfig.config.endTime,
                div_(
                    calcData.marketData.totalBorrows,
                    calcData.marketData.marketBorrowIndex
                )
            );

            // Calculate outstanding supplier side rewards
            uint256 supplierRewardsAccrued = calculateSupplyRewardsForUser(
                emissionConfig,
                supplyUpdate.newIndex,
                calcData.mTokenInfo.mTokenBalance,
                _user
            );

            uint256 borrowerRewardsAccrued = calculateBorrowRewardsForUser(
                emissionConfig,
                borrowUpdate.newIndex,
                calcData.marketData.marketBorrowIndex,
                calcData.mTokenInfo,
                _user
            );

            outputRewardData[index] = RewardInfo({
                emissionToken: emissionConfig.config.emissionToken,
                totalAmount: borrowerRewardsAccrued + supplierRewardsAccrued,
                supplySide: supplierRewardsAccrued,
                borrowSide: borrowerRewardsAccrued
            });
        }

        return outputRewardData;
    }

    /// @notice A view to get the current emission caps
    function getCurrentEmissionCap() external view returns (uint256) {
        return emissionCap;
    }

    /// @notice view to get the cached global supply index for an mToken and emission index
    /// @param mToken The market to get a config for
    /// @param index The index of the config to get
    function getGlobalSupplyIndex(
        address mToken,
        uint256 index
    ) public view returns (uint256) {
        MarketEmissionConfig storage emissionConfig = marketConfigs[mToken][
            index
        ];

        // Set the new values in storage
        return emissionConfig.config.supplyGlobalIndex;
    }

    /// @notice view to get the cached global borrow index for an mToken and emission index
    /// @param mToken The market to get a config for
    /// @param index The index of the config to get
    function getGlobalBorrowIndex(
        address mToken,
        uint256 index
    ) public view returns (uint256) {
        MarketEmissionConfig storage emissionConfig = marketConfigs[mToken][
            index
        ];

        // Set the new values in storage
        return emissionConfig.config.borrowGlobalIndex;
    }

    /*
    ====================================================================================================
     Administrative API

     Should be only callable by the comptroller's admin (usually the timelock), this is the only way
     to add new configurations to the markets. There's also a rescue assets function that will sweep
     tokens out of this contract and to the timelock, the thought being that rescuing accidentally sent
     funds or sweeping existing tokens to a new distributor is possible.
    ====================================================================================================
    */

    /**
     * @notice Add a new emission configuration for a specific market
     * @dev Emission config must not already exist for the specified market (unique to the emission token)
     */
    function _addEmissionConfig(
        MToken _mToken,
        address _owner,
        address _emissionToken,
        uint256 _supplyEmissionPerSec,
        uint256 _borrowEmissionsPerSec,
        uint256 _endTime
    ) external onlyComptrollersAdmin {
        // Ensure market is listed in the comptroller before accepting a config for it (should always be checked
        // in the comptroller first, but never hurts to codify that assertion/requirement here.
        (bool tokenIsListed, ) = comptroller.markets(address(_mToken));
        require(
            tokenIsListed,
            "The market requested to be added is un-listed!"
        );

        // Sanity check emission speeds are below emissionCap
        require(
            _supplyEmissionPerSec < emissionCap,
            "Cannot set a supply reward speed higher than the emission cap!"
        );
        require(
            _borrowEmissionsPerSec < emissionCap,
            "Cannot set a borrow reward speed higher than the emission cap!"
        );

        // Sanity check end time is some time in the future
        require(
            _endTime > block.timestamp + 1,
            "The _endTime parameter must be in the future!"
        );

        MarketEmissionConfig[] storage configs = marketConfigs[
            address(_mToken)
        ];

        // Sanity check to ensure that the emission token doesn't already exist in a config
        for (uint256 index = 0; index < configs.length; index++) {
            MarketEmissionConfig storage mTokenConfig = configs[index];
            require(
                mTokenConfig.config.emissionToken != _emissionToken,
                "Emission token already listed!"
            );
        }

        // Things look good, create a config
        MarketConfig memory config = MarketConfig({
            // Set the owner of the reward distributor config
            owner: _owner,
            // Set the emission token address
            emissionToken: _emissionToken,
            // Set the time that the emission campaign should end at
            endTime: _endTime,
            // Initialize the global supply
            supplyGlobalTimestamp: safe32(
                block.timestamp,
                "block timestamp exceeds 32 bits"
            ),
            supplyGlobalIndex: initialIndexConstant,
            // Initialize the global borrow index + timestamp
            borrowGlobalTimestamp: safe32(
                block.timestamp,
                "block timestamp exceeds 32 bits"
            ),
            borrowGlobalIndex: initialIndexConstant,
            // Set supply and reward borrow speeds
            supplyEmissionsPerSec: _supplyEmissionPerSec,
            borrowEmissionsPerSec: _borrowEmissionsPerSec
        });

        emit NewConfigCreated(
            _mToken,
            _owner,
            _emissionToken,
            _supplyEmissionPerSec,
            _borrowEmissionsPerSec,
            _endTime
        );

        // Go push in our new config
        MarketEmissionConfig storage newConfig = configs.push();
        newConfig.config = config;
    }

    /**
     * @notice Sweep ERC-20 tokens from the comptroller to the admin
     * @param _tokenAddress The address of the token to transfer
     * @param _amount The amount of tokens to sweep, uint256.max means everything
     */
    function _rescueFunds(
        address _tokenAddress,
        uint256 _amount
    ) external onlyComptrollersAdmin {
        IERC20 token = IERC20(_tokenAddress);
        // Similar to mTokens, if this is uint256.max that means "transfer everything"
        if (_amount == type(uint256).max) {
            token.safeTransfer(
                comptroller.admin(),
                token.balanceOf(address(this))
            );
        } else {
            token.safeTransfer(comptroller.admin(), _amount);
        }

        emit FundsRescued(_tokenAddress, _amount);
    }

    /**
     * @notice Sets a new pause guardian, callable by the CURRENT pause guardian or comptroller's admin
     * @param _newPauseGuardian The new pause guardian
     */
    function _setPauseGuardian(
        address _newPauseGuardian
    ) external onlyPauseGuardianOrAdmin {
        require(
            _newPauseGuardian != address(0),
            "Pause Guardian can't be the 0 address!"
        );

        address currentPauseGuardian = pauseGuardian;

        pauseGuardian = _newPauseGuardian;

        emit NewPauseGuardian(currentPauseGuardian, _newPauseGuardian);
    }

    /**
     * @notice Sets a new emission cap for supply/borrow speeds
     * @param _newEmissionCap The new emission cap
     */
    function _setEmissionCap(
        uint256 _newEmissionCap
    ) external onlyComptrollersAdmin {
        uint256 oldEmissionCap = emissionCap;

        emissionCap = _newEmissionCap;

        emit NewEmissionCap(oldEmissionCap, _newEmissionCap);
    }

    /*
    ====================================================================================================
     Comptroller specific API

     This is the main integration points with the Moonwell Comptroller. Within the `allowMint`/`allowBorrow`/etc
     hooks, the comptroller will reach out to kick the global index update (updateMarketIndex) as well as update
     the supplier's/borrower's token specific distribution indices for that market
    ====================================================================================================
    */

    /**
     * @notice Updates the supply indices for a given market
     * @param _mToken The market to update
     */
    function updateMarketSupplyIndex(
        MToken _mToken
    ) external onlyComptrollerOrAdmin {
        updateMarketSupplyIndexInternal(_mToken);
    }

    /**
     * @notice Calculate the deltas in indices between this user's index and the global supplier index for all configs,
     *         and accrue any owed emissions to their supplierRewardsAccrued for this market's configs
     * @param _mToken The market to update
     * @param _supplier The supplier whose index will be updated
     * @param _sendTokens Whether to send tokens as part of calculating owed rewards
     */
    function disburseSupplierRewards(
        MToken _mToken,
        address _supplier,
        bool _sendTokens
    ) external onlyComptrollerOrAdmin {
        disburseSupplierRewardsInternal(_mToken, _supplier, _sendTokens);
    }

    /**
     * @notice Combine the above 2 functions into one that will update the global and user supplier indexes and
     *         disburse rewards
     * @param _mToken The market to update
     * @param _supplier The supplier whose index will be updated
     * @param _sendTokens Whether to send tokens as part of calculating owed rewards
     */
    function updateMarketSupplyIndexAndDisburseSupplierRewards(
        MToken _mToken,
        address _supplier,
        bool _sendTokens
    ) external onlyComptrollerOrAdmin {
        updateMarketSupplyIndexInternal(_mToken);
        disburseSupplierRewardsInternal(_mToken, _supplier, _sendTokens);
    }

    /**
     * @notice Updates the borrow indices for a given market
     * @param _mToken The market to update
     */
    function updateMarketBorrowIndex(
        MToken _mToken
    ) external onlyComptrollerOrAdmin {
        updateMarketBorrowIndexInternal(_mToken);
    }

    /**
     * @notice Calculate the deltas in indices between this user's index and the global borrower index for all configs,
     *         and accrue any owed emissions to their borrowerRewardsAccrued for this market's configs
     * @param _mToken The market to update
     * @param _borrower The borrower whose index will be updated
     * @param _sendTokens Whether to send tokens as part of calculating owed rewards
     */
    function disburseBorrowerRewards(
        MToken _mToken,
        address _borrower,
        bool _sendTokens
    ) external onlyComptrollerOrAdmin {
        disburseBorrowerRewardsInternal(_mToken, _borrower, _sendTokens);
    }

    /**
     * @notice Combine the above 2 functions into one that will update the global and user borrower indexes and
     *         disburse rewards
     * @param _mToken The market to update
     * @param _borrower The borrower whose index will be updated
     * @param _sendTokens Whether to send tokens as part of calculating owed rewards
     */
    function updateMarketBorrowIndexAndDisburseBorrowerRewards(
        MToken _mToken,
        address _borrower,
        bool _sendTokens
    ) external onlyComptrollerOrAdmin {
        updateMarketBorrowIndexInternal(_mToken);
        disburseBorrowerRewardsInternal(_mToken, _borrower, _sendTokens);
    }

    /*
    ====================================================================================================
     Pause Guardian API

     The pause guardian tooling is responsible for toggling on and off actual reward emissions. Things
     will still be accrued as normal, but the `sendRewards` function will simply not attempt to transfer
     any tokens out.

     Similarly to the pause guardians in the Comptroller, when the pause guardian pops this circuit
     breaker, only the comptroller's admin is able to unpause things and get tokens emitting again.
    ====================================================================================================
     */

    /// @notice Pauses reward sending *but not accrual*
    function _pauseRewards() external onlyPauseGuardianOrAdmin {
        _pause();

        emit RewardsPaused();
    }

    /// @notice Unpauses and allows reward sending once again
    function _unpauseRewards() external onlyComptrollersAdmin {
        _unpause();

        emit RewardsUnpaused();
    }

    /*
    ====================================================================================================
     Configuration Owner API

     This is a set of APIs for external parties/emission config owners to update their configs. They're
     able to transfer ownership, update emission speeds, and update the end time for a campaign. Worth
     noting, if the endTime is hit, no more rewards will be accrued, BUT you can call `_updateEndTime`
     to extend the specified campaign - if the campaign has ended already, then rewards will start
     accruing from the time of reactivation.
    ====================================================================================================
     */

    /**
     * @notice Update the supply emissions for a given mToken + emission token pair.
     * @param _mToken The market to change a config for
     * @param _emissionToken The underlying reward token address
     * @param _newSupplySpeed The supply side emission speed denoted in the underlying emission token's decimals
     */
    function _updateSupplySpeed(
        MToken _mToken,
        address _emissionToken,
        uint256 _newSupplySpeed
    ) external onlyEmissionConfigOwnerOrAdmin(_mToken, _emissionToken) {
        MarketEmissionConfig
            storage emissionConfig = fetchConfigByEmissionToken(
                _mToken,
                _emissionToken
            );

        uint256 currentSupplySpeed = emissionConfig
            .config
            .supplyEmissionsPerSec;

        require(
            _newSupplySpeed != currentSupplySpeed,
            "Can't set new supply emissions to be equal to current!"
        );
        require(
            _newSupplySpeed < emissionCap,
            "Cannot set a supply reward speed higher than the emission cap!"
        );

        // Make sure we update our indices before setting the new speed
        updateMarketSupplyIndexInternal(_mToken);

        // Update supply speed
        emissionConfig.config.supplyEmissionsPerSec = _newSupplySpeed;

        emit NewSupplyRewardSpeed(
            _mToken,
            _emissionToken,
            currentSupplySpeed,
            _newSupplySpeed
        );
    }

    /**
     * @notice Update the borrow emissions for a given mToken + emission token pair.
     * @param _mToken The market to change a config for
     * @param _emissionToken The underlying reward token address
     * @param _newBorrowSpeed The borrow side emission speed denoted in the underlying emission token's decimals
     */
    function _updateBorrowSpeed(
        MToken _mToken,
        address _emissionToken,
        uint256 _newBorrowSpeed
    ) external onlyEmissionConfigOwnerOrAdmin(_mToken, _emissionToken) {
        MarketEmissionConfig
            storage emissionConfig = fetchConfigByEmissionToken(
                _mToken,
                _emissionToken
            );

        uint256 currentBorrowSpeed = emissionConfig
            .config
            .borrowEmissionsPerSec;

        require(
            _newBorrowSpeed != currentBorrowSpeed,
            "Can't set new borrow emissions to be equal to current!"
        );
        require(
            _newBorrowSpeed < emissionCap,
            "Cannot set a borrow reward speed higher than the emission cap!"
        );

        // Make sure we update our indices before setting the new speed
        updateMarketBorrowIndexInternal(_mToken);

        // Update borrow speed
        emissionConfig.config.borrowEmissionsPerSec = _newBorrowSpeed;

        emit NewBorrowRewardSpeed(
            _mToken,
            _emissionToken,
            currentBorrowSpeed,
            _newBorrowSpeed
        );
    }

    /**
     * @notice Update the owner of a config
     * @param _mToken The market to change a config for
     * @param _emissionToken The underlying reward token address
     * @param _newOwner The new owner for this config
     */
    function _updateOwner(
        MToken _mToken,
        address _emissionToken,
        address _newOwner
    ) external onlyEmissionConfigOwnerOrAdmin(_mToken, _emissionToken) {
        MarketEmissionConfig
            storage emissionConfig = fetchConfigByEmissionToken(
                _mToken,
                _emissionToken
            );

        address currentOwner = emissionConfig.config.owner;

        emissionConfig.config.owner = _newOwner;
        emit NewEmissionConfigOwner(
            _mToken,
            _emissionToken,
            currentOwner,
            _newOwner
        );
    }

    /**
     * @notice Update the end time for an emission campaign, must be in the future
     * @param _mToken The market to change a config for
     * @param _emissionToken The underlying reward token address
     * @param _newEndTime The new desired end time
     */
    function _updateEndTime(
        MToken _mToken,
        address _emissionToken,
        uint256 _newEndTime
    ) external onlyEmissionConfigOwnerOrAdmin(_mToken, _emissionToken) {
        MarketEmissionConfig
            storage emissionConfig = fetchConfigByEmissionToken(
                _mToken,
                _emissionToken
            );

        uint256 currentEndTime = emissionConfig.config.endTime;

        // Must be older than our existing end time AND the current block
        require(
            _newEndTime > currentEndTime,
            "_newEndTime MUST be > currentEndTime"
        );
        require(
            _newEndTime > block.timestamp,
            "_newEndTime MUST be > block.timestamp"
        );

        // Update both global indices before setting the new end time. If rewards are off this just updates the
        // global block timestamp to the current second
        updateMarketBorrowIndexInternal(_mToken);
        updateMarketSupplyIndexInternal(_mToken);

        emissionConfig.config.endTime = _newEndTime;
        emit NewRewardEndTime(
            _mToken,
            _emissionToken,
            currentEndTime,
            _newEndTime
        );
    }

    /*
    ====================================================================================================
     Internal functions

     Internal functions used by other parts of this contract, views first then mutation functions
    ====================================================================================================
    */

    /**
     * @notice An internal view to calculate the total owed supplier rewards for a given supplier address
     * @param _emissionConfig The emission config to read index data from
     * @param _globalSupplyIndex The global supply index for a market
     * @param _supplierTokens The amount of this market's mTokens owned by a user
     * @param _supplier The address of the supplier
     */
    function calculateSupplyRewardsForUser(
        MarketEmissionConfig storage _emissionConfig,
        uint224 _globalSupplyIndex,
        uint256 _supplierTokens,
        address _supplier
    ) internal view returns (uint256) {
        uint256 userSupplyIndex = _emissionConfig.supplierIndices[_supplier];

        // If our user's index isn't set yet, set to the current global supply index
        if (
            userSupplyIndex == 0 && _globalSupplyIndex >= initialIndexConstant
        ) {
            userSupplyIndex = initialIndexConstant; //_globalSupplyIndex;
        }

        // Calculate change in the cumulative sum of the reward per cToken accrued
        Double memory deltaIndex = Double({
            mantissa: sub_(_globalSupplyIndex, userSupplyIndex)
        });

        // Calculate reward accrued: cTokenAmount * accruedPerCToken
        uint256 supplierDelta = mul_(_supplierTokens, deltaIndex);

        return
            add_(
                _emissionConfig.supplierRewardsAccrued[_supplier],
                supplierDelta
            );
    }

    /**
     * @notice An internal view to calculate the total owed borrower rewards for a given borrower address
     * @param _emissionConfig The emission config to read index data from
     * @param _globalBorrowIndex The global borrow index for a market
     * @param _marketBorrowIndex The mToken's borrowIndex
     * @param _mTokenData A struct holding a borrower's
     * @param _borrower The address of the supplier mToken balance and borrowed balance
     */
    function calculateBorrowRewardsForUser(
        MarketEmissionConfig storage _emissionConfig,
        uint224 _globalBorrowIndex,
        Exp memory _marketBorrowIndex,
        MTokenData memory _mTokenData,
        address _borrower
    ) internal view returns (uint256) {
        uint256 userBorrowIndex = _emissionConfig.borrowerIndices[_borrower];

        // If our user's index isn't set yet, set to the current global borrow index
        if (
            userBorrowIndex == 0 && _globalBorrowIndex >= initialIndexConstant
        ) {
            userBorrowIndex = initialIndexConstant; //userBorrowIndex = _globalBorrowIndex;
        }

        // Calculate change in the cumulative sum of the reward per cToken accrued
        Double memory deltaIndex = Double({
            mantissa: sub_(_globalBorrowIndex, userBorrowIndex)
        });

        uint borrowerAmount = div_(
            _mTokenData.borrowBalanceStored,
            _marketBorrowIndex
        );

        // Calculate reward accrued: mTokenAmount * accruedPerMToken
        uint borrowerDelta = mul_(borrowerAmount, deltaIndex);

        return
            add_(
                _emissionConfig.borrowerRewardsAccrued[_borrower],
                borrowerDelta
            );
    }

    /**
     * @notice An internal view to calculate the global reward indices while taking into account emissions end times.
     * @dev Denominator here is whatever fractional denominator is used to calculate the index. On the supply side
     *      it's simply mToken.totalSupply(), while on the borrow side it's (mToken.totalBorrows() / mToken.borrowIndex())
     * @param _emissionsPerSecond The configured emissions per second for this index
     * @param _currentTimestamp The current index timestamp
     * @param _currentIndex The current index
     * @param _rewardEndTime The end time for this reward config
     * @param _denominator The denominator used in the calculation (supply side == mToken.totalSupply,
     *        borrow side is (mToken.totalBorrows() / mToken.borrowIndex()).
     */
    function calculateNewIndex(
        uint256 _emissionsPerSecond,
        uint32 _currentTimestamp,
        uint224 _currentIndex,
        uint256 _rewardEndTime,
        uint256 _denominator
    ) internal view returns (IndexUpdate memory) {
        uint32 blockTimestamp = safe32(
            block.timestamp,
            "block timestamp exceeds 32 bits"
        );
        uint256 deltaTimestamps = sub_(
            blockTimestamp,
            uint256(_currentTimestamp)
        );

        // If our current block timestamp is newer than our emission end time, we need to halt
        // reward emissions by stinting the growth of the global index, but importantly not
        // the global timestamp. Should not be gte because the equivalent case makes a
        // 0 deltaTimestamp which doesn't accrue the last bit of rewards properly.
        if (blockTimestamp > _rewardEndTime) {
            // If our current index timestamp is less than our end time it means this
            // is the first time the endTime threshold has been breached, and we have
            // some left over rewards to accrue, so clamp deltaTimestamps to the whatever
            // window of rewards still remains.
            if (_currentTimestamp < _rewardEndTime) {
                deltaTimestamps = sub_(_rewardEndTime, _currentTimestamp);
            } else {
                // Otherwise just set deltaTimestamps to 0 to ensure that we short circuit
                // in the next step
                deltaTimestamps = 0;
            }
        }

        // Short circuit to update the timestamp but *not* the index if there's nothing
        // to calculate
        if (deltaTimestamps == 0 || _emissionsPerSecond == 0) {
            return
                IndexUpdate({
                    newIndex: _currentIndex,
                    newTimestamp: blockTimestamp
                });
        }

        // At this point we know we have to calculate a new index, so do so
        uint256 tokenAccrued = mul_(deltaTimestamps, _emissionsPerSecond);
        Double memory ratio = _denominator > 0
            ? fraction(tokenAccrued, _denominator)
            : Double({mantissa: 0});

        uint224 newIndex = safe224(
            add_(Double({mantissa: _currentIndex}), ratio).mantissa,
            "new index exceeds 224 bits"
        );

        return IndexUpdate({newIndex: newIndex, newTimestamp: blockTimestamp});
    }

    /**
     * @notice An internal view to find a config for a given market given a specific emission token
     * @dev Reverts if the mtoken + emission token combo could not be found.
     * @param _mToken The market to fetch a config for
     * @param _emissionToken The emission token to fetch a config for
     */
    function fetchConfigByEmissionToken(
        MToken _mToken,
        address _emissionToken
    ) internal view returns (MarketEmissionConfig storage) {
        MarketEmissionConfig[] storage configs = marketConfigs[
            address(_mToken)
        ];
        for (uint256 index = 0; index < configs.length; index++) {
            MarketEmissionConfig storage emissionConfig = configs[index];
            if (emissionConfig.config.emissionToken == _emissionToken) {
                return emissionConfig;
            }
        }

        revert("Unable to find emission token in mToken configs");
    }

    //
    // Internal mutable functions
    //

    /**
     * @notice An internal function to update the global supply index for a given mToken
     * @param _mToken The market to update the global supply index for
     */
    function updateMarketSupplyIndexInternal(MToken _mToken) internal {
        MarketEmissionConfig[] storage configs = marketConfigs[
            address(_mToken)
        ];

        uint256 totalMTokens = MTokenInterface(_mToken).totalSupply();

        // Iterate over all market configs and update their indexes + timestamps
        for (uint256 index = 0; index < configs.length; index++) {
            MarketEmissionConfig storage emissionConfig = configs[index];

            // Go calculate our new values
            IndexUpdate memory supplyUpdate = calculateNewIndex(
                emissionConfig.config.supplyEmissionsPerSec,
                emissionConfig.config.supplyGlobalTimestamp,
                emissionConfig.config.supplyGlobalIndex,
                emissionConfig.config.endTime,
                totalMTokens
            );

            // Set the new values in storage
            emissionConfig.config.supplyGlobalIndex = supplyUpdate.newIndex;
            emissionConfig.config.supplyGlobalTimestamp = supplyUpdate
                .newTimestamp;
            emit GlobalSupplyIndexUpdated(
                _mToken,
                emissionConfig.config.emissionToken,
                supplyUpdate.newIndex,
                supplyUpdate.newTimestamp
            );
        }
    }

    /**
     * @notice An internal function to disburse rewards for the supplier side of a a specific mToken
     * @dev will only send tokens when _sendTokens == true, otherwise just accrue rewards
     * @param _mToken The market to update the global supply index for
     * @param _supplier The supplier to disburse rewards for
     * @param _sendTokens Whether to actually send tokens instead of just accruing
     */
    function disburseSupplierRewardsInternal(
        MToken _mToken,
        address _supplier,
        bool _sendTokens
    ) internal {
        MarketEmissionConfig[] storage configs = marketConfigs[
            address(_mToken)
        ];

        uint256 supplierTokens = _mToken.balanceOf(_supplier);

        // Iterate over all market configs and update their indexes + timestamps
        for (uint256 index = 0; index < configs.length; index++) {
            MarketEmissionConfig storage emissionConfig = configs[index];

            uint256 totalRewardsOwed = calculateSupplyRewardsForUser(
                emissionConfig,
                emissionConfig.config.supplyGlobalIndex,
                supplierTokens,
                _supplier
            );

            // Update user's index to match global index
            emissionConfig.supplierIndices[_supplier] = emissionConfig
                .config
                .supplyGlobalIndex;
            // Update the user's total rewards owed
            emissionConfig.supplierRewardsAccrued[_supplier] = totalRewardsOwed;

            emit DisbursedSupplierRewards(
                _mToken,
                _supplier,
                emissionConfig.config.emissionToken,
                emissionConfig.supplierRewardsAccrued[_supplier]
            );

            // SendRewards will attempt to send only if it has enough emission tokens to do so,
            // and if it doesn't have enough it emits a InsufficientTokensToEmit event and returns
            // the rewards that couldn't be sent, which are the total of what a user is owed, so we
            // store it in supplierRewardsAccrued to make sure we don't lose rewards accrual if there's
            // not enough funds in the rewarder
            if (_sendTokens) {
                // Emit rewards for this token/pair
                uint256 unsendableRewards = sendReward(
                    payable(_supplier),
                    emissionConfig.supplierRewardsAccrued[_supplier],
                    emissionConfig.config.emissionToken
                );

                emissionConfig.supplierRewardsAccrued[
                    _supplier
                ] = unsendableRewards;
            }
        }
    }

    /**
     * @notice An internal function to update the global borrow index for a given mToken
     * @param _mToken The market to update the global borrow index for
     */
    function updateMarketBorrowIndexInternal(MToken _mToken) internal {
        MarketEmissionConfig[] storage configs = marketConfigs[
            address(_mToken)
        ];

        Exp memory marketBorrowIndex = Exp({
            mantissa: MToken(_mToken).borrowIndex()
        });
        uint256 totalBorrows = MToken(_mToken).totalBorrows();

        // Iterate over all market configs and update their indexes + timestamps
        for (uint256 index = 0; index < configs.length; index++) {
            MarketEmissionConfig storage emissionConfig = configs[index];

            // Go calculate our new borrow index
            IndexUpdate memory borrowIndexUpdate = calculateNewIndex(
                emissionConfig.config.borrowEmissionsPerSec,
                emissionConfig.config.borrowGlobalTimestamp,
                emissionConfig.config.borrowGlobalIndex,
                emissionConfig.config.endTime,
                div_(totalBorrows, marketBorrowIndex)
            );

            // Set the new values in storage
            emissionConfig.config.borrowGlobalIndex = borrowIndexUpdate
                .newIndex;
            emissionConfig.config.borrowGlobalTimestamp = borrowIndexUpdate
                .newTimestamp;

            // Emit an update
            emit GlobalBorrowIndexUpdated(
                _mToken,
                emissionConfig.config.emissionToken,
                emissionConfig.config.borrowGlobalIndex,
                emissionConfig.config.borrowGlobalTimestamp
            );
        }
    }

    /**
     * @notice An internal function to disburse rewards for the borrower side of a a specific mToken
     * @dev will only send tokens when _sendTokens == true, otherwise just accrue rewards
     * @param _mToken The market to update the global borrow index for
     * @param _borrower The borrower to disburse rewards for
     * @param _sendTokens Whether to actually send tokens instead of just accruing
     */
    function disburseBorrowerRewardsInternal(
        MToken _mToken,
        address _borrower,
        bool _sendTokens
    ) internal {
        MarketEmissionConfig[] storage configs = marketConfigs[
            address(_mToken)
        ];

        Exp memory marketBorrowIndex = Exp({mantissa: _mToken.borrowIndex()});
        MTokenData memory mTokenData = MTokenData({
            mTokenBalance: _mToken.balanceOf(_borrower),
            borrowBalanceStored: _mToken.borrowBalanceStored(_borrower)
        });

        // Iterate over all market configs and update their indexes + timestamps
        for (uint256 index = 0; index < configs.length; index++) {
            MarketEmissionConfig storage emissionConfig = configs[index];

            // Go calculate the total outstanding rewards for this user
            uint256 owedRewards = calculateBorrowRewardsForUser(
                emissionConfig,
                emissionConfig.config.borrowGlobalIndex,
                marketBorrowIndex,
                mTokenData,
                _borrower
            );

            // Update user's index to global index
            emissionConfig.borrowerIndices[_borrower] = emissionConfig
                .config
                .borrowGlobalIndex;

            // Update the accrued borrow side rewards for this user
            emissionConfig.borrowerRewardsAccrued[_borrower] = owedRewards;

            emit DisbursedBorrowerRewards(
                _mToken,
                _borrower,
                emissionConfig.config.emissionToken,
                emissionConfig.borrowerRewardsAccrued[_borrower]
            );

            // If we are instructed to send out rewards, do so and update the borrowerRewardsAccrued to
            // 0 if it was successful, or to `pendingRewards` if there was insufficient balance to send
            if (_sendTokens) {
                // Emit rewards for this token/pair
                uint256 pendingRewards = sendReward(
                    payable(_borrower),
                    emissionConfig.borrowerRewardsAccrued[_borrower],
                    emissionConfig.config.emissionToken
                );

                emissionConfig.borrowerRewardsAccrued[
                    _borrower
                ] = pendingRewards;
            }
        }
    }

    /**
     * @notice An internal function to send rewards to a user
     * @dev Non-reentrant and returns the amount of tokens that were successfully sent
     * @param _user The user address to send tokens to
     * @param _amount The amount of tokens to send
     * @param _rewardToken The reward token to send
     */
    function sendReward(
        address payable _user,
        uint256 _amount,
        address _rewardToken
    ) internal nonReentrant returns (uint256) {
        // Short circuit if we don't have anything to send out
        if (_amount == 0) {
            return _amount;
        }

        // If pause guardian is active, bypass all token transfers, but still accrue to local tally
        if (paused()) {
            return _amount;
        }

        IERC20 token = IERC20(_rewardToken);

        // Get the distributor's current balance
        uint256 currentTokenHoldings = token.balanceOf(address(this));

        // Only transfer out if we have enough of a balance to cover it (otherwise just accrue without sending)
        if (_amount > 0 && _amount <= currentTokenHoldings) {
            // Ensure we use SafeERC20 to revert even if the reward token isn't ERC20 compliant
            token.safeTransfer(_user, _amount);
            return 0;
        } else {
            // If we've hit here it means we weren't able to emit the reward and we should emit an event
            // instead of failing.
            emit InsufficientTokensToEmit(_user, _rewardToken, _amount);

            // By default, return the same amount as what's left over to send, we accrue reward but don't send them out
            return _amount;
        }
    }
}

File 2 of 24 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/Address.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

File 3 of 24 : Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

File 4 of 24 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

File 5 of 24 : IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 6 of 24 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

File 7 of 24 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
     * 0 before setting it to a non-zero value.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

File 8 of 24 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

File 9 of 24 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

File 10 of 24 : CarefulMath.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

/**
 * @title Careful Math
 * @author Moonwell
 * @notice Derived from OpenZeppelin's SafeMath library
 *         https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
 */
contract CarefulMath {
    /**
     * @dev Possible error codes that we can return
     */
    enum MathError {
        NO_ERROR,
        DIVISION_BY_ZERO,
        INTEGER_OVERFLOW,
        INTEGER_UNDERFLOW
    }

    /**
     * @dev Multiplies two numbers, returns an error on overflow.
     */
    function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
        if (a == 0) {
            return (MathError.NO_ERROR, 0);
        }

        uint c = a * b;

        if (c / a != b) {
            return (MathError.INTEGER_OVERFLOW, 0);
        } else {
            return (MathError.NO_ERROR, c);
        }
    }

    /**
     * @dev Integer division of two numbers, truncating the quotient.
     */
    function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
        if (b == 0) {
            return (MathError.DIVISION_BY_ZERO, 0);
        }

        return (MathError.NO_ERROR, a / b);
    }

    /**
     * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
     */
    function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
        if (b <= a) {
            return (MathError.NO_ERROR, a - b);
        } else {
            return (MathError.INTEGER_UNDERFLOW, 0);
        }
    }

    /**
     * @dev Adds two numbers, returns an error on overflow.
     */
    function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
        uint c = a + b;

        if (c >= a) {
            return (MathError.NO_ERROR, c);
        } else {
            return (MathError.INTEGER_OVERFLOW, 0);
        }
    }

    /**
     * @dev add a and b and then subtract c
     */
    function addThenSubUInt(
        uint a,
        uint b,
        uint c
    ) internal pure returns (MathError, uint) {
        (MathError err0, uint sum) = addUInt(a, b);

        if (err0 != MathError.NO_ERROR) {
            return (err0, 0);
        }

        return subUInt(sum, c);
    }
}

File 11 of 24 : Comptroller.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

import "./MToken.sol";
import "./ErrorReporter.sol";
import "./oracles/PriceOracle.sol";
import "./ComptrollerInterface.sol";
import "./ComptrollerStorage.sol";
import "./Unitroller.sol";

/**
 * @title Moonwell's Comptroller Contract
 * @author Moonwell
 */
contract Comptroller is
    ComptrollerV2Storage,
    ComptrollerInterface,
    ComptrollerErrorReporter,
    ExponentialNoError
{
    /// @notice Emitted when an admin supports a market
    event MarketListed(MToken mToken);

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

    /// @notice Emitted when an account exits a market
    event MarketExited(MToken mToken, 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(
        MToken mToken,
        uint oldCollateralFactorMantissa,
        uint newCollateralFactorMantissa
    );

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

    /// @notice Emitted when price oracle is changed
    event NewPriceOracle(
        PriceOracle oldPriceOracle,
        PriceOracle 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(MToken mToken, string action, bool pauseState);

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

    /// @notice Emitted when borrow cap guardian is changed
    event NewBorrowCapGuardian(
        address oldBorrowCapGuardian,
        address newBorrowCapGuardian
    );

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

    /// @notice Emitted when supply cap guardian is changed
    event NewSupplyCapGuardian(
        address oldSupplyCapGuardian,
        address newSupplyCapGuardian
    );

    /// @notice Emitted when reward distributor is changed
    event NewRewardDistributor(
        MultiRewardDistributor oldRewardDistributor,
        MultiRewardDistributor newRewardDistributor
    );

    // 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

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

    constructor() {
        admin = msg.sender;
    }

    /*** 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 (MToken[] memory) {
        MToken[] 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 mToken The mToken to check
     * @return True if the account is in the asset, otherwise false.
     */
    function checkMembership(
        address account,
        MToken mToken
    ) external view returns (bool) {
        return markets[address(mToken)].accountMembership[account];
    }

    /**
     * @notice Add assets to be included in account liquidity calculation
     * @param mTokens The list of addresses of the mToken markets to be enabled
     * @return Success indicator for whether each corresponding market was entered
     */
    function enterMarkets(
        address[] memory mTokens
    ) public override returns (uint[] memory) {
        uint len = mTokens.length;

        uint[] memory results = new uint[](len);
        for (uint i = 0; i < len; i++) {
            MToken mToken = MToken(mTokens[i]);

            results[i] = uint(addToMarketInternal(mToken, msg.sender));
        }

        return results;
    }

    /**
     * @notice Add the market to the borrower's "assets in" for liquidity calculations
     * @param mToken The market to enter
     * @param borrower The address of the account to modify
     * @return Success indicator for whether the market was entered
     */
    function addToMarketInternal(
        MToken mToken,
        address borrower
    ) internal returns (Error) {
        Market storage marketToJoin = markets[address(mToken)];

        if (!marketToJoin.isListed) {
            // market is not listed, cannot join
            return Error.MARKET_NOT_LISTED;
        }

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

        // 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(mToken);

        emit MarketEntered(mToken, borrower);

        return Error.NO_ERROR;
    }

    /**
     * @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 mTokenAddress The address of the asset to be removed
     * @return Whether or not the account successfully exited the market
     */
    function exitMarket(
        address mTokenAddress
    ) external override returns (uint) {
        MToken mToken = MToken(mTokenAddress);
        /* Get sender tokensHeld and amountOwed underlying from the mToken */
        (uint oErr, uint tokensHeld, uint amountOwed, ) = mToken
            .getAccountSnapshot(msg.sender);
        require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code

        /* Fail if the sender has a borrow balance */
        if (amountOwed != 0) {
            return
                fail(
                    Error.NONZERO_BORROW_BALANCE,
                    FailureInfo.EXIT_MARKET_BALANCE_OWED
                );
        }

        /* Fail if the sender is not permitted to redeem all of their tokens */
        uint allowed = redeemAllowedInternal(
            mTokenAddress,
            msg.sender,
            tokensHeld
        );
        if (allowed != 0) {
            return
                failOpaque(
                    Error.REJECTION,
                    FailureInfo.EXIT_MARKET_REJECTION,
                    allowed
                );
        }

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

        /* Return true if the sender is not already ��in�� the market */
        if (!marketToExit.accountMembership[msg.sender]) {
            return uint(Error.NO_ERROR);
        }

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

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

        // We *must* have found the asset in the list or our redundant data structure is broken
        assert(assetIndex < len);

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

        emit MarketExited(mToken, msg.sender);

        return uint(Error.NO_ERROR);
    }

    /*** Policy Hooks ***/

    /**
     * @notice Checks if the account should be allowed to mint tokens in the given market
     * @param mToken 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 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
     */
    function mintAllowed(
        address mToken,
        address minter,
        uint mintAmount
    ) external override returns (uint) {
        // Pausing is a very serious situation - we revert to sound the alarms
        require(!mintGuardianPaused[mToken], "mint is paused");

        // Shh - currently unused
        mintAmount;

        if (!markets[mToken].isListed) {
            return uint(Error.MARKET_NOT_LISTED);
        }

        uint supplyCap = supplyCaps[mToken];
        // Supply cap of 0 corresponds to unlimited supplying
        if (supplyCap != 0) {
            uint totalCash = MToken(mToken).getCash();
            uint totalBorrows = MToken(mToken).totalBorrows();
            uint totalReserves = MToken(mToken).totalReserves();
            // totalSupplies = totalCash + totalBorrows - totalReserves
            uint totalSupplies = sub_(
                add_(totalCash, totalBorrows),
                totalReserves
            );

            uint nextTotalSupplies = add_(totalSupplies, mintAmount);
            require(nextTotalSupplies < supplyCap, "market supply cap reached");
        }

        // Keep the flywheel moving
        updateAndDistributeSupplierRewardsForToken(mToken, minter);
        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Checks if the account should be allowed to redeem tokens in the given market
     * @param mToken The market to verify the redeem against
     * @param redeemer The account which would redeem the tokens
     * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
     * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
     */
    function redeemAllowed(
        address mToken,
        address redeemer,
        uint redeemTokens
    ) external override returns (uint) {
        uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens);
        if (allowed != uint(Error.NO_ERROR)) {
            return allowed;
        }

        // Keep the flywheel moving
        updateAndDistributeSupplierRewardsForToken(mToken, redeemer);

        return uint(Error.NO_ERROR);
    }

    function redeemAllowedInternal(
        address mToken,
        address redeemer,
        uint redeemTokens
    ) internal view returns (uint) {
        if (!markets[mToken].isListed) {
            return uint(Error.MARKET_NOT_LISTED);
        }

        /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
        if (!markets[mToken].accountMembership[redeemer]) {
            return uint(Error.NO_ERROR);
        }

        /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
        (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(
            redeemer,
            MToken(mToken),
            redeemTokens,
            0
        );
        if (err != Error.NO_ERROR) {
            return uint(err);
        }
        if (shortfall > 0) {
            return uint(Error.INSUFFICIENT_LIQUIDITY);
        }

        return uint(Error.NO_ERROR);
    }

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

        // Require tokens is zero or amount is also zero
        if (redeemTokens == 0 && redeemAmount > 0) {
            revert("redeemTokens zero");
        }
    }

    /**
     * @notice Checks if the account should be allowed to borrow the underlying asset of the given market
     * @param mToken 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 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
     */
    function borrowAllowed(
        address mToken,
        address borrower,
        uint borrowAmount
    ) external override returns (uint) {
        // Pausing is a very serious situation - we revert to sound the alarms
        require(!borrowGuardianPaused[mToken], "borrow is paused");

        if (!markets[mToken].isListed) {
            return uint(Error.MARKET_NOT_LISTED);
        }

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

            // attempt to add borrower to the market
            Error addToMarketErr = addToMarketInternal(
                MToken(msg.sender),
                borrower
            );
            if (addToMarketErr != Error.NO_ERROR) {
                return uint(addToMarketErr);
            }

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

        if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) {
            return uint(Error.PRICE_ERROR);
        }

        uint borrowCap = borrowCaps[mToken];
        // Borrow cap of 0 corresponds to unlimited borrowing
        if (borrowCap != 0) {
            uint totalBorrows = MToken(mToken).totalBorrows();
            uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
            require(nextTotalBorrows < borrowCap, "market borrow cap reached");
        }

        (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(
            borrower,
            MToken(mToken),
            0,
            borrowAmount
        );
        if (err != Error.NO_ERROR) {
            return uint(err);
        }
        if (shortfall > 0) {
            return uint(Error.INSUFFICIENT_LIQUIDITY);
        }

        // Keep the flywheel moving
        updateAndDistributeBorrowerRewardsForToken(mToken, borrower);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Checks if the account should be allowed to repay a borrow in the given market
     * @param mToken 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 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
     */
    function repayBorrowAllowed(
        address mToken,
        address payer,
        address borrower,
        uint repayAmount
    ) external override returns (uint) {
        // Shh - currently unused
        payer;
        borrower;
        repayAmount;

        if (!markets[mToken].isListed) {
            return uint(Error.MARKET_NOT_LISTED);
        }

        // Keep the flywheel moving
        updateAndDistributeBorrowerRewardsForToken(mToken, borrower);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Checks if the liquidation should be allowed to occur
     * @param mTokenBorrowed Asset which was borrowed by the borrower
     * @param mTokenCollateral 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
     */
    function liquidateBorrowAllowed(
        address mTokenBorrowed,
        address mTokenCollateral,
        address liquidator,
        address borrower,
        uint repayAmount
    ) external view override returns (uint) {
        // Shh - currently unused
        liquidator;

        if (
            !markets[mTokenBorrowed].isListed ||
            !markets[mTokenCollateral].isListed
        ) {
            return uint(Error.MARKET_NOT_LISTED);
        }

        /* The borrower must have shortfall in order to be liquidatable */
        (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
        if (err != Error.NO_ERROR) {
            return uint(err);
        }
        if (shortfall == 0) {
            return uint(Error.INSUFFICIENT_SHORTFALL);
        }

        /* The liquidator may not repay more than what is allowed by the closeFactor */
        uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(
            borrower
        );
        uint maxClose = mul_ScalarTruncate(
            Exp({mantissa: closeFactorMantissa}),
            borrowBalance
        );
        if (repayAmount > maxClose) {
            return uint(Error.TOO_MUCH_REPAY);
        }

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Checks if the seizing of assets should be allowed to occur
     * @param mTokenCollateral Asset which was used as collateral and will be seized
     * @param mTokenBorrowed 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 seizeAllowed(
        address mTokenCollateral,
        address mTokenBorrowed,
        address liquidator,
        address borrower,
        uint seizeTokens
    ) external override returns (uint) {
        // Pausing is a very serious situation - we revert to sound the alarms
        require(!seizeGuardianPaused, "seize is paused");

        // Shh - currently unused
        seizeTokens;

        if (
            !markets[mTokenCollateral].isListed ||
            !markets[mTokenBorrowed].isListed
        ) {
            return uint(Error.MARKET_NOT_LISTED);
        }

        if (
            MToken(mTokenCollateral).comptroller() !=
            MToken(mTokenBorrowed).comptroller()
        ) {
            return uint(Error.COMPTROLLER_MISMATCH);
        }

        // Keep the flywheel moving
        // Note: We don't update borrower indices here because as part of liquidations
        //       repayBorrowFresh is called, which in turn calls `borrowAllow`, which updates
        //       the liquidated borrower's indices.
        updateAndDistributeSupplierRewardsForToken(mTokenCollateral, borrower);
        updateAndDistributeSupplierRewardsForToken(
            mTokenCollateral,
            liquidator
        );

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Checks if the account should be allowed to transfer tokens in the given market
     * @param mToken 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 mTokens to transfer
     * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
     */
    function transferAllowed(
        address mToken,
        address src,
        address dst,
        uint transferTokens
    ) external override returns (uint) {
        // Pausing is a very serious situation - we revert to sound the alarms
        require(!transferGuardianPaused, "transfer is paused");

        // Currently the only consideration is whether or not
        //  the src is allowed to redeem this many tokens
        uint allowed = redeemAllowedInternal(mToken, src, transferTokens);
        if (allowed != uint(Error.NO_ERROR)) {
            return allowed;
        }

        // Keep the flywheel moving
        updateAndDistributeSupplierRewardsForToken(mToken, src);
        updateAndDistributeSupplierRewardsForToken(mToken, dst);

        return uint(Error.NO_ERROR);
    }

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

    /**
     * @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
     *  Note that `mTokenBalance` is the number of mTokens the account owns in the market,
     *  whereas `borrowBalance` is the amount of underlying that the account has borrowed.
     */
    struct AccountLiquidityLocalVars {
        uint sumCollateral;
        uint sumBorrowPlusEffects;
        uint mTokenBalance;
        uint borrowBalance;
        uint exchangeRateMantissa;
        uint oraclePriceMantissa;
        Exp collateralFactor;
        Exp exchangeRate;
        Exp oraclePrice;
        Exp tokensToDenom;
    }

    /**
     * @notice Determine the current account liquidity wrt collateral requirements
     * @return (possible error code (semi-opaque),
                account liquidity in excess of collateral requirements,
     *          account shortfall below collateral requirements)
     */
    function getAccountLiquidity(
        address account
    ) public view returns (uint, uint, uint) {
        (
            Error err,
            uint liquidity,
            uint shortfall
        ) = getHypotheticalAccountLiquidityInternal(
                account,
                MToken(address(0)),
                0,
                0
            );

        return (uint(err), liquidity, shortfall);
    }

    /**
     * @notice Determine the current account liquidity wrt collateral requirements
     * @return (possible error code,
                account liquidity in excess of collateral requirements,
     *          account shortfall below collateral requirements)
     */
    function getAccountLiquidityInternal(
        address account
    ) internal view returns (Error, uint, uint) {
        return
            getHypotheticalAccountLiquidityInternal(
                account,
                MToken(address(0)),
                0,
                0
            );
    }

    /**
     * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
     * @param mTokenModify 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 (possible error code (semi-opaque),
                hypothetical account liquidity in excess of collateral requirements,
     *          hypothetical account shortfall below collateral requirements)
     */
    function getHypotheticalAccountLiquidity(
        address account,
        address mTokenModify,
        uint redeemTokens,
        uint borrowAmount
    ) public view returns (uint, uint, uint) {
        (
            Error err,
            uint liquidity,
            uint shortfall
        ) = getHypotheticalAccountLiquidityInternal(
                account,
                MToken(mTokenModify),
                redeemTokens,
                borrowAmount
            );
        return (uint(err), liquidity, shortfall);
    }

    /**
     * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
     * @param mTokenModify 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
     * @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data,
     *  without calculating accumulated interest.
     * @return (possible error code,
                hypothetical account liquidity in excess of collateral requirements,
     *          hypothetical account shortfall below collateral requirements)
     */
    function getHypotheticalAccountLiquidityInternal(
        address account,
        MToken mTokenModify,
        uint redeemTokens,
        uint borrowAmount
    ) internal view returns (Error, uint, uint) {
        AccountLiquidityLocalVars memory vars; // Holds all our calculation results
        uint oErr;

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

            // Read the balances and exchange rate from the mToken
            (
                oErr,
                vars.mTokenBalance,
                vars.borrowBalance,
                vars.exchangeRateMantissa
            ) = asset.getAccountSnapshot(account);
            if (oErr != 0) {
                // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
                return (Error.SNAPSHOT_ERROR, 0, 0);
            }
            vars.collateralFactor = Exp({
                mantissa: markets[address(asset)].collateralFactorMantissa
            });
            vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});

            // Get the normalized price of the asset
            vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
            if (vars.oraclePriceMantissa == 0) {
                return (Error.PRICE_ERROR, 0, 0);
            }
            vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});

            // Pre-compute a conversion factor from tokens -> glmr (normalized price value)
            vars.tokensToDenom = mul_(
                mul_(vars.collateralFactor, vars.exchangeRate),
                vars.oraclePrice
            );

            // sumCollateral += tokensToDenom * mTokenBalance
            vars.sumCollateral = mul_ScalarTruncateAddUInt(
                vars.tokensToDenom,
                vars.mTokenBalance,
                vars.sumCollateral
            );

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

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

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

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

    /**
     * @notice Calculate number of tokens of collateral asset to seize given an underlying amount
     * @dev Used in liquidation (called in mToken.liquidateBorrowFresh)
     * @param mTokenBorrowed The address of the borrowed mToken
     * @param mTokenCollateral The address of the collateral mToken
     * @param actualRepayAmount The amount of mTokenBorrowed underlying to convert into mTokenCollateral tokens
     * @return (errorCode, number of mTokenCollateral tokens to be seized in a liquidation)
     */
    function liquidateCalculateSeizeTokens(
        address mTokenBorrowed,
        address mTokenCollateral,
        uint actualRepayAmount
    ) external view override returns (uint, uint) {
        /* Read oracle prices for borrowed and collateral markets */
        uint priceBorrowedMantissa = oracle.getUnderlyingPrice(
            MToken(mTokenBorrowed)
        );
        uint priceCollateralMantissa = oracle.getUnderlyingPrice(
            MToken(mTokenCollateral)
        );
        if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
            return (uint(Error.PRICE_ERROR), 0);
        }

        /*
         * Get the exchange rate and calculate the number of collateral tokens to seize:
         *  seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
         *  seizeTokens = seizeAmount / exchangeRate
         *   = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
         */
        uint exchangeRateMantissa = MToken(mTokenCollateral)
            .exchangeRateStored(); // Note: reverts on error
        uint seizeTokens;
        Exp memory numerator;
        Exp memory denominator;
        Exp memory ratio;

        numerator = mul_(
            Exp({mantissa: liquidationIncentiveMantissa}),
            Exp({mantissa: priceBorrowedMantissa})
        );
        denominator = mul_(
            Exp({mantissa: priceCollateralMantissa}),
            Exp({mantissa: exchangeRateMantissa})
        );
        ratio = div_(numerator, denominator);

        seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);

        return (uint(Error.NO_ERROR), seizeTokens);
    }

    /*** Admin Functions ***/

    /**
     * @notice Sets a new price oracle for the comptroller
     * @dev Admin function to set a new price oracle
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
        // Check caller is admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK
                );
        }

        // Track the old oracle for the comptroller
        PriceOracle oldOracle = oracle;

        // Set comptroller's oracle to newOracle
        oracle = newOracle;

        // Emit NewPriceOracle(oldOracle, newOracle)
        emit NewPriceOracle(oldOracle, newOracle);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Sets the closeFactor used when liquidating borrows
     * @dev Admin function to set closeFactor
     * @param newCloseFactorMantissa New close factor, scaled by 1e18
     * @return uint 0=success, otherwise a failure
     */
    function _setCloseFactor(
        uint newCloseFactorMantissa
    ) external returns (uint) {
        // Check caller is admin
        require(msg.sender == admin, "only admin can set close factor");

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

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Sets the collateralFactor for a market
     * @dev Admin function to set per-market collateralFactor
     * @param mToken The market to set the factor on
     * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
     * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
     */
    function _setCollateralFactor(
        MToken mToken,
        uint newCollateralFactorMantissa
    ) external returns (uint) {
        // Check caller is admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK
                );
        }

        // Verify market is listed
        Market storage market = markets[address(mToken)];
        if (!market.isListed) {
            return
                fail(
                    Error.MARKET_NOT_LISTED,
                    FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS
                );
        }

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

        // Check collateral factor <= 0.9
        Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
        if (lessThanExp(highLimit, newCollateralFactorExp)) {
            return
                fail(
                    Error.INVALID_COLLATERAL_FACTOR,
                    FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION
                );
        }

        // If collateral factor != 0, fail if price == 0
        if (
            newCollateralFactorMantissa != 0 &&
            oracle.getUnderlyingPrice(mToken) == 0
        ) {
            return
                fail(
                    Error.PRICE_ERROR,
                    FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE
                );
        }

        // 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(
            mToken,
            oldCollateralFactorMantissa,
            newCollateralFactorMantissa
        );

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Sets liquidationIncentive
     * @dev Admin function to set liquidationIncentive
     * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
     * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
     */
    function _setLiquidationIncentive(
        uint newLiquidationIncentiveMantissa
    ) external returns (uint) {
        // Check caller is admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK
                );
        }

        // Save current value for use in log
        uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;

        // Set liquidation incentive to new incentive
        liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;

        // Emit event with old incentive, new incentive
        emit NewLiquidationIncentive(
            oldLiquidationIncentiveMantissa,
            newLiquidationIncentiveMantissa
        );

        return uint(Error.NO_ERROR);
    }

    /**
     * @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 mToken The address of the market (token) to list
     * @return uint 0=success, otherwise a failure. (See enum Error for details)
     */
    function _supportMarket(MToken mToken) external returns (uint) {
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SUPPORT_MARKET_OWNER_CHECK
                );
        }

        if (markets[address(mToken)].isListed) {
            return
                fail(
                    Error.MARKET_ALREADY_LISTED,
                    FailureInfo.SUPPORT_MARKET_EXISTS
                );
        }

        require(mToken.isMToken(), "Must be an MToken"); // Sanity check to make sure its really a MToken

        Market storage newMarket = markets[address(mToken)];
        newMarket.isListed = true;
        newMarket.collateralFactorMantissa = 0;

        _addMarketInternal(address(mToken));

        emit MarketListed(mToken);

        return uint(Error.NO_ERROR);
    }

    function _addMarketInternal(address mToken) internal {
        for (uint i = 0; i < allMarkets.length; i++) {
            require(allMarkets[i] != MToken(mToken), "market already added");
        }
        allMarkets.push(MToken(mToken));
    }

    /**
     * @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
     * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
     * @param mTokens 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(
        MToken[] calldata mTokens,
        uint[] calldata newBorrowCaps
    ) external {
        require(
            msg.sender == admin || msg.sender == borrowCapGuardian,
            "only admin or borrow cap guardian can set borrow caps"
        );

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

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

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

    /**
     * @notice Admin function to change the Borrow Cap Guardian
     * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
     */
    function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
        require(msg.sender == admin, "only admin can set borrow cap guardian");

        // Save current value for inclusion in log
        address oldBorrowCapGuardian = borrowCapGuardian;

        // Store borrowCapGuardian with value newBorrowCapGuardian
        borrowCapGuardian = newBorrowCapGuardian;

        // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
        emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
    }

    /**
     * @notice Set the given supply caps for the given mToken markets. Supplying that brings total supplies to or above supply cap will revert.
     * @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying.
     * @param mTokens 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(
        MToken[] calldata mTokens,
        uint[] calldata newSupplyCaps
    ) external {
        require(
            msg.sender == admin || msg.sender == supplyCapGuardian,
            "only admin or supply cap guardian can set supply caps"
        );

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

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

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

    /**
     * @notice Admin function to change the Supply Cap Guardian
     * @param newSupplyCapGuardian The address of the new Supply Cap Guardian
     */
    function _setSupplyCapGuardian(address newSupplyCapGuardian) external {
        require(msg.sender == admin, "only admin can set supply cap guardian");

        // Save current value for inclusion in log
        address oldSupplyCapGuardian = supplyCapGuardian;

        // Store supplyCapGuardian with value newSupplyCapGuardian
        supplyCapGuardian = newSupplyCapGuardian;

        // Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian)
        emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian);
    }

    /**
     * @notice Admin function to change the Pause Guardian
     * @param newPauseGuardian The address of the new Pause Guardian
     * @return uint 0=success, otherwise a failure. (See enum Error for details)
     */
    function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK
                );
        }

        // Save current value for inclusion in log
        address oldPauseGuardian = pauseGuardian;

        // Store pauseGuardian with value newPauseGuardian
        pauseGuardian = newPauseGuardian;

        // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
        emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Admin function to change the Reward Distributor
     * @param newRewardDistributor The address of the new Reward Distributor
     */
    function _setRewardDistributor(
        MultiRewardDistributor newRewardDistributor
    ) public {
        require(msg.sender == admin, "Unauthorized");

        MultiRewardDistributor oldRewardDistributor = rewardDistributor;

        rewardDistributor = newRewardDistributor;

        emit NewRewardDistributor(oldRewardDistributor, newRewardDistributor);
    }

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

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

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

        borrowGuardianPaused[address(mToken)] = state;
        emit ActionPaused(mToken, "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"
        );
        require(msg.sender == admin || state == true, "only admin can 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"
        );
        require(msg.sender == admin || state == true, "only admin can unpause");

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

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

    /**
     * @notice Sweep ERC-20 tokens from the comptroller to the admin
     * @param _tokenAddress The address of the token to transfer
     * @param _amount The amount of tokens to sweep, uint.max means everything
     */
    function _rescueFunds(address _tokenAddress, uint _amount) external {
        require(msg.sender == admin, "Unauthorized");

        IERC20 token = IERC20(_tokenAddress);
        // Similar to mTokens, if this is uint.max that means "transfer everything"
        if (_amount == type(uint).max) {
            token.transfer(admin, token.balanceOf(address(this)));
        } else {
            token.transfer(admin, _amount);
        }
    }

    /*** WELL Distribution ***/

    /**
     * @notice Call out to the reward distributor to update its supply index and this user's index too
     * @param mToken The market to synchronize indexes for
     * @param supplier The supplier to whom rewards are going
     */
    function updateAndDistributeSupplierRewardsForToken(
        address mToken,
        address supplier
    ) internal {
        if (address(rewardDistributor) != address(0)) {
            rewardDistributor.updateMarketSupplyIndexAndDisburseSupplierRewards(
                MToken(mToken),
                supplier,
                false
            );
        }
    }

    /**
     * @notice Call out to the reward distributor to update its borrow index and this user's index too
     * @param mToken The market to synchronize indexes for
     * @param borrower The borrower to whom rewards are going
     */
    function updateAndDistributeBorrowerRewardsForToken(
        address mToken,
        address borrower
    ) internal {
        if (address(rewardDistributor) != address(0)) {
            rewardDistributor.updateMarketBorrowIndexAndDisburseBorrowerRewards(
                MToken(mToken),
                borrower,
                false
            );
        }
    }

    /**
     * @notice Claim all the WELL accrued by holder in all markets
     */
    function claimReward() public {
        claimReward(msg.sender, allMarkets);
    }

    /**
     * @notice Claim all the rewards accrued by specified holder in all markets
     * @param holder The address to claim rewards for
     */
    function claimReward(address holder) public {
        claimReward(holder, allMarkets);
    }

    /**
     * @notice Claim all the rewards accrued by holder in the specified markets
     * @param holder The address to claim rewards for
     * @param mTokens The list of markets to claim rewards in
     */
    function claimReward(address holder, MToken[] memory mTokens) public {
        address[] memory holders = new address[](1);
        holders[0] = holder;
        claimReward(holders, mTokens, true, true);
    }

    /**
     * @notice Claim all rewards for a specified group of users, tokens, and market sides
     * @param holders The addresses to claim for
     * @param mTokens The list of markets to claim in
     * @param borrowers Whether or not to claim earned by borrowing
     * @param suppliers Whether or not to claim earned by supplying
     */
    function claimReward(
        address[] memory holders,
        MToken[] memory mTokens,
        bool borrowers,
        bool suppliers
    ) public {
        require(
            address(rewardDistributor) != address(0),
            "No reward distributor configured!"
        );

        for (uint i = 0; i < mTokens.length; i++) {
            // Safety check that the supplied mTokens are active/listed
            MToken mToken = mTokens[i];
            require(markets[address(mToken)].isListed, "market must be listed");

            // Disburse supply side
            if (suppliers == true) {
                rewardDistributor.updateMarketSupplyIndex(mToken);
                for (
                    uint holderIndex = 0;
                    holderIndex < holders.length;
                    holderIndex++
                ) {
                    rewardDistributor.disburseSupplierRewards(
                        mToken,
                        holders[holderIndex],
                        true
                    );
                }
            }

            // Disburse borrow side
            if (borrowers == true) {
                rewardDistributor.updateMarketBorrowIndex(mToken);
                for (
                    uint holderIndex = 0;
                    holderIndex < holders.length;
                    holderIndex++
                ) {
                    rewardDistributor.disburseBorrowerRewards(
                        mToken,
                        holders[holderIndex],
                        true
                    );
                }
            }
        }
    }

    /**
     * @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 (MToken[] memory) {
        return allMarkets;
    }

    function getBlockTimestamp() public view returns (uint) {
        return block.timestamp;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_locked != 1, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _locked = 1;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _locked = 0;
    }
}

File 12 of 24 : ComptrollerInterface.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

abstract contract ComptrollerInterface {
    /// @notice Indicator that this is a Comptroller contract (for inspection)
    bool public constant isComptroller = true;

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

    function enterMarkets(
        address[] calldata mTokens
    ) external virtual returns (uint[] memory);
    function exitMarket(address mToken) external virtual returns (uint);

    /*** Policy Hooks ***/

    function mintAllowed(
        address mToken,
        address minter,
        uint mintAmount
    ) external virtual returns (uint);

    function redeemAllowed(
        address mToken,
        address redeemer,
        uint redeemTokens
    ) external virtual returns (uint);

    // Do not remove, still used by MToken
    function redeemVerify(
        address mToken,
        address redeemer,
        uint redeemAmount,
        uint redeemTokens
    ) external pure virtual;

    function borrowAllowed(
        address mToken,
        address borrower,
        uint borrowAmount
    ) external virtual returns (uint);

    function repayBorrowAllowed(
        address mToken,
        address payer,
        address borrower,
        uint repayAmount
    ) external virtual returns (uint);

    function liquidateBorrowAllowed(
        address mTokenBorrowed,
        address mTokenCollateral,
        address liquidator,
        address borrower,
        uint repayAmount
    ) external view virtual returns (uint);

    function seizeAllowed(
        address mTokenCollateral,
        address mTokenBorrowed,
        address liquidator,
        address borrower,
        uint seizeTokens
    ) external virtual returns (uint);

    function transferAllowed(
        address mToken,
        address src,
        address dst,
        uint transferTokens
    ) external virtual returns (uint);

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

    function liquidateCalculateSeizeTokens(
        address mTokenBorrowed,
        address mTokenCollateral,
        uint repayAmount
    ) external view virtual returns (uint, uint);
}

// The hooks that were patched out of the comptroller to make room for the supply caps, if we need them
abstract contract ComptrollerInterfaceWithAllVerificationHooks is
    ComptrollerInterface
{
    function mintVerify(
        address mToken,
        address minter,
        uint mintAmount,
        uint mintTokens
    ) external virtual;

    // Included in ComptrollerInterface already
    // function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) virtual external;

    function borrowVerify(
        address mToken,
        address borrower,
        uint borrowAmount
    ) external virtual;

    function repayBorrowVerify(
        address mToken,
        address payer,
        address borrower,
        uint repayAmount,
        uint borrowerIndex
    ) external virtual;

    function liquidateBorrowVerify(
        address mTokenBorrowed,
        address mTokenCollateral,
        address liquidator,
        address borrower,
        uint repayAmount,
        uint seizeTokens
    ) external virtual;

    function seizeVerify(
        address mTokenCollateral,
        address mTokenBorrowed,
        address liquidator,
        address borrower,
        uint seizeTokens
    ) external virtual;

    function transferVerify(
        address mToken,
        address src,
        address dst,
        uint transferTokens
    ) external virtual;
}

File 13 of 24 : ComptrollerStorage.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

import "./MToken.sol";
import "./oracles/PriceOracle.sol";
import "./rewards/MultiRewardDistributor.sol";

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 comptrollerImplementation;

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

contract ComptrollerVXStorage is UnitrollerAdminStorage {
    /**
     * @notice Oracle which gives the price of any given asset
     */
    PriceOracle 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 Per-account mapping of "assets you are in", capped by maxAssets
     */
    mapping(address => MToken[]) public accountAssets;

    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 Official mapping of mTokens -> Market metadata
     * @dev Used e.g. to determine if a market is supported
     */
    mapping(address => Market) public markets;

    /**
     * @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;
    bool public transferGuardianPaused;
    bool public seizeGuardianPaused;
    mapping(address => bool) public mintGuardianPaused;
    mapping(address => bool) public borrowGuardianPaused;

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

    // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
    address public borrowCapGuardian;

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

    struct RewardMarketState {
        /// @notice The market's last updated rewardBorrowIndex or rewardSupplyIndex
        uint224 index;
        /// @notice The block timestamp the index was last updated at
        uint32 timestamp;
    }

    /// @notice Reentrant status, 0: not entered, 1: entered
    uint256 internal _locked;
}

contract ComptrollerV2Storage is ComptrollerVXStorage {
    /// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market.
    address public supplyCapGuardian;

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

    /// @notice The Reward distributor used to emit protocol rewards
    MultiRewardDistributor public rewardDistributor;
}

File 14 of 24 : EIP20Interface.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

/**
 * @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 balance 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 success 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 success 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 success 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 remaining 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 15 of 24 : EIP20NonStandardInterface.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

/**
 * @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 balance 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 success 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 remaining 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 16 of 24 : ErrorReporter.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

contract ComptrollerErrorReporter {
    enum Error {
        NO_ERROR,
        UNAUTHORIZED,
        COMPTROLLER_MISMATCH,
        INSUFFICIENT_SHORTFALL,
        INSUFFICIENT_LIQUIDITY,
        INVALID_CLOSE_FACTOR,
        INVALID_COLLATERAL_FACTOR,
        INVALID_LIQUIDATION_INCENTIVE,
        MARKET_NOT_ENTERED, // no longer possible
        MARKET_NOT_LISTED,
        MARKET_ALREADY_LISTED,
        MATH_ERROR,
        NONZERO_BORROW_BALANCE,
        PRICE_ERROR,
        REJECTION,
        SNAPSHOT_ERROR,
        TOO_MANY_ASSETS,
        TOO_MUCH_REPAY
    }

    enum FailureInfo {
        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
        ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
        EXIT_MARKET_BALANCE_OWED,
        EXIT_MARKET_REJECTION,
        SET_CLOSE_FACTOR_OWNER_CHECK,
        SET_CLOSE_FACTOR_VALIDATION,
        SET_COLLATERAL_FACTOR_OWNER_CHECK,
        SET_COLLATERAL_FACTOR_NO_EXISTS,
        SET_COLLATERAL_FACTOR_VALIDATION,
        SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
        SET_IMPLEMENTATION_OWNER_CHECK,
        SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
        SET_LIQUIDATION_INCENTIVE_VALIDATION,
        SET_MAX_ASSETS_OWNER_CHECK,
        SET_PENDING_ADMIN_OWNER_CHECK,
        SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
        SET_PRICE_ORACLE_OWNER_CHECK,
        SUPPORT_MARKET_EXISTS,
        SUPPORT_MARKET_OWNER_CHECK,
        SET_PAUSE_GUARDIAN_OWNER_CHECK,
        SET_GAS_AMOUNT_OWNER_CHECK
    }

    /**
     * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
     * contract-specific code that enables us to report opaque error codes from upgradeable contracts.
     **/
    event Failure(uint error, uint info, uint detail);

    /**
     * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
     */
    function fail(Error err, FailureInfo info) internal returns (uint) {
        emit Failure(uint(err), uint(info), 0);

        return uint(err);
    }

    /**
     * @dev use this when reporting an opaque error from an upgradeable collaborator contract
     */
    function failOpaque(
        Error err,
        FailureInfo info,
        uint opaqueError
    ) internal returns (uint) {
        emit Failure(uint(err), uint(info), opaqueError);

        return uint(err);
    }
}

contract TokenErrorReporter {
    enum Error {
        NO_ERROR,
        UNAUTHORIZED,
        BAD_INPUT,
        COMPTROLLER_REJECTION,
        COMPTROLLER_CALCULATION_ERROR,
        INTEREST_RATE_MODEL_ERROR,
        INVALID_ACCOUNT_PAIR,
        INVALID_CLOSE_AMOUNT_REQUESTED,
        INVALID_COLLATERAL_FACTOR,
        MATH_ERROR,
        MARKET_NOT_FRESH,
        MARKET_NOT_LISTED,
        TOKEN_INSUFFICIENT_ALLOWANCE,
        TOKEN_INSUFFICIENT_BALANCE,
        TOKEN_INSUFFICIENT_CASH,
        TOKEN_TRANSFER_IN_FAILED,
        TOKEN_TRANSFER_OUT_FAILED
    }

    /*
     * Note: FailureInfo (but not Error) is kept in alphabetical order
     *       This is because FailureInfo grows significantly faster, and
     *       the order of Error has some meaning, while the order of FailureInfo
     *       is entirely arbitrary.
     */
    enum FailureInfo {
        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
        ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
        ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
        ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
        ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
        ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
        ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
        BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
        BORROW_ACCRUE_INTEREST_FAILED,
        BORROW_CASH_NOT_AVAILABLE,
        BORROW_FRESHNESS_CHECK,
        BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
        BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
        BORROW_MARKET_NOT_LISTED,
        BORROW_COMPTROLLER_REJECTION,
        LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
        LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
        LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
        LIQUIDATE_COMPTROLLER_REJECTION,
        LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
        LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
        LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
        LIQUIDATE_FRESHNESS_CHECK,
        LIQUIDATE_LIQUIDATOR_IS_BORROWER,
        LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
        LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
        LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
        LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
        LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
        LIQUIDATE_SEIZE_TOO_MUCH,
        MINT_ACCRUE_INTEREST_FAILED,
        MINT_COMPTROLLER_REJECTION,
        MINT_EXCHANGE_CALCULATION_FAILED,
        MINT_EXCHANGE_RATE_READ_FAILED,
        MINT_FRESHNESS_CHECK,
        MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
        MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
        MINT_TRANSFER_IN_FAILED,
        MINT_TRANSFER_IN_NOT_POSSIBLE,
        REDEEM_ACCRUE_INTEREST_FAILED,
        REDEEM_COMPTROLLER_REJECTION,
        REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
        REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
        REDEEM_EXCHANGE_RATE_READ_FAILED,
        REDEEM_FRESHNESS_CHECK,
        REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
        REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
        REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
        REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
        REDUCE_RESERVES_ADMIN_CHECK,
        REDUCE_RESERVES_CASH_NOT_AVAILABLE,
        REDUCE_RESERVES_FRESH_CHECK,
        REDUCE_RESERVES_VALIDATION,
        REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
        REPAY_BORROW_ACCRUE_INTEREST_FAILED,
        REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
        REPAY_BORROW_COMPTROLLER_REJECTION,
        REPAY_BORROW_FRESHNESS_CHECK,
        REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
        REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
        REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
        SET_COLLATERAL_FACTOR_OWNER_CHECK,
        SET_COLLATERAL_FACTOR_VALIDATION,
        SET_COMPTROLLER_OWNER_CHECK,
        SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
        SET_INTEREST_RATE_MODEL_FRESH_CHECK,
        SET_INTEREST_RATE_MODEL_OWNER_CHECK,
        SET_MAX_ASSETS_OWNER_CHECK,
        SET_ORACLE_MARKET_NOT_LISTED,
        SET_PENDING_ADMIN_OWNER_CHECK,
        SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
        SET_RESERVE_FACTOR_ADMIN_CHECK,
        SET_RESERVE_FACTOR_FRESH_CHECK,
        SET_RESERVE_FACTOR_BOUNDS_CHECK,
        TRANSFER_COMPTROLLER_REJECTION,
        TRANSFER_NOT_ALLOWED,
        TRANSFER_NOT_ENOUGH,
        TRANSFER_TOO_MUCH,
        ADD_RESERVES_ACCRUE_INTEREST_FAILED,
        ADD_RESERVES_FRESH_CHECK,
        ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE,
        SET_PROTOCOL_SEIZE_SHARE_ACCRUE_INTEREST_FAILED,
        SET_PROTOCOL_SEIZE_SHARE_OWNER_CHECK,
        SET_PROTOCOL_SEIZE_SHARE_FRESH_CHECK
    }

    /**
     * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
     * contract-specific code that enables us to report opaque error codes from upgradeable contracts.
     **/
    event Failure(uint error, uint info, uint detail);

    /**
     * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
     */
    function fail(Error err, FailureInfo info) internal returns (uint) {
        emit Failure(uint(err), uint(info), 0);

        return uint(err);
    }

    /**
     * @dev use this when reporting an opaque error from an upgradeable collaborator contract
     */
    function failOpaque(
        Error err,
        FailureInfo info,
        uint opaqueError
    ) internal returns (uint) {
        emit Failure(uint(err), uint(info), opaqueError);

        return uint(err);
    }
}

File 17 of 24 : Exponential.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

import "./CarefulMath.sol";
import "./ExponentialNoError.sol";

/**
 * @title Exponential module for storing fixed-precision decimals
 * @author Moonwell
 * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
 * @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 is CarefulMath, ExponentialNoError {
    /**
     * @dev Creates an exponential from numerator and denominator values.
     *      Note: Returns an error if (`num` * 10e18) > MAX_INT,
     *            or if `denom` is zero.
     */
    function getExp(
        uint num,
        uint denom
    ) internal pure returns (MathError, Exp memory) {
        (MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
        if (err0 != MathError.NO_ERROR) {
            return (err0, Exp({mantissa: 0}));
        }

        (MathError err1, uint rational) = divUInt(scaledNumerator, denom);
        if (err1 != MathError.NO_ERROR) {
            return (err1, Exp({mantissa: 0}));
        }

        return (MathError.NO_ERROR, Exp({mantissa: rational}));
    }

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

        return (error, Exp({mantissa: result}));
    }

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

        return (error, Exp({mantissa: result}));
    }

    /**
     * @dev Multiply an Exp by a scalar, returning a new Exp.
     */
    function mulScalar(
        Exp memory a,
        uint scalar
    ) internal pure returns (MathError, Exp memory) {
        (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
        if (err0 != MathError.NO_ERROR) {
            return (err0, Exp({mantissa: 0}));
        }

        return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
    }

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

        return (MathError.NO_ERROR, 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
    ) internal pure returns (MathError, uint) {
        (MathError err, Exp memory product) = mulScalar(a, scalar);
        if (err != MathError.NO_ERROR) {
            return (err, 0);
        }

        return addUInt(truncate(product), addend);
    }

    /**
     * @dev Divide an Exp by a scalar, returning a new Exp.
     */
    function divScalar(
        Exp memory a,
        uint scalar
    ) internal pure returns (MathError, Exp memory) {
        (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
        if (err0 != MathError.NO_ERROR) {
            return (err0, Exp({mantissa: 0}));
        }

        return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
    }

    /**
     * @dev Divide a scalar by an Exp, returning a new Exp.
     */
    function divScalarByExp(
        uint scalar,
        Exp memory divisor
    ) internal pure returns (MathError, Exp memory) {
        /*
          We are doing this as:
          getExp(mulUInt(expScale, 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`
        */
        (MathError err0, uint numerator) = mulUInt(expScale, scalar);
        if (err0 != MathError.NO_ERROR) {
            return (err0, Exp({mantissa: 0}));
        }
        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
    ) internal pure returns (MathError, uint) {
        (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
        if (err != MathError.NO_ERROR) {
            return (err, 0);
        }

        return (MathError.NO_ERROR, truncate(fraction));
    }

    /**
     * @dev Multiplies two exponentials, returning a new exponential.
     */
    function mulExp(
        Exp memory a,
        Exp memory b
    ) internal pure returns (MathError, Exp memory) {
        (MathError err0, uint doubleScaledProduct) = mulUInt(
            a.mantissa,
            b.mantissa
        );
        if (err0 != MathError.NO_ERROR) {
            return (err0, Exp({mantissa: 0}));
        }

        // 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.
        (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(
            halfExpScale,
            doubleScaledProduct
        );
        if (err1 != MathError.NO_ERROR) {
            return (err1, Exp({mantissa: 0}));
        }

        (MathError err2, uint product) = divUInt(
            doubleScaledProductWithHalfScale,
            expScale
        );
        // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
        assert(err2 == MathError.NO_ERROR);

        return (MathError.NO_ERROR, Exp({mantissa: product}));
    }

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

    /**
     * @dev Multiplies three exponentials, returning a new exponential.
     */
    function mulExp3(
        Exp memory a,
        Exp memory b,
        Exp memory c
    ) internal pure returns (MathError, Exp memory) {
        (MathError err, Exp memory ab) = mulExp(a, b);
        if (err != MathError.NO_ERROR) {
            return (err, ab);
        }
        return mulExp(ab, c);
    }

    /**
     * @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
    ) internal pure returns (MathError, Exp memory) {
        return getExp(a.mantissa, b.mantissa);
    }
}

File 18 of 24 : ExponentialNoError.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

/**
 * @title Exponential module for storing fixed-precision decimals
 * @author Moonwell
 * @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 ExponentialNoError {
    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 Truncates the given exp to a whole number value.
     *      For example, truncate(Exp{mantissa: 15 * expScale}) = 15
     */
    function truncate(Exp memory exp) internal pure returns (uint) {
        // Note: We are not using careful math here as we're performing a division that cannot fail
        return exp.mantissa / expScale;
    }

    /**
     * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
     */
    function mul_ScalarTruncate(
        Exp memory a,
        uint scalar
    ) internal pure returns (uint) {
        Exp memory product = mul_(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 mul_ScalarTruncateAddUInt(
        Exp memory a,
        uint scalar,
        uint addend
    ) internal pure returns (uint) {
        Exp memory product = mul_(a, scalar);
        return add_(truncate(product), addend);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function mul_(
        uint a,
        uint b,
        string memory errorMessage
    ) internal pure 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
    ) internal pure returns (Exp memory) {
        return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
    }

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

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

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

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

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

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

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

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

File 19 of 24 : InterestRateModel.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

/**
 * @title Moonwell's InterestRateModel Interface
 * @author Moonwell
 */
abstract contract InterestRateModel {
    /// @notice Indicator that this is an InterestRateModel contract (for inspection)
    bool public constant isInterestRateModel = true;

    /**
     * @notice Calculates the current borrow interest rate per timestamp
     * @param cash The total amount of cash the market has
     * @param borrows The total amount of borrows the market has outstanding
     * @param reserves The total amount of reserves the market has
     * @return The borrow rate per timestamp (as a percentage, and scaled by 1e18)
     */
    function getBorrowRate(
        uint cash,
        uint borrows,
        uint reserves
    ) external view virtual returns (uint);

    /**
     * @notice Calculates the current supply interest rate per timestamp
     * @param cash The total amount of cash the market has
     * @param borrows The total amount of borrows the market has outstanding
     * @param reserves The total amount of reserves the market has
     * @param reserveFactorMantissa The current reserve factor the market has
     * @return The supply rate per timestamp (as a percentage, and scaled by 1e18)
     */
    function getSupplyRate(
        uint cash,
        uint borrows,
        uint reserves,
        uint reserveFactorMantissa
    ) external view virtual returns (uint);
}

File 20 of 24 : MToken.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

import "./ComptrollerInterface.sol";
import "./MTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./InterestRateModel.sol";

/**
 * @title Moonwell's MToken Contract
 * @notice Abstract base for MTokens
 * @author Moonwell
 */
abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter {
    /**
     * @notice Initialize the money market
     * @param comptroller_ The address of the Comptroller
     * @param interestRateModel_ The address of the interest rate model
     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
     * @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(
        ComptrollerInterface comptroller_,
        InterestRateModel interestRateModel_,
        uint initialExchangeRateMantissa_,
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) public {
        require(msg.sender == admin, "only admin may initialize the market");
        require(
            accrualBlockTimestamp == 0 && borrowIndex == 0,
            "market may only be initialized once"
        );

        // Set initial exchange rate
        initialExchangeRateMantissa = initialExchangeRateMantissa_;
        require(
            initialExchangeRateMantissa > 0,
            "initial exchange rate must be greater than zero."
        );

        // Set the comptroller
        uint err = _setComptroller(comptroller_);
        require(err == uint(Error.NO_ERROR), "setting comptroller failed");

        // Initialize block timestamp and borrow index (block timestamp mocks depend on comptroller being set)
        accrualBlockTimestamp = getBlockTimestamp();
        borrowIndex = mantissaOne;

        // Set the interest rate model (depends on block timestamp / borrow index)
        err = _setInterestRateModelFresh(interestRateModel_);
        require(
            err == uint(Error.NO_ERROR),
            "setting interest rate model failed"
        );

        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;
    }

    /**
     * @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
     * @return Whether or not the transfer succeeded
     */
    function transferTokens(
        address spender,
        address src,
        address dst,
        uint tokens
    ) internal returns (uint) {
        /* Fail if transfer not allowed */
        uint allowed = comptroller.transferAllowed(
            address(this),
            src,
            dst,
            tokens
        );
        if (allowed != 0) {
            return
                failOpaque(
                    Error.COMPTROLLER_REJECTION,
                    FailureInfo.TRANSFER_COMPTROLLER_REJECTION,
                    allowed
                );
        }

        /* Do not allow self-transfers */
        if (src == dst) {
            return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
        }

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

        /* Do the calculations, checking for {under,over}flow */
        MathError mathErr;
        uint allowanceNew;
        uint srcTokensNew;
        uint dstTokensNew;

        (mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
        if (mathErr != MathError.NO_ERROR) {
            return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
        }

        (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
        if (mathErr != MathError.NO_ERROR) {
            return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
        }

        (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
        if (mathErr != MathError.NO_ERROR) {
            return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

        accountTokens[src] = srcTokensNew;
        accountTokens[dst] = dstTokensNew;

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

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

        // unused function
        // comptroller.transferVerify(address(this), src, dst, tokens);

        return uint(Error.NO_ERROR);
    }

    /**
     * @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 override nonReentrant returns (bool) {
        return
            transferTokens(msg.sender, msg.sender, dst, amount) ==
            uint(Error.NO_ERROR);
    }

    /**
     * @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 override nonReentrant returns (bool) {
        return
            transferTokens(msg.sender, src, dst, amount) ==
            uint(Error.NO_ERROR);
    }

    /**
     * @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 (uint.max means infinite)
     * @return Whether or not the approval succeeded
     */
    function approve(
        address spender,
        uint256 amount
    ) external override 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 (uint.max means infinite)
     */
    function allowance(
        address owner,
        address spender
    ) external view override 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 override returns (uint256) {
        return accountTokens[owner];
    }

    /**
     * @notice Get the underlying balance of the `owner`
     * @dev This also accrues interest in a transaction
     * @param owner The address of the account to query
     * @return The amount of underlying owned by `owner`
     */
    function balanceOfUnderlying(
        address owner
    ) external override returns (uint) {
        Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
        (MathError mErr, uint balance) = mulScalarTruncate(
            exchangeRate,
            accountTokens[owner]
        );
        require(mErr == MathError.NO_ERROR, "balance could not be calculated");
        return balance;
    }

    /**
     * @notice Get a snapshot of the account's balances, and the cached exchange rate
     * @dev This is used by comptroller to more efficiently perform liquidity checks.
     * @param account Address of the account to snapshot
     * @return (possible error, token balance, borrow balance, exchange rate mantissa)
     */
    function getAccountSnapshot(
        address account
    ) external view override returns (uint, uint, uint, uint) {
        uint mTokenBalance = accountTokens[account];
        uint borrowBalance;
        uint exchangeRateMantissa;

        MathError mErr;

        (mErr, borrowBalance) = borrowBalanceStoredInternal(account);
        if (mErr != MathError.NO_ERROR) {
            return (uint(Error.MATH_ERROR), 0, 0, 0);
        }

        (mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
        if (mErr != MathError.NO_ERROR) {
            return (uint(Error.MATH_ERROR), 0, 0, 0);
        }

        return (
            uint(Error.NO_ERROR),
            mTokenBalance,
            borrowBalance,
            exchangeRateMantissa
        );
    }

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

    /**
     * @notice Returns the current per-timestamp borrow interest rate for this mToken
     * @return The borrow interest rate per timestamp, scaled by 1e18
     */
    function borrowRatePerTimestamp() external view override returns (uint) {
        return
            interestRateModel.getBorrowRate(
                getCashPrior(),
                totalBorrows,
                totalReserves
            );
    }

    /**
     * @notice Returns the current per-timestamp supply interest rate for this mToken
     * @return The supply interest rate per timestamp, scaled by 1e18
     */
    function supplyRatePerTimestamp() external view override returns (uint) {
        return
            interestRateModel.getSupplyRate(
                getCashPrior(),
                totalBorrows,
                totalReserves,
                reserveFactorMantissa
            );
    }

    /**
     * @notice Returns the current total borrows plus accrued interest
     * @return The total borrows with interest
     */
    function totalBorrowsCurrent()
        external
        override
        nonReentrant
        returns (uint)
    {
        require(
            accrueInterest() == uint(Error.NO_ERROR),
            "accrue interest failed"
        );
        return totalBorrows;
    }

    /**
     * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
     * @param account The address whose balance should be calculated after updating borrowIndex
     * @return The calculated balance
     */
    function borrowBalanceCurrent(
        address account
    ) external override nonReentrant returns (uint) {
        require(
            accrueInterest() == uint(Error.NO_ERROR),
            "accrue interest failed"
        );
        return borrowBalanceStored(account);
    }

    /**
     * @notice Return the borrow balance of account based on stored data
     * @param account The address whose balance should be calculated
     * @return The calculated balance
     */
    function borrowBalanceStored(
        address account
    ) public view override returns (uint) {
        (MathError err, uint result) = borrowBalanceStoredInternal(account);
        require(
            err == MathError.NO_ERROR,
            "borrowBalanceStored: borrowBalanceStoredInternal failed"
        );
        return result;
    }

    /**
     * @notice Return the borrow balance of account based on stored data
     * @param account The address whose balance should be calculated
     * @return (error code, the calculated balance or 0 if error code is non-zero)
     */
    function borrowBalanceStoredInternal(
        address account
    ) internal view returns (MathError, uint) {
        /* Note: we do not assert that the market is up to date */
        MathError mathErr;
        uint principalTimesIndex;
        uint result;

        /* Get borrowBalance and borrowIndex */
        BorrowSnapshot storage borrowSnapshot = accountBorrows[account];

        /* If borrowBalance = 0 then borrowIndex is likely also 0.
         * Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
         */
        if (borrowSnapshot.principal == 0) {
            return (MathError.NO_ERROR, 0);
        }

        /* Calculate new borrow balance using the interest index:
         *  recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
         */
        (mathErr, principalTimesIndex) = mulUInt(
            borrowSnapshot.principal,
            borrowIndex
        );
        if (mathErr != MathError.NO_ERROR) {
            return (mathErr, 0);
        }

        (mathErr, result) = divUInt(
            principalTimesIndex,
            borrowSnapshot.interestIndex
        );
        if (mathErr != MathError.NO_ERROR) {
            return (mathErr, 0);
        }

        return (MathError.NO_ERROR, result);
    }

    /**
     * @notice Accrue interest then return the up-to-date exchange rate
     * @return Calculated exchange rate scaled by 1e18
     */
    function exchangeRateCurrent() public override nonReentrant returns (uint) {
        require(
            accrueInterest() == uint(Error.NO_ERROR),
            "accrue interest failed"
        );
        return exchangeRateStored();
    }

    /**
     * @notice Calculates the exchange rate from the underlying to the MToken
     * @dev This function does not accrue interest before calculating the exchange rate
     * @return Calculated exchange rate scaled by 1e18
     */
    function exchangeRateStored() public view override returns (uint) {
        (MathError err, uint result) = exchangeRateStoredInternal();
        require(
            err == MathError.NO_ERROR,
            "exchangeRateStored: exchangeRateStoredInternal failed"
        );
        return result;
    }

    /**
     * @notice Calculates the exchange rate from the underlying to the MToken
     * @dev This function does not accrue interest before calculating the exchange rate
     * @return (error code, calculated exchange rate scaled by 1e18)
     */
    function exchangeRateStoredInternal()
        internal
        view
        virtual
        returns (MathError, uint)
    {
        uint _totalSupply = totalSupply;
        if (_totalSupply == 0) {
            /*
             * If there are no tokens minted:
             *  exchangeRate = initialExchangeRate
             */
            return (MathError.NO_ERROR, initialExchangeRateMantissa);
        } else {
            /*
             * Otherwise:
             *  exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
             */
            uint totalCash = getCashPrior();
            uint cashPlusBorrowsMinusReserves;
            Exp memory exchangeRate;
            MathError mathErr;

            (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(
                totalCash,
                totalBorrows,
                totalReserves
            );
            if (mathErr != MathError.NO_ERROR) {
                return (mathErr, 0);
            }

            (mathErr, exchangeRate) = getExp(
                cashPlusBorrowsMinusReserves,
                _totalSupply
            );
            if (mathErr != MathError.NO_ERROR) {
                return (mathErr, 0);
            }

            return (MathError.NO_ERROR, exchangeRate.mantissa);
        }
    }

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

    /**
     * @notice Applies accrued interest to total borrows and reserves
     * @dev This calculates interest accrued from the last checkpointed block
     *   up to the current block and writes new checkpoint to storage.
     */
    function accrueInterest() public virtual override returns (uint) {
        /* Remember the initial block timestamp */
        uint currentBlockTimestamp = getBlockTimestamp();
        uint accrualBlockTimestampPrior = accrualBlockTimestamp;

        /* Short-circuit accumulating 0 interest */
        if (accrualBlockTimestampPrior == currentBlockTimestamp) {
            return uint(Error.NO_ERROR);
        }

        /* Read the previous values out of storage */
        uint cashPrior = getCashPrior();
        uint borrowsPrior = totalBorrows;
        uint reservesPrior = totalReserves;
        uint borrowIndexPrior = borrowIndex;

        /* Calculate the current borrow interest rate */
        uint borrowRateMantissa = interestRateModel.getBorrowRate(
            cashPrior,
            borrowsPrior,
            reservesPrior
        );
        require(
            borrowRateMantissa <= borrowRateMaxMantissa,
            "borrow rate is absurdly high"
        );

        /* Calculate the number of blocks elapsed since the last accrual */
        (MathError mathErr, uint blockDelta) = subUInt(
            currentBlockTimestamp,
            accrualBlockTimestampPrior
        );
        require(
            mathErr == MathError.NO_ERROR,
            "could not calculate block delta"
        );

        /*
         * Calculate the interest accumulated into borrows and reserves and the new index:
         *  simpleInterestFactor = borrowRate * blockDelta
         *  interestAccumulated = simpleInterestFactor * totalBorrows
         *  totalBorrowsNew = interestAccumulated + totalBorrows
         *  totalReservesNew = interestAccumulated * reserveFactor + totalReserves
         *  borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
         */

        Exp memory simpleInterestFactor;
        uint interestAccumulated;
        uint totalBorrowsNew;
        uint totalReservesNew;
        uint borrowIndexNew;

        (mathErr, simpleInterestFactor) = mulScalar(
            Exp({mantissa: borrowRateMantissa}),
            blockDelta
        );
        if (mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo
                        .ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
                    uint(mathErr)
                );
        }

        (mathErr, interestAccumulated) = mulScalarTruncate(
            simpleInterestFactor,
            borrowsPrior
        );
        if (mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo
                        .ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
                    uint(mathErr)
                );
        }

        (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
        if (mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo
                        .ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
                    uint(mathErr)
                );
        }

        (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(
            Exp({mantissa: reserveFactorMantissa}),
            interestAccumulated,
            reservesPrior
        );
        if (mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo
                        .ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
                    uint(mathErr)
                );
        }

        (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(
            simpleInterestFactor,
            borrowIndexPrior,
            borrowIndexPrior
        );
        if (mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo
                        .ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
                    uint(mathErr)
                );
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

        /* We write the previously calculated values into storage */
        accrualBlockTimestamp = currentBlockTimestamp;
        borrowIndex = borrowIndexNew;
        totalBorrows = totalBorrowsNew;
        totalReserves = totalReservesNew;

        /* We emit an AccrueInterest event */
        emit AccrueInterest(
            cashPrior,
            interestAccumulated,
            borrowIndexNew,
            totalBorrowsNew
        );

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Sender supplies assets into the market and receives mTokens in exchange
     * @dev Accrues interest whether or not the operation succeeds, unless reverted
     * @param mintAmount The amount of the underlying asset to supply
     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
     */
    function mintInternal(
        uint mintAmount
    ) internal nonReentrant returns (uint, uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
            return (
                fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED),
                0
            );
        }
        // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
        return mintFresh(msg.sender, mintAmount);
    }

    struct MintLocalVars {
        Error err;
        MathError mathErr;
        uint exchangeRateMantissa;
        uint mintTokens;
        uint totalSupplyNew;
        uint accountTokensNew;
        uint actualMintAmount;
    }

    /**
     * @notice User supplies assets into the market and receives mTokens in exchange
     * @dev Assumes interest has already been accrued up to the current block
     * @param minter The address of the account which is supplying the assets
     * @param mintAmount The amount of the underlying asset to supply
     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
     */
    function mintFresh(
        address minter,
        uint mintAmount
    ) internal returns (uint, uint) {
        /* Fail if mint not allowed */
        uint allowed = comptroller.mintAllowed(
            address(this),
            minter,
            mintAmount
        );
        if (allowed != 0) {
            return (
                failOpaque(
                    Error.COMPTROLLER_REJECTION,
                    FailureInfo.MINT_COMPTROLLER_REJECTION,
                    allowed
                ),
                0
            );
        }

        /* Verify market's block timestamp equals current block timestamp */
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return (
                fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK),
                0
            );
        }

        MintLocalVars memory vars;

        (
            vars.mathErr,
            vars.exchangeRateMantissa
        ) = exchangeRateStoredInternal();
        if (vars.mathErr != MathError.NO_ERROR) {
            return (
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED,
                    uint(vars.mathErr)
                ),
                0
            );
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

        /*
         *  We call `doTransferIn` for the minter and the mintAmount.
         *  Note: The mToken must handle variations between ERC-20 and GLMR 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 mToken holds an additional `actualMintAmount`
         *  of cash.
         */
        vars.actualMintAmount = doTransferIn(minter, mintAmount);

        /*
         * We get the current exchange rate and calculate the number of mTokens to be minted:
         *  mintTokens = actualMintAmount / exchangeRate
         */

        (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(
            vars.actualMintAmount,
            Exp({mantissa: vars.exchangeRateMantissa})
        );
        require(
            vars.mathErr == MathError.NO_ERROR,
            "MINT_EXCHANGE_CALCULATION_FAILED"
        );

        /*
         * We calculate the new total supply of mTokens and minter token balance, checking for overflow:
         *  totalSupplyNew = totalSupply + mintTokens
         *  accountTokensNew = accountTokens[minter] + mintTokens
         */
        (vars.mathErr, vars.totalSupplyNew) = addUInt(
            totalSupply,
            vars.mintTokens
        );
        require(
            vars.mathErr == MathError.NO_ERROR,
            "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"
        );

        (vars.mathErr, vars.accountTokensNew) = addUInt(
            accountTokens[minter],
            vars.mintTokens
        );
        require(
            vars.mathErr == MathError.NO_ERROR,
            "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 */
        // unused function
        // comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);

        return (uint(Error.NO_ERROR), vars.actualMintAmount);
    }

    /**
     * @notice Sender redeems mTokens in exchange for the underlying asset
     * @dev Accrues interest whether or not the operation succeeds, unless reverted
     * @param redeemTokens The number of mTokens to redeem into underlying
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function redeemInternal(
        uint redeemTokens
    ) internal nonReentrant returns (uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
            return
                fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
        }
        // redeemFresh emits redeem-specific logs on errors, so we don't need to
        return redeemFresh(payable(msg.sender), redeemTokens, 0);
    }

    /**
     * @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
     * @dev Accrues interest whether or not the operation succeeds, unless reverted
     * @param redeemAmount The amount of underlying to receive from redeeming mTokens
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function redeemUnderlyingInternal(
        uint redeemAmount
    ) internal nonReentrant returns (uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
            return
                fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
        }
        // redeemFresh emits redeem-specific logs on errors, so we don't need to
        return redeemFresh(payable(msg.sender), 0, redeemAmount);
    }

    struct RedeemLocalVars {
        Error err;
        MathError mathErr;
        uint exchangeRateMantissa;
        uint redeemTokens;
        uint redeemAmount;
        uint totalSupplyNew;
        uint accountTokensNew;
    }

    /**
     * @notice User redeems mTokens in exchange for the underlying asset
     * @dev Assumes interest has already been accrued up to the current block
     * @param redeemer The address of the account which is redeeming the tokens
     * @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
     * @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function redeemFresh(
        address payable redeemer,
        uint redeemTokensIn,
        uint redeemAmountIn
    ) internal returns (uint) {
        require(
            redeemTokensIn == 0 || redeemAmountIn == 0,
            "one of redeemTokensIn or redeemAmountIn must be zero"
        );

        RedeemLocalVars memory vars;

        /* exchangeRate = invoke Exchange Rate Stored() */
        (
            vars.mathErr,
            vars.exchangeRateMantissa
        ) = exchangeRateStoredInternal();
        if (vars.mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED,
                    uint(vars.mathErr)
                );
        }

        /* If redeemTokensIn > 0: */
        if (redeemTokensIn > 0) {
            /*
             * We calculate the exchange rate and the amount of underlying to be redeemed:
             *  redeemTokens = redeemTokensIn
             *  redeemAmount = redeemTokensIn x exchangeRateCurrent
             */
            if (redeemTokensIn == type(uint).max) {
                vars.redeemTokens = accountTokens[redeemer];
            } else {
                vars.redeemTokens = redeemTokensIn;
            }

            (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(
                Exp({mantissa: vars.exchangeRateMantissa}),
                vars.redeemTokens
            );
            if (vars.mathErr != MathError.NO_ERROR) {
                return
                    failOpaque(
                        Error.MATH_ERROR,
                        FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
                        uint(vars.mathErr)
                    );
            }
        } else {
            /*
             * We get the current exchange rate and calculate the amount to be redeemed:
             *  redeemTokens = redeemAmountIn / exchangeRate
             *  redeemAmount = redeemAmountIn
             */
            if (redeemAmountIn == type(uint).max) {
                vars.redeemTokens = accountTokens[redeemer];

                (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(
                    Exp({mantissa: vars.exchangeRateMantissa}),
                    vars.redeemTokens
                );
                if (vars.mathErr != MathError.NO_ERROR) {
                    return
                        failOpaque(
                            Error.MATH_ERROR,
                            FailureInfo
                                .REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
                            uint(vars.mathErr)
                        );
                }
            } else {
                vars.redeemAmount = redeemAmountIn;

                (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(
                    redeemAmountIn,
                    Exp({mantissa: vars.exchangeRateMantissa})
                );
                if (vars.mathErr != MathError.NO_ERROR) {
                    return
                        failOpaque(
                            Error.MATH_ERROR,
                            FailureInfo
                                .REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
                            uint(vars.mathErr)
                        );
                }
            }
        }

        /* Fail if redeem not allowed */
        uint allowed = comptroller.redeemAllowed(
            address(this),
            redeemer,
            vars.redeemTokens
        );
        if (allowed != 0) {
            return
                failOpaque(
                    Error.COMPTROLLER_REJECTION,
                    FailureInfo.REDEEM_COMPTROLLER_REJECTION,
                    allowed
                );
        }

        /* Verify market's block timestamp equals current block timestamp */
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.REDEEM_FRESHNESS_CHECK
                );
        }

        /*
         * We calculate the new total supply and redeemer balance, checking for underflow:
         *  totalSupplyNew = totalSupply - redeemTokens
         *  accountTokensNew = accountTokens[redeemer] - redeemTokens
         */
        (vars.mathErr, vars.totalSupplyNew) = subUInt(
            totalSupply,
            vars.redeemTokens
        );
        if (vars.mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
                    uint(vars.mathErr)
                );
        }

        (vars.mathErr, vars.accountTokensNew) = subUInt(
            accountTokens[redeemer],
            vars.redeemTokens
        );
        if (vars.mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
                    uint(vars.mathErr)
                );
        }

        /* Fail gracefully if protocol has insufficient cash */
        if (getCashPrior() < vars.redeemAmount) {
            return
                fail(
                    Error.TOKEN_INSUFFICIENT_CASH,
                    FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE
                );
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

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

        /* We emit a Transfer event, and a Redeem event */
        emit Transfer(redeemer, address(this), vars.redeemTokens);
        emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);

        /* We call the defense hook */
        comptroller.redeemVerify(
            address(this),
            redeemer,
            vars.redeemAmount,
            vars.redeemTokens
        );

        /*
         * We invoke doTransferOut for the redeemer and the redeemAmount.
         *  Note: The mToken must handle variations between ERC-20 and GLMR underlying.
         *  On success, the mToken has redeemAmount less of cash.
         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
         */
        doTransferOut(redeemer, vars.redeemAmount);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Sender borrows assets from the protocol to their own address
     * @param borrowAmount The amount of the underlying asset to borrow
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function borrowInternal(
        uint borrowAmount
    ) internal nonReentrant returns (uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
            return
                fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
        }
        // borrowFresh emits borrow-specific logs on errors, so we don't need to
        return borrowFresh(payable(msg.sender), borrowAmount);
    }

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

    /**
     * @notice Users borrow assets from the protocol to their own address
     * @param borrowAmount The amount of the underlying asset to borrow
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function borrowFresh(
        address payable borrower,
        uint borrowAmount
    ) internal returns (uint) {
        /* Fail if borrow not allowed */
        uint allowed = comptroller.borrowAllowed(
            address(this),
            borrower,
            borrowAmount
        );
        if (allowed != 0) {
            return
                failOpaque(
                    Error.COMPTROLLER_REJECTION,
                    FailureInfo.BORROW_COMPTROLLER_REJECTION,
                    allowed
                );
        }

        /* Verify market's block timestamp equals current block timestamp */
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.BORROW_FRESHNESS_CHECK
                );
        }

        /* Fail gracefully if protocol has insufficient underlying cash */
        if (getCashPrior() < borrowAmount) {
            return
                fail(
                    Error.TOKEN_INSUFFICIENT_CASH,
                    FailureInfo.BORROW_CASH_NOT_AVAILABLE
                );
        }

        BorrowLocalVars memory vars;

        /*
         * We calculate the new borrower and total borrow balances, failing on overflow:
         *  accountBorrowsNew = accountBorrows + borrowAmount
         *  totalBorrowsNew = totalBorrows + borrowAmount
         */
        (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(
            borrower
        );
        if (vars.mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
                    uint(vars.mathErr)
                );
        }

        (vars.mathErr, vars.accountBorrowsNew) = addUInt(
            vars.accountBorrows,
            borrowAmount
        );
        if (vars.mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo
                        .BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
                    uint(vars.mathErr)
                );
        }

        (vars.mathErr, vars.totalBorrowsNew) = addUInt(
            totalBorrows,
            borrowAmount
        );
        if (vars.mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
                    uint(vars.mathErr)
                );
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

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

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

        /*
         * We invoke doTransferOut for the borrower and the borrowAmount.
         *  Note: The mToken must handle variations between ERC-20 and GLMR underlying.
         *  On success, the mToken borrowAmount less of cash.
         *  doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
         */
        doTransferOut(borrower, borrowAmount);

        /* We call the defense hook */
        // unused function
        // comptroller.borrowVerify(address(this), borrower, borrowAmount);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Sender repays their own borrow
     * @param repayAmount The amount to repay
     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
     */
    function repayBorrowInternal(
        uint repayAmount
    ) internal nonReentrant returns (uint, uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
            return (
                fail(
                    Error(error),
                    FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED
                ),
                0
            );
        }
        // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
        return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
    }

    /**
     * @notice Sender repays a borrow belonging to borrower
     * @param borrower the account with the debt being payed off
     * @param repayAmount The amount to repay
     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
     */
    function repayBorrowBehalfInternal(
        address borrower,
        uint repayAmount
    ) internal nonReentrant returns (uint, uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
            return (
                fail(
                    Error(error),
                    FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED
                ),
                0
            );
        }
        // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
        return repayBorrowFresh(msg.sender, borrower, repayAmount);
    }

    struct RepayBorrowLocalVars {
        Error err;
        MathError mathErr;
        uint repayAmount;
        uint borrowerIndex;
        uint accountBorrows;
        uint accountBorrowsNew;
        uint totalBorrowsNew;
        uint actualRepayAmount;
    }

    /**
     * @notice Borrows are repaid by another user (possibly the borrower).
     * @param payer the account paying off the borrow
     * @param borrower the account with the debt being payed off
     * @param repayAmount the amount of underlying tokens being returned
     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
     */
    function repayBorrowFresh(
        address payer,
        address borrower,
        uint repayAmount
    ) internal returns (uint, uint) {
        /* Fail if repayBorrow not allowed */
        uint allowed = comptroller.repayBorrowAllowed(
            address(this),
            payer,
            borrower,
            repayAmount
        );
        if (allowed != 0) {
            return (
                failOpaque(
                    Error.COMPTROLLER_REJECTION,
                    FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION,
                    allowed
                ),
                0
            );
        }

        /* Verify market's block timestamp equals current block timestamp */
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return (
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.REPAY_BORROW_FRESHNESS_CHECK
                ),
                0
            );
        }

        RepayBorrowLocalVars memory vars;

        /* We remember the original borrowerIndex for verification purposes */
        vars.borrowerIndex = accountBorrows[borrower].interestIndex;

        /* We fetch the amount the borrower owes, with accumulated interest */
        (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(
            borrower
        );
        if (vars.mathErr != MathError.NO_ERROR) {
            return (
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo
                        .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
                    uint(vars.mathErr)
                ),
                0
            );
        }

        /* If repayAmount == uint.max, repayAmount = accountBorrows */
        if (repayAmount == type(uint).max) {
            vars.repayAmount = vars.accountBorrows;
        } else {
            vars.repayAmount = repayAmount;
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

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

        /*
         * We calculate the new borrower and total borrow balances, failing on underflow:
         *  accountBorrowsNew = accountBorrows - actualRepayAmount
         *  totalBorrowsNew = totalBorrows - actualRepayAmount
         */
        (vars.mathErr, vars.accountBorrowsNew) = subUInt(
            vars.accountBorrows,
            vars.actualRepayAmount
        );
        require(
            vars.mathErr == MathError.NO_ERROR,
            "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"
        );

        (vars.mathErr, vars.totalBorrowsNew) = subUInt(
            totalBorrows,
            vars.actualRepayAmount
        );
        require(
            vars.mathErr == MathError.NO_ERROR,
            "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"
        );

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

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

        /* We call the defense hook */
        // unused function
        // comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);

        return (uint(Error.NO_ERROR), vars.actualRepayAmount);
    }

    /**
     * @notice The sender liquidates the borrowers collateral.
     *  The collateral seized is transferred to the liquidator.
     * @param borrower The borrower of this mToken to be liquidated
     * @param mTokenCollateral The market in which to seize collateral from the borrower
     * @param repayAmount The amount of the underlying borrowed asset to repay
     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
     */
    function liquidateBorrowInternal(
        address borrower,
        uint repayAmount,
        MTokenInterface mTokenCollateral
    ) internal nonReentrant returns (uint, uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
            return (
                fail(
                    Error(error),
                    FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED
                ),
                0
            );
        }

        error = mTokenCollateral.accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
            return (
                fail(
                    Error(error),
                    FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED
                ),
                0
            );
        }

        // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
        return
            liquidateBorrowFresh(
                msg.sender,
                borrower,
                repayAmount,
                mTokenCollateral
            );
    }

    /**
     * @notice The liquidator liquidates the borrowers collateral.
     *  The collateral seized is transferred to the liquidator.
     * @param borrower The borrower of this mToken to be liquidated
     * @param liquidator The address repaying the borrow and seizing collateral
     * @param mTokenCollateral The market in which to seize collateral from the borrower
     * @param repayAmount The amount of the underlying borrowed asset to repay
     * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
     */
    function liquidateBorrowFresh(
        address liquidator,
        address borrower,
        uint repayAmount,
        MTokenInterface mTokenCollateral
    ) internal returns (uint, uint) {
        /* Fail if liquidate not allowed */
        uint allowed = comptroller.liquidateBorrowAllowed(
            address(this),
            address(mTokenCollateral),
            liquidator,
            borrower,
            repayAmount
        );
        if (allowed != 0) {
            return (
                failOpaque(
                    Error.COMPTROLLER_REJECTION,
                    FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION,
                    allowed
                ),
                0
            );
        }

        /* Verify market's block timestamp equals current block timestamp */
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return (
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.LIQUIDATE_FRESHNESS_CHECK
                ),
                0
            );
        }

        /* Verify mTokenCollateral market's block timestamp equals current block timestamp */
        if (mTokenCollateral.accrualBlockTimestamp() != getBlockTimestamp()) {
            return (
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK
                ),
                0
            );
        }

        /* Fail if borrower = liquidator */
        if (borrower == liquidator) {
            return (
                fail(
                    Error.INVALID_ACCOUNT_PAIR,
                    FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER
                ),
                0
            );
        }

        /* Fail if repayAmount = 0 */
        if (repayAmount == 0) {
            return (
                fail(
                    Error.INVALID_CLOSE_AMOUNT_REQUESTED,
                    FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO
                ),
                0
            );
        }

        /* Fail if repayAmount = uint.max */
        if (repayAmount == type(uint).max) {
            return (
                fail(
                    Error.INVALID_CLOSE_AMOUNT_REQUESTED,
                    FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX
                ),
                0
            );
        }

        /* Fail if repayBorrow fails */
        (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(
            liquidator,
            borrower,
            repayAmount
        );
        if (repayBorrowError != uint(Error.NO_ERROR)) {
            return (
                fail(
                    Error(repayBorrowError),
                    FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED
                ),
                0
            );
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

        /* We calculate the number of collateral tokens that will be seized */
        (uint amountSeizeError, uint seizeTokens) = comptroller
            .liquidateCalculateSeizeTokens(
                address(this),
                address(mTokenCollateral),
                actualRepayAmount
            );
        require(
            amountSeizeError == uint(Error.NO_ERROR),
            "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"
        );

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

        // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
        uint seizeError;
        if (address(mTokenCollateral) == address(this)) {
            seizeError = seizeInternal(
                address(this),
                liquidator,
                borrower,
                seizeTokens
            );
        } else {
            seizeError = mTokenCollateral.seize(
                liquidator,
                borrower,
                seizeTokens
            );
        }

        /* Revert if seize tokens fails (since we cannot be sure of side effects) */
        require(seizeError == uint(Error.NO_ERROR), "token seizure failed");

        /* We emit a LiquidateBorrow event */
        emit LiquidateBorrow(
            liquidator,
            borrower,
            actualRepayAmount,
            address(mTokenCollateral),
            seizeTokens
        );

        /* We call the defense hook */
        // unused function
        // comptroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);

        return (uint(Error.NO_ERROR), actualRepayAmount);
    }

    /**
     * @notice Transfers collateral tokens (this market) to the liquidator.
     * @dev Will fail unless called by another mToken during the process of liquidation.
     *  Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter.
     * @param liquidator The account receiving seized collateral
     * @param borrower The account having collateral seized
     * @param seizeTokens The number of mTokens to seize
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function seize(
        address liquidator,
        address borrower,
        uint seizeTokens
    ) external override nonReentrant returns (uint) {
        return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
    }

    struct SeizeInternalLocalVars {
        MathError mathErr;
        uint borrowerTokensNew;
        uint liquidatorTokensNew;
        uint liquidatorSeizeTokens;
        uint protocolSeizeTokens;
        uint protocolSeizeAmount;
        uint exchangeRateMantissa;
        uint totalReservesNew;
        uint totalSupplyNew;
    }

    /**
     * @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 MToken.
     *  Its absolutely critical to use msg.sender as the seizer mToken and not a parameter.
     * @param seizerToken The contract seizing the collateral (i.e. borrowed mToken)
     * @param liquidator The account receiving seized collateral
     * @param borrower The account having collateral seized
     * @param seizeTokens The number of mTokens to seize
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function seizeInternal(
        address seizerToken,
        address liquidator,
        address borrower,
        uint seizeTokens
    ) internal returns (uint) {
        /* Fail if seize not allowed */
        uint allowed = comptroller.seizeAllowed(
            address(this),
            seizerToken,
            liquidator,
            borrower,
            seizeTokens
        );
        if (allowed != 0) {
            return
                failOpaque(
                    Error.COMPTROLLER_REJECTION,
                    FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
                    allowed
                );
        }

        /* Fail if borrower = liquidator */
        if (borrower == liquidator) {
            return
                fail(
                    Error.INVALID_ACCOUNT_PAIR,
                    FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER
                );
        }

        SeizeInternalLocalVars memory vars;

        /*
         * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
         *  borrowerTokensNew = accountTokens[borrower] - seizeTokens
         *  liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
         */
        (vars.mathErr, vars.borrowerTokensNew) = subUInt(
            accountTokens[borrower],
            seizeTokens
        );
        if (vars.mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
                    uint(vars.mathErr)
                );
        }

        vars.protocolSeizeTokens = mul_(
            seizeTokens,
            Exp({mantissa: protocolSeizeShareMantissa})
        );
        vars.liquidatorSeizeTokens = sub_(
            seizeTokens,
            vars.protocolSeizeTokens
        );

        (
            vars.mathErr,
            vars.exchangeRateMantissa
        ) = exchangeRateStoredInternal();
        require(vars.mathErr == MathError.NO_ERROR, "exchange rate math error");

        vars.protocolSeizeAmount = mul_ScalarTruncate(
            Exp({mantissa: vars.exchangeRateMantissa}),
            vars.protocolSeizeTokens
        );

        vars.totalReservesNew = add_(totalReserves, vars.protocolSeizeAmount);
        vars.totalSupplyNew = sub_(totalSupply, vars.protocolSeizeTokens);

        (vars.mathErr, vars.liquidatorTokensNew) = addUInt(
            accountTokens[liquidator],
            vars.liquidatorSeizeTokens
        );
        if (vars.mathErr != MathError.NO_ERROR) {
            return
                failOpaque(
                    Error.MATH_ERROR,
                    FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
                    uint(vars.mathErr)
                );
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

        /* We write the previously calculated values into storage */
        totalReserves = vars.totalReservesNew;
        totalSupply = vars.totalSupplyNew;
        accountTokens[borrower] = vars.borrowerTokensNew;
        accountTokens[liquidator] = vars.liquidatorTokensNew;

        /* Emit a Transfer event */
        emit Transfer(borrower, liquidator, vars.liquidatorSeizeTokens);
        emit Transfer(borrower, address(this), vars.protocolSeizeTokens);
        emit ReservesAdded(
            address(this),
            vars.protocolSeizeAmount,
            vars.totalReservesNew
        );

        /* We call the defense hook */
        // unused function
        // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);

        return uint(Error.NO_ERROR);
    }

    /*** 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.
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setPendingAdmin(
        address payable newPendingAdmin
    ) external override returns (uint) {
        // Check caller = admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK
                );
        }

        // 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);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
     * @dev Admin function for pending admin to accept role and update admin
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _acceptAdmin() external override returns (uint) {
        // Check caller is pendingAdmin and pendingAdmin �� address(0)
        if (msg.sender != pendingAdmin || msg.sender == address(0)) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK
                );
        }

        // 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 = payable(address(0));

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

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Sets a new comptroller for the market
     * @dev Admin function to set a new comptroller
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setComptroller(
        ComptrollerInterface newComptroller
    ) public override returns (uint) {
        // Check caller is admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_COMPTROLLER_OWNER_CHECK
                );
        }

        ComptrollerInterface oldComptroller = comptroller;
        // Ensure invoke comptroller.isComptroller() returns true
        require(newComptroller.isComptroller(), "marker method returned false");

        // Set market's comptroller to newComptroller
        comptroller = newComptroller;

        // Emit NewComptroller(oldComptroller, newComptroller)
        emit NewComptroller(oldComptroller, newComptroller);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
     * @dev Admin function to accrue interest and set a new reserve factor
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setReserveFactor(
        uint newReserveFactorMantissa
    ) external override nonReentrant returns (uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
            return
                fail(
                    Error(error),
                    FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED
                );
        }
        // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
        return _setReserveFactorFresh(newReserveFactorMantissa);
    }

    /**
     * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
     * @dev Admin function to set a new reserve factor
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setReserveFactorFresh(
        uint newReserveFactorMantissa
    ) internal returns (uint) {
        // Check caller is admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK
                );
        }

        // Verify market's block timestamp equals current block timestamp
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK
                );
        }

        // Check newReserveFactor �� maxReserveFactor
        if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
            return
                fail(
                    Error.BAD_INPUT,
                    FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK
                );
        }

        uint oldReserveFactorMantissa = reserveFactorMantissa;
        reserveFactorMantissa = newReserveFactorMantissa;

        emit NewReserveFactor(
            oldReserveFactorMantissa,
            newReserveFactorMantissa
        );

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Accrues interest and reduces reserves by transferring from msg.sender
     * @param addAmount Amount of addition to reserves
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _addReservesInternal(
        uint addAmount
    ) internal nonReentrant returns (uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
            return
                fail(
                    Error(error),
                    FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED
                );
        }

        // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
        (error, ) = _addReservesFresh(addAmount);
        return error;
    }

    /**
     * @notice Add reserves by transferring from caller
     * @dev Requires fresh interest accrual
     * @param addAmount Amount of addition to reserves
     * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
     */
    function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
        // totalReserves + actualAddAmount
        uint totalReservesNew;
        uint actualAddAmount;

        // We fail gracefully unless market's block timestamp equals current block timestamp
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return (
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.ADD_RESERVES_FRESH_CHECK
                ),
                actualAddAmount
            );
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

        /*
         * We call doTransferIn for the caller and the addAmount
         *  Note: The mToken must handle variations between ERC-20 and GLMR underlying.
         *  On success, the mToken holds an additional addAmount of cash.
         *  doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
         *  it returns the amount actually transferred, in case of a fee.
         */

        actualAddAmount = doTransferIn(msg.sender, addAmount);

        totalReservesNew = totalReserves + actualAddAmount;

        /* Revert on overflow */
        require(
            totalReservesNew >= totalReserves,
            "add reserves unexpected overflow"
        );

        // Store reserves[n+1] = reserves[n] + actualAddAmount
        totalReserves = totalReservesNew;

        /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
        emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);

        /* Return (NO_ERROR, actualAddAmount) */
        return (uint(Error.NO_ERROR), actualAddAmount);
    }

    /**
     * @notice Accrues interest and reduces reserves by transferring to admin
     * @param reduceAmount Amount of reduction to reserves
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _reduceReserves(
        uint reduceAmount
    ) external override nonReentrant returns (uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
            return
                fail(
                    Error(error),
                    FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED
                );
        }
        // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
        return _reduceReservesFresh(reduceAmount);
    }

    /**
     * @notice Reduces reserves by transferring to admin
     * @dev Requires fresh interest accrual
     * @param reduceAmount Amount of reduction to reserves
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
        // totalReserves - reduceAmount
        uint totalReservesNew;

        // Check caller is admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.REDUCE_RESERVES_ADMIN_CHECK
                );
        }

        // We fail gracefully unless market's block timestamp equals current block timestamp
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.REDUCE_RESERVES_FRESH_CHECK
                );
        }

        // Fail gracefully if protocol has insufficient underlying cash
        if (getCashPrior() < reduceAmount) {
            return
                fail(
                    Error.TOKEN_INSUFFICIENT_CASH,
                    FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE
                );
        }

        // Check reduceAmount �� reserves[n] (totalReserves)
        if (reduceAmount > totalReserves) {
            return
                fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

        totalReservesNew = totalReserves - reduceAmount;
        // We checked reduceAmount <= totalReserves above, so this should never revert.
        require(
            totalReservesNew <= totalReserves,
            "reduce reserves unexpected underflow"
        );

        // Store reserves[n+1] = reserves[n] - reduceAmount
        totalReserves = totalReservesNew;

        // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
        doTransferOut(admin, reduceAmount);

        emit ReservesReduced(admin, reduceAmount, totalReservesNew);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
     * @dev Admin function to accrue interest and update the interest rate model
     * @param newInterestRateModel the new interest rate model to use
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setInterestRateModel(
        InterestRateModel newInterestRateModel
    ) public override returns (uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
            return
                fail(
                    Error(error),
                    FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED
                );
        }
        // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
        return _setInterestRateModelFresh(newInterestRateModel);
    }

    /**
     * @notice updates the interest rate model (*requires fresh interest accrual)
     * @dev Admin function to update the interest rate model
     * @param newInterestRateModel the new interest rate model to use
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setInterestRateModelFresh(
        InterestRateModel newInterestRateModel
    ) internal returns (uint) {
        // Used to store old model for use in the event that is emitted on success
        InterestRateModel oldInterestRateModel;

        // Check caller is admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK
                );
        }

        // We fail gracefully unless market's block timestamp equals current block timestamp
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK
                );
        }

        // Track the market's current interest rate model
        oldInterestRateModel = interestRateModel;

        // Ensure invoke newInterestRateModel.isInterestRateModel() returns true
        require(
            newInterestRateModel.isInterestRateModel(),
            "marker method returned false"
        );

        // Set the interest rate model to newInterestRateModel
        interestRateModel = newInterestRateModel;

        // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
        emit NewMarketInterestRateModel(
            oldInterestRateModel,
            newInterestRateModel
        );

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice accrues interest and updates the protocol seize share using _setProtocolSeizeShareFresh
     * @dev Admin function to accrue interest and update the protocol seize share
     * @param newProtocolSeizeShareMantissa the new protocol seize share to use
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setProtocolSeizeShare(
        uint newProtocolSeizeShareMantissa
    ) external override nonReentrant returns (uint) {
        uint error = accrueInterest();
        if (error != uint(Error.NO_ERROR)) {
            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of protocol seize share failed
            return
                fail(
                    Error(error),
                    FailureInfo.SET_PROTOCOL_SEIZE_SHARE_ACCRUE_INTEREST_FAILED
                );
        }
        // _setProtocolSeizeShareFresh emits protocol-seize-share-update-specific logs on errors, so we don't need to.
        return _setProtocolSeizeShareFresh(newProtocolSeizeShareMantissa);
    }

    /**
     * @notice updates the protocol seize share (*requires fresh interest accrual)
     * @dev Admin function to update the protocol seize share
     * @param newProtocolSeizeShareMantissa the new protocol seize share to use
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setProtocolSeizeShareFresh(
        uint newProtocolSeizeShareMantissa
    ) internal returns (uint) {
        // Used to store old share for use in the event that is emitted on success
        uint oldProtocolSeizeShareMantissa;

        // Check caller is admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_PROTOCOL_SEIZE_SHARE_OWNER_CHECK
                );
        }

        // We fail gracefully unless market's block timestamp equals current block timestamp
        if (accrualBlockTimestamp != getBlockTimestamp()) {
            return
                fail(
                    Error.MARKET_NOT_FRESH,
                    FailureInfo.SET_PROTOCOL_SEIZE_SHARE_FRESH_CHECK
                );
        }

        // Track the market's current protocol seize share
        oldProtocolSeizeShareMantissa = protocolSeizeShareMantissa;

        // Set the protocol seize share to newProtocolSeizeShareMantissa
        protocolSeizeShareMantissa = newProtocolSeizeShareMantissa;

        // Emit NewProtocolSeizeShareMantissa(oldProtocolSeizeShareMantissa, newProtocolSeizeShareMantissa)
        emit NewProtocolSeizeShare(
            oldProtocolSeizeShareMantissa,
            newProtocolSeizeShareMantissa
        );

        return uint(Error.NO_ERROR);
    }

    /*** Safe Token ***/

    /**
     * @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 virtual 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 virtual 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 virtual;

    /*** 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 21 of 24 : MTokenInterfaces.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
import "./EIP20NonStandardInterface.sol";
import "./ErrorReporter.sol";

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

    /// @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 Maximum borrow rate that can ever be applied (.0005% / block)
    uint internal constant borrowRateMaxMantissa = 0.0005e16;

    // @notice Maximum fraction of interest that can be set aside for reserves
    uint internal constant reserveFactorMaxMantissa = 1e18;

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

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

    /// @notice Contract which oversees inter-mToken operations
    ComptrollerInterface public comptroller;

    /// @notice Model which tells what the current interest rate should be
    InterestRateModel public interestRateModel;

    // @notice Initial exchange rate used when minting the first MTokens (used when totalSupply = 0)
    uint internal initialExchangeRateMantissa;

    /// @notice Fraction of interest currently set aside for reserves
    uint public reserveFactorMantissa;

    /// @notice Block number that interest was last accrued at
    uint public accrualBlockTimestamp;

    /// @notice Accumulator of the total earned interest rate since the opening of the market
    uint public borrowIndex;

    /// @notice Total amount of outstanding borrows of the underlying in this market
    uint public totalBorrows;

    /// @notice Total amount of reserves of the underlying held in this market
    uint public totalReserves;

    /// @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;

    /**
     * @notice Container for borrow balance information
     * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
     * @member interestIndex Global borrowIndex as of the most recent balance-changing action
     */
    struct BorrowSnapshot {
        uint principal;
        uint interestIndex;
    }

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

    /// @notice Share of seized collateral that is added to reserves
    uint public protocolSeizeShareMantissa;
}

abstract contract MTokenInterface is MTokenStorage {
    /// @notice Indicator that this is a MToken contract (for inspection)
    bool public constant isMToken = true;

    /*** Market Events ***/

    /// @notice Event emitted when interest is accrued
    event AccrueInterest(
        uint cashPrior,
        uint interestAccumulated,
        uint borrowIndex,
        uint totalBorrows
    );

    /// @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 redeemAmount, uint redeemTokens);

    /// @notice Event emitted when underlying 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 mTokenCollateral,
        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 comptroller is changed
    event NewComptroller(
        ComptrollerInterface oldComptroller,
        ComptrollerInterface newComptroller
    );

    /// @notice Event emitted when interestRateModel is changed
    event NewMarketInterestRateModel(
        InterestRateModel oldInterestRateModel,
        InterestRateModel newInterestRateModel
    );

    /// @notice Event emitted when the reserve factor is changed
    event NewReserveFactor(
        uint oldReserveFactorMantissa,
        uint newReserveFactorMantissa
    );

    /// @notice Event emitted when the protocol seize share is changed
    event NewProtocolSeizeShare(
        uint oldProtocolSeizeShareMantissa,
        uint newProtocolSeizeShareMantissa
    );

    /// @notice Event emitted when the reserves are added
    event ReservesAdded(
        address benefactor,
        uint addAmount,
        uint newTotalReserves
    );

    /// @notice Event emitted when the reserves are reduced
    event ReservesReduced(
        address admin,
        uint reduceAmount,
        uint newTotalReserves
    );

    /// @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 virtual returns (bool);
    function transferFrom(
        address src,
        address dst,
        uint amount
    ) external virtual returns (bool);
    function approve(
        address spender,
        uint amount
    ) external virtual returns (bool);
    function allowance(
        address owner,
        address spender
    ) external view virtual returns (uint);
    function balanceOf(address owner) external view virtual returns (uint);
    function balanceOfUnderlying(address owner) external virtual returns (uint);
    function getAccountSnapshot(
        address account
    ) external view virtual returns (uint, uint, uint, uint);
    function borrowRatePerTimestamp() external view virtual returns (uint);
    function supplyRatePerTimestamp() external view virtual returns (uint);
    function totalBorrowsCurrent() external virtual returns (uint);
    function borrowBalanceCurrent(
        address account
    ) external virtual returns (uint);
    function borrowBalanceStored(
        address account
    ) external view virtual returns (uint);
    function exchangeRateCurrent() external virtual returns (uint);
    function exchangeRateStored() external view virtual returns (uint);
    function getCash() external view virtual returns (uint);
    function accrueInterest() external virtual returns (uint);
    function seize(
        address liquidator,
        address borrower,
        uint seizeTokens
    ) external virtual returns (uint);

    /*** Admin Functions ***/

    function _setPendingAdmin(
        address payable newPendingAdmin
    ) external virtual returns (uint);
    function _acceptAdmin() external virtual returns (uint);
    function _setComptroller(
        ComptrollerInterface newComptroller
    ) external virtual returns (uint);
    function _setReserveFactor(
        uint newReserveFactorMantissa
    ) external virtual returns (uint);
    function _reduceReserves(uint reduceAmount) external virtual returns (uint);
    function _setInterestRateModel(
        InterestRateModel newInterestRateModel
    ) external virtual returns (uint);
    function _setProtocolSeizeShare(
        uint newProtocolSeizeShareMantissa
    ) external virtual returns (uint);
}

contract MErc20Storage {
    /// @notice Underlying asset for this MToken
    address public underlying;
}

abstract contract MErc20Interface is MErc20Storage {
    /*** User Interface ***/

    function mint(uint mintAmount) external virtual returns (uint);
    function mintWithPermit(
        uint mintAmount,
        uint deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external virtual returns (uint);
    function redeem(uint redeemTokens) external virtual returns (uint);
    function redeemUnderlying(
        uint redeemAmount
    ) external virtual returns (uint);
    function borrow(uint borrowAmount) external virtual returns (uint);
    function repayBorrow(uint repayAmount) external virtual returns (uint);
    function repayBorrowBehalf(
        address borrower,
        uint repayAmount
    ) external virtual returns (uint);
    function liquidateBorrow(
        address borrower,
        uint repayAmount,
        MTokenInterface mTokenCollateral
    ) external virtual returns (uint);
    function sweepToken(EIP20NonStandardInterface token) external virtual;

    /*** Admin Functions ***/

    function _addReserves(uint addAmount) external virtual returns (uint);
}

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

abstract contract MDelegatorInterface is MDelegationStorage {
    /// @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
    ) external virtual;
}

abstract contract MDelegateInterface is MDelegationStorage {
    /**
     * @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) external virtual;

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

File 22 of 24 : PriceOracle.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

import "../MToken.sol";

abstract contract PriceOracle {
    /// @notice Indicator that this is a PriceOracle contract (for inspection)
    bool public constant isPriceOracle = true;

    /**
     * @notice Get the underlying price of a mToken asset
     * @param mToken The mToken to get the underlying price of
     * @return The underlying asset price mantissa (scaled by 1e18).
     *  Zero means the price is unavailable.
     */
    function getUnderlyingPrice(
        MToken mToken
    ) external view virtual returns (uint);
}

File 23 of 24 : MultiRewardDistributorCommon.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

import "../MToken.sol";

// The commonly structures and events for the MultiRewardDistributor
interface MultiRewardDistributorCommon {
    struct MarketConfig {
        // The owner/admin of the emission config
        address owner;
        // The emission token
        address emissionToken;
        // Scheduled to end at this time
        uint endTime;
        // Supplier global state
        uint224 supplyGlobalIndex;
        uint32 supplyGlobalTimestamp;
        // Borrower global state
        uint224 borrowGlobalIndex;
        uint32 borrowGlobalTimestamp;
        uint supplyEmissionsPerSec;
        uint borrowEmissionsPerSec;
    }

    struct MarketEmissionConfig {
        MarketConfig config;
        mapping(address => uint) supplierIndices;
        mapping(address => uint) supplierRewardsAccrued;
        mapping(address => uint) borrowerIndices;
        mapping(address => uint) borrowerRewardsAccrued;
    }

    struct RewardInfo {
        address emissionToken;
        uint totalAmount;
        uint supplySide;
        uint borrowSide;
    }

    struct IndexUpdate {
        uint224 newIndex;
        uint32 newTimestamp;
    }

    struct MTokenData {
        uint mTokenBalance;
        uint borrowBalanceStored;
    }

    struct RewardWithMToken {
        address mToken;
        RewardInfo[] rewards;
    }

    // Global index updates
    event GlobalSupplyIndexUpdated(
        MToken mToken,
        address emissionToken,
        uint newSupplyIndex,
        uint32 newSupplyGlobalTimestamp
    );
    event GlobalBorrowIndexUpdated(
        MToken mToken,
        address emissionToken,
        uint newIndex,
        uint32 newTimestamp
    );

    // Reward Disbursal
    event DisbursedSupplierRewards(
        MToken indexed mToken,
        address indexed supplier,
        address indexed emissionToken,
        uint totalAccrued
    );
    event DisbursedBorrowerRewards(
        MToken indexed mToken,
        address indexed borrower,
        address indexed emissionToken,
        uint totalAccrued
    );

    // Admin update events
    event NewConfigCreated(
        MToken indexed mToken,
        address indexed owner,
        address indexed emissionToken,
        uint supplySpeed,
        uint borrowSpeed,
        uint endTime
    );
    event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
    event NewEmissionCap(uint oldEmissionCap, uint newEmissionCap);
    event NewEmissionConfigOwner(
        MToken indexed mToken,
        address indexed emissionToken,
        address currentOwner,
        address newOwner
    );
    event NewRewardEndTime(
        MToken indexed mToken,
        address indexed emissionToken,
        uint currentEndTime,
        uint newEndTime
    );
    event NewSupplyRewardSpeed(
        MToken indexed mToken,
        address indexed emissionToken,
        uint oldRewardSpeed,
        uint newRewardSpeed
    );
    event NewBorrowRewardSpeed(
        MToken indexed mToken,
        address indexed emissionToken,
        uint oldRewardSpeed,
        uint newRewardSpeed
    );
    event FundsRescued(address token, uint amount);

    // Pause guardian stuff
    event RewardsPaused();
    event RewardsUnpaused();

    // Errors
    event InsufficientTokensToEmit(
        address payable user,
        address rewardToken,
        uint amount
    );
}

File 24 of 24 : Unitroller.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.19;

import "./ErrorReporter.sol";
import "./ComptrollerStorage.sol";
/**
 * @title ComptrollerCore
 * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`.
 * MTokens should reference this contract as their comptroller.
 */
contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter {
    /**
     * @notice Emitted when pendingComptrollerImplementation is changed
     */
    event NewPendingImplementation(
        address oldPendingImplementation,
        address newPendingImplementation
    );

    /**
     * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller 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() {
        // Set admin to caller
        admin = msg.sender;
    }

    /*** Admin Functions ***/
    function _setPendingImplementation(
        address newPendingImplementation
    ) public returns (uint) {
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK
                );
        }

        address oldPendingImplementation = pendingComptrollerImplementation;

        pendingComptrollerImplementation = newPendingImplementation;

        emit NewPendingImplementation(
            oldPendingImplementation,
            pendingComptrollerImplementation
        );

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation
     * @dev Admin function for new implementation to accept it's role as implementation
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _acceptImplementation() public returns (uint) {
        // Check caller is pendingImplementation and pendingImplementation �� address(0)
        if (
            msg.sender != pendingComptrollerImplementation ||
            pendingComptrollerImplementation == address(0)
        ) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK
                );
        }

        // Save current values for inclusion in log
        address oldImplementation = comptrollerImplementation;
        address oldPendingImplementation = pendingComptrollerImplementation;

        comptrollerImplementation = pendingComptrollerImplementation;

        pendingComptrollerImplementation = address(0);

        emit NewImplementation(oldImplementation, comptrollerImplementation);
        emit NewPendingImplementation(
            oldPendingImplementation,
            pendingComptrollerImplementation
        );

        return uint(Error.NO_ERROR);
    }

    /**
     * @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.
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
        // Check caller = admin
        if (msg.sender != admin) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK
                );
        }

        // 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);

        return uint(Error.NO_ERROR);
    }

    /**
     * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
     * @dev Admin function for pending admin to accept role and update admin
     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
     */
    function _acceptAdmin() public returns (uint) {
        // Check caller is pendingAdmin and pendingAdmin �� address(0)
        if (msg.sender != pendingAdmin || msg.sender == address(0)) {
            return
                fail(
                    Error.UNAUTHORIZED,
                    FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK
                );
        }

        // 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);

        return uint(Error.NO_ERROR);
    }

    /**
     * @dev Delegates execution to an implementation contract.
     * It returns to the external caller whatever the implementation returns
     * or forwards reverts.
     */
    fallback() external {
        // delegate all other functions to current implementation
        (bool success, ) = comptrollerImplementation.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
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "evmVersion": "paris",
  "viaIR": false,
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract MToken","name":"mToken","type":"address"},{"indexed":true,"internalType":"address","name":"borrower","type":"address"},{"indexed":true,"internalType":"address","name":"emissionToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalAccrued","type":"uint256"}],"name":"DisbursedBorrowerRewards","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract MToken","name":"mToken","type":"address"},{"indexed":true,"internalType":"address","name":"supplier","type":"address"},{"indexed":true,"internalType":"address","name":"emissionToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalAccrued","type":"uint256"}],"name":"DisbursedSupplierRewards","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FundsRescued","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract MToken","name":"mToken","type":"address"},{"indexed":false,"internalType":"address","name":"emissionToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"newIndex","type":"uint256"},{"indexed":false,"internalType":"uint32","name":"newTimestamp","type":"uint32"}],"name":"GlobalBorrowIndexUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract MToken","name":"mToken","type":"address"},{"indexed":false,"internalType":"address","name":"emissionToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"newSupplyIndex","type":"uint256"},{"indexed":false,"internalType":"uint32","name":"newSupplyGlobalTimestamp","type":"uint32"}],"name":"GlobalSupplyIndexUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address payable","name":"user","type":"address"},{"indexed":false,"internalType":"address","name":"rewardToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"InsufficientTokensToEmit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract MToken","name":"mToken","type":"address"},{"indexed":true,"internalType":"address","name":"emissionToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"oldRewardSpeed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRewardSpeed","type":"uint256"}],"name":"NewBorrowRewardSpeed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract MToken","name":"mToken","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"emissionToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"supplySpeed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"borrowSpeed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"endTime","type":"uint256"}],"name":"NewConfigCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldEmissionCap","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newEmissionCap","type":"uint256"}],"name":"NewEmissionCap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract MToken","name":"mToken","type":"address"},{"indexed":true,"internalType":"address","name":"emissionToken","type":"address"},{"indexed":false,"internalType":"address","name":"currentOwner","type":"address"},{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"NewEmissionConfigOwner","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":true,"internalType":"contract MToken","name":"mToken","type":"address"},{"indexed":true,"internalType":"address","name":"emissionToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"currentEndTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newEndTime","type":"uint256"}],"name":"NewRewardEndTime","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract MToken","name":"mToken","type":"address"},{"indexed":true,"internalType":"address","name":"emissionToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"oldRewardSpeed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRewardSpeed","type":"uint256"}],"name":"NewSupplyRewardSpeed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[],"name":"RewardsPaused","type":"event"},{"anonymous":false,"inputs":[],"name":"RewardsUnpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_emissionToken","type":"address"},{"internalType":"uint256","name":"_supplyEmissionPerSec","type":"uint256"},{"internalType":"uint256","name":"_borrowEmissionsPerSec","type":"uint256"},{"internalType":"uint256","name":"_endTime","type":"uint256"}],"name":"_addEmissionConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"_pauseRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"_rescueFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newEmissionCap","type":"uint256"}],"name":"_setEmissionCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newPauseGuardian","type":"address"}],"name":"_setPauseGuardian","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"_unpauseRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_emissionToken","type":"address"},{"internalType":"uint256","name":"_newBorrowSpeed","type":"uint256"}],"name":"_updateBorrowSpeed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_emissionToken","type":"address"},{"internalType":"uint256","name":"_newEndTime","type":"uint256"}],"name":"_updateEndTime","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_emissionToken","type":"address"},{"internalType":"address","name":"_newOwner","type":"address"}],"name":"_updateOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_emissionToken","type":"address"},{"internalType":"uint256","name":"_newSupplySpeed","type":"uint256"}],"name":"_updateSupplySpeed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"comptroller","outputs":[{"internalType":"contract Comptroller","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_borrower","type":"address"},{"internalType":"bool","name":"_sendTokens","type":"bool"}],"name":"disburseBorrowerRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_supplier","type":"address"},{"internalType":"bool","name":"_sendTokens","type":"bool"}],"name":"disburseSupplierRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"emissionCap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"}],"name":"getAllMarketConfigs","outputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"emissionToken","type":"address"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"uint224","name":"supplyGlobalIndex","type":"uint224"},{"internalType":"uint32","name":"supplyGlobalTimestamp","type":"uint32"},{"internalType":"uint224","name":"borrowGlobalIndex","type":"uint224"},{"internalType":"uint32","name":"borrowGlobalTimestamp","type":"uint32"},{"internalType":"uint256","name":"supplyEmissionsPerSec","type":"uint256"},{"internalType":"uint256","name":"borrowEmissionsPerSec","type":"uint256"}],"internalType":"struct MultiRewardDistributorCommon.MarketConfig[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_emissionToken","type":"address"}],"name":"getConfigForMarket","outputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"emissionToken","type":"address"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"uint224","name":"supplyGlobalIndex","type":"uint224"},{"internalType":"uint32","name":"supplyGlobalTimestamp","type":"uint32"},{"internalType":"uint224","name":"borrowGlobalIndex","type":"uint224"},{"internalType":"uint32","name":"borrowGlobalTimestamp","type":"uint32"},{"internalType":"uint256","name":"supplyEmissionsPerSec","type":"uint256"},{"internalType":"uint256","name":"borrowEmissionsPerSec","type":"uint256"}],"internalType":"struct MultiRewardDistributorCommon.MarketConfig","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentEmissionCap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_emissionToken","type":"address"}],"name":"getCurrentOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"mToken","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getGlobalBorrowIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"mToken","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getGlobalSupplyIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_user","type":"address"}],"name":"getOutstandingRewardsForUser","outputs":[{"components":[{"internalType":"address","name":"emissionToken","type":"address"},{"internalType":"uint256","name":"totalAmount","type":"uint256"},{"internalType":"uint256","name":"supplySide","type":"uint256"},{"internalType":"uint256","name":"borrowSide","type":"uint256"}],"internalType":"struct MultiRewardDistributorCommon.RewardInfo[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"getOutstandingRewardsForUser","outputs":[{"components":[{"internalType":"address","name":"mToken","type":"address"},{"components":[{"internalType":"address","name":"emissionToken","type":"address"},{"internalType":"uint256","name":"totalAmount","type":"uint256"},{"internalType":"uint256","name":"supplySide","type":"uint256"},{"internalType":"uint256","name":"borrowSide","type":"uint256"}],"internalType":"struct MultiRewardDistributorCommon.RewardInfo[]","name":"rewards","type":"tuple[]"}],"internalType":"struct MultiRewardDistributorCommon.RewardWithMToken[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initialIndexConstant","outputs":[{"internalType":"uint224","name":"","type":"uint224"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_comptroller","type":"address"},{"internalType":"address","name":"_pauseGuardian","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"marketConfigs","outputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"emissionToken","type":"address"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"uint224","name":"supplyGlobalIndex","type":"uint224"},{"internalType":"uint32","name":"supplyGlobalTimestamp","type":"uint32"},{"internalType":"uint224","name":"borrowGlobalIndex","type":"uint224"},{"internalType":"uint32","name":"borrowGlobalTimestamp","type":"uint32"},{"internalType":"uint256","name":"supplyEmissionsPerSec","type":"uint256"},{"internalType":"uint256","name":"borrowEmissionsPerSec","type":"uint256"}],"internalType":"struct MultiRewardDistributorCommon.MarketConfig","name":"config","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pauseGuardian","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"}],"name":"updateMarketBorrowIndex","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_borrower","type":"address"},{"internalType":"bool","name":"_sendTokens","type":"bool"}],"name":"updateMarketBorrowIndexAndDisburseBorrowerRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"}],"name":"updateMarketSupplyIndex","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract MToken","name":"_mToken","type":"address"},{"internalType":"address","name":"_supplier","type":"address"},{"internalType":"bool","name":"_sendTokens","type":"bool"}],"name":"updateMarketSupplyIndexAndDisburseSupplierRewards","outputs":[],"stateMutability":"nonpayable","type":"function"}]

608060405234801561001057600080fd5b506000805460ff19169055600180556144bb8061002e6000396000f3fe608060405234801561001057600080fd5b50600436106101e55760003560e01c806373a1f3d01161010f578063c11a70b3116100a2578063e66b98c911610071578063e66b98c914610433578063e88d9c1b14610446578063ea0f3dff1461044e578063ed302dfd1461046157600080fd5b8063c11a70b3146103da578063c9a06b45146103ed578063dbc7779b1461040d578063e0ed91161461042057600080fd5b80638b62a51a116100de5780638b62a51a14610381578063ad1a9280146103a1578063adc75e52146103b4578063b2fa9e10146103c757600080fd5b806373a1f3d0146103285780637e218f901461033b5780637f7336ba1461035b5780638220d7cf1461036e57600080fd5b80633616b04b116101875780635c975abb116101565780635c975abb146102d95780635f5af1aa146102ef5780635fe3b56714610302578063610393a01461031557600080fd5b80633616b04b146102a3578063375fea29146102b6578063472db55d146102be578063485cc955146102c657600080fd5b806310d47dc7116101c357806310d47dc71461023f57806314f557731461025257806324a3d62214610265578063283923801461029057600080fd5b8063019047d6146101ea57806307e8ce85146101ff5780630cd8bbc514610228575b600080fd5b6101fd6101f8366004613b42565b61048e565b005b61021261020d366004613b5f565b610553565b60405161021f9190613b98565b60405180910390f35b61023160065481565b60405190815260200161021f565b6101fd61024d366004613c15565b6109af565b6101fd610260366004613c15565b610a6f565b600554610278906001600160a01b031681565b6040516001600160a01b03909116815260200161021f565b6101fd61029e366004613c60565b610b2a565b6101fd6102b1366004613c79565b610c0b565b6101fd610e04565b6101fd610ee7565b6101fd6102d4366004613b5f565b610fb5565b60005460ff16604051901515815260200161021f565b6101fd6102fd366004613b42565b61124e565b600454610278906001600160a01b031681565b6101fd610323366004613c79565b61137e565b610231610336366004613cba565b611537565b61034e610349366004613b42565b611589565b60405161021f9190613d81565b6101fd610369366004613c79565b6116f2565b6101fd61037c366004613b42565b6118ab565b61039461038f366004613b5f565b611964565b60405161021f9190613dc4565b6102786103af366004613b5f565b611a08565b6101fd6103c2366004613c15565b611a27565b6102316103d5366004613cba565b611ae0565b6103946103e8366004613cba565b611b32565b6104006103fb366004613b42565b611bee565b60405161021f9190613dd3565b6101fd61041b366004613cba565b611d61565b6101fd61042e366004613c15565b611fc7565b6101fd610441366004613ea7565b612080565b600654610231565b6101fd61045c366004613ee7565b6121ae565b6104766a0c097ce7bc90715b34b9f160241b81565b6040516001600160e01b03909116815260200161021f565b6004546001600160a01b0316331480610522575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156104e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061050d9190613f4c565b6001600160a01b0316336001600160a01b0316145b6105475760405162461bcd60e51b815260040161053e90613f69565b60405180910390fd5b610550816126bc565b50565b6001600160a01b038216600090815260036020526040812080546060929067ffffffffffffffff81111561058957610589613fc7565b6040519080825280602002602001820160405280156105ee57816020015b6105db604051806080016040528060006001600160a01b031681526020016000815260200160008152602001600081525090565b8152602001906001900390816105a75790505b509050600060405180604001604052806040518060600160405280896001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610647573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061066b9190613fdd565b8152602001896001600160a01b03166347bd37186040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106d29190613fdd565b815260200160405180602001604052808b6001600160a01b031663aa5af0fd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610720573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107449190613fdd565b90529052815260408051808201918290526370a0823160e01b9091526001600160a01b03888116604483015260209092019181908a166370a0823160648301602060405180830381865afa1580156107a0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107c49190613fdd565b81526040516395dd919360e01b81526001600160a01b038a811660048301526020909201918b16906395dd919390602401602060405180830381865afa158015610812573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108369190613fdd565b90529052905060005b83548110156109a257600084828154811061085c5761085c613ff6565b6000918252602082206005600b9092020190810154600382015460028301548751519395506108a39363ffffffff600160e01b840416926001600160e01b0316919061290f565b600683015460048401546002850154875160208101516040909101519495506000946108f5949363ffffffff600160e01b820416936001600160e01b039091169290916108f09190612ac3565b61290f565b905060006109118484600001518860200151600001518d612ae8565b905060006109328584600001518960000151604001518a602001518f612ba4565b604080516080810190915260018701546001600160a01b031681529091506020810161095e8484614022565b81526020018381526020018281525088878151811061097f5761097f613ff6565b60200260200101819052505050505050808061099a90614035565b91505061083f565b5090925050505b92915050565b6004546001600160a01b0316331480610a43575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610a0a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a2e9190613f4c565b6001600160a01b0316336001600160a01b0316145b610a5f5760405162461bcd60e51b815260040161053e90613f69565b610a6a838383612c73565b505050565b6004546001600160a01b0316331480610b03575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610aca573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aee9190613f4c565b6001600160a01b0316336001600160a01b0316145b610b1f5760405162461bcd60e51b815260040161053e90613f69565b610a6a838383612e35565b60048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610b71573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b959190613f4c565b6001600160a01b0316336001600160a01b031614610bc55760405162461bcd60e51b815260040161053e9061404e565b600680549082905560408051828152602081018490527f8d2ad4bb95e94ce8d50ed07769a97467ba4db3f80fc0badf6c81d0907a0b410a91015b60405180910390a15050565b82826000610c1983836130ed565b80549091506001600160a01b0316331480610caf575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610c76573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c9a9190613f4c565b6001600160a01b0316336001600160a01b0316145b610ccb5760405162461bcd60e51b815260040161053e9061409f565b6000610cd787876130ed565b6002810154909150808611610d3a5760405162461bcd60e51b8152602060048201526024808201527f5f6e6577456e6454696d65204d555354206265203e2063757272656e74456e6460448201526354696d6560e01b606482015260840161053e565b428611610d975760405162461bcd60e51b815260206004820152602560248201527f5f6e6577456e6454696d65204d555354206265203e20626c6f636b2e74696d6560448201526407374616d760dc1b606482015260840161053e565b610da0886126bc565b610da9886131cc565b6002820186905560408051828152602081018890526001600160a01b03808a1692908b16917f10f16113484fbc6e60553a394eb2a3ae47999b610e4212fad6903486dbca7f9291015b60405180910390a35050505050505050565b6005546001600160a01b0316331480610e98575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610e5f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e839190613f4c565b6001600160a01b0316336001600160a01b0316145b610eb45760405162461bcd60e51b815260040161053e90614106565b610ebc613335565b6040517fb83b93884b98604cbc549e7e4a81a9e49bd62c603026ec82f04915037258c56490600090a1565b60048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610f2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f529190613f4c565b6001600160a01b0316336001600160a01b031614610f825760405162461bcd60e51b815260040161053e9061404e565b610f8a61338f565b6040517f24abc2b8df8d63728da8fe06c1555853a3f293f812e1ebd4303a5d6df7173e6c90600090a1565b600254610100900460ff1615808015610fd55750600254600160ff909116105b80610fef5750303b158015610fef575060025460ff166001145b6110525760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b606482015260840161053e565b6002805460ff191660011790558015611075576002805461ff0019166101001790555b6001600160a01b0383166110d75760405162461bcd60e51b815260206004820152602360248201527f436f6d7074726f6c6c65722063616e277420626520746865203020616464726560448201526273732160e81b606482015260840161053e565b6001600160a01b0382166110fd5760405162461bcd60e51b815260040161053e9061416f565b600480546001600160a01b0319166001600160a01b038516908117825560408051623f1ee960e11b815290519192627e3dd29282820192602092908290030181865afa158015611151573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061117591906141b5565b6111db5760405162461bcd60e51b815260206004820152603160248201527f43616e27742062696e6420746f20736f6d657468696e6720746861742773206e6044820152706f74206120636f6d7074726f6c6c65722160781b606482015260840161053e565b600580546001600160a01b0319166001600160a01b03841617905568056bc75e2d631000006006558015610a6a576002805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498906020015b60405180910390a1505050565b6005546001600160a01b03163314806112e2575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156112a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112cd9190613f4c565b6001600160a01b0316336001600160a01b0316145b6112fe5760405162461bcd60e51b815260040161053e90614106565b6001600160a01b0381166113245760405162461bcd60e51b815260040161053e9061416f565b600580546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527f0613b6ee6a04f0d09f390e4d9318894b9f6ac7fd83897cd8d18896ba579c401e9101610bff565b8282600061138c83836130ed565b80549091506001600160a01b0316331480611422575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156113e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061140d9190613f4c565b6001600160a01b0316336001600160a01b0316145b61143e5760405162461bcd60e51b815260040161053e9061409f565b600061144a87876130ed565b60058101549091508086036114c05760405162461bcd60e51b815260206004820152603660248201527f43616e277420736574206e657720737570706c7920656d697373696f6e7320746044820152756f20626520657175616c20746f2063757272656e742160501b606482015260840161053e565b60065486106114e15760405162461bcd60e51b815260040161053e906141d2565b6114ea886131cc565b6005820186905560408051828152602081018890526001600160a01b03808a1692908b16917fc4d50731808aa5d941c471c0b29364fecd810aa0565344f6cdcab2c873422baf9101610df2565b6001600160a01b038216600090815260036020526040812080548291908490811061156457611564613ff6565b60009182526020909120600b90910201600301546001600160e01b0316949350505050565b6001600160a01b038116600090815260036020526040812080546060929067ffffffffffffffff8111156115bf576115bf613fc7565b6040519080825280602002602001820160405280156115f857816020015b6115e5613ae1565b8152602001906001900390816115dd5790505b50905060005b82548110156116ea57600083828154811061161b5761161b613ff6565b60009182526020918290206040805161012081018252600b90930290910180546001600160a01b0390811684526001820154169383019390935260028301549082015260038201546001600160e01b03808216606084015263ffffffff600160e01b9283900481166080850152600485015491821660a08501529190041660c0820152600582015460e082015260068201546101008201528451919250908490849081106116cb576116cb613ff6565b60200260200101819052505080806116e290614035565b9150506115fe565b509392505050565b8282600061170083836130ed565b80549091506001600160a01b0316331480611796575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa15801561175d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117819190613f4c565b6001600160a01b0316336001600160a01b0316145b6117b25760405162461bcd60e51b815260040161053e9061409f565b60006117be87876130ed565b60068101549091508086036118345760405162461bcd60e51b815260206004820152603660248201527f43616e277420736574206e657720626f72726f7720656d697373696f6e7320746044820152756f20626520657175616c20746f2063757272656e742160501b606482015260840161053e565b60065486106118555760405162461bcd60e51b815260040161053e9061422f565b61185e886126bc565b6006820186905560408051828152602081018890526001600160a01b03808a1692908b16917f8fc43850ed5c7aaa0ce83829a1a40202c3fcf8257788d69881611dff1a0b32e99101610df2565b6004546001600160a01b031633148061193f575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015611906573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061192a9190613f4c565b6001600160a01b0316336001600160a01b0316145b61195b5760405162461bcd60e51b815260040161053e90613f69565b610550816131cc565b61196c613ae1565b600061197884846130ed565b604080516101208101825282546001600160a01b039081168252600184015416602082015260028301549181019190915260038201546001600160e01b03808216606084015263ffffffff600160e01b9283900481166080850152600485015491821660a08501529190041660c0820152600582015460e082015260069091015461010082015291505092915050565b600080611a1584846130ed565b546001600160a01b0316949350505050565b6004546001600160a01b0316331480611abb575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015611a82573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611aa69190613f4c565b6001600160a01b0316336001600160a01b0316145b611ad75760405162461bcd60e51b815260040161053e90613f69565b610b1f836126bc565b6001600160a01b0382166000908152600360205260408120805482919084908110611b0d57611b0d613ff6565b60009182526020909120600b90910201600401546001600160e01b0316949350505050565b60036020528160005260406000208181548110611b4e57600080fd5b60009182526020918290206040805161012081018252600b90930290910180546001600160a01b0390811684526001820154169383019390935260028301549082015260038201546001600160e01b03808216606084015263ffffffff600160e01b9283900481166080850152600485015491821660a08501529190041660c0820152600582015460e08201526006909101546101008201529150829050565b600480546040805163b0772d0b60e01b815290516060936000936001600160a01b03169263b0772d0b928183019286928290030181865afa158015611c37573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052611c5f919081019061429c565b90506000815167ffffffffffffffff811115611c7d57611c7d613fc7565b604051908082528060200260200182016040528015611cc357816020015b604080518082019091526000815260606020820152815260200190600190039081611c9b5790505b50905060005b82518110156116ea576000611cf7848381518110611ce957611ce9613ff6565b602002602001015187610553565b90506040518060400160405280858481518110611d1657611d16613ff6565b60200260200101516001600160a01b0316815260200182815250838381518110611d4257611d42613ff6565b6020026020010181905250508080611d5990614035565b915050611cc9565b60048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015611da8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dcc9190613f4c565b6001600160a01b0316336001600160a01b031614611dfc5760405162461bcd60e51b815260040161053e9061404e565b8160018201611efd57611ef8600460009054906101000a90046001600160a01b03166001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e5b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e7f9190613f4c565b6040516370a0823160e01b81523060048201526001600160a01b038416906370a0823190602401602060405180830381865afa158015611ec3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ee79190613fdd565b6001600160a01b03841691906133c8565b611f88565b611f88600460009054906101000a90046001600160a01b03166001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f53573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f779190613f4c565b6001600160a01b03831690846133c8565b604080516001600160a01b0385168152602081018490527fc4474c2790e13695f6d2b6f1d8e164290b55370f87a542fd7711abe0a1bf40ac9101611241565b6004546001600160a01b031633148061205b575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015612022573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120469190613f4c565b6001600160a01b0316336001600160a01b0316145b6120775760405162461bcd60e51b815260040161053e90613f69565b610a5f836131cc565b8282600061208e83836130ed565b80549091506001600160a01b0316331480612124575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156120eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061210f9190613f4c565b6001600160a01b0316336001600160a01b0316145b6121405760405162461bcd60e51b815260040161053e9061409f565b600061214c87876130ed565b80546001600160a01b038781166001600160a01b03198316811784556040805193831680855260208501929092529394509289821692918b16917f6ca67f2e3675f2b549fe77271364ebde88b3c7eb3ef84af329c373ca64fa25789101610df2565b60048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156121f5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122199190613f4c565b6001600160a01b0316336001600160a01b0316146122495760405162461bcd60e51b815260040161053e9061404e565b60048054604051638e8f294b60e01b81526001600160a01b038981169382019390935260009290911690638e8f294b906024016040805180830381865afa158015612298573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122bc9190614361565b509050806123235760405162461bcd60e51b815260206004820152602e60248201527f546865206d61726b65742072657175657374656420746f20626520616464656460448201526d20697320756e2d6c69737465642160901b606482015260840161053e565b60065484106123445760405162461bcd60e51b815260040161053e906141d2565b60065483106123655760405162461bcd60e51b815260040161053e9061422f565b612370426001614022565b82116123d45760405162461bcd60e51b815260206004820152602d60248201527f546865205f656e6454696d6520706172616d65746572206d757374206265206960448201526c6e20746865206675747572652160981b606482015260840161053e565b6001600160a01b0387166000908152600360205260408120905b815481101561249057600082828154811061240b5761240b613ff6565b60009182526020909120600b9091020160018101549091506001600160a01b0389811691160361247d5760405162461bcd60e51b815260206004820152601e60248201527f456d697373696f6e20746f6b656e20616c7265616479206c6973746564210000604482015260640161053e565b508061248881614035565b9150506123ee565b506000604051806101200160405280896001600160a01b03168152602001886001600160a01b031681526020018581526020016a0c097ce7bc90715b34b9f160241b6001600160e01b0316815260200161251f426040518060400160405280601f81526020017f626c6f636b2074696d657374616d70206578636565647320333220626974730081525061341a565b63ffffffff1681526020016a0c097ce7bc90715b34b9f160241b6001600160e01b03168152602001612586426040518060400160405280601f81526020017f626c6f636b2074696d657374616d70206578636565647320333220626974730081525061341a565b63ffffffff168152602001878152602001868152509050866001600160a01b0316886001600160a01b03168a6001600160a01b03167fa76959d76a349a0b8fd3120607e3aea6af58897ae6531bfe60a0267c4ea0c2728989896040516125ff939291909283526020830191909152604082015260600190565b60405180910390a481546001818101845560009384526020938490208351600b9093020180546001600160a01b039384166001600160a01b03199182161782559484015191810180549290931691909416179055604081015160028301556060810151608082015163ffffffff908116600160e01b9081026001600160e01b0393841617600386015560a084015160c085015190921602911617600483015560e08101516005830155610100015160069091015550505050505050565b6001600160a01b0381166000818152600360209081526040808320815180840180845263aa5af0fd60e01b905291519094919283929163aa5af0fd91602480860192908187030181865afa158015612718573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061273c9190613fdd565b81525090506000836001600160a01b03166347bd37186040518163ffffffff1660e01b8152600401602060405180830381865afa158015612781573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127a59190613fdd565b905060005b83548110156129085760008482815481106127c7576127c7613ff6565b6000918252602082206006600b90920201908101546004820154600283015492945061280f9263ffffffff600160e01b830416916001600160e01b0316906108f0898b612ac3565b905080600001518260000160040160006101000a8154816001600160e01b0302191690836001600160e01b03160217905550806020015182600001600401601c6101000a81548163ffffffff021916908363ffffffff1602179055507f24b735e493aede533ed6134442bad7e2ea2e72d71739de4c97f020174f5e3bcd878360000160010160009054906101000a90046001600160a01b03168460000160040160009054906101000a90046001600160e01b031685600001600401601c9054906101000a900463ffffffff166040516128eb949392919061438f565b60405180910390a15050808061290090614035565b9150506127aa565b5050505050565b60408051808201909152600080825260208201526000612964426040518060400160405280601f81526020017f626c6f636b2074696d657374616d70206578636565647320333220626974730081525061341a565b9050600061297e8263ffffffff168863ffffffff1661344a565b9050848263ffffffff1611156129b757848763ffffffff1610156129b3576129ac858863ffffffff1661344a565b90506129b7565b5060005b8015806129c2575087155b156129f4576040518060400160405280876001600160e01b031681526020018363ffffffff1681525092505050612aba565b6000612a00828a613484565b90506000808611612a205760405180602001604052806000815250612a2a565b612a2a82876134c6565b90506000612a8c612a5260405180602001604052808c6001600160e01b03168152508461350a565b5160408051808201909152601a81527f6e657720696e64657820657863656564732032323420626974730000000000006020820152613536565b90506040518060400160405280826001600160e01b031681526020018663ffffffff16815250955050505050505b95945050505050565b6000612ae1612ada84670de0b6b3a7640000613484565b835161355d565b9392505050565b6001600160a01b038116600090815260078501602052604081205480158015612b2857506a0c097ce7bc90715b34b9f160241b6001600160e01b03861610155b15612b3e57506a0c097ce7bc90715b34b9f160241b5b60006040518060200160405280612b5e886001600160e01b03168561344a565b905290506000612b6e8683613590565b6001600160a01b038616600090815260088a016020526040902054909150612b9690826135b9565b93505050505b949350505050565b6001600160a01b038116600090815260098601602052604081205480158015612be457506a0c097ce7bc90715b34b9f160241b6001600160e01b03871610155b15612bfa57506a0c097ce7bc90715b34b9f160241b5b60006040518060200160405280612c1a896001600160e01b03168561344a565b81525090506000612c2f866020015188612ac3565b90506000612c3d8284613590565b6001600160a01b0387166000908152600a8c016020526040902054909150612c6590826135b9565b9a9950505050505050505050565b6001600160a01b0383811660008181526003602052604080822090516370a0823160e01b81529386166004850152929091906370a0823190602401602060405180830381865afa158015612ccb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cef9190613fdd565b905060005b8254811015612e2d576000838281548110612d1157612d11613ff6565b6000918252602082206003600b9092020190810154909250612d3f9083906001600160e01b0316868a612ae8565b60038301546001600160a01b03808a16600081815260078701602090815260408083206001600160e01b039096169095556008880190528390208490556001860154925193945091811692908b16907f51761e1f6548bc99f2a61f299986e1b08a489f06622f689a413e02d7654a476690612dbd9086815260200190565b60405180910390a48515612e18576001600160a01b03808816600090815260088401602052604081205460018501549192612dfb928b9291166135ef565b6001600160a01b0389166000908152600885016020526040902055505b50508080612e2590614035565b915050612cf4565b505050505050565b6001600160a01b0383166000818152600360209081526040808320815180840180845263aa5af0fd60e01b905291519094919283929163aa5af0fd91602480860192908187030181865afa158015612e91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612eb59190613fdd565b905260408051808201918290526370a0823160e01b9091526001600160a01b038681166044830152919250600091819088166370a0823160648301602060405180830381865afa158015612f0d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f319190613fdd565b81526040516395dd919360e01b81526001600160a01b0388811660048301526020909201918916906395dd919390602401602060405180830381865afa158015612f7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fa39190613fdd565b9052905060005b83548110156130e4576000848281548110612fc757612fc7613ff6565b6000918252602082206004600b9092020190810154909250612ff69083906001600160e01b031687878c612ba4565b60048301546001600160a01b03808b16600081815260098701602090815260408083206001600160e01b03909616909555600a880190528390208490556001860154925193945091811692908c16907f48a32d6daeb4317b45f49c3a1c0b1bd7d53a175d1f46c425138e328900cdccb4906130749086815260200190565b60405180910390a486156130cf576001600160a01b038089166000908152600a84016020526040812054600185015491926130b2928c9291166135ef565b6001600160a01b038a166000908152600a85016020526040902055505b505080806130dc90614035565b915050612faa565b50505050505050565b6001600160a01b0382166000908152600360205260408120815b815481101561316b57600082828154811061312457613124613ff6565b60009182526020909120600b9091020160018101549091506001600160a01b038681169116036131585792506109a9915050565b508061316381614035565b915050613107565b5060405162461bcd60e51b815260206004820152602f60248201527f556e61626c6520746f2066696e6420656d697373696f6e20746f6b656e20696e60448201526e206d546f6b656e20636f6e6669677360881b606482015260840161053e565b6001600160a01b038116600081815260036020908152604080832081516318160ddd60e01b815291519094926318160ddd92600480820193918290030181865afa15801561321e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132429190613fdd565b905060005b825481101561332f57600083828154811061326457613264613ff6565b6000918252602082206005600b9092020190810154600382015460028301549294506132a89263ffffffff600160e01b830416916001600160e01b0316908861290f565b8051602082015163ffffffff8116600160e01b026001600160e01b03831617600386015560018501546040519394507f79af45fe3972eecc4b95252214ad1d36529435ab4d4ae291d62a2ee5a0cc050093613312938b936001600160a01b0390931692909161438f565b60405180910390a15050808061332790614035565b915050613247565b50505050565b61333d613717565b6000805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586133723390565b6040516001600160a01b03909116815260200160405180910390a1565b61339761375f565b6000805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa33613372565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610a6a9084906137a8565b60008164010000000084106134425760405162461bcd60e51b815260040161053e91906143ea565b509192915050565b6000612ae18383604051806040016040528060158152602001747375627472616374696f6e20756e646572666c6f7760581b81525061387d565b6000612ae183836040518060400160405280601781526020017f6d756c7469706c69636174696f6e206f766572666c6f770000000000000000008152506138ac565b60408051602081019091526000815260405180602001604052806135016134fb866a0c097ce7bc90715b34b9f160241b613484565b8561355d565b90529392505050565b6040805160208101909152600081526040518060200160405280613501856000015185600001516135b9565b600081600160e01b84106134425760405162461bcd60e51b815260040161053e91906143ea565b6000612ae183836040518060400160405280600e81526020016d646976696465206279207a65726f60901b815250613908565b60006a0c097ce7bc90715b34b9f160241b6135af848460000151613484565b612ae1919061441d565b6000612ae18383604051806040016040528060118152602001706164646974696f6e206f766572666c6f7760781b815250613934565b60006135f9613965565b8260000361360857508161370e565b60005460ff161561361a57508161370e565b6040516370a0823160e01b815230600482015282906000906001600160a01b038316906370a0823190602401602060405180830381865afa158015613663573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136879190613fdd565b90506000851180156136995750808511155b156136bd576136b26001600160a01b03831687876133c8565b60009250505061370e565b604080516001600160a01b038089168252861660208201529081018690527f8b079e2b0be6cc9631b7883d8478590fe708e9d360391aab49aa147901fc7a379060600160405180910390a184925050505b612ae160018055565b60005460ff161561375d5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640161053e565b565b60005460ff1661375d5760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604482015260640161053e565b60006137fd826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166139be9092919063ffffffff16565b905080516000148061381e57508080602001905181019061381e91906141b5565b610a6a5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161053e565b600081848411156138a15760405162461bcd60e51b815260040161053e91906143ea565b50612b9c838561443f565b60008315806138b9575082155b156138c657506000612ae1565b60006138d28486614452565b9050836138df868361441d565b1483906138ff5760405162461bcd60e51b815260040161053e91906143ea565b50949350505050565b600081836139295760405162461bcd60e51b815260040161053e91906143ea565b50612b9c838561441d565b6000806139418486614022565b905082858210156138ff5760405162461bcd60e51b815260040161053e91906143ea565b6002600154036139b75760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015260640161053e565b6002600155565b6060612b9c848460008585600080866001600160a01b031685876040516139e59190614469565b60006040518083038185875af1925050503d8060008114613a22576040519150601f19603f3d011682016040523d82523d6000602084013e613a27565b606091505b5091509150613a3887838387613a43565b979650505050505050565b60608315613ab2578251600003613aab576001600160a01b0385163b613aab5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161053e565b5081612b9c565b612b9c8383815115613ac75781518083602001fd5b8060405162461bcd60e51b815260040161053e91906143ea565b6040805161012081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810182905261010081019190915290565b6001600160a01b038116811461055057600080fd5b600060208284031215613b5457600080fd5b8135612ae181613b2d565b60008060408385031215613b7257600080fd5b8235613b7d81613b2d565b91506020830135613b8d81613b2d565b809150509250929050565b6020808252825182820181905260009190848201906040850190845b81811015613bfb57835180516001600160a01b0316845260208082015190850152604080820151908501526060908101519084015260808301938501939250600101613bb4565b50909695505050505050565b801515811461055057600080fd5b600080600060608486031215613c2a57600080fd5b8335613c3581613b2d565b92506020840135613c4581613b2d565b91506040840135613c5581613c07565b809150509250925092565b600060208284031215613c7257600080fd5b5035919050565b600080600060608486031215613c8e57600080fd5b8335613c9981613b2d565b92506020840135613ca981613b2d565b929592945050506040919091013590565b60008060408385031215613ccd57600080fd5b8235613cd881613b2d565b946020939093013593505050565b80516001600160a01b03908116835260208083015190911690830152604080820151908301526060808201516001600160e01b03169083015260808082015190613d379084018263ffffffff169052565b5060a0810151613d5260a08401826001600160e01b03169052565b5060c0810151613d6a60c084018263ffffffff169052565b5060e0818101519083015261010090810151910152565b6020808252825182820181905260009190848201906040850190845b81811015613bfb57613db0838551613ce6565b928401926101209290920191600101613d9d565b61012081016109a98284613ce6565b60006020808301818452808551808352604092508286019150828160051b8701018488016000805b84811015613e9857898403603f19018652825180516001600160a01b03168552880151888501889052805188860181905290890190839060608701905b80831015613e8357835180516001600160a01b031683526020808201519084015260408082015190840152606090810151908301526080820191508b84019350600183019250613e38565b50978a01979550505091870191600101613dfb565b50919998505050505050505050565b600080600060608486031215613ebc57600080fd5b8335613ec781613b2d565b92506020840135613ed781613b2d565b91506040840135613c5581613b2d565b60008060008060008060c08789031215613f0057600080fd5b8635613f0b81613b2d565b95506020870135613f1b81613b2d565b94506040870135613f2b81613b2d565b959894975094956060810135955060808101359460a0909101359350915050565b600060208284031215613f5e57600080fd5b8151612ae181613b2d565b602080825260409082018190527f4f6e6c792074686520636f6d7074726f6c6c6572206f7220636f6d7074726f6c908201527f6c65722061646d696e2063616e2063616c6c20746869732066756e6374696f6e606082015260800190565b634e487b7160e01b600052604160045260246000fd5b600060208284031215613fef57600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b808201808211156109a9576109a961400c565b6000600182016140475761404761400c565b5060010190565b60208082526031908201527f4f6e6c792074686520636f6d7074726f6c6c657227732061646d696e6973747260408201527061746f722063616e20646f20746869732160781b606082015260800190565b60208082526041908201527f4f6e6c792074686520636f6e666967206f776e6572206f7220636f6d7074726f60408201527f6c6c65722061646d696e2063616e2063616c6c20746869732066756e6374696f6060820152603760f91b608082015260a00190565b60208082526043908201527f4f6e6c792074686520706175736520677561726469616e206f7220636f6d707460408201527f726f6c6c65722061646d696e2063616e2063616c6c20746869732066756e637460608201526234b7b760e91b608082015260a00190565b60208082526026908201527f506175736520477561726469616e2063616e277420626520746865203020616460408201526564726573732160d01b606082015260800190565b6000602082840312156141c757600080fd5b8151612ae181613c07565b6020808252603e908201527f43616e6e6f7420736574206120737570706c792072657761726420737065656460408201527f20686967686572207468616e2074686520656d697373696f6e20636170210000606082015260800190565b6020808252603e908201527f43616e6e6f7420736574206120626f72726f772072657761726420737065656460408201527f20686967686572207468616e2074686520656d697373696f6e20636170210000606082015260800190565b805161429781613b2d565b919050565b600060208083850312156142af57600080fd5b825167ffffffffffffffff808211156142c757600080fd5b818501915085601f8301126142db57600080fd5b8151818111156142ed576142ed613fc7565b8060051b604051601f19603f8301168101818110858211171561431257614312613fc7565b60405291825284820192508381018501918883111561433057600080fd5b938501935b82851015614355576143468561428c565b84529385019392850192614335565b98975050505050505050565b6000806040838503121561437457600080fd5b825161437f81613c07565b6020939093015192949293505050565b6001600160a01b0394851681529290931660208301526001600160e01b0316604082015263ffffffff909116606082015260800190565b60005b838110156143e15781810151838201526020016143c9565b50506000910152565b60208152600082518060208401526144098160408501602087016143c6565b601f01601f19169190910160400192915050565b60008261443a57634e487b7160e01b600052601260045260246000fd5b500490565b818103818111156109a9576109a961400c565b80820281158282048414176109a9576109a961400c565b6000825161447b8184602087016143c6565b919091019291505056fea26469706673582212205a79833b52f6aeb743eb9c43a4bbff93f524799e37c886a9f8b277ad03f9557b64736f6c63430008130033

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101e55760003560e01c806373a1f3d01161010f578063c11a70b3116100a2578063e66b98c911610071578063e66b98c914610433578063e88d9c1b14610446578063ea0f3dff1461044e578063ed302dfd1461046157600080fd5b8063c11a70b3146103da578063c9a06b45146103ed578063dbc7779b1461040d578063e0ed91161461042057600080fd5b80638b62a51a116100de5780638b62a51a14610381578063ad1a9280146103a1578063adc75e52146103b4578063b2fa9e10146103c757600080fd5b806373a1f3d0146103285780637e218f901461033b5780637f7336ba1461035b5780638220d7cf1461036e57600080fd5b80633616b04b116101875780635c975abb116101565780635c975abb146102d95780635f5af1aa146102ef5780635fe3b56714610302578063610393a01461031557600080fd5b80633616b04b146102a3578063375fea29146102b6578063472db55d146102be578063485cc955146102c657600080fd5b806310d47dc7116101c357806310d47dc71461023f57806314f557731461025257806324a3d62214610265578063283923801461029057600080fd5b8063019047d6146101ea57806307e8ce85146101ff5780630cd8bbc514610228575b600080fd5b6101fd6101f8366004613b42565b61048e565b005b61021261020d366004613b5f565b610553565b60405161021f9190613b98565b60405180910390f35b61023160065481565b60405190815260200161021f565b6101fd61024d366004613c15565b6109af565b6101fd610260366004613c15565b610a6f565b600554610278906001600160a01b031681565b6040516001600160a01b03909116815260200161021f565b6101fd61029e366004613c60565b610b2a565b6101fd6102b1366004613c79565b610c0b565b6101fd610e04565b6101fd610ee7565b6101fd6102d4366004613b5f565b610fb5565b60005460ff16604051901515815260200161021f565b6101fd6102fd366004613b42565b61124e565b600454610278906001600160a01b031681565b6101fd610323366004613c79565b61137e565b610231610336366004613cba565b611537565b61034e610349366004613b42565b611589565b60405161021f9190613d81565b6101fd610369366004613c79565b6116f2565b6101fd61037c366004613b42565b6118ab565b61039461038f366004613b5f565b611964565b60405161021f9190613dc4565b6102786103af366004613b5f565b611a08565b6101fd6103c2366004613c15565b611a27565b6102316103d5366004613cba565b611ae0565b6103946103e8366004613cba565b611b32565b6104006103fb366004613b42565b611bee565b60405161021f9190613dd3565b6101fd61041b366004613cba565b611d61565b6101fd61042e366004613c15565b611fc7565b6101fd610441366004613ea7565b612080565b600654610231565b6101fd61045c366004613ee7565b6121ae565b6104766a0c097ce7bc90715b34b9f160241b81565b6040516001600160e01b03909116815260200161021f565b6004546001600160a01b0316331480610522575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156104e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061050d9190613f4c565b6001600160a01b0316336001600160a01b0316145b6105475760405162461bcd60e51b815260040161053e90613f69565b60405180910390fd5b610550816126bc565b50565b6001600160a01b038216600090815260036020526040812080546060929067ffffffffffffffff81111561058957610589613fc7565b6040519080825280602002602001820160405280156105ee57816020015b6105db604051806080016040528060006001600160a01b031681526020016000815260200160008152602001600081525090565b8152602001906001900390816105a75790505b509050600060405180604001604052806040518060600160405280896001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610647573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061066b9190613fdd565b8152602001896001600160a01b03166347bd37186040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106d29190613fdd565b815260200160405180602001604052808b6001600160a01b031663aa5af0fd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610720573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107449190613fdd565b90529052815260408051808201918290526370a0823160e01b9091526001600160a01b03888116604483015260209092019181908a166370a0823160648301602060405180830381865afa1580156107a0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107c49190613fdd565b81526040516395dd919360e01b81526001600160a01b038a811660048301526020909201918b16906395dd919390602401602060405180830381865afa158015610812573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108369190613fdd565b90529052905060005b83548110156109a257600084828154811061085c5761085c613ff6565b6000918252602082206005600b9092020190810154600382015460028301548751519395506108a39363ffffffff600160e01b840416926001600160e01b0316919061290f565b600683015460048401546002850154875160208101516040909101519495506000946108f5949363ffffffff600160e01b820416936001600160e01b039091169290916108f09190612ac3565b61290f565b905060006109118484600001518860200151600001518d612ae8565b905060006109328584600001518960000151604001518a602001518f612ba4565b604080516080810190915260018701546001600160a01b031681529091506020810161095e8484614022565b81526020018381526020018281525088878151811061097f5761097f613ff6565b60200260200101819052505050505050808061099a90614035565b91505061083f565b5090925050505b92915050565b6004546001600160a01b0316331480610a43575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610a0a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a2e9190613f4c565b6001600160a01b0316336001600160a01b0316145b610a5f5760405162461bcd60e51b815260040161053e90613f69565b610a6a838383612c73565b505050565b6004546001600160a01b0316331480610b03575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610aca573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aee9190613f4c565b6001600160a01b0316336001600160a01b0316145b610b1f5760405162461bcd60e51b815260040161053e90613f69565b610a6a838383612e35565b60048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610b71573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b959190613f4c565b6001600160a01b0316336001600160a01b031614610bc55760405162461bcd60e51b815260040161053e9061404e565b600680549082905560408051828152602081018490527f8d2ad4bb95e94ce8d50ed07769a97467ba4db3f80fc0badf6c81d0907a0b410a91015b60405180910390a15050565b82826000610c1983836130ed565b80549091506001600160a01b0316331480610caf575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610c76573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c9a9190613f4c565b6001600160a01b0316336001600160a01b0316145b610ccb5760405162461bcd60e51b815260040161053e9061409f565b6000610cd787876130ed565b6002810154909150808611610d3a5760405162461bcd60e51b8152602060048201526024808201527f5f6e6577456e6454696d65204d555354206265203e2063757272656e74456e6460448201526354696d6560e01b606482015260840161053e565b428611610d975760405162461bcd60e51b815260206004820152602560248201527f5f6e6577456e6454696d65204d555354206265203e20626c6f636b2e74696d6560448201526407374616d760dc1b606482015260840161053e565b610da0886126bc565b610da9886131cc565b6002820186905560408051828152602081018890526001600160a01b03808a1692908b16917f10f16113484fbc6e60553a394eb2a3ae47999b610e4212fad6903486dbca7f9291015b60405180910390a35050505050505050565b6005546001600160a01b0316331480610e98575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610e5f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e839190613f4c565b6001600160a01b0316336001600160a01b0316145b610eb45760405162461bcd60e51b815260040161053e90614106565b610ebc613335565b6040517fb83b93884b98604cbc549e7e4a81a9e49bd62c603026ec82f04915037258c56490600090a1565b60048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015610f2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f529190613f4c565b6001600160a01b0316336001600160a01b031614610f825760405162461bcd60e51b815260040161053e9061404e565b610f8a61338f565b6040517f24abc2b8df8d63728da8fe06c1555853a3f293f812e1ebd4303a5d6df7173e6c90600090a1565b600254610100900460ff1615808015610fd55750600254600160ff909116105b80610fef5750303b158015610fef575060025460ff166001145b6110525760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b606482015260840161053e565b6002805460ff191660011790558015611075576002805461ff0019166101001790555b6001600160a01b0383166110d75760405162461bcd60e51b815260206004820152602360248201527f436f6d7074726f6c6c65722063616e277420626520746865203020616464726560448201526273732160e81b606482015260840161053e565b6001600160a01b0382166110fd5760405162461bcd60e51b815260040161053e9061416f565b600480546001600160a01b0319166001600160a01b038516908117825560408051623f1ee960e11b815290519192627e3dd29282820192602092908290030181865afa158015611151573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061117591906141b5565b6111db5760405162461bcd60e51b815260206004820152603160248201527f43616e27742062696e6420746f20736f6d657468696e6720746861742773206e6044820152706f74206120636f6d7074726f6c6c65722160781b606482015260840161053e565b600580546001600160a01b0319166001600160a01b03841617905568056bc75e2d631000006006558015610a6a576002805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498906020015b60405180910390a1505050565b6005546001600160a01b03163314806112e2575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156112a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112cd9190613f4c565b6001600160a01b0316336001600160a01b0316145b6112fe5760405162461bcd60e51b815260040161053e90614106565b6001600160a01b0381166113245760405162461bcd60e51b815260040161053e9061416f565b600580546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527f0613b6ee6a04f0d09f390e4d9318894b9f6ac7fd83897cd8d18896ba579c401e9101610bff565b8282600061138c83836130ed565b80549091506001600160a01b0316331480611422575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156113e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061140d9190613f4c565b6001600160a01b0316336001600160a01b0316145b61143e5760405162461bcd60e51b815260040161053e9061409f565b600061144a87876130ed565b60058101549091508086036114c05760405162461bcd60e51b815260206004820152603660248201527f43616e277420736574206e657720737570706c7920656d697373696f6e7320746044820152756f20626520657175616c20746f2063757272656e742160501b606482015260840161053e565b60065486106114e15760405162461bcd60e51b815260040161053e906141d2565b6114ea886131cc565b6005820186905560408051828152602081018890526001600160a01b03808a1692908b16917fc4d50731808aa5d941c471c0b29364fecd810aa0565344f6cdcab2c873422baf9101610df2565b6001600160a01b038216600090815260036020526040812080548291908490811061156457611564613ff6565b60009182526020909120600b90910201600301546001600160e01b0316949350505050565b6001600160a01b038116600090815260036020526040812080546060929067ffffffffffffffff8111156115bf576115bf613fc7565b6040519080825280602002602001820160405280156115f857816020015b6115e5613ae1565b8152602001906001900390816115dd5790505b50905060005b82548110156116ea57600083828154811061161b5761161b613ff6565b60009182526020918290206040805161012081018252600b90930290910180546001600160a01b0390811684526001820154169383019390935260028301549082015260038201546001600160e01b03808216606084015263ffffffff600160e01b9283900481166080850152600485015491821660a08501529190041660c0820152600582015460e082015260068201546101008201528451919250908490849081106116cb576116cb613ff6565b60200260200101819052505080806116e290614035565b9150506115fe565b509392505050565b8282600061170083836130ed565b80549091506001600160a01b0316331480611796575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa15801561175d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117819190613f4c565b6001600160a01b0316336001600160a01b0316145b6117b25760405162461bcd60e51b815260040161053e9061409f565b60006117be87876130ed565b60068101549091508086036118345760405162461bcd60e51b815260206004820152603660248201527f43616e277420736574206e657720626f72726f7720656d697373696f6e7320746044820152756f20626520657175616c20746f2063757272656e742160501b606482015260840161053e565b60065486106118555760405162461bcd60e51b815260040161053e9061422f565b61185e886126bc565b6006820186905560408051828152602081018890526001600160a01b03808a1692908b16917f8fc43850ed5c7aaa0ce83829a1a40202c3fcf8257788d69881611dff1a0b32e99101610df2565b6004546001600160a01b031633148061193f575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015611906573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061192a9190613f4c565b6001600160a01b0316336001600160a01b0316145b61195b5760405162461bcd60e51b815260040161053e90613f69565b610550816131cc565b61196c613ae1565b600061197884846130ed565b604080516101208101825282546001600160a01b039081168252600184015416602082015260028301549181019190915260038201546001600160e01b03808216606084015263ffffffff600160e01b9283900481166080850152600485015491821660a08501529190041660c0820152600582015460e082015260069091015461010082015291505092915050565b600080611a1584846130ed565b546001600160a01b0316949350505050565b6004546001600160a01b0316331480611abb575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015611a82573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611aa69190613f4c565b6001600160a01b0316336001600160a01b0316145b611ad75760405162461bcd60e51b815260040161053e90613f69565b610b1f836126bc565b6001600160a01b0382166000908152600360205260408120805482919084908110611b0d57611b0d613ff6565b60009182526020909120600b90910201600401546001600160e01b0316949350505050565b60036020528160005260406000208181548110611b4e57600080fd5b60009182526020918290206040805161012081018252600b90930290910180546001600160a01b0390811684526001820154169383019390935260028301549082015260038201546001600160e01b03808216606084015263ffffffff600160e01b9283900481166080850152600485015491821660a08501529190041660c0820152600582015460e08201526006909101546101008201529150829050565b600480546040805163b0772d0b60e01b815290516060936000936001600160a01b03169263b0772d0b928183019286928290030181865afa158015611c37573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052611c5f919081019061429c565b90506000815167ffffffffffffffff811115611c7d57611c7d613fc7565b604051908082528060200260200182016040528015611cc357816020015b604080518082019091526000815260606020820152815260200190600190039081611c9b5790505b50905060005b82518110156116ea576000611cf7848381518110611ce957611ce9613ff6565b602002602001015187610553565b90506040518060400160405280858481518110611d1657611d16613ff6565b60200260200101516001600160a01b0316815260200182815250838381518110611d4257611d42613ff6565b6020026020010181905250508080611d5990614035565b915050611cc9565b60048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015611da8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dcc9190613f4c565b6001600160a01b0316336001600160a01b031614611dfc5760405162461bcd60e51b815260040161053e9061404e565b8160018201611efd57611ef8600460009054906101000a90046001600160a01b03166001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e5b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e7f9190613f4c565b6040516370a0823160e01b81523060048201526001600160a01b038416906370a0823190602401602060405180830381865afa158015611ec3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ee79190613fdd565b6001600160a01b03841691906133c8565b611f88565b611f88600460009054906101000a90046001600160a01b03166001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f53573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f779190613f4c565b6001600160a01b03831690846133c8565b604080516001600160a01b0385168152602081018490527fc4474c2790e13695f6d2b6f1d8e164290b55370f87a542fd7711abe0a1bf40ac9101611241565b6004546001600160a01b031633148061205b575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa158015612022573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120469190613f4c565b6001600160a01b0316336001600160a01b0316145b6120775760405162461bcd60e51b815260040161053e90613f69565b610a5f836131cc565b8282600061208e83836130ed565b80549091506001600160a01b0316331480612124575060048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156120eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061210f9190613f4c565b6001600160a01b0316336001600160a01b0316145b6121405760405162461bcd60e51b815260040161053e9061409f565b600061214c87876130ed565b80546001600160a01b038781166001600160a01b03198316811784556040805193831680855260208501929092529394509289821692918b16917f6ca67f2e3675f2b549fe77271364ebde88b3c7eb3ef84af329c373ca64fa25789101610df2565b60048054604080516303e1469160e61b815290516001600160a01b039092169263f851a4409282820192602092908290030181865afa1580156121f5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122199190613f4c565b6001600160a01b0316336001600160a01b0316146122495760405162461bcd60e51b815260040161053e9061404e565b60048054604051638e8f294b60e01b81526001600160a01b038981169382019390935260009290911690638e8f294b906024016040805180830381865afa158015612298573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122bc9190614361565b509050806123235760405162461bcd60e51b815260206004820152602e60248201527f546865206d61726b65742072657175657374656420746f20626520616464656460448201526d20697320756e2d6c69737465642160901b606482015260840161053e565b60065484106123445760405162461bcd60e51b815260040161053e906141d2565b60065483106123655760405162461bcd60e51b815260040161053e9061422f565b612370426001614022565b82116123d45760405162461bcd60e51b815260206004820152602d60248201527f546865205f656e6454696d6520706172616d65746572206d757374206265206960448201526c6e20746865206675747572652160981b606482015260840161053e565b6001600160a01b0387166000908152600360205260408120905b815481101561249057600082828154811061240b5761240b613ff6565b60009182526020909120600b9091020160018101549091506001600160a01b0389811691160361247d5760405162461bcd60e51b815260206004820152601e60248201527f456d697373696f6e20746f6b656e20616c7265616479206c6973746564210000604482015260640161053e565b508061248881614035565b9150506123ee565b506000604051806101200160405280896001600160a01b03168152602001886001600160a01b031681526020018581526020016a0c097ce7bc90715b34b9f160241b6001600160e01b0316815260200161251f426040518060400160405280601f81526020017f626c6f636b2074696d657374616d70206578636565647320333220626974730081525061341a565b63ffffffff1681526020016a0c097ce7bc90715b34b9f160241b6001600160e01b03168152602001612586426040518060400160405280601f81526020017f626c6f636b2074696d657374616d70206578636565647320333220626974730081525061341a565b63ffffffff168152602001878152602001868152509050866001600160a01b0316886001600160a01b03168a6001600160a01b03167fa76959d76a349a0b8fd3120607e3aea6af58897ae6531bfe60a0267c4ea0c2728989896040516125ff939291909283526020830191909152604082015260600190565b60405180910390a481546001818101845560009384526020938490208351600b9093020180546001600160a01b039384166001600160a01b03199182161782559484015191810180549290931691909416179055604081015160028301556060810151608082015163ffffffff908116600160e01b9081026001600160e01b0393841617600386015560a084015160c085015190921602911617600483015560e08101516005830155610100015160069091015550505050505050565b6001600160a01b0381166000818152600360209081526040808320815180840180845263aa5af0fd60e01b905291519094919283929163aa5af0fd91602480860192908187030181865afa158015612718573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061273c9190613fdd565b81525090506000836001600160a01b03166347bd37186040518163ffffffff1660e01b8152600401602060405180830381865afa158015612781573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127a59190613fdd565b905060005b83548110156129085760008482815481106127c7576127c7613ff6565b6000918252602082206006600b90920201908101546004820154600283015492945061280f9263ffffffff600160e01b830416916001600160e01b0316906108f0898b612ac3565b905080600001518260000160040160006101000a8154816001600160e01b0302191690836001600160e01b03160217905550806020015182600001600401601c6101000a81548163ffffffff021916908363ffffffff1602179055507f24b735e493aede533ed6134442bad7e2ea2e72d71739de4c97f020174f5e3bcd878360000160010160009054906101000a90046001600160a01b03168460000160040160009054906101000a90046001600160e01b031685600001600401601c9054906101000a900463ffffffff166040516128eb949392919061438f565b60405180910390a15050808061290090614035565b9150506127aa565b5050505050565b60408051808201909152600080825260208201526000612964426040518060400160405280601f81526020017f626c6f636b2074696d657374616d70206578636565647320333220626974730081525061341a565b9050600061297e8263ffffffff168863ffffffff1661344a565b9050848263ffffffff1611156129b757848763ffffffff1610156129b3576129ac858863ffffffff1661344a565b90506129b7565b5060005b8015806129c2575087155b156129f4576040518060400160405280876001600160e01b031681526020018363ffffffff1681525092505050612aba565b6000612a00828a613484565b90506000808611612a205760405180602001604052806000815250612a2a565b612a2a82876134c6565b90506000612a8c612a5260405180602001604052808c6001600160e01b03168152508461350a565b5160408051808201909152601a81527f6e657720696e64657820657863656564732032323420626974730000000000006020820152613536565b90506040518060400160405280826001600160e01b031681526020018663ffffffff16815250955050505050505b95945050505050565b6000612ae1612ada84670de0b6b3a7640000613484565b835161355d565b9392505050565b6001600160a01b038116600090815260078501602052604081205480158015612b2857506a0c097ce7bc90715b34b9f160241b6001600160e01b03861610155b15612b3e57506a0c097ce7bc90715b34b9f160241b5b60006040518060200160405280612b5e886001600160e01b03168561344a565b905290506000612b6e8683613590565b6001600160a01b038616600090815260088a016020526040902054909150612b9690826135b9565b93505050505b949350505050565b6001600160a01b038116600090815260098601602052604081205480158015612be457506a0c097ce7bc90715b34b9f160241b6001600160e01b03871610155b15612bfa57506a0c097ce7bc90715b34b9f160241b5b60006040518060200160405280612c1a896001600160e01b03168561344a565b81525090506000612c2f866020015188612ac3565b90506000612c3d8284613590565b6001600160a01b0387166000908152600a8c016020526040902054909150612c6590826135b9565b9a9950505050505050505050565b6001600160a01b0383811660008181526003602052604080822090516370a0823160e01b81529386166004850152929091906370a0823190602401602060405180830381865afa158015612ccb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cef9190613fdd565b905060005b8254811015612e2d576000838281548110612d1157612d11613ff6565b6000918252602082206003600b9092020190810154909250612d3f9083906001600160e01b0316868a612ae8565b60038301546001600160a01b03808a16600081815260078701602090815260408083206001600160e01b039096169095556008880190528390208490556001860154925193945091811692908b16907f51761e1f6548bc99f2a61f299986e1b08a489f06622f689a413e02d7654a476690612dbd9086815260200190565b60405180910390a48515612e18576001600160a01b03808816600090815260088401602052604081205460018501549192612dfb928b9291166135ef565b6001600160a01b0389166000908152600885016020526040902055505b50508080612e2590614035565b915050612cf4565b505050505050565b6001600160a01b0383166000818152600360209081526040808320815180840180845263aa5af0fd60e01b905291519094919283929163aa5af0fd91602480860192908187030181865afa158015612e91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612eb59190613fdd565b905260408051808201918290526370a0823160e01b9091526001600160a01b038681166044830152919250600091819088166370a0823160648301602060405180830381865afa158015612f0d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f319190613fdd565b81526040516395dd919360e01b81526001600160a01b0388811660048301526020909201918916906395dd919390602401602060405180830381865afa158015612f7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fa39190613fdd565b9052905060005b83548110156130e4576000848281548110612fc757612fc7613ff6565b6000918252602082206004600b9092020190810154909250612ff69083906001600160e01b031687878c612ba4565b60048301546001600160a01b03808b16600081815260098701602090815260408083206001600160e01b03909616909555600a880190528390208490556001860154925193945091811692908c16907f48a32d6daeb4317b45f49c3a1c0b1bd7d53a175d1f46c425138e328900cdccb4906130749086815260200190565b60405180910390a486156130cf576001600160a01b038089166000908152600a84016020526040812054600185015491926130b2928c9291166135ef565b6001600160a01b038a166000908152600a85016020526040902055505b505080806130dc90614035565b915050612faa565b50505050505050565b6001600160a01b0382166000908152600360205260408120815b815481101561316b57600082828154811061312457613124613ff6565b60009182526020909120600b9091020160018101549091506001600160a01b038681169116036131585792506109a9915050565b508061316381614035565b915050613107565b5060405162461bcd60e51b815260206004820152602f60248201527f556e61626c6520746f2066696e6420656d697373696f6e20746f6b656e20696e60448201526e206d546f6b656e20636f6e6669677360881b606482015260840161053e565b6001600160a01b038116600081815260036020908152604080832081516318160ddd60e01b815291519094926318160ddd92600480820193918290030181865afa15801561321e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132429190613fdd565b905060005b825481101561332f57600083828154811061326457613264613ff6565b6000918252602082206005600b9092020190810154600382015460028301549294506132a89263ffffffff600160e01b830416916001600160e01b0316908861290f565b8051602082015163ffffffff8116600160e01b026001600160e01b03831617600386015560018501546040519394507f79af45fe3972eecc4b95252214ad1d36529435ab4d4ae291d62a2ee5a0cc050093613312938b936001600160a01b0390931692909161438f565b60405180910390a15050808061332790614035565b915050613247565b50505050565b61333d613717565b6000805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586133723390565b6040516001600160a01b03909116815260200160405180910390a1565b61339761375f565b6000805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa33613372565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610a6a9084906137a8565b60008164010000000084106134425760405162461bcd60e51b815260040161053e91906143ea565b509192915050565b6000612ae18383604051806040016040528060158152602001747375627472616374696f6e20756e646572666c6f7760581b81525061387d565b6000612ae183836040518060400160405280601781526020017f6d756c7469706c69636174696f6e206f766572666c6f770000000000000000008152506138ac565b60408051602081019091526000815260405180602001604052806135016134fb866a0c097ce7bc90715b34b9f160241b613484565b8561355d565b90529392505050565b6040805160208101909152600081526040518060200160405280613501856000015185600001516135b9565b600081600160e01b84106134425760405162461bcd60e51b815260040161053e91906143ea565b6000612ae183836040518060400160405280600e81526020016d646976696465206279207a65726f60901b815250613908565b60006a0c097ce7bc90715b34b9f160241b6135af848460000151613484565b612ae1919061441d565b6000612ae18383604051806040016040528060118152602001706164646974696f6e206f766572666c6f7760781b815250613934565b60006135f9613965565b8260000361360857508161370e565b60005460ff161561361a57508161370e565b6040516370a0823160e01b815230600482015282906000906001600160a01b038316906370a0823190602401602060405180830381865afa158015613663573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136879190613fdd565b90506000851180156136995750808511155b156136bd576136b26001600160a01b03831687876133c8565b60009250505061370e565b604080516001600160a01b038089168252861660208201529081018690527f8b079e2b0be6cc9631b7883d8478590fe708e9d360391aab49aa147901fc7a379060600160405180910390a184925050505b612ae160018055565b60005460ff161561375d5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640161053e565b565b60005460ff1661375d5760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604482015260640161053e565b60006137fd826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166139be9092919063ffffffff16565b905080516000148061381e57508080602001905181019061381e91906141b5565b610a6a5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161053e565b600081848411156138a15760405162461bcd60e51b815260040161053e91906143ea565b50612b9c838561443f565b60008315806138b9575082155b156138c657506000612ae1565b60006138d28486614452565b9050836138df868361441d565b1483906138ff5760405162461bcd60e51b815260040161053e91906143ea565b50949350505050565b600081836139295760405162461bcd60e51b815260040161053e91906143ea565b50612b9c838561441d565b6000806139418486614022565b905082858210156138ff5760405162461bcd60e51b815260040161053e91906143ea565b6002600154036139b75760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015260640161053e565b6002600155565b6060612b9c848460008585600080866001600160a01b031685876040516139e59190614469565b60006040518083038185875af1925050503d8060008114613a22576040519150601f19603f3d011682016040523d82523d6000602084013e613a27565b606091505b5091509150613a3887838387613a43565b979650505050505050565b60608315613ab2578251600003613aab576001600160a01b0385163b613aab5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161053e565b5081612b9c565b612b9c8383815115613ac75781518083602001fd5b8060405162461bcd60e51b815260040161053e91906143ea565b6040805161012081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810182905261010081019190915290565b6001600160a01b038116811461055057600080fd5b600060208284031215613b5457600080fd5b8135612ae181613b2d565b60008060408385031215613b7257600080fd5b8235613b7d81613b2d565b91506020830135613b8d81613b2d565b809150509250929050565b6020808252825182820181905260009190848201906040850190845b81811015613bfb57835180516001600160a01b0316845260208082015190850152604080820151908501526060908101519084015260808301938501939250600101613bb4565b50909695505050505050565b801515811461055057600080fd5b600080600060608486031215613c2a57600080fd5b8335613c3581613b2d565b92506020840135613c4581613b2d565b91506040840135613c5581613c07565b809150509250925092565b600060208284031215613c7257600080fd5b5035919050565b600080600060608486031215613c8e57600080fd5b8335613c9981613b2d565b92506020840135613ca981613b2d565b929592945050506040919091013590565b60008060408385031215613ccd57600080fd5b8235613cd881613b2d565b946020939093013593505050565b80516001600160a01b03908116835260208083015190911690830152604080820151908301526060808201516001600160e01b03169083015260808082015190613d379084018263ffffffff169052565b5060a0810151613d5260a08401826001600160e01b03169052565b5060c0810151613d6a60c084018263ffffffff169052565b5060e0818101519083015261010090810151910152565b6020808252825182820181905260009190848201906040850190845b81811015613bfb57613db0838551613ce6565b928401926101209290920191600101613d9d565b61012081016109a98284613ce6565b60006020808301818452808551808352604092508286019150828160051b8701018488016000805b84811015613e9857898403603f19018652825180516001600160a01b03168552880151888501889052805188860181905290890190839060608701905b80831015613e8357835180516001600160a01b031683526020808201519084015260408082015190840152606090810151908301526080820191508b84019350600183019250613e38565b50978a01979550505091870191600101613dfb565b50919998505050505050505050565b600080600060608486031215613ebc57600080fd5b8335613ec781613b2d565b92506020840135613ed781613b2d565b91506040840135613c5581613b2d565b60008060008060008060c08789031215613f0057600080fd5b8635613f0b81613b2d565b95506020870135613f1b81613b2d565b94506040870135613f2b81613b2d565b959894975094956060810135955060808101359460a0909101359350915050565b600060208284031215613f5e57600080fd5b8151612ae181613b2d565b602080825260409082018190527f4f6e6c792074686520636f6d7074726f6c6c6572206f7220636f6d7074726f6c908201527f6c65722061646d696e2063616e2063616c6c20746869732066756e6374696f6e606082015260800190565b634e487b7160e01b600052604160045260246000fd5b600060208284031215613fef57600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b808201808211156109a9576109a961400c565b6000600182016140475761404761400c565b5060010190565b60208082526031908201527f4f6e6c792074686520636f6d7074726f6c6c657227732061646d696e6973747260408201527061746f722063616e20646f20746869732160781b606082015260800190565b60208082526041908201527f4f6e6c792074686520636f6e666967206f776e6572206f7220636f6d7074726f60408201527f6c6c65722061646d696e2063616e2063616c6c20746869732066756e6374696f6060820152603760f91b608082015260a00190565b60208082526043908201527f4f6e6c792074686520706175736520677561726469616e206f7220636f6d707460408201527f726f6c6c65722061646d696e2063616e2063616c6c20746869732066756e637460608201526234b7b760e91b608082015260a00190565b60208082526026908201527f506175736520477561726469616e2063616e277420626520746865203020616460408201526564726573732160d01b606082015260800190565b6000602082840312156141c757600080fd5b8151612ae181613c07565b6020808252603e908201527f43616e6e6f7420736574206120737570706c792072657761726420737065656460408201527f20686967686572207468616e2074686520656d697373696f6e20636170210000606082015260800190565b6020808252603e908201527f43616e6e6f7420736574206120626f72726f772072657761726420737065656460408201527f20686967686572207468616e2074686520656d697373696f6e20636170210000606082015260800190565b805161429781613b2d565b919050565b600060208083850312156142af57600080fd5b825167ffffffffffffffff808211156142c757600080fd5b818501915085601f8301126142db57600080fd5b8151818111156142ed576142ed613fc7565b8060051b604051601f19603f8301168101818110858211171561431257614312613fc7565b60405291825284820192508381018501918883111561433057600080fd5b938501935b82851015614355576143468561428c565b84529385019392850192614335565b98975050505050505050565b6000806040838503121561437457600080fd5b825161437f81613c07565b6020939093015192949293505050565b6001600160a01b0394851681529290931660208301526001600160e01b0316604082015263ffffffff909116606082015260800190565b60005b838110156143e15781810151838201526020016143c9565b50506000910152565b60208152600082518060208401526144098160408501602087016143c6565b601f01601f19169190910160400192915050565b60008261443a57634e487b7160e01b600052601260045260246000fd5b500490565b818103818111156109a9576109a961400c565b80820281158282048414176109a9576109a961400c565b6000825161447b8184602087016143c6565b919091019291505056fea26469706673582212205a79833b52f6aeb743eb9c43a4bbff93f524799e37c886a9f8b277ad03f9557b64736f6c63430008130033

Block Transaction Gas Used Reward
view all blocks produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.