Contract 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d

Contract Overview

Balance:
0 DEV
Txn Hash Method
Block
From
To
Value [Txn Fee]
0x5ff59a9910b96f615d5b6df7b1509f1c4d1acda8cd7b4ee3422b84029d3178c20x6080604025240912022-07-20 17:50:30255 days 15 hrs ago0xb6010d7ac4a8e9fa3e88b25f287fe725f2215208 IN  Contract Creation0 DEV0.002792672
[ Download CSV Export 
Latest 25 internal transaction
Parent Txn Hash Block From To Value
0x9487e0a14de45cec574724ebe959162d40122c33ec1ad88a092523bc520d90a527665412022-09-02 16:58:24211 days 16 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x650dd5652ff2a753a61830cc84c8f77787ab48810 DEV
0x9487e0a14de45cec574724ebe959162d40122c33ec1ad88a092523bc520d90a527665412022-09-02 16:58:24211 days 16 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x00000000000000000000000000000000000008020 DEV
0x9487e0a14de45cec574724ebe959162d40122c33ec1ad88a092523bc520d90a527665412022-09-02 16:58:24211 days 16 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x00000000000000000000000000000000000008020 DEV
0x9487e0a14de45cec574724ebe959162d40122c33ec1ad88a092523bc520d90a527665412022-09-02 16:58:24211 days 16 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x00000000000000000000000000000000000008020 DEV
0x9487e0a14de45cec574724ebe959162d40122c33ec1ad88a092523bc520d90a527665412022-09-02 16:58:24211 days 16 hrs ago 0xfd7eb415312314387414064dd5a139dc0853b4570x638fa495cebaef4cb6e30a4c8442009c851c1f7d0 DEV
0xb7bd08958e100ad218a1be6d3dd8764e7e6decc00104b6943d8f637e662be7df27631952022-09-02 3:34:54212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x650dd5652ff2a753a61830cc84c8f77787ab48810 DEV
0xb7bd08958e100ad218a1be6d3dd8764e7e6decc00104b6943d8f637e662be7df27631952022-09-02 3:34:54212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0xff3d51eb7dd6779ee490bc1cc5572dcce830d44f0 DEV
0xb7bd08958e100ad218a1be6d3dd8764e7e6decc00104b6943d8f637e662be7df27631952022-09-02 3:34:54212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0xff3d51eb7dd6779ee490bc1cc5572dcce830d44f0 DEV
0xb7bd08958e100ad218a1be6d3dd8764e7e6decc00104b6943d8f637e662be7df27631952022-09-02 3:34:54212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0xff3d51eb7dd6779ee490bc1cc5572dcce830d44f0 DEV
0xb7bd08958e100ad218a1be6d3dd8764e7e6decc00104b6943d8f637e662be7df27631952022-09-02 3:34:54212 days 6 hrs ago 0xfd7eb415312314387414064dd5a139dc0853b4570x638fa495cebaef4cb6e30a4c8442009c851c1f7d0 DEV
0x78de73cc00d855f4277a922a48e244057a5acdf08f8deb059b998608f77aa52227631902022-09-02 3:33:54212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x650dd5652ff2a753a61830cc84c8f77787ab48810 DEV
0x78de73cc00d855f4277a922a48e244057a5acdf08f8deb059b998608f77aa52227631902022-09-02 3:33:54212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x00000000000000000000000000000000000008020 DEV
0x78de73cc00d855f4277a922a48e244057a5acdf08f8deb059b998608f77aa52227631902022-09-02 3:33:54212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x00000000000000000000000000000000000008020 DEV
0x78de73cc00d855f4277a922a48e244057a5acdf08f8deb059b998608f77aa52227631902022-09-02 3:33:54212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x00000000000000000000000000000000000008020 DEV
0x78de73cc00d855f4277a922a48e244057a5acdf08f8deb059b998608f77aa52227631902022-09-02 3:33:54212 days 6 hrs ago 0xfd7eb415312314387414064dd5a139dc0853b4570x638fa495cebaef4cb6e30a4c8442009c851c1f7d0 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0xff3d51eb7dd6779ee490bc1cc5572dcce830d44f0 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x650dd5652ff2a753a61830cc84c8f77787ab48810 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x650dd5652ff2a753a61830cc84c8f77787ab48810 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0xa994b047646ffd9a1f718c74ca20e5563cd1f9560 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0xa994b047646ffd9a1f718c74ca20e5563cd1f9560 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x3bbc46255ad28157494ca895d424bd14df0b131d0 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x3bbc46255ad28157494ca895d424bd14df0b131d0 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x077ab9b515ff939966c91b71e34ed3c5322185f00 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x077ab9b515ff939966c91b71e34ed3c5322185f00 DEV
0x07725d8cc689ddcfa1f9c2ea7550a9e1b5d99228b562ee1036cbced34f9096f627631492022-09-02 3:23:06212 days 6 hrs ago 0x638fa495cebaef4cb6e30a4c8442009c851c1f7d0x650dd5652ff2a753a61830cc84c8f77787ab48810 DEV
[ Download CSV Export 
Loading

Similar Match Source Code
Note: This contract matches the deployed ByteCode of the Source Code for Contract 0x82bb93Ce3a7247eFaA905E11693E5a0dCE0117F6

Contract Name:
QollateralManager

Compiler Version
v0.8.9+commit.e5eed63a

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 15 : QollateralManager.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./interfaces/IFixedRateMarket.sol";
import "./interfaces/IQAdmin.sol";
import "./interfaces/IQPriceOracle.sol";
import "./interfaces/IQollateralManager.sol";
import "./interfaces/moonwell/MTokenInterfaces.sol";
import "./libraries/QTypes.sol";

contract QollateralManager is Initializable, IQollateralManager {

  using SafeERC20 for IERC20;
  
  /// @notice Contract storing all global Qoda parameters
  IQAdmin private _qAdmin;

  /// @notice Contract for price oracle feeds
  IQPriceOracle private _qPriceOracle;

  /// @notice 0x0 null address for convenience
  address constant NULL = address(0);

  /// @notice Native Token (WETH equivalent) for convenience
  address constant _NATIVE_TOKEN_ADDRESS = 0x0000000000000000000000000000000000000802;
  
  /// @notice Use this for quick lookups of collateral balances by asset
  /// account => tokenAddress => balanceLocal
  mapping(address => mapping(IERC20 => uint)) private _collateralBalances;

  /// @notice Iterable list of all collateral addresses which an account has nonzero balance.
  /// Use this when calculating `collateralValue` for liquidity considerations
  /// account => tokenAddresses[]
  mapping(address => IERC20[]) private _iterableCollateralAddresses;
  
  /// @notice Iterable list of all markets which an account has participated.
  /// Use this when calculating `totalBorrowValue` for liquidity considerations
  /// account => fixedRateMarketAddresses[]
  mapping(address => IFixedRateMarket[]) private _iterableAccountMarkets;

  /// @notice Non-iterable list of collateral which an account has nonzero balance.
  /// Use this for quick lookups
  /// account => tokenAddress => bool;
  mapping(address => mapping(IERC20 => bool)) private _accountCollateral;

  /// @notice Non-iterable list of markets which an account has participated.
  /// Use this for quick lookups
  /// account => fixedRateMarketAddress => bool;
  mapping(address => mapping(IFixedRateMarket => bool)) private _accountMarkets;
  
  /// @notice Constructor for upgradeable contracts
  /// @param qAdminAddress_ Address of the `QAdmin` contract
  /// @param qPriceOracleAddress_ Address of the `QPriceOracle` contract
  function initialize(address qAdminAddress_, address qPriceOracleAddress_) external initializer {
    _qAdmin = IQAdmin(qAdminAddress_);
    _qPriceOracle = IQPriceOracle(qPriceOracleAddress_);
  }

  /// @notice Needed for receiving native token when redeeming from Moonwell
  receive() external payable {}

  modifier onlyAdmin() {
    require(_qAdmin.hasRole(_qAdmin.ADMIN_ROLE(), msg.sender), "QollateralManager: only admin");
    _;
  }

  modifier onlyMarket() {
    require(_qAdmin.hasRole(_qAdmin.MARKET_ROLE(), msg.sender), "QollateralManager: only market");
    _;
  }
  
  /** ADMIN/RESTRICTED FUNCTIONS **/

  /// @notice Record when an account has either borrowed or lent into a
  /// `FixedRateMarket`. This is necessary because we need to iterate
  /// across all markets that an account has borrowed/lent to to calculate their
  /// `borrowValue`. Only the `FixedRateMarket` contract itself may call
  /// this function
  /// @param account User account
  /// @param market Address of the `FixedRateMarket` market
  function _addAccountMarket(address account, IFixedRateMarket market) external onlyMarket {

    // Record that account now has participated in this `FixedRateMarket`
    if(!_accountMarkets[account][market]){
      _accountMarkets[account][market] = true;
      _iterableAccountMarkets[account].push(market);
    }

    /// Emit the event
    emit AddAccountMarket(account, address(market));
  }

  /// @notice Transfer collateral balances from one account to another. Only
  /// `FixedRateMarket` contracts can call this restricted function. This is used
  /// for when a liquidator liquidates an account.
  /// @param token ERC20 token
  /// @param from Sender address
  /// @param to Recipient address
  /// @param amount Amount to transfer
  function _transferCollateral(
                               IERC20 token,
                               address from,
                               address to,
                               uint amount
                               ) external onlyMarket {

    // Check `from` address has enough collateral balance
    require(
            amount <= _collateralBalances[from][token],
            "QollateralManager: `from` balance too low"
            );

    // Transfer the balance to recipient    
    _subtractCollateral(from, token, amount);
    token.safeTransfer(to, amount);

    // Emit the event
    emit TransferCollateral(address(token), from, to, amount);    
  }

  /** USER INTERFACE **/

  /// @notice Users call this to deposit collateral to fund their borrows
  /// @param token ERC20 token
  /// @param amount Amount to deposit (in local ccy)
  /// @return uint New collateral balance
  function depositCollateral(IERC20 token, uint amount) external returns(uint) {
    return _depositCollateral(msg.sender, token, amount);
  }

  /// @notice Users call this to deposit collateral to fund their borrows, where their
  /// collateral is automatically wrapped into MTokens for convenience so users can
  /// automatically earn interest on their collateral.
  /// @param underlying Underlying ERC20 token
  /// @param amount Amount to deposit (in underlying local currency)
  /// @return uint New collateral balance (in MToken balance)
  function depositCollateralWithMTokenWrap(IERC20 underlying, uint amount) external returns(uint) {
    return _depositCollateralWithMTokenWrap(msg.sender, underlying, amount);
  }
  
  /// @notice Users call this to withdraw collateral
  /// @param token ERC20 token
  /// @param amount Amount to withdraw (in local ccy)
  /// @return uint New collateral balance 
  function withdrawCollateral(IERC20 token, uint amount) external returns(uint) {
    return _withdrawCollateral(msg.sender, token, amount);
  }

  /// @notice Users call this to withdraw mToken collateral, where their
  /// collateral is automatically unwrapped into underlying tokens for
  /// convenience.
  /// @param mTokenAddress Yield-bearing token address
  /// @param amount Amount to withdraw (in mToken local currency)
  /// @return uint New collateral balance (in MToken balance)
  function withdrawCollateralWithMTokenUnwrap(
                                              address mTokenAddress,
                                              uint amount
                                              ) external returns(uint) {
    return _withdrawCollateralWithMTokenUnwrap(msg.sender, mTokenAddress, amount);
  }

  
  /** VIEW FUNCTIONS **/

  /// @notice Get the address of the `QAdmin` contract
  /// @return address Address of `QAdmin` contract
  function qAdmin() external view returns(address){
    return address(_qAdmin);
  }

  /// @notice Return what the collateral ratio for an account would be
  /// with a hypothetical collateral withdraw and/or token borrow.
  /// The collateral ratio is calculated as:
  /// (`virtualCollateralValue` / `virtualBorrowValue`)
  /// If the returned value falls below 1e8, the account can be liquidated
  /// @param account User account
  /// @param withdrawToken Currency of hypothetical withdraw
  /// @param withdrawAmount Amount of hypothetical withdraw in local currency
  /// @param borrowMarket Market of hypothetical borrow
  /// @param borrowAmount Amount of hypothetical borrow in local ccy
  /// @return uint Hypothetical collateral ratio
  function hypotheticalCollateralRatio(
                                       address account,
                                       IERC20 withdrawToken,
                                       uint withdrawAmount,
                                       IFixedRateMarket borrowMarket,
                                       uint borrowAmount
                                       ) external view returns(uint){
    return _getHypotheticalCollateralRatio(
                                           account,
                                           withdrawToken,
                                           withdrawAmount,
                                           borrowMarket,
                                           borrowAmount
                                           );                                          
  }

  /// @notice Return the current collateral ratio for an account.
  /// The collateral ratio is calculated as:
  /// (`virtualCollateralValue` / `virtualBorrowValue`)
  /// If the returned value falls below 1e8, the account can be liquidated
  /// @param account User account
  /// @return uint Collateral ratio
  function collateralRatio(address account) external view returns(uint){
    return _getHypotheticalCollateralRatio(
                                           account,
                                           IERC20(NULL),
                                           0,
                                           IFixedRateMarket(NULL),
                                           0
                                           );
  }

  /// @notice Get the `collateralFactor` weighted value (in USD) of all the
  /// collateral deposited for an account
  /// @param account Account to query
  /// @return uint Total value of account in USD
  function virtualCollateralValue(address account) external view returns(uint){
    return _getHypotheticalCollateralValue(account, IERC20(NULL), 0, true);
  }

  /// @notice Get the `collateralFactor` weighted value (in USD) for the tokens
  /// deposited for an account
  /// @param account Account to query
  /// @param token ERC20 token
  /// @return uint Value of token collateral of account in USD
  function virtualCollateralValueByToken(
                                         address account,
                                         IERC20 token
                                         ) external view returns(uint){
    return _getHypotheticalCollateralValueByToken(account, token, 0, true);
  }

  /// @notice Get the `marketFactor` weighted net borrows (i.e. borrows - lends)
  /// in USD summed across all `Market`s participated in by the user
  /// @param account Account to query
  /// @return uint Borrow value of account in USD
  function virtualBorrowValue(address account) external view returns(uint){
    return _getHypotheticalBorrowValue(account, IFixedRateMarket(NULL), 0, true);
  }

  /// @notice Get the `marketFactor` weighted net borrows (i.e. borrows - lends)
  /// in USD for a particular `Market`
  /// @param account Account to query
  /// @param market `FixedRateMarket` contract
  /// @return uint Borrow value of account in USD
  function virtualBorrowValueByMarket(
                                      address account,
                                      IFixedRateMarket market
                                      ) external view returns(uint){
    return _getHypotheticalBorrowValueByMarket(account, market, 0, true);
  }
  
  /// @notice Get the unweighted value (in USD) of all the collateral deposited
  /// for an account
  /// @param account Account to query
  /// @return uint Total value of account in USD
  function realCollateralValue(address account) external view returns(uint){
    return _getHypotheticalCollateralValue(account, IERC20(NULL), 0, false);
  }
  
  /// @notice Get the unweighted value (in USD) of the tokens deposited
  /// for an account
  /// @param account Account to query
  /// @param token ERC20 token
  /// @return uint Value of token collateral of account in USD
  function realCollateralValueByToken(
                                      address account,
                                      IERC20 token
                                      ) external view returns(uint){
    return _getHypotheticalCollateralValueByToken(account, token, 0, false);
  }
  
  /// @notice Get the unweighted current net value borrowed (i.e. borrows - lends)
  /// in USD summed across all `Market`s participated in by the user
  /// @param account Account to query
  /// @return uint Borrow value of account in USD
  function realBorrowValue(address account) external view returns(uint){
    return _getHypotheticalBorrowValue(account, IFixedRateMarket(NULL), 0, false);
  }

  /// @notice Get the unweighted current net value borrowed (i.e. borrows - lends)
  /// in USD for a particular `Market`
  /// @param account Account to query
  /// @param market `FixedRateMarket` contract
  /// @return uint Borrow value of account in USD
  function realBorrowValueByMarket(
                                   address account,
                                   IFixedRateMarket market
                                   ) external view returns(uint){
    return _getHypotheticalBorrowValueByMarket(account, market, 0, false);
  }

  /// @notice Get the minimum collateral ratio. Scaled by 1e8.
  /// @return uint Minimum collateral ratio
  function minCollateralRatio() external view returns(uint){
    return _qAdmin.minCollateralRatio();
  }

  /// @notice Get the initial collateral ratio. Scaled by 1e8
  /// @return uint Initial collateral ratio
  function initCollateralRatio() external view returns(uint){
    return _qAdmin.initCollateralRatio();
  }

  /// @notice Get the close factor. Scaled by 1e8
  /// @return uint Close factor
  function closeFactor() external view returns(uint){
    return _qAdmin.closeFactor();
  }

  /// @notice Get the liquidation incentive. Scaled by 1e8
  /// @return uint Liquidation incentive
  function liquidationIncentive() external view returns(uint){
    return _qAdmin.liquidationIncentive();
  }

  /// @notice Use this for quick lookups of collateral balances by asset
  /// @param account User account  
  /// @param token ERC20 token
  /// @return uint Balance in local
  function collateralBalance(address account, IERC20 token) external view returns(uint){
    return _collateralBalances[account][token];
  }

  /// @notice Get iterable list of collateral addresses which an account has nonzero balance.
  /// @param account User account
  /// @return address[] Iterable list of ERC20 token addresses
  function iterableCollateralAddresses(address account) external view returns(IERC20[] memory){
    return _iterableCollateralAddresses[account];
  }

  /// @notice Quick lookup of whether an account has a particular collateral
  /// @param account User account
  /// @param token ERC20 token addresses
  /// @return bool True if account has collateralized with given ERC20 token, false otherwise
  function accountCollateral(address account, IERC20 token) external view returns(bool) {
    return _accountCollateral[account][token];
  }
  
  /// @notice Get iterable list of all Markets which an account has participated
  /// @param account User account
  /// @return address[] Iterable list of `FixedRateLoanMarket` contract addresses
  function iterableAccountMarkets(address account) external view returns(IFixedRateMarket[] memory){
    return _iterableAccountMarkets[account];
  }

  /// @notice Quick lookup of whether an account has participated in a Market
  /// @param account User account
  /// @param market`FixedRateLoanMarket` contract
  /// @return bool True if participated, false otherwise
  function accountMarkets(address account, IFixedRateMarket market) external view returns(bool){
    return _accountMarkets[account][market];
  }

  /// @notice Converts any local value into its value in USD using oracle feed price
  /// @param token ERC20 token
  /// @param amountLocal Amount denominated in terms of the ERC20 token
  /// @return uint Amount in USD
  function localToUSD(
                      IERC20 token,
                      uint amountLocal
                      ) external view returns(uint){
    return _qPriceOracle.localToUSD(token, amountLocal);
  }

  /// @notice Converts any value in USD into its value in local using oracle feed price
  /// @param token ERC20 token
  /// @param valueUSD Amount in USD
  /// @return uint Amount denominated in terms of the ERC20 token
  function USDToLocal(
                      IERC20 token,
                      uint valueUSD
                      ) external view returns(uint){
    return _qPriceOracle.USDToLocal(token, valueUSD);
  }
  
  /** INTERNAL FUNCTIONS **/

  /// @notice Return what the collateral ratio for an account would be
  /// with a hypothetical collateral withdraw and/or token borrow.
  /// The collateral ratio is calculated as:
  /// (`virtualCollateralValue` / `virtualBorrowValue`)
  /// If the returned value falls below 1e8, the account can be liquidated
  /// @param account User account
  /// @param withdrawToken Currency of hypothetical withdraw
  /// @param withdrawAmount Amount of hypothetical withdraw in local currency
  /// @param borrowMarket Market of hypothetical borrow
  /// @param borrowAmount Amount of hypothetical borrow in local ccy
  /// @return uint Hypothetical collateral ratio
  function _getHypotheticalCollateralRatio(
                                           address account,
                                           IERC20 withdrawToken,
                                           uint withdrawAmount,
                                           IFixedRateMarket borrowMarket,
                                           uint borrowAmount
                                           ) internal view returns(uint){
    
    // The numerator is the weighted hypothetical collateral value
    uint num = _getHypotheticalCollateralValue(
                                               account,
                                               withdrawToken,
                                               withdrawAmount,
                                               true
                                               );

    // The denominator is the weighted hypothetical borrow value
    uint denom = _getHypotheticalBorrowValue(
                                             account,
                                             borrowMarket,
                                             borrowAmount,
                                             true
                                             );

    if(denom == 0){
      // Need to handle division by zero if account has no borrows
      return _qAdmin.UINT_MAX();      
    }else{
      // Return the collateral  ratio as a value from 0-1, scaled by 1e8
      return num * _qAdmin.MANTISSA_COLLATERAL_RATIO() / denom;
    }        
  }

  /// @notice Return what the total collateral value for an account would be
  /// with a hypothetical withdraw, with an option for weighted or unweighted value
  /// @param account Account to query
  /// @param withdrawToken Currency of hypothetical withdraw
  /// @param withdrawAmount Amount of hypothetical withdraw in local currency
  /// @param applyCollateralFactor True to get the `collateralFactor` weighted value, false otherwise
  /// @return uint Total value of account in USD
  function _getHypotheticalCollateralValue(
                                           address account,
                                           IERC20 withdrawToken,
                                           uint withdrawAmount,
                                           bool applyCollateralFactor
                                           ) internal view returns(uint){
            
    uint totalValueUSD = 0;

    for(uint i=0; i<_iterableCollateralAddresses[account].length; i++){

      // Get the token address in i'th slot of `_iterableCollateralAddresses[account]`
      IERC20 token = _iterableCollateralAddresses[account][i];

      // Check if token address matches hypothetical withdraw token
      if(address(token) == address(withdrawToken)){
        // Add value to total minus the hypothetical withdraw amount
        totalValueUSD += _getHypotheticalCollateralValueByToken(
                                                                account,
                                                                token,
                                                                withdrawAmount,
                                                                applyCollateralFactor
                                                                );
      }else{
        // Add value to total with zero hypothetical withdraw amount
        totalValueUSD += _getHypotheticalCollateralValueByToken(
                                                                account,
                                                                token,
                                                                0,
                                                                applyCollateralFactor
                                                                );
      }
    }
    
    return totalValueUSD;
  }

  /// @notice Return what the collateral value by token for an account would be
  /// with a hypothetical withdraw, with an option for weighted or unweighted value
  /// @param account Account to query
  /// @param token ERC20 token
  /// @param withdrawAmount Amount of hypothetical withdraw in local currency
  /// @param applyCollateralFactor True to get the `collateralFactor` weighted value, false otherwise
  /// @return uint Total value of account in USD
  function _getHypotheticalCollateralValueByToken(
                                                  address account,
                                                  IERC20 token,
                                                  uint withdrawAmount,
                                                  bool applyCollateralFactor
                                                  ) internal view returns(uint){

    require(
            withdrawAmount <= _collateralBalances[account][token],
            "QollateralManager: withdraw amount must be <= to collateral balance"
            );
    
    // Get the `Asset` associated to this token
    QTypes.Asset memory asset = _qAdmin.assets(token);

    // Value of collateral in any unsupported `Asset` is zero
    if(!asset.isEnabled){
      return 0;
    }
    
    // Get the local balance of the account for the given `token`
    uint balanceLocal = _collateralBalances[account][token];

    // Subtract any hypothetical withdraw amount. Guaranteed not to underflow
    balanceLocal -= withdrawAmount;
    
    // Convert the local balance to USD
    uint valueUSD = _qPriceOracle.localToUSD(token, balanceLocal);
    
    if(applyCollateralFactor){
      // Apply the `collateralFactor` to get the discounted value of the asset       
      valueUSD = valueUSD * asset.collateralFactor / _qAdmin.MANTISSA_FACTORS();
    }
    
    return valueUSD;
  }

  /// @notice Return what the total borrow value for an account would be
  /// with a hypothetical borrow, with an option for weighted or unweighted value  
  /// @param account Account to query
  /// @param borrowMarket Market of hypothetical borrow
  /// @param borrowAmount Amount of hypothetical borrow in local ccy
  /// @param applyMarketFactor True to get the `marketFactor` weighted value, false otherwise
  /// @return uint Borrow value of account in USD
  function _getHypotheticalBorrowValue(
                                       address account,
                                       IFixedRateMarket borrowMarket,
                                       uint borrowAmount,
                                       bool applyMarketFactor
                                       ) internal view returns(uint){
    
    uint totalValueUSD = 0;
    for(uint i=0; i<_iterableAccountMarkets[account].length; i++){
      
      // Get the market address in i'th slot of `_iterableAccountMarkets[account]`
      IFixedRateMarket market = _iterableAccountMarkets[account][i];
      
      // Check if the user is requesting to borrow more in this `Market`
      if(address(market) == address(borrowMarket)){
        // User requesting to borrow more in this `Market`, add the amount to borrows
        totalValueUSD += _getHypotheticalBorrowValueByMarket(
                                                             account,
                                                             market,
                                                             borrowAmount,
                                                             applyMarketFactor
                                                             );
      }else{
        // User not requesting to borrow more in this `Market`, just get current value
        totalValueUSD += _getHypotheticalBorrowValueByMarket(
                                                             account,
                                                             market,
                                                             0,
                                                             applyMarketFactor
                                                             );
      }
    }
    return totalValueUSD;    
  }

  /// @notice Return what the borrow value by `Market` for an account would be
  /// with a hypothetical borrow, with an option for weighted or unweighted value  
  /// @param account Account to query
  /// @param borrowMarket Market of the hypothetical borrow
  /// @param borrowAmount Amount of hypothetical borrow in local ccy
  /// @param applyMarketFactor True to get the `marketFactor` weighted value, false otherwise
  /// @return uint Borrow value of account in USD (6 decimal places)
  function _getHypotheticalBorrowValueByMarket(
                                               address account,
                                               IFixedRateMarket borrowMarket,
                                               uint borrowAmount,
                                               bool applyMarketFactor
                                               ) internal view returns(uint){
    
    // Total `borrowsLocal` should be current borrow plus `borrowAmount`
    uint borrowsLocal = borrowMarket.accountBorrows(account) + borrowAmount;

    // Total `lendsLocal` is just the user's balance of qTokens
    uint lendsLocal = borrowMarket.balanceOf(account);
    if(lendsLocal >= borrowsLocal){
      // Default to zero if lends greater than borrows
      return 0;
    }else{
      
      // Get the net amount being borrowed in local
      // Guaranteed not to underflow from the above check
      uint borrowValueLocal = borrowsLocal - lendsLocal;     

      // Convert from local value to value in USD
      IERC20 token = borrowMarket.underlyingToken();
      QTypes.Asset memory asset = _qAdmin.assets(token);
      uint borrowValueUSD = _qPriceOracle.localToUSD(token, borrowValueLocal);

      if(applyMarketFactor){
        // Apply the `marketFactor` to get the risk premium value of the borrow
        borrowValueUSD = borrowValueUSD * _qAdmin.MANTISSA_FACTORS() / asset.marketFactor;
      }
      
      return borrowValueUSD;
    }
  }

  /// @notice Users call this to deposit collateral to fund their borrows
  /// @param account Address of user
  /// @param token ERC20 token
  /// @param amount Amount to deposit (in local ccy)
  /// @return uint New collateral balance
  function _depositCollateral(address account, IERC20 token, uint amount) internal returns(uint) {
    
    // Transfer the collateral from the account to this contract
    uint balanceBefore = token.balanceOf(address(this));
    token.safeTransferFrom(account, address(this), amount);
    uint balanceAfter = token.balanceOf(address(this));

    // Get more accurate amount of user deposit
    uint actualDeposit = balanceAfter - balanceBefore;    
    
    // Update internal account collateral balance mappings
    _addCollateral(account, token, actualDeposit);
        
    // Return the account's updated collateral balance for this token
    return _collateralBalances[account][token];
  }

  /// @notice Users call this to deposit collateral to fund their borrows, where their
  /// collateral is automatically wrapped into MTokens for convenience so users can
  /// automatically earn interest on their collateral.
  /// @param account Address of the user
  /// @param underlying Underlying ERC20 token
  /// @param amount Amount to deposit (in underlying local currency)
  /// @return uint New collateral balance (in MToken balance)
  function _depositCollateralWithMTokenWrap(
                                            address account,
                                            IERC20 underlying,
                                            uint amount
                                            ) internal returns(uint) {

    // Get the address of the corresponding MToken
    address mTokenAddress = _qAdmin.underlyingToMToken(underlying);
    
    // Check that the MToken asset has been enabled as collateral
    require(mTokenAddress != address(0), "QollateralManager: MToken wrap not supported");
    
    // Transfer the underlying collateral from the account to this contract
    uint balanceBeforeUnderlying = underlying.balanceOf(address(this));
    underlying.safeTransferFrom(account, address(this), amount);
    uint balanceAfterUnderlying = underlying.balanceOf(address(this));
    
    // Get accurate amount of user deposit
    uint actualDepositUnderlying = balanceAfterUnderlying - balanceBeforeUnderlying;

    // Make underlying token approval
    // NOTE: This "approve" call should be safe as it only approves the bare
    // minimum transferred, but in general be careful of attacks here. We are
    // relying on the above "require" check that `mTokenAddress` is a safe
    // address, so we should make sure that only admin is able to add
    // `mTokenAddress` as a whitelisted address or else an attacker can
    // potentially drain funds
    underlying.approve(mTokenAddress, actualDepositUnderlying);
    
    if(address(underlying) == _NATIVE_TOKEN_ADDRESS) {
      // Hardcode special logic for native token ERC20
      // Moonwell uses the Compound-style transferring of  native token
      // so we must follow a different interface
      MGlimmerInterface mToken = MGlimmerInterface(mTokenAddress);

      // Forward user collateral to MToken
      uint balanceBeforeMToken = mToken.balanceOf(address(this));
      mToken.mint{value: actualDepositUnderlying}();
      uint balanceAfterMToken = mToken.balanceOf(address(this));

      // Get accurate amount of mtokens minted
      uint actualDepositMToken = balanceAfterMToken - balanceBeforeMToken;

      // Update internal account collateral balance mappings
      _addCollateral(account, mToken, actualDepositMToken);

      return _collateralBalances[account][mToken];
      
    } else {
      // Generic logic for all other ERC20 tokens using
      // ERC20 transfer function
      MErc20Interface mToken = MErc20Interface(mTokenAddress);

      // Forward user collateral to MToken
      uint balanceBeforeMToken = mToken.balanceOf(address(this));
      mToken.mint(actualDepositUnderlying);
      uint balanceAfterMToken = mToken.balanceOf(address(this));

      // Get accurate amount of mTokens minted
      uint actualDepositMToken = balanceAfterMToken - balanceBeforeMToken;

      // Update internal account collateral balance mappings
      _addCollateral(account, mToken, actualDepositMToken);

      return _collateralBalances[account][mToken];      
    }
    
  }
  
  /// @notice Users call this to withdraw collateral
  /// @param account Address of user
  /// @param token ERC20 token
  /// @param amount Amount to withdraw (in local ccy)
  /// @return uint New collateral balance 
  function _withdrawCollateral(address account, IERC20 token, uint amount) internal returns(uint) {

    // Get the hypothetical collateral ratio after withdrawal
    uint collateralRatio_ = _getHypotheticalCollateralRatio(
                                                            account,
                                                            token,
                                                            amount,
                                                            IFixedRateMarket(NULL),
                                                            0
                                                            );
    
    // Amount must be positive
    require(amount > 0, "QollateralManager: amount must be positive");

    // Check that the `collateralRatio` after withdrawal is still healthy.
    // User is only allowed to withdraw up to `_initCollateralRatio`, not
    // `_minCollateralRatio`, for their own protection against instant liquidations.
    require(
            collateralRatio_ >= _qAdmin.initCollateralRatio(),
            "QollateralManager: withdraw amount will cause undercollateralized account"
            );

    // Update internal account collateral balance mappings
    _subtractCollateral(account, token, amount);

    // Send collateral from the protocol to the account
    token.safeTransfer(account, amount);

    // Emit the event
    emit WithdrawCollateral(account, address(token), amount);

    // Return the account's updated collateral balance for this token
    return _collateralBalances[account][token];
  }

  /// @notice Users call this to withdraw mToken collateral, where their
  /// collateral is automatically unwrapped into underlying tokens for
  /// convenience.
  /// @param account Address of the user
  /// @param mTokenAddress Yield-bearing token address
  /// @param amount Amount to withdraw (in mToken local currency)
  /// @return uint New collateral balance (in MToken balance)
  function _withdrawCollateralWithMTokenUnwrap(
                                               address account,
                                               address mTokenAddress,
                                               uint amount
                                               ) internal returns(uint) {

    // Get the corresponding underlying
    address underlyingAddress  = _qAdmin.assets(IERC20(mTokenAddress)).underlying;
    IERC20 underlying = IERC20(underlyingAddress);
    
    if(underlyingAddress == _NATIVE_TOKEN_ADDRESS) {
      // Hardcode special logic for native token ERC20
      // Moonwell uses the Compound-style transferring of native token
      // so we must follow a different interface
      MGlimmerInterface mToken = MGlimmerInterface(mTokenAddress);

      // Redeem mTokens for underlying and return it to user
      uint balanceBeforeUnderlying = underlying.balanceOf(address(this));
      mToken.redeem(amount);
      uint balanceAfterUnderlying = underlying.balanceOf(address(this));
      
      // Get accurate amount of underlying redeemed
      uint actualAmountUnderlying = balanceAfterUnderlying - balanceBeforeUnderlying;

      // Update internal account collateral balance mappings
      _subtractCollateral(account, mToken, amount);

      // Send unwrapped underlying collateral from the protocol to the account
      underlying.transfer(account, actualAmountUnderlying);

      // Emit the event
      emit WithdrawCollateral(account, mTokenAddress, amount);
      
    } else {
      // Generic logic for all other ERC20 tokens using
      // ERC20 transfer function
      MErc20Interface mToken = MErc20Interface(mTokenAddress);

      // Redeem mTokens for underlying and return it to user
      uint balanceBeforeUnderlying = underlying.balanceOf(address(this));
      mToken.redeem(amount);
      uint balanceAfterUnderlying = underlying.balanceOf(address(this));
      
      // Get accurate amount of underlying redeemed
      uint actualAmountUnderlying = balanceAfterUnderlying - balanceBeforeUnderlying;

      // Update internal account collateral balance mappings
      _subtractCollateral(account, mToken, amount);

      // Send unwrapped underlying collateral from the protocol to the account
      underlying.transfer(account, actualAmountUnderlying);

      // Emit the event
      emit WithdrawCollateral(account, mTokenAddress, amount);
    }
    
    return _collateralBalances[account][IERC20(mTokenAddress)];
  }

  
  /// @notice Add to internal account collateral balance and related mappings
  /// @param account User account
  /// @param token Currency which the collateral will be denominated in
  /// @param amount Amount to add
  function _addCollateral(address account, IERC20 token, uint amount) internal{

    // Get the associated `Asset` to the token address
    QTypes.Asset memory asset = _qAdmin.assets(token);

    // Only enabled assets are supported as collateral
    require(asset.isEnabled, "QollateralManager: asset not supported");

    // Record that sender now has collateral deposited in this currency
    // This should only be updated once per account when initially depositing
    // collateral in a new currency to ensure that the `_accountCollateral` mapping
    // remains unique
    if(!_accountCollateral[account][token]){
      _iterableCollateralAddresses[account].push(token);
      _accountCollateral[account][token] = true;
    }

    // Record the increase in collateral balance for the account
    _collateralBalances[account][token] += amount;

    // Emit the event
    emit DepositCollateral(account, address(token), amount);
  }

  /// @notice Subtract from internal account collateral balance and related mappings
  /// @param account User account
  /// @param token Currency which the collateral will be denominated in
  /// @param amount Amount to subtract
  function _subtractCollateral(address account, IERC20 token, uint amount) internal{

    // Check that user has enough collateral to be subtracted
    require(
            _collateralBalances[account][token] >= amount,
            "QollateralManager: not enough collateral"
            );
    
    // Record the decrease in collateral balance for the account
    _collateralBalances[account][token] -= amount;
  }

}

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

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.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]
 * ```
 * 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. Equivalent to `reinitializer(1)`.
     */
    modifier initializer() {
        bool isTopLevelCall = _setInitializedVersion(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.
     *
     * `initializer` is equivalent to `reinitializer(1)`, so 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.
     *
     * 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.
     */
    modifier reinitializer(uint8 version) {
        bool isTopLevelCall = _setInitializedVersion(version);
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _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.
     */
    function _disableInitializers() internal virtual {
        _setInitializedVersion(type(uint8).max);
    }

    function _setInitializedVersion(uint8 version) private returns (bool) {
        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
        // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level
        // of initializers, because in other contexts the contract may have been reentered.
        if (_initializing) {
            require(
                version == 1 && !AddressUpgradeable.isContract(address(this)),
                "Initializable: contract is already initialized"
            );
            return false;
        } else {
            require(_initialized < version, "Initializable: contract is already initialized");
            _initialized = version;
            return true;
        }
    }
}

File 3 of 15 : MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a / b + (a % b == 0 ? 0 : 1);
    }
}

File 4 of 15 : IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Upgradeable {
    /**
     * @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 5 of 15 : SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
    using AddressUpgradeable for address;

    function safeTransfer(
        IERC20Upgradeable token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20Upgradeable 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(
        IERC20Upgradeable 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));
    }

    function safeIncreaseAllowance(
        IERC20Upgradeable token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20Upgradeable token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @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(IERC20Upgradeable 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");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 6 of 15 : IFixedRateMarket.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IERC20MetadataUpgradeable as IERC20Metadata} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";

interface IFixedRateMarket is IERC20, IERC20Metadata {

  /// @notice Emitted when a borrower repays borrow.
  /// Boolean flag `withQTokens`= true if repaid via qTokens, false otherwise.
  event RepayBorrow(address indexed borrower, uint amount, bool withQTokens);

  /// @notice Emitted when a borrower is liquidated
  event LiquidateBorrow(
    address indexed borrower,
    address indexed liquidator,
    uint amount,
    address collateralTokenAddress,
    uint reward
  );

  /// @notice Emitted when a borrower and lender are matched for a fixed rate loan
  event FixedRateLoan(
    bytes32 indexed quoteId,
    address indexed borrower,
    address indexed lender,
    uint amountPV,
    uint amountFV);

  /// @notice Emitted when an account cancels their Quote
  event CancelQuote(address indexed account, uint nonce);

  /// @notice Emitted when an account redeems their qTokens
  event RedeemQTokens(address indexed account, uint amount);
    
  /** USER INTERFACE **/

  /// @notice Execute against Quote as a borrower.
  /// @param amountPV Amount that the borrower wants to execute as PV
  /// @param lender Account of the lender
  /// @param quoteType *Lender's* type preference, 0 for PV+APR, 1 for FV+APR
  /// @param quoteExpiryTime Timestamp after which the quote is no longer valid
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param cashflow Can be PV or FV depending on `quoteType`
  /// @param nonce For uniqueness of signature
  /// @param signature signed hash of the Quote message
  /// @return uint, uint Loan amount (`amountPV`) and repayment amount (`amountFV`)
  function borrow(
                  uint amountPV,
                  address lender,
                  uint8 quoteType,
                  uint64 quoteExpiryTime,
                  uint64 APR,
                  uint cashflow,
                  uint nonce,
                  bytes memory signature
                  ) external returns(uint, uint);

  /// @notice Execute against Quote as a lender.
  /// @param amountPV Amount that the lender wants to execute as PV
  /// @param borrower Account of the borrower
  /// @param quoteType *Borrower's* type preference, 0 for PV+APR, 1 for FV+APR
  /// @param quoteExpiryTime Timestamp after which the quote is no longer valid
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param cashflow Can be PV or FV depending on `quoteType`
  /// @param nonce For uniqueness of signature
  /// @param signature signed hash of the Quote message
  /// @return uint, uint Loan amount (`amountPV`) and repayment amount (`amountFV`)
  function lend(
                uint amountPV,
                address borrower,
                uint8 quoteType,
                uint64 quoteExpiryTime,
                uint64 APR,
                uint cashflow,
                uint nonce,
                bytes memory signature
                ) external returns(uint, uint);
  
  /// @notice Borrower will make repayments to the smart contract, which
  /// holds the value in escrow until maturity to release to lenders.
  /// @param amount Amount to repay
  /// @return uint Remaining account borrow amount
  function repayBorrow(uint amount) external returns(uint);

  /// @notice By setting the nonce in `_voidNonces` to true, this is equivalent to
  /// invalidating the Quote (i.e. cancelling the quote)
  /// param nonce Nonce of the Quote to be cancelled
  function cancelQuote(uint nonce) external;

  /// @notice This function allows net lenders to redeem qTokens for the
  /// underlying token. Redemptions may only be permitted after loan maturity
  /// plus `_maturityGracePeriod`. The public interface redeems the entire qToken
  /// balance.
  /// @param amount Amount of qTokens to redeem
  function redeemQTokens(uint amount) external;
  
  /// @notice If an account is in danger of being undercollateralized (i.e.
  /// liquidityRatio < 1.0), any user may liquidate that account by paying
  /// back the loan on behalf of the account. In return, the liquidator receives
  /// collateral belonging to the account equal in value to the repayment amount
  /// in USD plus the liquidation incentive amount as a bonus.
  /// @param borrower Address of account that is undercollateralized
  /// @param amount Amount to repay on behalf of account
  /// @param collateralToken Liquidator's choice of which currency to be paid in
  function liquidateBorrow(
                           address borrower,
                           uint amount,
                           IERC20 collateralToken
                           ) external;
  
  /** VIEW FUNCTIONS **/
  
  /// @notice Get the address of the `QollateralManager`
  /// @return address
  function qollateralManager() external view returns(address);

  /// @notice Get the address of the ERC20 token which the loan will be denominated
  /// @return IERC20
  function underlyingToken() external view returns(IERC20);

  /// @notice Get the UNIX timestamp (in seconds) when the market matures
  /// @return uint
  function maturity() external view returns(uint);

  /// @notice Get the minimum quote size for this market
  /// @return uint Minimum quote size, in PV terms, local currency
  function minQuoteSize() external view returns(uint);
  
  /// @notice True if a nonce for a Quote is voided, false otherwise.
  /// Used for checking if a Quote is a duplicated.
  /// @param account Account to query
  /// @param nonce Nonce to query
  /// @return bool True if used, false otherwise
  function isNonceVoid(address account, uint nonce) external view returns(bool);

  /// @notice Get the total balance of borrows by user
  /// @param account Account to query
  /// @return uint Borrows
  function accountBorrows(address account) external view returns(uint);

  /// @notice Get the current total partial fill for a Quote
  /// @param quoteId ID of the Quote - this is the keccak256 hash of the signature
  /// @return uint Partial fill
  function quoteFill(bytes32 quoteId) external view returns(uint);

  
}

File 7 of 15 : IQAdmin.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IAccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol";
import "./IFixedRateMarket.sol";
import "../libraries/QTypes.sol";

interface IQAdmin is IAccessControlUpgradeable {

  /// @notice Emitted when a new FixedRateMarket is deployed
  event CreateFixedRateMarket(address indexed marketAddress, address indexed tokenAddress, uint maturity);
  
  /// @notice Emitted when a new `Asset` is added
  event AddAsset(
                 address indexed tokenAddress,
                 bool isYieldBearing,
                 address oracleFeed,
                 uint collateralFactor,
                 uint marketFactor);

  /// @notice Emitted when setting `collateralFactor`
  event SetCollateralFactor(address indexed tokenAddress, uint oldValue, uint newValue);

  /// @notice Emitted when setting `marketFactor`
  event SetMarketFactor(address indexed tokenAddress, uint oldValue, uint newValue);

  /// @notice Emitted when setting `minQuoteSize`
  event SetMinQuoteSize(address indexed tokenAddress, uint oldValue, uint newValue);
  
  /// @notice Emitted when `_initCollateralRatio` gets updated
  event SetInitCollateralRatio(uint oldValue, uint newValue);

  /// @notice Emitted when `_closeFactor` gets updated
  event SetCloseFactor(uint oldValue, uint newValue);

  /// @notice Emitted when `_maturityGracePeriod` gets updated
  event SetMaturityGracePeriod(uint oldValue, uint newValue);
  
  /// @notice Emitted when `_liquidationIncentive` gets updated
  event SetLiquidationIncentive(uint oldValue, uint newValue);

  /// @notice Emitted when `_protocolFee` gets updated
  event SetProtocolFee(uint oldValue, uint newValue);
  
  /** ADMIN FUNCTIONS **/

  /// @notice Call upon initialization after deploying `QollateralManager` contract
  /// @param qollateralManagerAddress Address of `QollateralManager` deployment
  function _initializeQollateralManager(address qollateralManagerAddress) external;
  
  /// @notice Admin function for adding new Assets. An Asset must be added before it
  /// can be used as collateral or borrowed. Note: We can create functionality for
  /// allowing borrows of a token but not using it as collateral by setting
  /// `collateralFactor` to zero.
  /// @param token ERC20 token corresponding to the Asset
  /// @param isYieldBearing True if token bears interest (eg aToken, cToken, mToken, etc)
  /// @param underlying Address of the underlying token
  /// @param oracleFeed Chainlink price feed address
  /// @param collateralFactor 0.0 to 1.0 (scaled to 1e8) for discounting risky assets
  /// @param marketFactor 0.0 to 1.0 (scaled to 1e8) for premium on risky borrows
  function _addAsset(
                     IERC20 token,
                     bool isYieldBearing,
                     address underlying,
                     address oracleFeed,
                     uint collateralFactor,
                     uint marketFactor
                     ) external;

  /// @notice Adds a new `FixedRateMarket` contract into the internal mapping of
  /// whitelisted market addresses
  /// @param market New `FixedRateMarket` contract
  function _addFixedRateMarket(IFixedRateMarket market) external;
  
  /// @notice Update the `collateralFactor` for a given `Asset`
  /// @param token ERC20 token corresponding to the Asset
  /// @param collateralFactor 0.0 to 1.0 (scaled to 1e8) for discounting risky assets
  function _setCollateralFactor(IERC20 token, uint collateralFactor) external;

  /// @notice Update the `marketFactor` for a given `Asset`
  /// @param token Address of the token corresponding to the Asset
  /// @param marketFactor 0.0 to 1.0 (scaled to 1e8) for discounting risky assets
  function _setMarketFactor(IERC20 token, uint marketFactor) external;

  /// @notice Set the minimum quote size for a particular `FixedRateMarket`
  /// @param market Address of the `FixedRateMarket` contract
  /// @param minQuoteSize_ Size in PV terms, local currency
  function _setMinQuoteSize(IFixedRateMarket market, uint minQuoteSize_) external;
  
  /// @notice Set the global initial collateral ratio
  /// @param initCollateralRatio_ New collateral ratio value
  function _setInitCollateralRatio(uint initCollateralRatio_) external;

  /// @notice Set the global close factor
  /// @param closeFactor_ New close factor value
  function _setCloseFactor(uint closeFactor_) external;

  function _setMaturityGracePeriod(uint maturityGracePeriod_) external;
  
  /// @notice Set the global liquidation incetive
  /// @param liquidationIncentive_ New liquidation incentive value
  function _setLiquidationIncentive(uint liquidationIncentive_) external;

  /// @notice Set the global annualized protocol fees in basis points
  /// @param protocolFee_ New protocol fee value (scaled to 1e4)
  function _setProtocolFee(uint protocolFee_) external;

  /** VIEW FUNCTIONS **/

  function ADMIN_ROLE() external view returns(bytes32);

  function MARKET_ROLE() external view returns(bytes32);
  
  /// @notice Get the address of the `QollateralManager` contract
  function qollateralManager() external view returns(address);
  
  /// @notice Gets the `Asset` mapped to the address of a ERC20 token
  /// @param token ERC20 token
  /// @return QTypes.Asset Associated `Asset`
  function assets(IERC20 token) external view returns(QTypes.Asset memory);

  /// @notice Get the MToken market corresponding to any underlying ERC20
  /// tokenAddress => mTokenAddress
  function underlyingToMToken(IERC20 token) external view returns(address);
  
  /// @notice Gets the address of the `FixedRateMarket` contract
  /// @param token ERC20 token
  /// @param maturity UNIX timestamp of the maturity date
  /// @return IFixedRateMarket Address of `FixedRateMarket` contract
  function fixedRateMarkets(IERC20 token, uint maturity) external view returns(IFixedRateMarket);

  /// @notice Check whether an address is a valid FixedRateMarket address.
  /// Can be used for checks for inter-contract admin/restricted function call.
  /// @param market `FixedRateMarket` contract
  /// @return bool True if valid false otherwise
  function isMarketEnabled(IFixedRateMarket market) external view returns(bool);

  function minQuoteSize(IFixedRateMarket market) external view returns(uint);
  
  function minCollateralRatio() external view returns(uint);

  function initCollateralRatio() external view returns(uint);

  function closeFactor() external view returns(uint);

  function maturityGracePeriod() external view returns(uint);
  
  function liquidationIncentive() external view returns(uint);

  function protocolFee() external view returns(uint);
  
  /// @notice 2**256 - 1
  function UINT_MAX() external pure returns(uint);
  
  /// @notice Generic mantissa corresponding to ETH decimals
  function MANTISSA_DEFAULT() external pure returns(uint);

  /// @notice Mantissa for stablecoins
  function MANTISSA_STABLECOIN() external pure returns(uint);
  
  /// @notice Mantissa for collateral ratio
  function MANTISSA_COLLATERAL_RATIO() external pure returns(uint);

  /// @notice `assetFactor` and `marketFactor` have up to 8 decimal places precision
  function MANTISSA_FACTORS() external pure returns(uint);

  /// @notice Basis points have 4 decimal place precision
  function MANTISSA_BPS() external pure returns(uint);

  /// @notice `collateralFactor` cannot be above 1.0
  function MAX_COLLATERAL_FACTOR() external pure returns(uint);

  /// @notice `marketFactor` cannot be above 1.0
  function MAX_MARKET_FACTOR() external pure returns(uint);
  
}

File 8 of 15 : IQPriceOracle.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";

interface IQPriceOracle {
  
  /// @notice Converts any local value into its value in USD using oracle feed price
  /// @param token ERC20 token
  /// @param amountLocal Amount denominated in terms of the ERC20 token
  /// @return uint Amount in USD
  function localToUSD(IERC20 token, uint amountLocal) external view returns(uint);

  /// @notice Converts any value in USD into its value in local using oracle feed price
  /// @param token ERC20 token
  /// @param valueUSD Amount in USD
  /// @return uint Amount denominated in terms of the ERC20 token
  function USDToLocal(IERC20 token, uint valueUSD) external view returns(uint);

  /// @notice Convenience function for getting price feed from Chainlink oracle
  /// @param oracleFeed Address of the chainlink oracle feed
  /// @return answer uint256, decimals uint8
  function priceFeed(address oracleFeed) external view returns(uint256, uint8);  
}

File 9 of 15 : IQollateralManager.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./IFixedRateMarket.sol";

interface IQollateralManager {

  /// @notice Emitted when an account deposits collateral into the contract
  event DepositCollateral(address indexed account, address tokenAddress, uint amount);

  /// @notice Emitted when an account withdraws collateral from the contract
  event WithdrawCollateral(address indexed account, address tokenAddress, uint amount);
  
  /// @notice Emitted when an account first interacts with the `Market`
  event AddAccountMarket(address indexed account, address indexed market);

  /// @notice Emitted when collateral is transferred from one account to another
  event TransferCollateral(address indexed tokenAddress, address indexed from, address indexed to, uint amount);
  
  /// @notice Constructor for upgradeable contracts
  /// @param qAdminAddress_ Address of the `QAdmin` contract
  /// @param qPriceOracleAddress_ Address of the `QPriceOracle` contract
  function initialize(address qAdminAddress_, address qPriceOracleAddress_) external;

 /** ADMIN/RESTRICTED FUNCTIONS **/

  /// @notice Record when an account has either borrowed or lent into a
  /// `FixedRateMarket`. This is necessary because we need to iterate
  /// across all markets that an account has borrowed/lent to to calculate their
  /// `borrowValue`. Only the `FixedRateMarket` contract itself may call
  /// this function
  /// @param account User account
  /// @param market Address of the `FixedRateMarket` market
  function _addAccountMarket(address account, IFixedRateMarket market) external;

  /// @notice Transfer collateral balances from one account to another. Only
  /// `FixedRateMarket` contracts can call this restricted function. This is used
  /// for when a liquidator liquidates an account.
  /// @param token ERC20 token
  /// @param from Sender address
  /// @param to Recipient address
  /// @param amount Amount to transfer
  function _transferCollateral(IERC20 token, address from, address to, uint amount) external;
  
  /** USER INTERFACE **/
  
  /// @notice Users call this to deposit collateral to fund their borrows
  /// @param token ERC20 token
  /// @param amount Amount to deposit (in local ccy)
  /// @return uint New collateral balance
  function depositCollateral(IERC20 token, uint amount) external returns(uint);

  /// @notice Users call this to deposit collateral to fund their borrows, where their
  /// collateral is automatically wrapped into MTokens for convenience so users can
  /// automatically earn interest on their collateral.
  /// @param underlying Underlying ERC20 token
  /// @param amount Amount to deposit (in underlying local currency)
  /// @return uint New collateral balance (in MToken balance)
  function depositCollateralWithMTokenWrap(IERC20 underlying, uint amount) external returns(uint);
  
  /// @notice Users call this to withdraw collateral
  /// @param token ERC20 token
  /// @param amount Amount to withdraw (in local ccy)
  /// @return uint New collateral balance
  function withdrawCollateral(IERC20 token, uint amount) external returns(uint);

  /// @notice Users call this to withdraw mToken collateral, where their
  /// collateral is automatically unwrapped into underlying tokens for
  /// convenience.
  /// @param mTokenAddress Yield-bearing token address
  /// @param amount Amount to withdraw (in mToken local currency)
  /// @return uint New collateral balance (in MToken balance)
  function withdrawCollateralWithMTokenUnwrap(
                                              address mTokenAddress,
                                              uint amount
                                              ) external returns(uint);
  
  /** VIEW FUNCTIONS **/

  /// @notice Get the address of the `QAdmin` contract
  /// @return address Address of `QAdmin` contract
  function qAdmin() external view returns(address);

  /// @notice Return what the collateral ratio for an account would be
  /// with a hypothetical collateral withdraw and/or token borrow.
  /// The collateral ratio is calculated as:
  /// (`virtualCollateralValue` / `virtualBorrowValue`)
  /// If the returned value falls below 1e8, the account can be liquidated
  /// @param account User account
  /// @param withdrawToken Currency of hypothetical withdraw
  /// @param withdrawAmount Amount of hypothetical withdraw in local currency
  /// @param borrowMarket Market of hypothetical borrow
  /// @param borrowAmount Amount of hypothetical borrow in local ccy
  /// @return uint Hypothetical collateral ratio
  function hypotheticalCollateralRatio(
                                       address account,
                                       IERC20 withdrawToken,
                                       uint withdrawAmount,
                                       IFixedRateMarket borrowMarket,
                                       uint borrowAmount
                                       ) external view returns(uint);

  /// @notice Return the current collateral ratio for an account.
  /// The collateral ratio is calculated as:
  /// (`virtualCollateralValue` / `virtualBorrowValue`)
  /// If the returned value falls below 1e8, the account can be liquidated
  /// @param account User account
  /// @return uint Collateral ratio
  function collateralRatio(address account) external view returns(uint);
  
  /// @notice Get the `collateralFactor` weighted value (in USD) of all the
  /// collateral deposited for an account
  /// @param account Account to query
  /// @return uint Total value of account in USD
  function virtualCollateralValue(address account) external view returns(uint);
  
  /// @notice Get the `collateralFactor` weighted value (in USD) for the tokens
  /// deposited for an account
  /// @param account Account to query
  /// @param token ERC20 token
  /// @return uint Value of token collateral of account in USD
  function virtualCollateralValueByToken(
                                         address account,
                                         IERC20 token
                                         ) external view returns(uint);

  /// @notice Get the `marketFactor` weighted net borrows (i.e. borrows - lends)
  /// in USD summed across all `Market`s participated in by the user
  /// @param account Account to query
  /// @return uint Borrow value of account in USD
  function virtualBorrowValue(address account) external view returns(uint);
  
  /// @notice Get the `marketFactor` weighted net borrows (i.e. borrows - lends)
  /// in USD for a particular `Market`
  /// @param account Account to query
  /// @param market `FixedRateMarket` contract
  /// @return uint Borrow value of account in USD
  function virtualBorrowValueByMarket(
                                      address account,
                                      IFixedRateMarket market
                                      ) external view returns(uint);
  
  /// @notice Get the unweighted value (in USD) of all the collateral deposited
  /// for an account
  /// @param account Account to query
  /// @return uint Total value of account in USD
  function realCollateralValue(address account) external view returns(uint);
  
  /// @notice Get the unweighted value (in USD) of the tokens deposited
  /// for an account
  /// @param account Account to query
  /// @param token ERC20 token
  /// @return uint Value of token collateral of account in USD
  function realCollateralValueByToken(
                                      address account,
                                      IERC20 token
                                      ) external view returns(uint);
  
  /// @notice Get the unweighted current net value borrowed (i.e. borrows - lends)
  /// in USD summed across all `Market`s participated in by the user
  /// @param account Account to query
  /// @return uint Borrow value of account in USD
  function realBorrowValue(address account) external view returns(uint);

  /// @notice Get the unweighted current net value borrowed (i.e. borrows - lends)
  /// in USD for a particular `Market`
  /// @param account Account to query
  /// @param market `FixedRateMarket` contract
  /// @return uint Borrow value of account in USD
  function realBorrowValueByMarket(
                                   address account,
                                   IFixedRateMarket market
                                   ) external view returns(uint);

  /// @notice Get the minimum collateral ratio. Scaled by 1e8.
  /// @return uint Minimum collateral ratio
  function minCollateralRatio() external view returns(uint);
  
  /// @notice Get the initial collateral ratio. Scaled by 1e8
  /// @return uint Initial collateral ratio
  function initCollateralRatio() external view returns(uint);
  
  /// @notice Get the close factor. Scaled by 1e8
  /// @return uint Close factor
  function closeFactor() external view returns(uint);

  /// @notice Get the liquidation incentive. Scaled by 1e8
  /// @return uint Liquidation incentive
  function liquidationIncentive() external view returns(uint);
  
  /// @notice Use this for quick lookups of collateral balances by asset
  /// @param account User account
  /// @param token ERC20 token
  /// @return uint Balance in local
  function collateralBalance(address account, IERC20 token) external view returns(uint);

  /// @notice Get iterable list of collateral addresses which an account has nonzero balance.
  /// @param account User account
  /// @return address[] Iterable list of ERC20 token addresses
  function iterableCollateralAddresses(address account) external view returns(IERC20[] memory);

  /// @notice Quick lookup of whether an account has a particular collateral
  /// @param account User account
  /// @param token ERC20 token addresses
  /// @return bool True if account has collateralized with given ERC20 token, false otherwise
  function accountCollateral(address account, IERC20 token) external view returns(bool);

  /// @notice Get iterable list of all Markets which an account has participated
  /// @param account User account
  /// @return address[] Iterable list of `FixedRateLoanMarket` contract addresses
  function iterableAccountMarkets(address account) external view returns(IFixedRateMarket[] memory);
                                                                         
  /// @notice Quick lookup of whether an account has participated in a Market
  /// @param account User account
  /// @param market`FixedRateLoanMarket` contract
  /// @return bool True if participated, false otherwise
  function accountMarkets(address account, IFixedRateMarket market) external view returns(bool);
                                                                       
  /// @notice Converts any local value into its value in USD using oracle feed price
  /// @param token ERC20 token
  /// @param amountLocal Amount denominated in terms of the ERC20 token
  /// @return uint Amount in USD
  function localToUSD(IERC20 token, uint amountLocal) external view returns(uint);

  /// @notice Converts any value in USD into its value in local using oracle feed price
  /// @param token ERC20 token
  /// @param valueUSD Amount in USD
  /// @return uint Amount denominated in terms of the ERC20 token
  function USDToLocal(IERC20 token, uint valueUSD) external view returns(uint);
}

File 10 of 15 : MTokenInterfaces.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./InterestRateModel.sol";

interface MTokenInterface is IERC20 {
 
  function accrualBlockTimestamp() external view returns(uint);
  function exchangeRateStored() external view returns(uint);
  function getCash() external view returns(uint);
  function totalBorrows() external view returns(uint);
  function totalReserves() external view returns(uint);
  function reserveFactorMantissa() external view returns(uint);
  function interestRateModel() external view returns(InterestRateModel);
  
}

interface MErc20Interface is MTokenInterface {

  function mint(uint mintAmount) external returns (uint);
  function redeem(uint redeemTokens) external returns (uint);
  function redeemUnderlying(uint redeemAmount) external returns (uint);
  function borrow(uint borrowAmount) external returns (uint);
  function repayBorrow(uint repayAmount) external returns (uint);
  function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
  function liquidateBorrow(address borrower, uint repayAmount, MTokenInterface mTokenCollateral) external returns (uint);
  
}

interface MGlimmerInterface is MTokenInterface {

  function mint() external payable;
  function redeem(uint redeemTokens) external returns (uint);
  function redeemUnderlying(uint redeemAmount) external returns (uint);
  function borrow(uint borrowAmount) external returns (uint);
  function repayBorrow() external payable;
  function repayBorrowBehalf(address borrower) external payable;
  function liquidateBorrow(address borrower, MTokenInterface mTokenCollateral) external payable;
  
}

File 11 of 15 : QTypes.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

library QTypes {

  /// @notice Contains all the details of an Asset. Assets  must be defined
  /// before they can be used as collateral.
  /// @member isEnabled True if an asset is defined, false otherwise
  /// @member isYieldBearing True if token bears interest (eg aToken, cToken, mToken, etc)
  /// @member underlying Address of the underlying token
  /// @member oracleFeed Address of the corresponding chainlink oracle feed
  /// @member collateralFactor 0.0 to 1.0 (scaled to 1e8) for discounting risky assets
  /// @member marketFactor 0.0 1.0 for premium on risky borrows
  /// @member maturities Iterable storage for all enabled maturities
  struct Asset {
    bool isEnabled;
    bool isYieldBearing;
    address underlying;
    address oracleFeed;
    uint collateralFactor;
    uint marketFactor;
    uint[] maturities;
  }

  /// @notice Contains all the fields of a published Quote
  /// @notice quoteId ID of the quote - this is the keccak256 hash of signature
  /// @param marketAddress Address of `FixedRateLoanMarket` contract
  /// @param quoter Account of the Quoter
  /// @param quoteType 0 for PV+APR, 1 for FV+APR
  /// @param side 0 if Quoter is borrowing, 1 if Quoter is lending
  /// @param quoteExpiryTime Timestamp after which the quote is no longer valid
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param cashflow Can be PV or FV depending on `quoteType`
  /// @param nonce For uniqueness of signature
  /// @param signature Signed hash of the Quote message
  struct Quote {
    bytes32 quoteId;
    address marketAddress;
    address quoter;
    uint8 quoteType;
    uint8 side;
    uint64 quoteExpiryTime; //if 0, then quote never expires
    uint64 APR;
    uint cashflow;
    uint nonce;
    bytes signature;
  }
  

}

File 12 of 15 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @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
     * ====
     *
     * [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason 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 {
            // 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

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 13 of 15 : IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

File 14 of 15 : IAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

File 15 of 15 : InterestRateModel.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

interface InterestRateModel {

  /**
   * @notice Calculates the current borrow interest rate per timestmp
   * @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 timestmp (as a percentage, and scaled by 1e18)
   */
    function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);

    /**
     * @notice Calculates the current supply interest rate per timestmp
     * @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 timestmp (as a percentage, and scaled by 1e18)
     */
    function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa)  external view returns (uint);

  
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "metadata": {
    "useLiteralContent": true
  },
  "libraries": {}
}

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"market","type":"address"}],"name":"AddAccountMarket","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"DepositCollateral","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TransferCollateral","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"WithdrawCollateral","type":"event"},{"inputs":[{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"},{"internalType":"uint256","name":"valueUSD","type":"uint256"}],"name":"USDToLocal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IFixedRateMarket","name":"market","type":"address"}],"name":"_addAccountMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"_transferCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"}],"name":"accountCollateral","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IFixedRateMarket","name":"market","type":"address"}],"name":"accountMarkets","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"closeFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"}],"name":"collateralBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"collateralRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"depositCollateral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20Upgradeable","name":"underlying","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"depositCollateralWithMTokenWrap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IERC20Upgradeable","name":"withdrawToken","type":"address"},{"internalType":"uint256","name":"withdrawAmount","type":"uint256"},{"internalType":"contract IFixedRateMarket","name":"borrowMarket","type":"address"},{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"hypotheticalCollateralRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initCollateralRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"qAdminAddress_","type":"address"},{"internalType":"address","name":"qPriceOracleAddress_","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"iterableAccountMarkets","outputs":[{"internalType":"contract IFixedRateMarket[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"iterableCollateralAddresses","outputs":[{"internalType":"contract IERC20Upgradeable[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidationIncentive","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"},{"internalType":"uint256","name":"amountLocal","type":"uint256"}],"name":"localToUSD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minCollateralRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"qAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"realBorrowValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IFixedRateMarket","name":"market","type":"address"}],"name":"realBorrowValueByMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"realCollateralValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"}],"name":"realCollateralValueByToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"virtualBorrowValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IFixedRateMarket","name":"market","type":"address"}],"name":"virtualBorrowValueByMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"virtualCollateralValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"}],"name":"virtualCollateralValueByToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawCollateral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"mTokenAddress","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawCollateralWithMTokenUnwrap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

608060405234801561001057600080fd5b50613193806100206000396000f3fe6080604052600436106101c55760003560e01c80637dee6c47116100f7578063b8f3ece111610095578063ce40130811610064578063ce40130814610549578063d820971a14610580578063e7602b9d146105a0578063f617bb84146105e657600080fd5b8063b8f3ece1146104d4578063bfeabd0d146104e9578063c4c050f614610509578063ca40742c1461052957600080fd5b80638c6090dc116100d15780638c6090dc1461045f5780638c765e941461047f5780639ec321dc14610494578063a5d5db0c146104b457600080fd5b80637dee6c471461040a5780637e26c7951461042a57806384da26661461044a57600080fd5b80633b51cf0c1161016457806363c63d371161013e57806363c63d371461038a57806365abacad146103aa5780636a6af352146103ca57806375adbdab146103ea57600080fd5b80633b51cf0c1461031b578063485cc9551461034857806352a494eb1461036a57600080fd5b80632a722581116101a05780632a72258114610272578063320cc768146102925780633416a91e146102db578063350c35e9146102fb57600080fd5b806225ce9f146101d157806305308b9f1461022f5780631de88a3d1461025257600080fd5b366101cc57005b600080fd5b3480156101dd57600080fd5b5061021a6101ec366004612c49565b6001600160a01b03918216600090815260056020908152604080832093909416825291909152205460ff1690565b60405190151581526020015b60405180910390f35b34801561023b57600080fd5b50610244610606565b604051908152602001610226565b34801561025e57600080fd5b5061024461026d366004612c82565b610692565b34801561027e57600080fd5b5061024461028d366004612c82565b6106a6565b34801561029e57600080fd5b5061021a6102ad366004612c49565b6001600160a01b03918216600090815260066020908152604080832093909416825291909152205460ff1690565b3480156102e757600080fd5b506102446102f6366004612c49565b610729565b34801561030757600080fd5b50610244610316366004612c82565b610739565b34801561032757600080fd5b5061033b610336366004612cae565b610746565b6040516102269190612ccb565b34801561035457600080fd5b50610368610363366004612c49565b6107bc565b005b34801561037657600080fd5b50610368610385366004612d18565b61086c565b34801561039657600080fd5b506102446103a5366004612c49565b610abf565b3480156103b657600080fd5b506102446103c5366004612cae565b610ace565b3480156103d657600080fd5b506102446103e5366004612cae565b610ae4565b3480156103f657600080fd5b50610244610405366004612c49565b610af4565b34801561041657600080fd5b50610244610425366004612c82565b610b04565b34801561043657600080fd5b50610244610445366004612c49565b610b37565b34801561045657600080fd5b50610244610b46565b34801561046b57600080fd5b5061024461047a366004612d69565b610b95565b34801561048b57600080fd5b50610244610bb0565b3480156104a057600080fd5b506102446104af366004612cae565b610bff565b3480156104c057600080fd5b506102446104cf366004612c82565b610c0f565b3480156104e057600080fd5b50610244610c1c565b3480156104f557600080fd5b50610244610504366004612cae565b610c6b565b34801561051557600080fd5b5061033b610524366004612cae565b610c7b565b34801561053557600080fd5b50610244610544366004612cae565b610cef565b34801561055557600080fd5b506000546201000090046001600160a01b03166040516001600160a01b039091168152602001610226565b34801561058c57600080fd5b5061024461059b366004612c82565b610d00565b3480156105ac57600080fd5b506102446105bb366004612c49565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b3480156105f257600080fd5b50610368610601366004612c49565b610d0d565b60008060029054906101000a90046001600160a01b03166001600160a01b03166305308b9f6040518163ffffffff1660e01b815260040160206040518083038186803b15801561065557600080fd5b505afa158015610669573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061068d9190612dc4565b905090565b600061069f338484610f26565b9392505050565b600154604051632a72258160e01b81526000916001600160a01b031690632a722581906106d99086908690600401612ddd565b60206040518083038186803b1580156106f157600080fd5b505afa158015610705573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061069f9190612dc4565b600061069f838360006001611490565b600061069f338484611802565b6001600160a01b0381166000908152600360209081526040918290208054835181840281018401909452808452606093928301828280156107b057602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610792575b50505050509050919050565b60006107c86001611a15565b905080156107e0576000805461ff0019166101001790555b6000805462010000600160b01b031916620100006001600160a01b038681169190910291909117909155600180546001600160a01b0319169184169190911790558015610867576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050565b60005460408051633e27ec9b60e01b81529051620100009092046001600160a01b0316916391d14854918391633e27ec9b91600480820192602092909190829003018186803b1580156108be57600080fd5b505afa1580156108d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f69190612dc4565b6040516001600160e01b031960e084901b168152600481019190915233602482015260440160206040518083038186803b15801561093357600080fd5b505afa158015610947573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061096b9190612e06565b6109bc5760405162461bcd60e51b815260206004820152601e60248201527f516f6c6c61746572616c4d616e616765723a206f6e6c79206d61726b6574000060448201526064015b60405180910390fd5b6001600160a01b03808416600090815260026020908152604080832093881683529290522054811115610a435760405162461bcd60e51b815260206004820152602960248201527f516f6c6c61746572616c4d616e616765723a206066726f6d602062616c616e636044820152686520746f6f206c6f7760b81b60648201526084016109b3565b610a4e838583611aa2565b610a626001600160a01b0385168383611b69565b816001600160a01b0316836001600160a01b0316856001600160a01b03167f29db89d45e1a802b4d55e202984fce9faf1d30aedf86503ff1ea0ed9ebb6420184604051610ab191815260200190565b60405180910390a450505050565b600061069f8383600080611bbf565b6000610ade826000806001611e71565b92915050565b6000610ade826000806000611e71565b600061069f838360006001611bbf565b600154604051637dee6c4760e01b81526000916001600160a01b031690637dee6c47906106d99086908690600401612ddd565b600061069f8383600080611490565b60008060029054906101000a90046001600160a01b03166001600160a01b03166384da26666040518163ffffffff1660e01b815260040160206040518083038186803b15801561065557600080fd5b6000610ba48686868686611f36565b90505b95945050505050565b60008060029054906101000a90046001600160a01b03166001600160a01b0316638c765e946040518163ffffffff1660e01b815260040160206040518083038186803b15801561065557600080fd5b6000610ade826000806001612088565b600061069f338484612143565b60008060029054906101000a90046001600160a01b03166001600160a01b031663b8f3ece16040518163ffffffff1660e01b815260040160206040518083038186803b15801561065557600080fd5b6000610ade826000806000612088565b6001600160a01b0381166000908152600460209081526040918290208054835181840281018401909452808452606093928301828280156107b0576020028201919060005260206000209081546001600160a01b031681526001909101906020018083116107925750505050509050919050565b6000610ade82600080600080611f36565b600061069f33848461229b565b60005460408051633e27ec9b60e01b81529051620100009092046001600160a01b0316916391d14854918391633e27ec9b91600480820192602092909190829003018186803b158015610d5f57600080fd5b505afa158015610d73573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d979190612dc4565b6040516001600160e01b031960e084901b168152600481019190915233602482015260440160206040518083038186803b158015610dd457600080fd5b505afa158015610de8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e0c9190612e06565b610e585760405162461bcd60e51b815260206004820152601e60248201527f516f6c6c61746572616c4d616e616765723a206f6e6c79206d61726b6574000060448201526064016109b3565b6001600160a01b0380831660009081526006602090815260408083209385168352929052205460ff16610ee2576001600160a01b038083166000818152600660209081526040808320948616808452948252808320805460ff1916600190811790915593835260048252822080549384018155825290200180546001600160a01b03191690911790555b806001600160a01b0316826001600160a01b03167f2c814b8b1df59b1bc4d0cc4be2f114e513254af06ca6a21a5a0784478c13a31760405160405180910390a35050565b60008054604051630f9eed1b60e11b81526001600160a01b03858116600483015283926201000090041690631f3dda369060240160206040518083038186803b158015610f7257600080fd5b505afa158015610f86573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610faa9190612e2c565b90506001600160a01b0381166110175760405162461bcd60e51b815260206004820152602c60248201527f516f6c6c61746572616c4d616e616765723a204d546f6b656e2077726170206e60448201526b1bdd081cdd5c1c1bdc9d195960a21b60648201526084016109b3565b6040516370a0823160e01b81523060048201526000906001600160a01b038616906370a082319060240160206040518083038186803b15801561105957600080fd5b505afa15801561106d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110919190612dc4565b90506110a86001600160a01b038616873087612820565b6040516370a0823160e01b81523060048201526000906001600160a01b038716906370a082319060240160206040518083038186803b1580156110ea57600080fd5b505afa1580156110fe573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111229190612dc4565b905060006111308383612e5f565b60405163095ea7b360e01b81529091506001600160a01b0388169063095ea7b3906111619087908590600401612ddd565b602060405180830381600087803b15801561117b57600080fd5b505af115801561118f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111b39190612e06565b506001600160a01b0387166108021415611367576040516370a0823160e01b815230600482015284906000906001600160a01b038316906370a082319060240160206040518083038186803b15801561120b57600080fd5b505afa15801561121f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112439190612dc4565b9050816001600160a01b0316631249c58b846040518263ffffffff1660e01b81526004016000604051808303818588803b15801561128057600080fd5b505af1158015611294573d6000803e3d6000fd5b50506040516370a0823160e01b8152306004820152600093506001600160a01b03861692506370a0823191506024015b60206040518083038186803b1580156112dc57600080fd5b505afa1580156112f0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113149190612dc4565b905060006113228383612e5f565b905061132f8c858361285e565b5050506001600160a01b03808a16600090815260026020908152604080832094909316825292909252902054945061069f9350505050565b6040516370a0823160e01b815230600482015284906000906001600160a01b038316906370a082319060240160206040518083038186803b1580156113ab57600080fd5b505afa1580156113bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113e39190612dc4565b60405163140e25ad60e31b8152600481018590529091506001600160a01b0383169063a0712d6890602401602060405180830381600087803b15801561142857600080fd5b505af115801561143c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114609190612dc4565b506040516370a0823160e01b81523060048201526000906001600160a01b038416906370a08231906024016112c4565b604051636a0747a560e11b81526001600160a01b038581166004830152600091829185919087169063d40e8f4a9060240160206040518083038186803b1580156114d957600080fd5b505afa1580156114ed573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115119190612dc4565b61151b9190612e76565b6040516370a0823160e01b81526001600160a01b0388811660048301529192506000918716906370a082319060240160206040518083038186803b15801561156257600080fd5b505afa158015611576573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061159a9190612dc4565b90508181106115ae576000925050506117fa565b60006115ba8284612e5f565b90506000876001600160a01b0316632495a5996040518163ffffffff1660e01b815260040160206040518083038186803b1580156115f757600080fd5b505afa15801561160b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061162f9190612e2c565b60008054604051631e23703160e31b81526001600160a01b038085166004830152939450919262010000909104169063f11b81889060240160006040518083038186803b15801561167f57600080fd5b505afa158015611693573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526116bb9190810190612f5d565b600154604051637dee6c4760e01b81529192506000916001600160a01b0390911690637dee6c47906116f39086908890600401612ddd565b60206040518083038186803b15801561170b57600080fd5b505afa15801561171f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117439190612dc4565b905087156117ed578160a00151600060029054906101000a90046001600160a01b03166001600160a01b031663de01c9cb6040518163ffffffff1660e01b815260040160206040518083038186803b15801561179e57600080fd5b505afa1580156117b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117d69190612dc4565b6117e09083613022565b6117ea9190613041565b90505b95506117fa945050505050565b949350505050565b600080611813858585600080611f36565b9050600083116118785760405162461bcd60e51b815260206004820152602a60248201527f516f6c6c61746572616c4d616e616765723a20616d6f756e74206d75737420626044820152696520706f73697469766560b01b60648201526084016109b3565b600060029054906101000a90046001600160a01b03166001600160a01b031663b8f3ece16040518163ffffffff1660e01b815260040160206040518083038186803b1580156118c657600080fd5b505afa1580156118da573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118fe9190612dc4565b8110156119855760405162461bcd60e51b815260206004820152604960248201527f516f6c6c61746572616c4d616e616765723a20776974686472617720616d6f7560448201527f6e742077696c6c20636175736520756e646572636f6c6c61746572616c697a6560648201526819081858d8dbdd5b9d60ba1b608482015260a4016109b3565b611990858585611aa2565b6119a46001600160a01b0385168685611b69565b846001600160a01b03167f1607da8e9144035d8537941425741e9e3569c81d34a7f8e0c5c44635dc71692185856040516119df929190612ddd565b60405180910390a25050506001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b60008054610100900460ff1615611a5c578160ff166001148015611a385750303b155b611a545760405162461bcd60e51b81526004016109b390613063565b506000919050565b60005460ff808416911610611a835760405162461bcd60e51b81526004016109b390613063565b506000805460ff191660ff92909216919091179055600190565b919050565b6001600160a01b03808416600090815260026020908152604080832093861683529290522054811115611b285760405162461bcd60e51b815260206004820152602860248201527f516f6c6c61746572616c4d616e616765723a206e6f7420656e6f75676820636f6044820152671b1b185d195c985b60c21b60648201526084016109b3565b6001600160a01b03808416600090815260026020908152604080832093861683529290529081208054839290611b5f908490612e5f565b9091555050505050565b6108678363a9059cbb60e01b8484604051602401611b88929190612ddd565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612a5b565b6001600160a01b038085166000908152600260209081526040808320938716835292905290812054831115611c685760405162461bcd60e51b815260206004820152604360248201527f516f6c6c61746572616c4d616e616765723a20776974686472617720616d6f7560448201527f6e74206d757374206265203c3d20746f20636f6c6c61746572616c2062616c616064820152626e636560e81b608482015260a4016109b3565b60008054604051631e23703160e31b81526001600160a01b038781166004830152620100009092049091169063f11b81889060240160006040518083038186803b158015611cb557600080fd5b505afa158015611cc9573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052611cf19190810190612f5d565b8051909150611d045760009150506117fa565b6001600160a01b03808716600090815260026020908152604080832093891683529290522054611d348582612e5f565b600154604051637dee6c4760e01b81529192506000916001600160a01b0390911690637dee6c4790611d6c908a908690600401612ddd565b60206040518083038186803b158015611d8457600080fd5b505afa158015611d98573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dbc9190612dc4565b90508415611e6657600060029054906101000a90046001600160a01b03166001600160a01b031663de01c9cb6040518163ffffffff1660e01b815260040160206040518083038186803b158015611e1257600080fd5b505afa158015611e26573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e4a9190612dc4565b6080840151611e599083613022565b611e639190613041565b90505b979650505050505050565b600080805b6001600160a01b038716600090815260046020526040902054811015611f2c576001600160a01b0387166000908152600460205260408120805483908110611ec057611ec06130b1565b6000918252602090912001546001600160a01b0390811691508716811415611eff57611eee88828888611490565b611ef89084612e76565b9250611f19565b611f0c8882600088611490565b611f169084612e76565b92505b5080611f24816130c7565b915050611e76565b5095945050505050565b600080611f468787876001612088565b90506000611f578886866001611e71565b905080611fed57600060029054906101000a90046001600160a01b03166001600160a01b031663782d2b536040518163ffffffff1660e01b815260040160206040518083038186803b158015611fac57600080fd5b505afa158015611fc0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fe49190612dc4565b92505050610ba7565b80600060029054906101000a90046001600160a01b03166001600160a01b0316638b2f81d66040518163ffffffff1660e01b815260040160206040518083038186803b15801561203c57600080fd5b505afa158015612050573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120749190612dc4565b61207e9084613022565b611fe49190613041565b600080805b6001600160a01b038716600090815260036020526040902054811015611f2c576001600160a01b03871660009081526003602052604081208054839081106120d7576120d76130b1565b6000918252602090912001546001600160a01b03908116915087168114156121165761210588828888611bbf565b61210f9084612e76565b9250612130565b6121238882600088611bbf565b61212d9084612e76565b92505b508061213b816130c7565b91505061208d565b6040516370a0823160e01b815230600482015260009081906001600160a01b038516906370a082319060240160206040518083038186803b15801561218757600080fd5b505afa15801561219b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121bf9190612dc4565b90506121d66001600160a01b038516863086612820565b6040516370a0823160e01b81523060048201526000906001600160a01b038616906370a082319060240160206040518083038186803b15801561221857600080fd5b505afa15801561222c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122509190612dc4565b9050600061225e8383612e5f565b905061226b87878361285e565b505050506001600160a01b0392831660009081526002602090815260408083209490951682529290925250205490565b60008054604051631e23703160e31b81526001600160a01b0385811660048301528392620100009004169063f11b81889060240160006040518083038186803b1580156122e757600080fd5b505afa1580156122fb573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526123239190810190612f5d565b604001519050806001600160a01b0381166108021415612599576040516370a0823160e01b815230600482015285906000906001600160a01b038416906370a082319060240160206040518083038186803b15801561238157600080fd5b505afa158015612395573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123b99190612dc4565b60405163db006a7560e01b8152600481018890529091506001600160a01b0383169063db006a7590602401602060405180830381600087803b1580156123fe57600080fd5b505af1158015612412573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124369190612dc4565b506040516370a0823160e01b81523060048201526000906001600160a01b038516906370a082319060240160206040518083038186803b15801561247957600080fd5b505afa15801561248d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124b19190612dc4565b905060006124bf8383612e5f565b90506124cc8a858a611aa2565b60405163a9059cbb60e01b81526001600160a01b0386169063a9059cbb906124fa908d908590600401612ddd565b602060405180830381600087803b15801561251457600080fd5b505af1158015612528573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061254c9190612e06565b50896001600160a01b03167f1607da8e9144035d8537941425741e9e3569c81d34a7f8e0c5c44635dc7169218a8a604051612588929190612ddd565b60405180910390a2505050506127f1565b6040516370a0823160e01b815230600482015285906000906001600160a01b038416906370a082319060240160206040518083038186803b1580156125dd57600080fd5b505afa1580156125f1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126159190612dc4565b60405163db006a7560e01b8152600481018890529091506001600160a01b0383169063db006a7590602401602060405180830381600087803b15801561265a57600080fd5b505af115801561266e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126929190612dc4565b506040516370a0823160e01b81523060048201526000906001600160a01b038516906370a082319060240160206040518083038186803b1580156126d557600080fd5b505afa1580156126e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061270d9190612dc4565b9050600061271b8383612e5f565b90506127288a858a611aa2565b60405163a9059cbb60e01b81526001600160a01b0386169063a9059cbb90612756908d908590600401612ddd565b602060405180830381600087803b15801561277057600080fd5b505af1158015612784573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127a89190612e06565b50896001600160a01b03167f1607da8e9144035d8537941425741e9e3569c81d34a7f8e0c5c44635dc7169218a8a6040516127e4929190612ddd565b60405180910390a2505050505b505050506001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b6040516001600160a01b03808516602483015283166044820152606481018290526128589085906323b872dd60e01b90608401611b88565b50505050565b60008054604051631e23703160e31b81526001600160a01b038581166004830152620100009092049091169063f11b81889060240160006040518083038186803b1580156128ab57600080fd5b505afa1580156128bf573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526128e79190810190612f5d565b80519091506129475760405162461bcd60e51b815260206004820152602660248201527f516f6c6c61746572616c4d616e616765723a206173736574206e6f74207375706044820152651c1bdc9d195960d21b60648201526084016109b3565b6001600160a01b0380851660009081526005602090815260408083209387168352929052205460ff166129d4576001600160a01b0384811660008181526003602090815260408083208054600180820183559185528385200180546001600160a01b031916968a1696871790559383526005825280832094835293905291909120805460ff191690911790555b6001600160a01b03808516600090815260026020908152604080832093871683529290529081208054849290612a0b908490612e76565b92505081905550836001600160a01b03167fef12f18e2b6578b91b3c852c423ca8ee530f65f20f770e62a7ce8aa08e1ab7778484604051612a4d929190612ddd565b60405180910390a250505050565b6000612ab0826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612b2d9092919063ffffffff16565b8051909150156108675780806020019051810190612ace9190612e06565b6108675760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016109b3565b60606117fa8484600085856001600160a01b0385163b612b8f5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016109b3565b600080866001600160a01b03168587604051612bab919061310e565b60006040518083038185875af1925050503d8060008114612be8576040519150601f19603f3d011682016040523d82523d6000602084013e612bed565b606091505b5091509150611e6682828660608315612c0757508161069f565b825115612c175782518084602001fd5b8160405162461bcd60e51b81526004016109b3919061312a565b6001600160a01b0381168114612c4657600080fd5b50565b60008060408385031215612c5c57600080fd5b8235612c6781612c31565b91506020830135612c7781612c31565b809150509250929050565b60008060408385031215612c9557600080fd5b8235612ca081612c31565b946020939093013593505050565b600060208284031215612cc057600080fd5b813561069f81612c31565b6020808252825182820181905260009190848201906040850190845b81811015612d0c5783516001600160a01b031683529284019291840191600101612ce7565b50909695505050505050565b60008060008060808587031215612d2e57600080fd5b8435612d3981612c31565b93506020850135612d4981612c31565b92506040850135612d5981612c31565b9396929550929360600135925050565b600080600080600060a08688031215612d8157600080fd5b8535612d8c81612c31565b94506020860135612d9c81612c31565b9350604086013592506060860135612db381612c31565b949793965091946080013592915050565b600060208284031215612dd657600080fd5b5051919050565b6001600160a01b03929092168252602082015260400190565b80518015158114611a9d57600080fd5b600060208284031215612e1857600080fd5b61069f82612df6565b8051611a9d81612c31565b600060208284031215612e3e57600080fd5b815161069f81612c31565b634e487b7160e01b600052601160045260246000fd5b600082821015612e7157612e71612e49565b500390565b60008219821115612e8957612e89612e49565b500190565b634e487b7160e01b600052604160045260246000fd5b60405160e0810167ffffffffffffffff81118282101715612ec757612ec7612e8e565b60405290565b600082601f830112612ede57600080fd5b8151602067ffffffffffffffff80831115612efb57612efb612e8e565b8260051b604051601f19603f83011681018181108482111715612f2057612f20612e8e565b604052938452858101830193838101925087851115612f3e57600080fd5b83870191505b84821015611e6657815183529183019190830190612f44565b600060208284031215612f6f57600080fd5b815167ffffffffffffffff80821115612f8757600080fd5b9083019060e08286031215612f9b57600080fd5b612fa3612ea4565b612fac83612df6565b8152612fba60208401612df6565b6020820152612fcb60408401612e21565b6040820152612fdc60608401612e21565b60608201526080830151608082015260a083015160a082015260c08301518281111561300757600080fd5b61301387828601612ecd565b60c08301525095945050505050565b600081600019048311821515161561303c5761303c612e49565b500290565b60008261305e57634e487b7160e01b600052601260045260246000fd5b500490565b6020808252602e908201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160408201526d191e481a5b9a5d1a585b1a5e995960921b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b60006000198214156130db576130db612e49565b5060010190565b60005b838110156130fd5781810151838201526020016130e5565b838111156128585750506000910152565b600082516131208184602087016130e2565b9190910192915050565b60208152600082518060208401526131498160408501602087016130e2565b601f01601f1916919091016040019291505056fea2646970667358221220480742bdc35dc25b06e415e9be96a6ca03891026f3b25e872b28f31a8d407e4464736f6c63430008090033

Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading