GLMR Price: $0.020875 (-2.25%)

Contract

0xEF4bDd1Ba1Ef4D5fB8BF91f08c54D7E6015bf439

Overview

GLMR Balance

Moonbeam Chain LogoMoonbeam Chain LogoMoonbeam Chain Logo0 GLMR

GLMR Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

Please try again later

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

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0xE1A87A40...f8e6E0E8B
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
FixedRateMarket

Compiler Version
v0.8.18+commit.87f61d96

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 25 : FixedRateMarket.sol
// SPDX-License-Identifier: NONE
pragma solidity ^0.8.9;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./interfaces/IFeeEmissionsQontroller.sol";
import "./interfaces/IFixedRateMarket.sol";
import "./interfaces/IQollateralManager.sol";
import "./interfaces/IQPriceOracle.sol";
import "./interfaces/ITradingEmissionsQontroller.sol";
import "./interfaces/IQAdmin.sol";
import "./interfaces/IQuoteManager.sol";
import "./interfaces/IWETH.sol";
import "./libraries/Interest.sol";
import "./libraries/LinkedList.sol";
import "./libraries/QTypes.sol";

contract FixedRateMarket is Initializable, ERC20Upgradeable, IFixedRateMarket {

  using SafeERC20 for IERC20;
  using LinkedList for LinkedList.OrderbookSide;

  /// @notice Reserve storage gap so introduction of new parent class later on can be done via upgrade
  uint256[50] __gap;
  
  /// @notice Borrow side enum
  uint8 private constant _SIDE_BORROW = 0;

  /// @notice Lend side enum
  uint8 private constant _SIDE_LEND = 1;

  /// @notice Internal representation on null pointer for linked lists
  uint64 private constant _NULL_POINTER = 0;

  /// @notice Token dust size - effectively treat it as zero
  uint private constant _DUST = 100;
  
  /// @notice Contract storing all global Qoda parameters
  IQAdmin private _qAdmin;

  /// @notice Address of the ERC20 token which the loan will be denominated
  IERC20 private _underlying;
  
  /// @notice UNIX timestamp (in seconds) when the market matures
  uint private _maturity;

  /// @notice Storage for all borrows by a user
  /// account => principalPlusInterest
  mapping(address => uint) private _accountBorrows;

  /// @notice Storage for qTokens redeemed so far by a user
  /// account => qTokensRedeemed
  mapping(address => uint) private _tokensRedeemed;

  /// @notice Tokens redeemed across all users so far
  uint private _tokensRedeemedTotal;

  /// @notice Total protocol fee accrued in this market so far, in local currency
  uint private _totalAccruedFees;

  /// @notice For calculation of prorated protocol fee
  uint private constant ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60;
  
  /// @notice Contract managing quotes
  IQuoteManager private _quoteManager;
  
  uint256 private constant _NOT_ENTERED = 1;
  uint256 private constant _ENTERED = 2;
  
  /// @notice Same as _status in `@openzeppelin/contracts/security/ReentrancyGuard.sol`
  /// Reconstruct here instead of inheritance is to avoid storage slot sequence problem during
  /// contract upgrade
  uint256 private _status;

  /// @notice Constructor for upgradeable contracts
  /// @param qAdminAddr_ Address of the `QAdmin` contract
  /// @param underlyingAddr_ Address of the underlying loan token denomination
  /// @param maturity_ UNIX timestamp (in seconds) when the market matures
  /// @param name_ Name of the market's ERC20 token
  /// @param symbol_ Symbol of the market's ERC20 token
  function initialize(
                      address qAdminAddr_,
                      address underlyingAddr_,
                      uint maturity_,
                      string memory name_,
                      string memory symbol_
                      ) public initializer {
    __ERC20_init(name_, symbol_);
    _qAdmin = IQAdmin(qAdminAddr_);
    _underlying = IERC20(underlyingAddr_);
    _maturity = maturity_;
  }
  
  /// @notice Needed for native token operation when withdrawing from WETH
  receive() external payable {}
  
  modifier onlyAdmin() {
    require(_qAdmin.hasRole(_qAdmin.ADMIN_ROLE(), msg.sender), "FRM0");
    _;
  }

  /// @notice Modifier which checks that contract and specified operation is not paused
  modifier whenNotPaused(uint operationId) {
    require(!_qAdmin.isPaused(address(this), operationId), "FRM27");
    _;
  }
  
  /// @notice Logic copied from `@openzeppelin/contracts/security/ReentrancyGuard.sol`
  /// Reconstruct here instead of inheritance is to avoid storage slot sequence problem during
  /// contract upgrade
  modifier nonReentrant() {
    // On the first call to nonReentrant, _notEntered will be true
    require(_status != _ENTERED, "FRM28");

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

    _;

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

  /** ADMIN FUNCTIONS **/
  
  /// @notice Call upon initialization after deploying `QuoteManager` contract
  /// @param quoteManagerAddress Address of `QuoteManager` deployment
  function _setQuoteManager(address quoteManagerAddress) external onlyAdmin {
    // Initialize the value
    _quoteManager = IQuoteManager(quoteManagerAddress);

    // Emit the event
    emit SetQuoteManager(quoteManagerAddress);
  }
  
  /** USER INTERFACE **/

  /// @notice Creates a new  `Quote` and adds it to the `OrderbookSide` linked list by side
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param quoteType 0 for PV+APR, 1 for FV+APR
  /// @param APR In decimal form scaled by 1e4 (ex. 1052 = 10.52%)
  /// @param cashflow Can be PV or FV depending on `quoteType`
  function createQuote(uint8 side, uint8 quoteType, uint64 APR, uint cashflow) external {
    _quoteManager.createQuote(side, msg.sender, quoteType, APR, cashflow);
  }
  
  /// @notice Analogue of market order to borrow against current lend `Quote`s.
  /// Only fills at most up to `amountPV`, any unfilled amount is discarded.
  /// @param amountPV The maximum amount to borrow
  /// @param maxAPR Only accept `Quote`s up to specified APR. You may think of
  /// this as a maximum slippage tolerance variable
  function borrow(uint amountPV, uint64 maxAPR) external nonReentrant whenNotPaused(301) {
    _execMarketOrder(_SIDE_LEND, msg.sender, amountPV, maxAPR, false);
  }
  
  /// @notice Analogue of market order to borrow against current lend `Quote`s.
  /// Only fills at most up to `amountPV`, any unfilled amount is discarded.
  /// ETH will be sent to borrower
  /// @param amountPV The maximum amount to borrow
  /// @param maxAPR Only accept `Quote`s up to specified APR. You may think of
  /// this as a maximum slippage tolerance variable
  function borrowETH(uint amountPV, uint64 maxAPR) external nonReentrant whenNotPaused(301) {
    require(address(_underlying) == _qAdmin.WETH(), "FRM24 ETH operation not permitted in this market");
    _execMarketOrder(_SIDE_LEND, msg.sender, amountPV, maxAPR, true);
  }

  /// @notice Analogue of market order to lend against current borrow `Quote`s.
  /// Only fills at most up to `amountPV`, any unfilled amount is discarded.
  /// @param amountPV The maximum amount to lend
  /// @param minAPR Only accept `Quote`s up to specified APR. You may think of
  /// this as a maximum slippage tolerance variable
  function lend(uint amountPV, uint64 minAPR) external nonReentrant whenNotPaused(302) {
    _execMarketOrder(_SIDE_BORROW, msg.sender, amountPV, minAPR, false);
  }
  
  /// @notice Analogue of market order to lend against current borrow `Quote`s.
  /// Only fills at most up to `msg.value`, any unfilled amount is discarded.
  /// Excessive amount will be sent back to lender
  /// Note that protocol fee should also be included as ETH sent in the function call
  /// @param minAPR Only accept `Quote`s up to specified APR. You may think of
  /// this as a maximum slippage tolerance variable
  function lendETH(uint64 minAPR) external payable nonReentrant whenNotPaused(302) {
    require(address(_underlying) == _qAdmin.WETH(), "FRM24 ETH operation not permitted in this market");
    
    // Deduce corresponding amountPV if protocol fee is not included 
    uint amountPV = hypotheticalMaxLendPV(msg.value);
    
    uint executedPV = _execMarketOrder(_SIDE_BORROW, msg.sender, amountPV, minAPR, true);
    
    _refundExcessiveETH(executedPV + proratedProtocolFee(executedPV));
  }

  /// @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 nonReentrant whenNotPaused(303) returns(uint) {
    return _repayBorrow(msg.sender, amount, false, false);
  }
  
  /// @notice Borrower will make repayments to the smart contract using ETH, which
  /// holds the value in escrow until maturity to release to lenders.
  /// @return uint Remaining account borrow amount
  function repayBorrowWithETH() external payable nonReentrant whenNotPaused(303) returns(uint) {
    require(address(_underlying) == _qAdmin.WETH(), "FRM24 ETH operation not permitted in this market");
    uint balanceBefore = _accountBorrows[msg.sender];
    uint balanceAfter = _repayBorrow(msg.sender, msg.value, true, false);
    _refundExcessiveETH(balanceBefore - balanceAfter);
    return balanceAfter;
  }
  
  /// @notice Cancel `Quote` by id. Note this is a O(1) operation
  /// since `OrderbookSide` uses hashmaps under the hood. However, it is
  /// O(n) against the array of `Quote` ids by account so we should ensure
  /// that array should not grow too large in practice.
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param id Id of the `Quote`
  function cancelQuote(uint8 side, uint64 id) external {
    _quoteManager.cancelQuote(true, side, msg.sender, id);
  }
  
  /// @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 specified amount
  /// of qToken from existing balance.
  /// @param amount Amount of qTokens to redeem
  /// @return uint Amount of qTokens redeemed
  function redeemQTokensByRatio(uint amount) external nonReentrant whenNotPaused(304) returns(uint) {
    return _redeemQTokensByRatio(amount, false);
  }

  /// @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.
  /// @return uint Amount of qTokens redeemed
  function redeemAllQTokensByRatio() external nonReentrant whenNotPaused(304) returns(uint) {
    return _redeemQTokensByRatio(_redeemableQTokens(msg.sender), false);
  }
  
  /// @notice This function allows net lenders to redeem qTokens for ETH.
  /// Redemptions may only be permitted after loan maturity plus 
  /// `_maturityGracePeriod`. The public interface redeems specified amount
  /// of qToken from existing balance.
  /// @param amount Amount of qTokens to redeem
  /// @return uint Amount of qTokens redeemed
  function redeemQTokensByRatioWithETH(uint amount) external nonReentrant whenNotPaused(304) returns(uint) {
    require(address(_underlying) == _qAdmin.WETH(), "FRM24 ETH operation not permitted in this market");
    return _redeemQTokensByRatio(amount, true);
  }
  
  /// @notice This function allows net lenders to redeem qTokens for ETH.
  /// Redemptions may only be permitted after loan maturity plus
  /// `_maturityGracePeriod`. The public interface redeems the entire qToken
  /// balance.
  /// @return uint Amount of qTokens redeemed
  function redeemAllQTokensByRatioWithETH() external nonReentrant whenNotPaused(304) returns(uint) {
    require(address(_underlying) == _qAdmin.WETH(), "FRM24 ETH operation not permitted in this market");
    return _redeemQTokensByRatio(_redeemableQTokens(msg.sender), true);
  }

  /// @notice If an account is in danger of being underwater (i.e. collateralRatio < 1.0)
  /// or has not repaid past maturity plus `_repaymentGracePeriod`, 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 to liquidate
  /// @param amount Amount to repay on behalf of account in the currency of the loan
  /// @param collateralToken Liquidator's choice of which currency to be paid in
  function liquidateBorrow(address borrower, uint amount, IERC20 collateralToken) external nonReentrant whenNotPaused(305) {
    _liquidateBorrow(borrower, amount, collateralToken, false);
  }
    
  /** VIEW FUNCTIONS **/

  /// @notice Get the address of the `QAdmin`
  /// @return address
  function qAdmin() external view returns(address) {
    return address(_qAdmin);
  }
  
  /// @notice Get the address of the `QollateralManager`
  /// @return address
  function qollateralManager() external view returns(address){
    return _qAdmin.qollateralManager();
  }
  
  /// @notice Get the address of the `QuoteManager`
  /// @return address
  function quoteManager() external view returns(address){
    return address(_quoteManager);
  }

  /// @notice Get the address of the ERC20 token which the loan will be denominated
  /// @return IERC20
  function underlyingToken() external view returns(IERC20) {
    return _underlying;
  }
  
  /// @notice Get the UNIX timestamp (in seconds) when the market matures
  /// @return uint
  function maturity() external view returns(uint){
    return _maturity;
  }

  /// @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) {
    return _qAdmin.minQuoteSize(address(this));
  }

  /// @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){
    return _accountBorrows[account];
  }

  /// @notice Get the linked list pointer top of book for `Quote` by side
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @return uint64 id of top of book `Quote` 
  function getQuoteHeadId(uint8 side) external view returns(uint64) {
    return _quoteManager.getQuoteHeadId(side);
  }

  /// @notice Get the top of book for `Quote` by side
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @return QTypes.Quote head `Quote`
  function getQuoteHead(uint8 side) external view returns(QTypes.Quote memory) {
    return _quoteManager.getQuoteHead(side);
  }
  
  /// @notice Get the `Quote` for the given `side` and `id`
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param id Id of `Quote`
  /// @return QTypes.Quote `Quote` associated with the id
  function getQuote(uint8 side, uint64 id) external view returns(QTypes.Quote memory) {
    return _quoteManager.getQuote(side, id);
  }

  /// @notice Get all live `Quote` id's by `account` and `side`
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param account Account to query
  /// @return uint[] Unsorted array of borrow `Quote` id's
  function getAccountQuotes(uint8 side, address account) external view returns(uint64[] memory) {
    return _quoteManager.getAccountQuotes(side, account);
  }

  /// @notice Get the number of active `Quote`s by `side` in the orderbook
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @return uint Number of `Quote`s
  function getNumQuotes(uint8 side) external view returns(uint) {
    return _quoteManager.getNumQuotes(side);
  }
    
  /// @notice Gets the `protocolFee` associated with this market
  /// @return uint annualized protocol fee, scaled by 1e4
  function protocolFee() public view returns(uint) {
    // If fee emissions qontroller is not defined, no protocol fee will be charged
    if (address(_qAdmin.feeEmissionsQontroller()) == address(0)) {
      return 0;
    }
    return _qAdmin.protocolFee(address(this));
  }

  /// @notice Gets the `protocolFee` associated with this market, prorated by time till maturity 
  /// @param amount loan amount
  /// @return uint prorated protocol fee in local currency
  function proratedProtocolFee(uint amount) public view returns(uint) {
    return proratedProtocolFee(amount, block.timestamp);
  }

  /// @notice Gets the `protocolFee` associated with this market, prorated by time till maturity 
  /// @param amount loan amount
  /// @param timestamp UNIX timestamp in seconds
  /// @return uint prorated protocol fee in local currency
  function proratedProtocolFee(uint amount, uint timestamp) public view returns(uint) {
    require(timestamp < _maturity, "FRM11 market expired");
    return amount * protocolFee() * (_maturity - timestamp) / _qAdmin.MANTISSA_BPS() / ONE_YEAR_IN_SECONDS;
  }
  
  /// @notice Get amount of qTokens user can redeem based on current loan repayment ratio
  /// @return uint amount of qTokens user can redeem
  function redeemableQTokens() external view returns(uint) {
    return _redeemableQTokens(msg.sender);
  }

  /// @notice Get amount of qTokens user can redeem based on current loan repayment ratio
  /// @param account Account to query
  /// @return uint amount of qTokens user can redeem
  function redeemableQTokens(address account) external view returns(uint) {
    return _redeemableQTokens(account);
  }
  
  /// @notice Gets the current `redemptionRatio` where owned qTokens can be redeemed up to
  /// @return uint redemption ratio, capped and scaled by 1e18
  function redemptionRatio() external view returns(uint) {
    return _redeemableQTokensByRatio(_qAdmin.MANTISSA_DEFAULT());
  }

  /// @notice Tokens redeemed across all users so far
  function tokensRedeemedTotal() external view returns(uint) {
    return _tokensRedeemedTotal;
  }
  
  /// @notice Get total protocol fee accrued in this market so far, in local currency
  /// @return uint accrued fee
  function totalAccruedFees() external view returns(uint) {
    return _totalAccruedFees;
  }

  /// @notice Get the PV of a cashflow amount based on the `quoteType`
  /// @param quoteType 0 for PV, 1 for FV
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param sTime PV start time
  /// @param eTime FV end time
  /// @param amount Value to be PV'ed
  /// @return uint PV of the `amount`
  function getPV(
                 uint8 quoteType,
                 uint64 APR,
                 uint amount,
                 uint sTime,
                 uint eTime
                 ) public view returns(uint) {
    return _quoteManager.getPV(quoteType, APR, amount, sTime, eTime);
  }

  /// @notice Get the FV of a cashflow amount based on the `quoteType`
  /// @param quoteType 0 for PV, 1 for FV
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param sTime PV start time
  /// @param eTime FV end time
  /// @param amount Value to be FV'ed
  /// @return uint FV of the `amount`
  function getFV(
                 uint8 quoteType,
                 uint64 APR,
                 uint amount,
                 uint sTime,
                 uint eTime
                 ) public view returns(uint) {
    return _quoteManager.getFV(quoteType, APR, amount, sTime, eTime);    
  }
  
  /// @notice Get maximum value user can lend with given amount when protocol fee is factored in.
  /// Mantissa is added to reduce precision error during calculation
  /// @param amount Lending amount with protocol fee factored in
  /// @return uint Maximum value user can lend with protocol fee considered
  function hypotheticalMaxLendPV(uint amount) public view returns (uint) {
    return (amount * 1e8) / (1e8 + proratedProtocolFee(1e8));
  }
  
  
  /** INTERNAL FUNCTIONS **/

  /// @notice Called under the hood by external `borrow` and `lend` functions.
  /// This function loops through the opposite `OrderbookSide`, executing loans
  /// until either the full amount is filled, the `OrderbookSide` is empty, or
  /// no more `Quote`s exist that satisfy the `limitAPR` set by the market order.
  /// @param quoteSide 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param account Address of the `Acceptor`
  /// @param amountPV Amount that the `Acceptor` wants to execute, as PV
  /// @param limitAPR Only accept `Quote`s up to specified APR. You may think of
  /// this as a maximum slippage tolerance variable
  /// @param isPaidInETH Is amount being paid in ETH
  /// @return uint Total amount executed in PV terms
  function _execMarketOrder(
                            uint8 quoteSide,
                            address account,
                            uint amountPV,
                            uint64 limitAPR,
                            bool isPaidInETH
                            ) internal returns (uint) {

    // Store the initial requested `Acceptor` size - must be positive
    require(amountPV > 0, "FRM1 amount=0");    
    uint amountRemaining = amountPV;

    // Start `Quote`s from head
    QTypes.Quote memory currQuote = _quoteManager.getQuoteHead(quoteSide);

    uint totalExecutedPV = 0;
    uint totalExecutedFV = 0;
    
    while(amountRemaining > 0) {
      
      if((quoteSide == _SIDE_LEND && limitAPR < currQuote.APR) ||
         (quoteSide == _SIDE_BORROW && limitAPR > currQuote.APR)) {
        
        // Stop loop condition: `limitAPR` works as a limit price.
        // Since `Quote`s are ordered by APR, if the current `Quote` is past
        // the limit, we know all remaining `Quote`s will not satisfy the
        // `Acceptor`s conditions
        break;

      } else if(currQuote.id == _NULL_POINTER) {

        // Stop loop condition: No more `Quote`s remaining
        break;

      } else if(account == currQuote.quoter) {

        // Cannot execute `Quote` against self - just ignore it
        // Move to the next `Quote` in line
        currQuote = _quoteManager.getQuote(quoteSide, currQuote.next);

      } else if(!_quoteManager.isQuoteValid(quoteSide, currQuote)) {

        // Store the pointer to the next best `Quote`
        uint64 next = currQuote.next;

        // Clean up invalid `Quote`s. If the current `Quote` is not valid, it
        // will be cancelled automatically without notice to the creator of
        // the `Quote`
        _quoteManager.cancelQuote(false, quoteSide, currQuote.quoter, currQuote.id);

        // Move to the next `Quote` in line
        currQuote = _quoteManager.getQuote(quoteSide, next);        

      } else {

        // `Quote` is valid. Preprocess and then execute the loan
        (uint execAmountPV, uint execAmountFV) = _preprocessLoan(quoteSide, currQuote.id, account, amountRemaining, isPaidInETH);
        totalExecutedPV += execAmountPV;
        totalExecutedFV += execAmountFV;
        
        // Just in case of potential rounding errors, floor the new `amountRemaining` at zero
        if(amountRemaining > execAmountPV) {
          amountRemaining = amountRemaining - execAmountPV;
        } else {
          amountRemaining = 0;
        }

        // Move to the next `Quote` in line
        currQuote = _quoteManager.getQuote(quoteSide, currQuote.next);
      }      
    }
    if (totalExecutedPV > 0) {
      emit ExecMarketOrder(quoteSide, account, totalExecutedPV, totalExecutedFV);
    }
    return totalExecutedPV;
  }

  /// @notice Intermediary function that handles order/quote sides, PV/FV
  /// and actual executed amount calculations, and updates `Quote` fill status
  /// @param quoteSide 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param quoteId Id of the `Quote`
  /// @param acceptor Address of the `Acceptor`
  /// @param acceptorAmountPV Amount that the `Acceptor` wants to execute, as PV
  /// @param isPaidInETH Is amount being paid in ETH
  /// @return uint execAmountPV uint execAmountFV
  function _preprocessLoan(
                           uint8 quoteSide,
                           uint64 quoteId,
                           address acceptor,
                           uint acceptorAmountPV,
                           bool isPaidInETH
                           ) internal returns(uint,uint){

    // Get immutable instance of `Quote`
    QTypes.Quote memory quote = _quoteManager.getQuote(quoteSide, quoteId);
    
    uint execAmountPV;
    uint execAmountFV;
    if(quote.quoteType == 0){ // Quote is in PV terms

      // Executing Amount must be the smaller of the `Quoter` and `Acceptor` size
      execAmountPV = Math.min(acceptorAmountPV, quote.cashflow - quote.filled);

      // Get the equivalent executed amount in PV terms
      execAmountFV = Interest.PVToFV(
                                     quote.APR,
                                     execAmountPV,
                                     block.timestamp,
                                     _maturity,
                                     _qAdmin.MANTISSA_BPS()
                                     );

      // Update the filled amount for the `Quote`
      quote.filled += execAmountPV;
      _quoteManager.fillQuote(quoteSide, quoteId, execAmountPV);
      
    }else { // Quote is in FV terms
      
      // Get the equivalent FV amount of Acceptor's original amount
      uint acceptorAmountFV = Interest.PVToFV(
                                              quote.APR,
                                              acceptorAmountPV,
                                              block.timestamp,
                                              _maturity,
                                              _qAdmin.MANTISSA_BPS()
                                              );      

      // Executing Amount must be the smaller of the `Quoter` and `Acceptor` size
      execAmountFV = Math.min(acceptorAmountFV, quote.cashflow - quote.filled);

      // Get the equivalent executed amount in PV terms
      execAmountPV = Interest.FVToPV(
                                     quote.APR,
                                     execAmountFV,
                                     block.timestamp,
                                     _maturity,
                                     _qAdmin.MANTISSA_BPS()
                                     );

      // Update the filled amount for the `Quote`
      quote.filled += execAmountFV;
      _quoteManager.fillQuote(quoteSide, quoteId, execAmountFV);
      
    }

    address quoter = quote.quoter;
    uint64 apr = quote.APR;
    if (quote.cashflow - quote.filled < _DUST) {
      // If `Quote` is fully filled (minus dust), remove it from the `OrderbookSide`
      _quoteManager.cancelQuote(false, quoteSide, quote.quoter, quote.id);
    }
    
    // Create the loan, taking care to differentiate whether the `Quoter` is the
    // lender and `Acceptor` is the borrower, or vice versa
    if (quoteSide == _SIDE_BORROW) {
      return _createFixedRateLoan(quoteSide, quoter, acceptor, execAmountPV, execAmountFV, proratedProtocolFee(execAmountPV), apr, isPaidInETH);
    } 
    if (quoteSide == _SIDE_LEND) {
      return _createFixedRateLoan(quoteSide, acceptor, quoter, execAmountPV, execAmountFV, proratedProtocolFee(execAmountPV), apr, isPaidInETH);
    } 
    revert("FRM14 invalid side");
  }

  /// @notice Mint the future `qToken`s to the lender, add `amountFV` to the
  /// borrower's debts, transfer `amountPV` from lender to borrower, and accrue
  /// `protocolFee`s to the `FeeEmissionsQontroller`
  /// @param quoteSide 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param borrower Account of the borrower
  /// @param lender Account of the lender
  /// @param amountPV Size of the initial loan paid by lender
  /// @param amountFV Final amount that must be paid by borrower
  /// @param protocolFee_ Protocol fee to be paid by both lender and borrower in the transaction
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param isPaidInETH Is amount being paid in ETH
  /// @return uint execAmountPV uint execAmountFV
  function _createFixedRateLoan(
                                uint8 quoteSide,
                                address borrower,
                                address lender,
                                uint amountPV,
                                uint amountFV,
                                uint protocolFee_,
                                uint64 APR,
                                bool isPaidInETH
                                ) internal returns(uint, uint){

    // Loan amount must be strictly positive
    require(amountPV > 0, "FRM1 amount=0");

    // Interest rate needs to be positive
    require(amountPV < amountFV, "FRM16 invalid APR");

    // AmountPV should be able to cover protocolFee cost
    require(amountPV > protocolFee_, "FRM9 amount < protocolFee");

    // Cannot execute loan against self
    require(lender != borrower, "FRM17 invalid counterparty");

    // Cannot Create a loan past its maturity time
    require(block.timestamp < _maturity, "FRM18 invalid maturity");

    // If contract is to act on behalf of lender, assume upstream has handled related fund transfer to the contract.
    // So no fund availability check is needed here.
    if (quoteSide != _SIDE_BORROW || !isPaidInETH) {
      // Check lender has approved contract spend
      require(
              _underlying.allowance(lender, address(this)) >= amountPV + protocolFee_,
              "FRM2 not enough allowance"
              );
  
      // Check lender has enough balance
      require(
              _underlying.balanceOf(lender) >= amountPV + protocolFee_,
              "FRM3 not enough balance"
              );
    }

    // TODO: is there any way to only require the `amountPV` at time of inception of
    // loan and slowly converge the required collateral to equal `amountFV` by end
    // of loan? This allows for improved capital efficiency / less collateral upfront
    // required by borrower
    
    // Check if borrowing amount is above max borrow and update market participated  
    _checkRatioAndAddParticipatedMarket(borrower, lender, amountFV);
    
    // The borrow amount of the borrower increases by the full `amountFV`
    _accountBorrows[borrower] += amountFV;
    
    // Net off borrow amount with any balance of qTokens the borrower may have
    _repayBorrow(borrower, balanceOf(borrower), false, true);

    // Transfer `amountPV` from lender to borrower, and protocolFee from both
    // lender and borrower to `FeeEmissionsQontroller`.
    // Note that lender will pay `protocolFee_` from their account balance,
    // while borrower will pay `protocolFee_` from their borrowed amount. So
    // total amount involved in transfer = amountPV + protocolFee_
    // Also note that if it is WETH market and borrower intends to receive ETH,
    // contract will receive on behalf and do token unwrapping outside this function
    IFeeEmissionsQontroller feq = IFeeEmissionsQontroller(_qAdmin.feeEmissionsQontroller());
    bool lenderInitiate = quoteSide == _SIDE_BORROW;
    if (address(feq) == address(0)) {
      _transferTokenOrETH(lender, borrower, amountPV, isPaidInETH && lenderInitiate, isPaidInETH && !lenderInitiate);
    } else {
      // No token unwrapping is need for FeeEmissionsQontroller as target recipient
      _transferTokenOrETH(lender, address(feq), protocolFee_ * 2, isPaidInETH && lenderInitiate, false);
      _transferTokenOrETH(lender, borrower, amountPV - protocolFee_, isPaidInETH && lenderInitiate, isPaidInETH && !lenderInitiate);

      _totalAccruedFees += protocolFee_ * 2;
      feq.receiveFees(_underlying, protocolFee_ * 2);
    }

    // Lender receives `amountFV` amount in qTokens
    // Put this last to protect against reentracy
    //TODO Probably want use a reentrancy guard instead here
    _mint(lender, amountFV);
    
    // Net off the minted amount with any borrow amounts the lender may have
    _repayBorrow(lender, balanceOf(lender), false, true);

    // Finally, report trading volumes for trading rewards
    _updateTradingRewards(borrower, lender, amountPV);

    // Emit the matched borrower and lender and fixed rate loan terms
    emit FixedRateLoan(quoteSide, borrower, lender, amountPV, amountFV, protocolFee_, APR);

    return (amountPV, amountFV);
  }
  
  /// @notice Check if borrowing amount is breaching maximum allow amount borrow,
  /// which is determined by initCollateralRatio and creditLimit.
  /// Note `_initCollateralRatio` is a larger value than `_minCollateralRatio`. 
  /// This protects users from taking loans at the minimum threshold, 
  /// putting them at risk of instant liquidation.
  /// @param borrower Account of the borrower
  /// @param lender Account of the lender
  /// @param amountFV Final amount that must be paid by borrower
  function _checkRatioAndAddParticipatedMarket(address borrower, address lender, uint amountFV) internal {
    IQollateralManager qm = IQollateralManager(_qAdmin.qollateralManager());
    IFixedRateMarket currentMarket = IFixedRateMarket(address(this));
    uint maxBorrowFV = qm.hypotheticalMaxBorrowFV(borrower, currentMarket);
    require(amountFV <= maxBorrowFV, "FRM22 permitted amount exceeded for borrower");

    // Record that the lender/borrow have participated in this market
    if(!qm.accountMarkets(lender, currentMarket)){
      qm._addAccountMarket(lender, currentMarket);
    }
    if(!qm.accountMarkets(borrower, currentMarket)){
      qm._addAccountMarket(borrower, currentMarket);
    }
  }

  /// @notice Internal function for lender to redeem qTokens after maturity
  /// please see `redeemQTokensByRatio()` for parameter and return value description
  /// @param amount Amount of qTokens to redeem
  /// @param isPaidInETH Is amount being paid in ETH
  /// @return uint Amount of qTokens redeemed
  function _redeemQTokensByRatio(uint amount, bool isPaidInETH) internal returns(uint) {
    // Redeem is not possible if targeted redeemable amount is zero  
    require(amount > 0, "FRM23 target redeem amount = 0");
    
    // Enforce maturity + grace period before allowing redemptions
    require(block.timestamp > _maturity + _qAdmin.maturityGracePeriod(), "FRM4 cannot redeem early");

    // Amount to redeem must not exceed loan repayment ratio
    require(amount <= _redeemableQTokens(msg.sender), "FRM20 amount > redeemableTokens");

    // Burn the qToken balance
    _burn(msg.sender, amount);

    // Increase redeemed amount
    _tokensRedeemed[msg.sender] += amount;
    _tokensRedeemedTotal += amount;

    // Release the underlying token back to the lender
    _transferTokenOrETH(address(this), msg.sender, amount, false, isPaidInETH);

    // Emit the event
    emit RedeemQTokens(msg.sender, amount);

    return amount;
  }
  
  /// @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
  /// @param isPaidInETH Is amount being paid in ETH
  /// @param isPaidInQTokens Is amount being paid with qTokens
  /// @return uint Remaining account borrow amount
  function _repayBorrow(address account, uint amount, bool isPaidInETH, bool isPaidInQTokens) internal returns(uint){

    // Don't allow users to pay more than necessary
    amount = Math.min(amount, _accountBorrows[account]);
    
    if (isPaidInQTokens) {
      if(amount == 0) {      
        // Short-circuit: If user has no qTokens, no need to do anything
        return _accountBorrows[account];
      }
      
      // Burn the qTokens from the account and subtract the amount for the user's borrows
      _burn(account, amount);
    } else {
      // Repayment amount must be positive
      require(amount > 0, "FRM1 amount=0");
      
      // Transfer amount from borrower to contract for escrow until maturity
      _transferTokenOrETH(account, address(this), amount, isPaidInETH, false);
    }

    // Deduct from the account's total debts
    // Guaranteed not to underflow due to the flooring on amount above
    _accountBorrows[account] -= amount;
    
    // Emit the event
    emit RepayBorrow(account, amount, isPaidInQTokens);

    return _accountBorrows[account];
  }
  
  /// @notice If an account is in danger of being underwater (i.e. collateralRatio < 1.0)
  /// or has not repaid past maturity plus `_repaymentGracePeriod`, 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 to liquidate
  /// @param amount Amount to repay on behalf of account in the currency of the loan
  /// @param collateralToken Liquidator's choice of which currency to be paid in
  /// @param isPaidInETH Is amount being paid in ETH
  /// @return uint Amount transferred for liquidation
  function _liquidateBorrow(address borrower, uint amount, IERC20 collateralToken, bool isPaidInETH) internal returns(uint) {

    IQollateralManager qm = IQollateralManager(_qAdmin.qollateralManager());
    uint repaymentGracePeriod = _qAdmin.repaymentGracePeriod();

    // Ensure borrower is either underwater or past payment due date.
    // These are the necessary conditions before borrower can be liquidated.
    require(
            qm.collateralRatio(borrower) < _qAdmin.minCollateralRatio(borrower) ||
            block.timestamp > _maturity + repaymentGracePeriod,
            "FRM5 not liquidatable"
            );
    
    // For borrowers that are underwater, liquidator can only repay up
    // to a percentage of the full loan balance determined by the `closeFactor`
    uint closeFactor = qm.closeFactor();
    
    // For borrowers that are past due date, ignore the close factor - liquidator
    // can liquidate the entire sum
    if(block.timestamp > _maturity){
      closeFactor = _qAdmin.MANTISSA_FACTORS();
    }

    // Liquidator cannot repay more than the percentage of the full loan balance
    // determined by `closeFactor`
    uint maxRepayment = _accountBorrows[borrower] * closeFactor / _qAdmin.MANTISSA_FACTORS();
    amount = Math.min(amount, maxRepayment);

    // Amount must be positive
    require(amount > 0, "FRM1 amount=0");

    // Get USD value of amount paid
    uint amountUSD = qm.localToUSD(_underlying, amount);

    // Get USD value of amount plus liquidity incentive
    uint rewardUSD = amountUSD * _qAdmin.liquidationIncentive() / _qAdmin.MANTISSA_FACTORS();

    // Get the local amount of collateral to reward liquidator
    uint rewardLocal = qm.USDToLocal(collateralToken, rewardUSD);

    // Ensure the borrower has enough collateral balance to pay the liquidator
    require(rewardLocal <= qm.collateralBalance(borrower, collateralToken), "FRM7 not enough collateral");

    // Liquidator repays the loan on behalf of borrower
    _transferTokenOrETH(msg.sender, address(this), amount, isPaidInETH, false);

    // Credit the borrower's account
    _accountBorrows[borrower] -= amount;

    // Emit the event
    emit LiquidateBorrow(borrower, msg.sender, amount, address(collateralToken), rewardLocal);

    // Transfer the collateral balance from borrower to the liquidator
    qm._transferCollateral(collateralToken, borrower, msg.sender, rewardLocal);
    
    // Return amount transferred for liquidation
    return amount;
  }
  
  /// @notice Tracks the amount traded, its associated protocol fees, normalize
  /// to USD, and reports the data to `TradingEmissionsQontroller` which handles
  /// disbursing token rewards for trading volumes
  /// @param borrower Address of the borrower
  /// @param lender Address of the lender
  /// @param amountPV Amount traded (in local currency, in PV terms)
  function _updateTradingRewards(address borrower, address lender, uint amountPV) internal {
    // Instantiate interfaces
    ITradingEmissionsQontroller teq = ITradingEmissionsQontroller(_qAdmin.tradingEmissionsQontroller());
    
    if (address(teq) != address(0)) {
      
      IQPriceOracle oracle = IQPriceOracle(_qAdmin.qPriceOracle());

      // Get the associated protocol fees generated by the amount
      uint feeLocal = proratedProtocolFee(amountPV);
    
      // Convert the fee to USD
      uint feeUSD = oracle.localToUSD(_underlying, feeLocal);
        
      // report volumes to `TradingEmissionsQontroller`
      teq.updateRewards(borrower, lender, feeUSD);
    }
  }

  
  /** INTERNAL VIEW FUNCTIONS **/

  /// @notice Get amount of qTokens user can redeem based on current loan repayment ratio
  /// @param userAddress Address of the account to check
  /// @return uint amount of qTokens user can redeem
  function _redeemableQTokens(address userAddress) internal view returns(uint) {
    uint held = balanceOf(userAddress);
    if (held <= 0) {
      return 0;
    }
    uint redeemed = _tokensRedeemed[userAddress];
    uint redeemable = _redeemableQTokensByRatio(held + redeemed);
    return redeemable > redeemed ? redeemable - redeemed : 0;
  }
  
  /// @notice Gets the current `redemptionRatio` where owned qTokens can be redeemed up to
  /// @param amount amount of qToken for ratio to be applied to
  /// @return uint redeemable qToken with `redemptionRatio` applied, capped by amount inputted
  function _redeemableQTokensByRatio(uint amount) internal view returns(uint) {
    uint repaidTotal = _underlying.balanceOf(address(this)) + _tokensRedeemedTotal; // escrow + redeemed qTokens
    uint loanTotal = totalSupply() + _tokensRedeemedTotal; // redeemed tokens are also part of all minted qTokens
    uint ratio = repaidTotal * amount / loanTotal;
    return Math.min(ratio, amount);
  }
  
  /// @notice Transfer fund from sender to receiver, with handling of ETH wrapping and unwrapping
  /// if needed. Note that this function will not perform balance check and it should be done
  /// in the caller.
  /// @param sender Account of the sender
  /// @param receiver Account of the receiver
  /// @param amount Size of the fund to be transferred from sender to receiver
  /// @param isSendingETH Indicate if sender is sending fund with ETH
  /// @param isReceivingETH Indicate if receiver is receiving fund with ETH
  function _transferTokenOrETH(
                               address sender,
                               address receiver,
                               uint amount,
                               bool isSendingETH,
                               bool isReceivingETH                        
                               ) internal {
    address sender_ = sender;
    address receiver_ = receiver;
    
    // If it is ETH transfer, contract will send/receive on behalf
    // and do needed token wrapping/unwrapping
    if (isSendingETH) {
      sender_ = address(this);
    }
    if (isReceivingETH) {
      receiver_ = address(this);
    }
    
    // If sender uses ETH for transfer, token wrapping is needed
    if (isSendingETH) {
      IWETH weth = IWETH(_qAdmin.WETH());
      weth.deposit{ value: amount }();
    }
    
    // Transfer `amount` from sender to receiver
    if (sender_ == address(this)) {
      _underlying.safeTransfer(receiver_, amount);
    } else {
      _underlying.safeTransferFrom(sender_, receiver_, amount);
    }
    
    // For receiver getting ETH in transfer, token unwrapping is needed
    if (isReceivingETH) {
      IWETH weth = IWETH(_qAdmin.WETH());
      weth.withdraw(amount);
      (bool success,) = receiver.call{value: amount}("");
      require(success, "FRM25 unsuccessful ETH transfer");
    }
  }
  
  /** ERC20 Implementation **/

  /// @notice Number of decimal places of the qToken should match the number
  /// of decimal places of the underlying token
  /// @return uint8 Number of decimal places
  function decimals() public view override(ERC20Upgradeable, IERC20MetadataUpgradeable) returns(uint8) {
    //TODO possible for ERC20 to not define decimals. Do we need to handle this?
    return IERC20Metadata(address(_underlying)).decimals();
  }

  /// @notice This hook requires users trying to transfer their qTokens to only
  /// be able to transfer tokens in excess of their current borrows. This is to
  /// protect the protocol from users gaming the collateral management system
  /// by borrowing off of the qToken and then immediately transferring out the
  /// qToken to another address, leaving the borrowing account uncollateralized
  /// @param from Address of the sender
  /// @param to Address of the receiver
  /// @param amount Amount of tokens to send
  function _beforeTokenTransfer(
                                address from,
                                address to,
                                uint256 amount
                                ) internal virtual override {

    // Call parent hook first
    super._beforeTokenTransfer(from, to, amount);

    // Ignore hook for 0x000... address (e.g. _mint, _burn functions)
    if(from == address(0) || to == address(0)){
      return;
    }

    // Transfers rejected if borrows exceed lends
    require(balanceOf(from) > _accountBorrows[from], "FRM8 borrows > lends");

    // Safe from underflow after previous require statement
    require(amount <= balanceOf(from) - _accountBorrows[from], "FRM21 amount > borrows");

  }

  /// @notice This hook requires users to automatically repay any borrows their
  /// accounts may still have after receiving the qTokens
  /// @param from Address of the sender
  /// @param to Address of the receiver
  /// @param amount Amount of tokens to send
  function _afterTokenTransfer(
                                address from,
                                address to,
                                uint256 amount
                                ) internal virtual override {

    // Call parent hook first
    super._afterTokenTransfer(from, to, amount);

    // Ignore hook for 0x000... address (e.g. _mint, _burn functions)
    if(from == address(0) || to == address(0)){
      return;
    }

    _repayBorrow(to, amount, false, true);
  }
  
  /// @notice If user sends more ETH than is actually being executed, the excessive amount should
  /// be refunded to the user
  /// @param amountConsumed amount used in this transaction
  function _refundExcessiveETH(uint amountConsumed) internal {
    if (amountConsumed < msg.value) {
      (bool success,) = msg.sender.call{value: msg.value - amountConsumed}("");
      require(success, "FRM25 unsuccessful ETH transfer");
    }
  }

  /// @notice Transfer allows qToken to be transferred from one address to another, but if is called after maturity,
  /// redeemable amount will be subjected to current loan repayment ratio
  /// @param to Address of the receiver
  /// @param amount Amount of qTokens to send
  /// @return true if the transfer is successful
  function transfer(address to, uint256 amount) public virtual override(ERC20Upgradeable, IERC20Upgradeable) whenNotPaused(306) returns (bool) {
    return _transferFrom(msg.sender, to, amount);
  }

  /// @notice TransferFrom allows spender to transfer qToken to another account in users' behalf,
  /// but if is called after maturity, redeemable amount will be subjected to current loan repayment ratio
  /// @param from Address of the qToken owner
  /// @param to Address of the receiver
  /// @param amount Amount of qTokens to send
  /// @return true if the transfer is successful
  function transferFrom(address from, address to, uint256 amount) public virtual override(ERC20Upgradeable, IERC20Upgradeable) whenNotPaused(306) returns (bool) {
    return _transferFrom(from, to, amount);
  }

  /// @notice Internal function for spender to transfer qToken to another account in users' behalf,
  /// please see `transferFrom()` for parameter and return value description
  function _transferFrom(address from, address to, uint256 amount) internal returns (bool) {
    // After maturity, amount to redeem must not exceed loan repayment ratio
    if (block.timestamp > _maturity) {
      require(block.timestamp > _maturity + _qAdmin.maturityGracePeriod(), "FRM4 cannot redeem early");
      uint redeemableTokens = _redeemableQTokens(from);
      require(amount <= redeemableTokens, "FRM20 amount > redeemableTokens");

      // qToken transferred away is considered the same as redeemed by the user
      // redeemed token in total does not change because qToken transferred still exist in the contract
      _tokensRedeemed[from] += amount;
    }
    if (from == msg.sender) {
      return super.transfer(to, amount);
    }
    return super.transferFrom(from, to, amount);
  }
  
  function approve(address spender, uint256 amount) public virtual override(ERC20Upgradeable, IERC20Upgradeable) whenNotPaused(306) returns (bool) {
    return super.approve(spender, amount);
  }

  function increaseAllowance(address spender, uint256 addedValue) public virtual override(ERC20Upgradeable) whenNotPaused(306) returns (bool) {
    return super.increaseAllowance(spender, addedValue);
  }

  function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override(ERC20Upgradeable) whenNotPaused(306) returns (bool) {
    return super.decreaseAllowance(spender, subtractedValue);
  }

}

File 2 of 25 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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 = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * `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) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[45] private __gap;
}

// 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 IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @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);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

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

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

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

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

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

    function safeIncreaseAllowance(
        IERC20 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(
        IERC20 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));
        }
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @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 == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`.
        // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
        // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
        // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
        // good first aproximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1;
        uint256 x = a;
        if (x >> 128 > 0) {
            x >>= 128;
            result <<= 64;
        }
        if (x >> 64 > 0) {
            x >>= 64;
            result <<= 32;
        }
        if (x >> 32 > 0) {
            x >>= 32;
            result <<= 16;
        }
        if (x >> 16 > 0) {
            x >>= 16;
            result <<= 8;
        }
        if (x >> 8 > 0) {
            x >>= 8;
            result <<= 4;
        }
        if (x >> 4 > 0) {
            x >>= 4;
            result <<= 2;
        }
        if (x >> 2 > 0) {
            result <<= 1;
        }

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        uint256 result = sqrt(a);
        if (rounding == Rounding.Up && result * result < a) {
            result += 1;
        }
        return result;
    }
}

//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IFeeEmissionsQontroller {

  /// @notice Emitted when user claims emissions
  event ClaimEmissions(address indexed account, uint amount);

  /// @notice Emitted when fee is accrued in a round
  event FeesAccrued(uint indexed round, address token, uint amount, uint amountInRound);

  /// @notice Emitted when we move to a new round
  event NewFeeEmissionsRound(uint indexed currentPeriod, uint startTime, uint endTime);

  /** ACCESS CONTROLLED FUNCTIONS **/

  function receiveFees(IERC20 underlyingToken, uint feeLocal) external;

  function veIncrease(address account, uint veIncreased) external;

  function veReset(address account) external;

  /** USER INTERFACE **/

  function claimEmissions() external;

  function claimEmissions(address account) external;


  /** VIEW FUNCTIONS **/
  
  function claimableEmissions() external view returns (uint);
  
  function claimableEmissions(address account) external view returns (uint);
  
  function expectedClaimableEmissions() external view returns (uint);
  
  function expectedClaimableEmissions(address account) external view returns (uint);

  function qAdmin() external view returns (address);

  function veToken() external view returns (address);

  function swapContract() external view returns (address);

  function WETH() external view returns (IERC20);

  function emissionsRound() external view returns (uint, uint, uint);
  
  function emissionsRound(uint round_) external view returns (uint, uint, uint);

  function timeTillRoundEnd() external view returns (uint);

  function stakedVeAtRound(address account, uint round) external view returns (uint);

  function roundInterval() external view returns (uint);

  function currentRound() external view returns (uint);

  function lastClaimedRound() external view returns (uint);

  function lastClaimedRound(address account) external view returns (uint);

  function lastClaimedVeBalance() external view returns (uint);

  function lastClaimedVeBalance(address account) external view returns (uint);
  
  function claimedEmissions() external view returns (uint);
    
  function claimedEmissions(address account) external view returns (uint);

  function totalFeesAccrued() external view returns (uint);

  function totalFeesClaimed() external view returns (uint);

}

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

import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../libraries/QTypes.sol";

interface IFixedRateMarket is IERC20Upgradeable, IERC20MetadataUpgradeable {
  
  /// @notice Emitted when market order is created and loan can be created with one or more quotes
  event ExecMarketOrder(
                        uint8 indexed quoteSide,
                        address indexed account,
                        uint totalExecutedPV,
                        uint totalExecutedFV
                        );
  
  /// @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 collateralTokenAddr,
                        uint reward
                        );
  
  /// @notice Emitted when a borrower and lender are matched for a fixed rate loan
  event FixedRateLoan(
                      uint8 indexed quoteSide,
                      address indexed borrower,
                      address indexed lender,
                      uint amountPV,
                      uint amountFV,
                      uint feeIncurred,
                      uint64 APR
                      );
  
  /// @notice Emitted when an account redeems their qTokens
  event RedeemQTokens(address indexed account, uint amount);
    
  /// @notice Emitted when setting `_quoteManager`
  event SetQuoteManager(address quoteManagerAddress);


  /** ADMIN FUNCTIONS **/
  
  /// @notice Call upon initialization after deploying `QuoteManager` contract
  /// @param quoteManagerAddress Address of `QuoteManager` deployment
  function _setQuoteManager(address quoteManagerAddress) external;
  
  /** USER INTERFACE **/
  
  /// @notice Creates a new  `Quote` and adds it to the `OrderbookSide` linked list by side
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param quoteType 0 for PV+APR, 1 for FV+APR
  /// @param APR In decimal form scaled by 1e4 (ex. 1052 = 10.52%)
  /// @param cashflow Can be PV or FV depending on `quoteType`
  function createQuote(uint8 side, uint8 quoteType, uint64 APR, uint cashflow) external;
  
  /// @notice Analogue of market order to borrow against current lend `Quote`s.
  /// Only fills at most up to `amountPV`, any unfilled amount is discarded.
  /// @param amountPV The maximum amount to borrow
  /// @param maxAPR Only accept `Quote`s up to specified APR. You may think of
  /// this as a maximum slippage tolerance variable
  function borrow(uint amountPV, uint64 maxAPR) external;
    
  /// @notice Analogue of market order to borrow against current lend `Quote`s.
  /// Only fills at most up to `amountPV`, any unfilled amount is discarded.
  /// ETH will be sent to borrower
  /// @param amountPV The maximum amount to borrow
  /// @param maxAPR Only accept `Quote`s up to specified APR. You may think of
  /// this as a maximum slippage tolerance variable
  function borrowETH(uint amountPV, uint64 maxAPR) external;

  /// @notice Analogue of market order to lend against current borrow `Quote`s.
  /// Only fills at most up to `amountPV`, any unfilled amount is discarded.
  /// @param amountPV The maximum amount to lend
  /// @param minAPR Only accept `Quote`s up to specified APR. You may think of
  /// this as a maximum slippage tolerance variable
  function lend(uint amountPV, uint64 minAPR) external;
    
  /// @notice Analogue of market order to lend against current borrow `Quote`s.
  /// Only fills at most up to `msg.value`, any unfilled amount is discarded.
  /// Excessive amount will be sent back to lender
  /// Note that protocol fee should also be included as ETH sent in the function call
  /// @param minAPR Only accept `Quote`s up to specified APR. You may think of
  /// this as a maximum slippage tolerance variable
  function lendETH(uint64 minAPR) external payable;

  /// @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 Borrower will make repayments to the smart contract using ETH, which
  /// holds the value in escrow until maturity to release to lenders.
  /// @return uint Remaining account borrow amount
  function repayBorrowWithETH() external payable returns(uint);
  
  /// @notice Cancel `Quote` by id. Note this is a O(1) operation
  /// since `OrderbookSide` uses hashmaps under the hood. However, it is
  /// O(n) against the array of `Quote` ids by account so we should ensure
  /// that array should not grow too large in practice.
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param id Id of the `Quote`
  function cancelQuote(uint8 side, uint64 id) 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 specified amount
  /// of qToken from existing balance.
  /// @param amount Amount of qTokens to redeem
  /// @return uint Amount of qTokens redeemed
  function redeemQTokensByRatio(uint amount) external returns(uint);

  /// @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.
  /// @return uint Amount of qTokens redeemed
  function redeemAllQTokensByRatio() external returns(uint);
  
  /// @notice This function allows net lenders to redeem qTokens for ETH.
  /// Redemptions may only be permitted after loan maturity plus 
  /// `_maturityGracePeriod`. The public interface redeems specified amount
  /// of qToken from existing balance.
  /// @param amount Amount of qTokens to redeem
  /// @return uint Amount of qTokens redeemed
  function redeemQTokensByRatioWithETH(uint amount) external returns(uint);
    
  /// @notice This function allows net lenders to redeem qTokens for ETH.
  /// Redemptions may only be permitted after loan maturity plus
  /// `_maturityGracePeriod`. The public interface redeems the entire qToken
  /// balance.
  /// @return uint Amount of qTokens redeemed
  function redeemAllQTokensByRatioWithETH() external returns(uint);

  /// @notice If an account is in danger of being underwater (i.e. collateralRatio < 1.0)
  /// or has not repaid past maturity plus `_repaymentGracePeriod`, 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 to liquidate
  /// @param amount Amount to repay on behalf of account in the currency of the loan
  /// @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 `QAdmin`
  /// @return address
  function qAdmin() external view returns(address);
  
  /// @notice Get the address of the `QollateralManager`
  /// @return address
  function qollateralManager() external view returns(address);
    
  /// @notice Get the address of the `QuoteManager`
  /// @return address
  function quoteManager() 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 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 linked list pointer top of book for `Quote` by side
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @return uint64 id of top of book `Quote` 
  function getQuoteHeadId(uint8 side) external view returns(uint64);

  /// @notice Get the top of book for `Quote` by side
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @return QTypes.Quote head `Quote`
  function getQuoteHead(uint8 side) external view returns(QTypes.Quote memory);
  
  /// @notice Get the `Quote` for the given `side` and `id`
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param id Id of `Quote`
  /// @return QTypes.Quote `Quote` associated with the id
  function getQuote(uint8 side, uint64 id) external view returns(QTypes.Quote memory);

  /// @notice Get all live `Quote` id's by `account` and `side`
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param account Account to query
  /// @return uint[] Unsorted array of borrow `Quote` id's
  function getAccountQuotes(uint8 side, address account) external view returns(uint64[] memory);

  /// @notice Get the number of active `Quote`s by `side` in the orderbook
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @return uint Number of `Quote`s
  function getNumQuotes(uint8 side) external view returns(uint);
    
  /// @notice Gets the `protocolFee` associated with this market
  /// @return uint annualized protocol fee, scaled by 1e4
  function protocolFee() external view returns(uint);

  /// @notice Gets the `protocolFee` associated with this market, prorated by time till maturity 
  /// @param amount loan amount
  /// @return uint prorated protocol fee in local currency
  function proratedProtocolFee(uint amount) external view returns(uint);
  
  /// @notice Gets the `protocolFee` associated with this market, prorated by time till maturity 
  /// @param amount loan amount
  /// @param timestamp UNIX timestamp in seconds
  /// @return uint prorated protocol fee in local currency
  function proratedProtocolFee(uint amount, uint timestamp) external view returns(uint);

  /// @notice Get amount of qTokens user can redeem based on current loan repayment ratio
  /// @return uint amount of qTokens user can redeem
  function redeemableQTokens() external view returns(uint);
  
  /// @notice Get amount of qTokens user can redeem based on current loan repayment ratio
  /// @param account Account to query
  /// @return uint amount of qTokens user can redeem
  function redeemableQTokens(address account) external view returns(uint);
  
  /// @notice Gets the current `redemptionRatio` where owned qTokens can be redeemed up to
  /// @return uint redemption ratio, capped and scaled by 1e18
  function redemptionRatio() external view returns(uint);

  /// @notice Tokens redeemed across all users so far
  function tokensRedeemedTotal() external view returns(uint);
  
  /// @notice Get total protocol fee accrued in this market so far, in local currency
  /// @return uint accrued fee
  function totalAccruedFees() external view returns(uint);

  /// @notice Get the PV of a cashflow amount based on the `quoteType`
  /// @param quoteType 0 for PV, 1 for FV
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param sTime PV start time
  /// @param eTime FV end time
  /// @param amount Value to be PV'ed
  /// @return uint PV of the `amount`
  function getPV(
                 uint8 quoteType,
                 uint64 APR,
                 uint amount,
                 uint sTime,
                 uint eTime
                 ) external view returns(uint);

  /// @notice Get the FV of a cashflow amount based on the `quoteType`
  /// @param quoteType 0 for PV, 1 for FV
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param sTime PV start time
  /// @param eTime FV end time
  /// @param amount Value to be FV'ed
  /// @return uint FV of the `amount`
  function getFV(
                 uint8 quoteType,
                 uint64 APR,
                 uint amount,
                 uint sTime,
                 uint eTime
                 ) external view returns(uint);

  /// @notice Get maximum value user can lend with given amount when protocol fee is factored in.
  /// Mantissa is added to reduce precision error during calculation
  /// @param amount Lending amount with protocol fee factored in
  /// @return uint Maximum value user can lend with protocol fee considered
  function hypotheticalMaxLendPV(uint amount) external view returns (uint);
  
}

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

import "@openzeppelin/contracts/token/ERC20/IERC20.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 deposit collateral to fund their borrows, where their
  /// collateral is automatically wrapped from ETH to WETH.
  /// @return uint New collateral balance (in WETH balance)
  function depositCollateralWithETH() external payable returns(uint);
  
  /// @notice Users call this to deposit collateral to fund their borrows, where their
  /// collateral is automatically wrapped from ETH into MTokens for convenience so users can
  /// automatically earn interest on their collateral.
  /// @return uint New collateral balance (in MToken balance)
  function depositCollateralWithMTokenWrapWithETH() external payable 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);
    
  /// @notice Users call this to withdraw ETH collateral, where their
  /// collateral is automatically unwrapped from WETH for convenience.
  /// @param amount Amount to withdraw (in WETH local currency)
  /// @return uint New collateral balance (in WETH balance)
  function withdrawCollateralWithETH(uint amount) external returns(uint);
  
  /// @notice Users call this to withdraw mToken collateral, where their
  /// collateral is automatically unwrapped into ETH for convenience.
  /// @param amount Amount to withdraw (in WETH local currency)
  /// @return uint New collateral balance (in MToken balance)
  function withdrawCollateralWithMTokenWrapWithETH(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 Get the address of the `QPriceOracle` contract
  /// @return address Address of `QPriceOracle` contract
  function qPriceOracle() external view returns(address);

  /// @notice Get all enabled `Asset`s
  /// @return address[] iterable list of enabled `Asset`s
  function allAssets() external view returns(address[] memory);
  
  /// @notice Gets the `CollateralFactor` associated with a ERC20 token
  /// @param token ERC20 token
  /// @return uint Collateral Factor, scaled by 1e8
  function collateralFactor(IERC20 token) external view returns(uint);

  /// @notice Gets the `MarketFactor` associated with a ERC20 token
  /// @param token ERC20 token
  /// @return uint Market Factor, scaled by 1e8
  function marketFactor(IERC20 token) external view returns(uint);
  
  /// @notice Return what the collateral ratio for an account would be
  /// with a hypothetical collateral withdraw/deposit and/or token borrow/lend.
  /// 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 hypotheticalToken Currency of hypothetical withdraw / deposit
  /// @param withdrawAmount Amount of hypothetical withdraw in local currency
  /// @param depositAmount Amount of hypothetical deposit in local currency
  /// @param hypotheticalMarket Market of hypothetical borrow
  /// @param borrowAmount Amount of hypothetical borrow in local ccy
  /// @param lendAmount Amount of hypothetical lend in local ccy
  /// @return uint Hypothetical collateral ratio
  function hypotheticalCollateralRatio(
                                       address account,
                                       IERC20 hypotheticalToken,
                                       uint withdrawAmount,
                                       uint depositAmount,
                                       IFixedRateMarket hypotheticalMarket,
                                       uint borrowAmount,
                                       uint lendAmount
                                       ) 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, scaled to 1e18
  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, scaled to 1e18
  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, scaled to 1e18
  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, scaled to 1e18
  function virtualBorrowValueByMarket(
                                      address account,
                                      IFixedRateMarket market
                                      ) external view returns(uint);

  /// @notice Return what the weighted total borrow value for an account would be with a hypothetical borrow  
  /// @param account Account to query
  /// @param hypotheticalMarket Market of hypothetical borrow / lend
  /// @param borrowAmount Amount of hypothetical borrow in local ccy
  /// @param lendAmount Amount of hypothetical lend in local ccy
  /// @return uint Borrow value of account in USD, scaled to 1e18
  function hypotheticalVirtualBorrowValue(
                                          address account,
                                          IFixedRateMarket hypotheticalMarket,
                                          uint borrowAmount,
                                          uint lendAmount
                                          ) 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, scaled to 1e18
  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, scaled to 1e18
  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, scaled to 1e18
  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, scaled to 1e18
  function realBorrowValueByMarket(
                                   address account,
                                   IFixedRateMarket market
                                   ) external view returns(uint);
  
  /// @notice Get an account's maximum available borrow amount in a specific FixedRateMarket.
  /// For example, what is the maximum amount of GLMRJUL22 that an account can borrow
  /// while ensuring their account health continues to be acceptable?
  /// Note: This function will return 0 if market to borrow is disabled
  /// Note: This function will return creditLimit() if maximum amount allowed for one market exceeds creditLimit()
  /// Note: User can only borrow up to `initCollateralRatio` for their own protection against instant liquidations
  /// @param account User account
  /// @param borrowMarket Address of the `FixedRateMarket` market to borrow
  /// @return uint Maximum available amount user can borrow (in FV) without breaching `initCollateralRatio`
  function hypotheticalMaxBorrowFV(address account, IFixedRateMarket borrowMarket) 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 minimum collateral ratio for a user account. Scaled by 1e8.
  /// @param account User account 
  /// @return uint Minimum collateral ratio
  function minCollateralRatio(address account) 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 initial collateral ratio for a user account. Scaled by 1e8
  /// @param account User account 
  /// @return uint Initial collateral ratio
  function initCollateralRatio(address account) 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, scaled to 1e18
  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);
}

//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.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);
  
  /// @notice Get the address of the `QAdmin` contract
  /// @return address Address of `QAdmin` contract
  function qAdmin() external view returns(address);
}

//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

interface ITradingEmissionsQontroller {

  /** ACCESS CONTROLLED FUNCTIONS **/
  
  /// @notice Use the fees generated (in USD) as basis to calculate how much
  /// token reward to disburse for trading volumes. Only `FixedRateMarket`
  /// contracts may call this function.
  /// @param borrower Address of the borrower
  /// @param lender Address of the lender
  /// @param feeUSD Fees generated (in USD, scaled to 1e18)
  function updateRewards(address borrower, address lender, uint feeUSD) external;

  
  /** USER INTERFACE **/

  /// @notice Mint the unclaimed rewards to user and reset their claimable emissions
  function claimEmissions() external;

  
  /** VIEW FUNCTIONS **/

  /// @notice Checks the amount of unclaimed trading rewards that the user can claim
  /// @param account Address of the user
  /// @return uint Amount of QODA token rewards the user may claim
  function claimableEmissions(address account) external view returns(uint);

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

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

  function numPhases() external view returns(uint);

  function currentPhase() external view returns(uint);

  function totalAllocation() external view returns(uint);

  function emissionsPhase(uint phase) external view returns(uint, uint, uint);
  
}

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

import "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.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 existing `Asset` is removed
  event RemoveAsset(address indexed tokenAddress);
  
  /// @notice Emitted when setting `_weth`
  event SetWETH(address wethAddress);

  /// @notice Emitted when setting `_qollateralManager`
  event SetQollateralManager(address qollateralManagerAddress);

  /// @notice Emitted when setting `_stakingEmissionsQontroller`
  event SetStakingEmissionsQontroller(address stakingEmissionsQontrollerAddress);

  /// @notice Emitted when setting `_tradingEmissionsQontroller`
  event SetTradingEmissionsQontroller(address tradingEmissionsQontrollerAddress);

  /// @notice Emitted when setting `_feeEmissionsQontroller`
  event SetFeeEmissionsQontroller(address feeEmissionsQontrollerAddress);

  /// @notice Emitted when setting `_veQoda`
  event SetVeQoda(address veQodaAddress);
  
  /// @notice Emitted when setting `_qodaLens`
  event SetQodaLens(address qodaLensAddress);
  
  /// @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 `_minCollateralRatioDefault` and `_initCollateralRatioDefault` get updated
  event SetCollateralRatio(uint oldMinValue, uint oldInitValue, uint newMinValue, uint newInitValue);
  
  /// @notice Emitted when `CreditFacility` gets updated
  event SetCreditFacility(address account, bool oldEnabled, uint oldMinValue, uint oldInitValue, uint oldCreditValue, bool newEnabled, uint newMinValue, uint newInitValue, uint newCreditValue);
  
  /// @notice Emitted when `_closeFactor` gets updated
  event SetCloseFactor(uint oldValue, uint newValue);

  /// @notice Emitted when `_repaymentGracePeriod` gets updated
  event SetRepaymentGracePeriod(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);
  
  /// @notice Emitted when pause state of all `FixedRateMarket` contract is changed
  event SetMarketPaused(bool paused);
  
  /// @notice Emitted when pause state of a particular contract is changed
  event SetContractPaused(address contractAddr, bool paused);
  
  /// @notice Emitted when pause state of a particular operation is changed
  event SetOperationPaused(uint operationId, bool paused);
  
  /** ADMIN FUNCTIONS **/

  /// @notice Call upon initialization after deploying `QAdmin` contract
  /// @param wethAddress Address of `WETH` contract of the network 
  function _setWETH(address wethAddress) external;
  
  /// @notice Call upon initialization after deploying `QollateralManager` contract
  /// @param qollateralManagerAddress Address of `QollateralManager` deployment
  function _setQollateralManager(address qollateralManagerAddress) external;

  /// @notice Call upon initialization after deploying `StakingEmissionsQontroller` contract
  /// @param stakingEmissionsQontrollerAddress Address of `StakingEmissionsQontroller` deployment
  function _setStakingEmissionsQontroller(address stakingEmissionsQontrollerAddress) external;

  /// @notice Call upon initialization after deploying `TradingEmissionsQontroller` contract
  /// @param tradingEmissionsQontrollerAddress Address of `TradingEmissionsQontroller` deployment
  function _setTradingEmissionsQontroller(address tradingEmissionsQontrollerAddress) external;

  /// @notice Call upon initialization after deploying `FeeEmissionsQontroller` contract
  /// @param feeEmissionsQontrollerAddress Address of `FeeEmissionsQontroller` deployment
  function _setFeeEmissionsQontroller(address feeEmissionsQontrollerAddress) external;

  /// @notice Call upon initialization after deploying `veQoda` contract
  /// @param veQodaAddress Address of `veQoda` deployment
  function _setVeQoda(address veQodaAddress) external;
  
  /// @notice Call upon initialization after deploying `QodaLens` contract
  /// @param qodaLensAddress Address of `QodaLens` deployment
  function _setQodaLens(address qodaLensAddress) external;
  
  /// @notice Set credit facility for specified account
  /// @param account_ account for credit facility adjustment
  /// @param enabled_ If credit facility should be enabled
  /// @param minCollateralRatio_ New minimum collateral ratio value
  /// @param initCollateralRatio_ New initial collateral ratio value
  /// @param creditLimit_ new credit limit in USD, scaled by 1e18
  function _setCreditFacility(address account_, bool enabled_, uint minCollateralRatio_, uint initCollateralRatio_, uint creditLimit_) 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 tokenAddress 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(
                     address tokenAddress,
                     bool isYieldBearing,
                     address underlying,
                     address oracleFeed,
                     uint collateralFactor,
                     uint marketFactor
                     ) external;
  
  /// @notice Admin function for removing an asset
  /// @param token ERC20 token corresponding to the Asset
  function _removeAsset(IERC20 token) external;

  /// @notice Adds a new `FixedRateMarket` contract into the internal mapping of
  /// whitelisted market addresses
  /// @param marketAddress New `FixedRateMarket` contract address
  /// @param protocolFee_ Corresponding protocol fee in basis points
  /// @param minQuoteSize_ Size in PV terms, local currency
  function _addFixedRateMarket(
                               address marketAddress,
                               uint protocolFee_,
                               uint minQuoteSize_
                               ) 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 marketAddress Address of the `FixedRateMarket` contract
  /// @param minQuoteSize_ Size in PV terms, local currency
  function _setMinQuoteSize(address marketAddress, uint minQuoteSize_) external;
  
  /// @notice Set the global minimum and initial collateral ratio
  /// @param minCollateralRatio_ New global minimum collateral ratio value
  /// @param initCollateralRatio_ New global initial collateral ratio value
  function _setCollateralRatio(uint minCollateralRatio_, uint initCollateralRatio_) external;
  
  /// @notice Set the global close factor
  /// @param closeFactor_ New close factor value
  function _setCloseFactor(uint closeFactor_) external;

  /// @notice Set the global repayment grace period
  /// @param repaymentGracePeriod_ New repayment grace period
  function _setRepaymentGracePeriod(uint repaymentGracePeriod_) external;

  /// @notice Set the global maturity grace period
  /// @param maturityGracePeriod_ New maturity grace period
  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 for each market in basis points
  /// @param marketAddress Address of the `FixedRateMarket` contract
  /// @param protocolFee_ New protocol fee value (scaled to 1e4)
  function _setProtocolFee(address marketAddress, uint protocolFee_) external;
  
  /// @notice Set the global threshold in USD for protocol fee transfer
  /// @param thresholdUSD_ New threshold USD value (scaled by 1e6)
  function _setThresholdUSD(uint thresholdUSD_) external;
  
  /// @notice Pause/unpause all markets for admin
  /// @param paused Boolean to indicate if all markets should be paused
  function _setMarketsPaused(bool paused) external;
  
  /// @notice Pause/unpause specified list of contracts for admin
  /// @param contractsAddr List of contract addresses to pause/unpause
  /// @param paused Boolean to indicate if specified contract should be paused
  function _setContractPaused(address[] memory contractsAddr, bool paused) external;
  
  /// @notice Pause/unpause specified contract for admin
  /// @param contractAddr Address of contract to pause/unpause
  /// @param paused Boolean to indicate if specified contract should be paused
  function _setContractPaused(address contractAddr, bool paused) external;
  
  /// @notice Pause/unpause specified list of operations for admin
  /// @param operationIds List of ids for operation to pause/unpause
  /// @param paused Boolean to indicate if specified operation should be paused
  function _setOperationPaused(uint[] memory operationIds, bool paused) external;
  
  /// @notice Pause/unpause specified operation for admin
  /// @param operationId Id for operation to pause/unpause
  /// @param paused Boolean to indicate if specified operation should be paused
  function _setOperationPaused(uint operationId, bool paused) external;
  
  /** VIEW FUNCTIONS **/

  function ADMIN_ROLE() external view returns(bytes32);

  function MARKET_ROLE() external view returns(bytes32);

  function MINTER_ROLE() external view returns(bytes32);

  function VETOKEN_ROLE() external view returns(bytes32);
  
  /// @notice Get the address of the `WETH` contract
  function WETH() external view returns(address);
  
  /// @notice Get the address of the `QollateralManager` contract
  function qollateralManager() external view returns(address);

  /// @notice Get the address of the `QPriceOracle` contract
  function qPriceOracle() external view returns(address);

  /// @notice Get the address of the `StakingEmissionsQontroller` contract
  function stakingEmissionsQontroller() external view returns(address);

  /// @notice Get the address of the `TradingEmissionsQontroller` contract
  function tradingEmissionsQontroller() external view returns(address);

  /// @notice Get the address of the `FeeEmissionsQontroller` contract
  function feeEmissionsQontroller() external view returns(address);

  /// @notice Get the address of the `veQoda` contract
  function veQoda() external view returns(address);
  
  /// @notice Get the address of the `QodaLens` contract
  function qodaLens() external view returns(address);

  /// @notice Get the credit limit with associated address, scaled by 1e18
  function creditLimit(address account_) external view returns(uint);
  
  /// @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 all enabled `Asset`s
  /// @return address[] iterable list of enabled `Asset`s
  function allAssets() external view returns(address[] memory);

  /// @notice Gets the `oracleFeed` associated with a ERC20 token
  /// @param token ERC20 token
  /// @return address Address of the oracle feed
  function oracleFeed(IERC20 token) external view returns(address);
  
  /// @notice Gets the `CollateralFactor` associated with a ERC20 token
  /// @param token ERC20 token
  /// @return uint Collateral Factor, scaled by 1e8
  function collateralFactor(IERC20 token) external view returns(uint);

  /// @notice Gets the `MarketFactor` associated with a ERC20 token
  /// @param token ERC20 token
  /// @return uint Market Factor, scaled by 1e8
  function marketFactor(IERC20 token) external view returns(uint);

  /// @notice Gets the `maturities` associated with a ERC20 token
  /// @param token ERC20 token
  /// @return uint[] array of UNIX timestamps (in seconds) of the maturity dates
  function maturities(IERC20 token) external view returns(uint[] 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 address Address of `FixedRateMarket` contract
  function fixedRateMarkets(IERC20 token, uint maturity) external view returns(address);

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

  function minQuoteSize(address marketAddress) external view returns(uint);
  
  function minCollateralRatio() external view returns(uint);
  
  function minCollateralRatio(address account) external view returns(uint);
  
  function initCollateralRatio() external view returns(uint);
  
  function initCollateralRatio(address account) external view returns(uint);
  
  function closeFactor() external view returns(uint);

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

  /// @notice Annualized protocol fee in basis points, scaled by 1e4
  function protocolFee(address marketAddress) external view returns(uint);

  /// @notice threshold in USD where protocol fee from each market will be transferred into `FeeEmissionsQontroller`
  /// once this amount is reached, scaled by 1e6
  function thresholdUSD() external view returns(uint);
  
  /// @notice Boolean to indicate if all markets are paused
  function marketsPaused() external view returns(bool);
  
  /// @notice Boolean to indicate if specified contract address is paused
  function contractPaused(address contractAddr) external view returns(bool);
  
  /// @notice Boolean to indicate if specified operation is paused
  function operationPaused(uint operationId) external view returns(bool);
  
  /// @notice Check if given combination of contract address and operation should be allowed
  function isPaused(address contractAddr, uint operationId) external view returns(bool);
  
  /// @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 USD
  function MANTISSA_USD() 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 Staked Qoda has 6 decimal place precision
  function MANTISSA_STAKING() 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);

  /// @notice version number of this contract, will be bumped upon contractual change
  function VERSION_NUMBER() external pure returns(string memory);
}

//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

import "../libraries/QTypes.sol";

interface IQuoteManager {
  
  /// @notice Emitted when an account creates a new `Quote`
  event CreateQuote(
                    uint8 indexed side,
                    address indexed quoter,
                    uint64 id,
                    uint8 quoteType,
                    uint64 APR,
                    uint cashflow
                    );
  
  /// @notice Emitted when a `Quote` is filled and/or cancelled
  event RemoveQuote(
                    address indexed quoter,
                    bool isUserCanceled,
                    uint8 side,
                    uint64 id,
                    uint8 quoteType,
                    uint64 APR,
                    uint cashflow,
                    uint filled
                    );
  
  /** USER INTERFACE **/
    
  /// @notice Creates a new  `Quote` and adds it to the `OrderbookSide` linked list by side
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param quoter Account of the Quoter
  /// @param quoteType 0 for PV+APR, 1 for FV+APR
  /// @param APR In decimal form scaled by 1e4 (ex. 1052 = 10.52%)
  /// @param cashflow Can be PV or FV depending on `quoteType`
  function createQuote(uint8 side, address quoter, uint8 quoteType, uint64 APR, uint cashflow) external;
    
  /// @notice Cancel `Quote` by id. Note this is a O(1) operation
  /// since `OrderbookSide` uses hashmaps under the hood. However, it is
  /// O(n) against the array of `Quote` ids by account so we should ensure
  /// that array should not grow too large in practice.
  /// @param isUserCanceled True if user actively canceled `Quote`, false otherwise
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param quoter Address of the `Quoter`
  /// @param id Id of the `Quote`
  function cancelQuote(bool isUserCanceled, uint8 side, address quoter, uint64 id) external;
    
  /// @notice Fill existing `Quote` by side and id
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param id Id of the `Quote`
  /// @param amount Amount to be filled
  function fillQuote(uint8 side, uint64 id, uint amount) external;
    
  /** VIEW FUNCTIONS **/
  
  /// @notice Get the address of the `QAdmin`
  /// @return address
  function qAdmin() external view returns(address);
  
  /// @notice Get the address of the `FixedRateMarket`
  /// @return address
  function fixedRateMarket() external view returns(address);
    
  /// @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 Get the linked list pointer top of book for `Quote` by side
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @return uint64 id of top of book `Quote` 
  function getQuoteHeadId(uint8 side) external view returns(uint64);

  /// @notice Get the top of book for `Quote` by side
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @return QTypes.Quote head `Quote`
  function getQuoteHead(uint8 side) external view returns(QTypes.Quote memory);
  
  /// @notice Get the `Quote` for the given `side` and `id`
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param id Id of `Quote`
  /// @return QTypes.Quote `Quote` associated with the id
  function getQuote(uint8 side, uint64 id) external view returns(QTypes.Quote memory);

  /// @notice Get all live `Quote` id's by `account` and `side`
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param account Account to query
  /// @return uint[] Unsorted array of borrow `Quote` id's
  function getAccountQuotes(uint8 side, address account) external view returns(uint64[] memory);

  /// @notice Get the number of active `Quote`s by `side` in the orderbook
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @return uint Number of `Quote`s
  function getNumQuotes(uint8 side) external view returns(uint);
  
  /// @notice Checks whether a `Quote` is still valid. Importantly, for lenders,
  /// we need to check if the `Quoter` currently has enough balance to perform
  /// a lend, since the `Quoter` can always remove balance/allowance immediately
  /// after creating the `Quote`. Likewise, for borrowers, we need to check if
  /// the `Quoter` has enough collateral to perform a borrow, since the `Quoter`
  /// can always remove collateral immediately after creating the `Quote`.
  /// @param side 0 for borrow `Quote`, 1 for lend `Quote`
  /// @param quote `Quote` to check for validity
  /// @return bool True if valid false otherwise
  function isQuoteValid(uint8 side, QTypes.Quote memory quote) external view returns(bool);
  
  /// @notice Get the PV of a cashflow amount based on the `quoteType`
  /// @param quoteType 0 for PV, 1 for FV
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param sTime PV start time
  /// @param eTime FV end time
  /// @param amount Value to be PV'ed
  /// @return uint PV of the `amount`
  function getPV(
                 uint8 quoteType,
                 uint64 APR,
                 uint amount,
                 uint sTime,
                 uint eTime
                 ) external view returns(uint);

  /// @notice Get the FV of a cashflow amount based on the `quoteType`
  /// @param quoteType 0 for PV, 1 for FV
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param sTime PV start time
  /// @param eTime FV end time
  /// @param amount Value to be FV'ed
  /// @return uint FV of the `amount`
  function getFV(
                 uint8 quoteType,
                 uint64 APR,
                 uint amount,
                 uint sTime,
                 uint eTime
                 ) external view returns(uint);
}

//SPDX-License-Identifier: NONE
pragma solidity ^0.8.9;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

/// @title Interface for WETH9
interface IWETH is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

library Interest {

  function PVToFV(
                  uint64 APR,
                  uint PV,
                  uint sTime,
                  uint eTime,
                  uint mantissaAPR
                  ) internal pure returns(uint){

    require(sTime < eTime, "invalid time interval");

    // Seconds per 365-day year (60 * 60 * 24 * 365)
    uint year = 31536000;
    
    // elapsed time from now to maturity
    uint elapsed = eTime - sTime;

    uint interest = PV * APR * elapsed / mantissaAPR / year;

    return PV + interest;    
  }

  function FVToPV(
                  uint64 APR,
                  uint FV,
                  uint sTime,
                  uint eTime,
                  uint mantissaAPR
                  ) internal pure returns(uint){

    require(sTime < eTime, "invalid time interval");

    // Seconds per 365-day year (60 * 60 * 24 * 365)
    uint year = 31536000;
    
    // elapsed time from now to maturity
    uint elapsed = eTime - sTime;

    uint num = FV * mantissaAPR * year;
    uint denom = mantissaAPR * year + APR * elapsed;

    return num / denom;
    
  }  
}

//SPDX-License-Identifier: NONE
pragma solidity ^0.8.9;

import "./QTypes.sol";

library LinkedList {

  struct OrderbookSide {
    uint64 head;
    uint64 tail;
    uint64 idCounter;
    uint64 length;
    mapping(uint64 => QTypes.Quote) quotes;
  }

    
  /// @notice Get the `Quote` with id `id`
  function get(OrderbookSide storage self, uint64 id) internal view returns(QTypes.Quote memory){
    QTypes.Quote memory quote = self.quotes[id];
    return quote;
  }
    
  /// @notice Insert a new `Quote` as the new head of the linked list
  /// @return uint64 Id of the new `Quote`
  function addHead(
                   OrderbookSide storage self,
                   address quoter,
                   uint8 quoteType,
                   uint64 APR,
                   uint cashflow                    
                   ) internal returns(uint64){

    // Create a new unlinked object representing the new head
    QTypes.Quote memory newQuote = createQuote(self, quoter, quoteType, APR, cashflow);

    // Link `newQuote` before the current head
    link(self, newQuote.id, self.head);

    // Set the head pointer to `newQuote`
    setHeadId(self, newQuote.id);

    if(self.tail == 0) {
      // `OrderbookSide` is currently empty, so set tail = head
      setTailId(self, newQuote.id);
    }

    return newQuote.id;
  }

  /// @notice Insert a new `Quote` as the tail of the linked list
  /// @return uint64 Id of the new `Quote`
  function addTail(
                   OrderbookSide storage self,
                   address quoter,
                   uint8 quoteType,
                   uint64 APR,
                   uint cashflow
                   ) internal returns(uint64) {
    
    if (self.head == 0) {

      // `OrderbookSide` is currently empty, so set head = tail
      return addHead(self, quoter, quoteType, APR, cashflow);

    } else {

      // Create a new unlinked object representing the new tail
      QTypes.Quote memory newQuote = createQuote(self, quoter, quoteType, APR, cashflow);

      // Link `newQuote` after the current tail
      link(self, self.tail, newQuote.id);

      // Set the tail pointer to `newQuote`
      setTailId(self, newQuote.id);

      return newQuote.id;
    }    
  }


  /// @notice Remove the `Quote` with id `id` from the linked list
  function remove(OrderbookSide storage self, uint64 id) internal {

    QTypes.Quote memory quoteToRemove = self.quotes[id];

    if(self.head == id && self.tail == id) {
      // `OrderbookSide` only has one element. Reset both head and tail pointers
      setHeadId(self, 0);
      setTailId(self, 0);
    } else if (self.head == id) {
      // `quoteToRemove` is the current head, so set the next item in the linked list to be head
      setHeadId(self, quoteToRemove.next);
      self.quotes[quoteToRemove.next].prev = 0;
    } else if (self.tail == id) {
      // `quoteToRemove` is the current tail, so set the prev item in the linked list to be tail
      setTailId(self, quoteToRemove.prev);
      self.quotes[quoteToRemove.prev].next = 0;
    } else {
      // Link the `Quote`s before and after `quoteToRemove` together
      link(self, quoteToRemove.prev, quoteToRemove.next);
    }

    // Ready to delete `quoteToRemove`
    delete self.quotes[quoteToRemove.id];

    // Decrement the length of the `OrderbookSide`
    self.length--;
  }
  
  /// @notice Insert a new `Quote` after the `Quote` with id `prev`
  /// @return uint64 Id of the new `Quote`
  function insertAfter(
                       OrderbookSide storage self,
                       uint64 prev,
                       address quoter,
                       uint8 quoteType,
                       uint64 APR,
                       uint cashflow
                       ) internal returns(uint64){
    
    if(prev == self.tail) {     

      // Prev element is the tail, make this `Quote` the new tail
      return addTail(self, quoter, quoteType, APR, cashflow);
            
    } else {

      // Create a new unlinked object representing the new `Quote`
      QTypes.Quote memory newQuote = createQuote(self, quoter, quoteType, APR, cashflow);

      // Get the `Quote`s before and after `newQuote`
      QTypes.Quote memory prevQuote = self.quotes[prev];      
      QTypes.Quote memory nextQuote = self.quotes[prevQuote.next];

      // Insert the new `Quote` between `prevQuote` and `nextQuote`
      link(self, newQuote.id, nextQuote.id);
      link(self, prevQuote.id, newQuote.id);

      return newQuote.id;
    }    
  }

  /// @notice Insert a new `Quote` before the `Quote` with id `next`
  /// @return uint64 Id of the new `Quote`
  function insertBefore(
                        OrderbookSide storage self,
                        uint64 next,
                        address quoter,
                        uint8 quoteType,
                        uint64 APR,
                        uint cashflow
                        ) internal returns(uint64){

    if(next == self.head) {

      // Next element is the head, make this `Quote` the new head
      return addHead(self, quoter, quoteType, APR, cashflow);
      
    } else {

      // inserting before `next` is equivalent to inserting after `next.prev`
      return insertAfter(self, self.quotes[next].prev, quoter, quoteType, APR, cashflow);
      
    }
    
  }
                        
  /// @notice Update the pointer to head of the linked list
  function setHeadId(OrderbookSide storage self, uint64 head) internal {
    self.head = head;
  }

  /// @notice Update the pointer to tail of the linked list
  function setTailId(OrderbookSide storage self, uint64 tail) internal {
    self.tail = tail;
  }
  
  /// @notice Create a new unlinked `Quote`
  function createQuote(
                       OrderbookSide storage self,
                       address quoter,
                       uint8 quoteType,
                       uint64 APR,
                       uint cashflow
                       ) internal returns(QTypes.Quote memory) {

    // Increment the counter for new id's.
    // Note this means non-empty linked lists start with id = 1
    self.idCounter = self.idCounter + 1;    
    
    // Create a new unlinked `Quote` with the latest `idCounter`
    QTypes.Quote memory newQuote = QTypes.Quote(self.idCounter, 0, 0, quoter, quoteType, APR, cashflow, 0);
    
    // Add the `Quote` to the internal mapping of `Quote`s
    self.quotes[newQuote.id] = newQuote;
    
    // Increment the length of the `OrderbookSide`
    self.length++;
    
    return newQuote;
  }

  /// @notice Link two `Quote`s together
  function link(
                OrderbookSide storage self,
                uint64 prev,
                uint64 next
                ) internal {
    
    self.quotes[prev].next = next;
    self.quotes[next].prev = prev;
    
  }
  
}

File 18 of 25 : 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 created Quote
  /// @param id ID of the quote
  /// @param next Next quote in the list
  /// @param prev Previous quote in the list
  /// @param quoter Account of the Quoter
  /// @param quoteType 0 for PV+APR, 1 for FV+APR
  /// @param APR In decimal form scaled by 1e4 (ex. 10.52% = 1052)
  /// @param cashflow Can be PV or FV depending on `quoteType`
  /// @param filled Amount quote has got filled partially 
  struct Quote {
    uint64 id;
    uint64 next;
    uint64 prev;
    address quoter;
    uint8 quoteType;
    uint64 APR;
    uint cashflow;
    uint filled;
  }
  
  /// @notice Contains all the configurations customizable to an address
  /// @member enabled If config for an address is enabled. When enabled is false, credit limit is infinite even if value is 0
  /// @member minCollateralRatio If collateral ratio falls below `_minCollateralRatio`, it is subject to liquidation. Scaled by 1e8
  /// @member initCollateralRatio When initially taking a loan, collateral ratio must be higher than this. `initCollateralRatio` should always be higher than `minCollateralRatio`. Scaled by 1e8
  /// @member creditLimit Allowed limit in virtual USD for each address to do uncollateralized borrow, scaled by 1e18
  struct CreditFacility {
    bool enabled;
    uint minCollateralRatio;
    uint initCollateralRatio;
    uint creditLimit;
  }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

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

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

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

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

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

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [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 Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(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
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

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

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

Contract Security Audit

Contract ABI

API
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"quoteSide","type":"uint8"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalExecutedPV","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalExecutedFV","type":"uint256"}],"name":"ExecMarketOrder","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"quoteSide","type":"uint8"},{"indexed":true,"internalType":"address","name":"borrower","type":"address"},{"indexed":true,"internalType":"address","name":"lender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountPV","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountFV","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"feeIncurred","type":"uint256"},{"indexed":false,"internalType":"uint64","name":"APR","type":"uint64"}],"name":"FixedRateLoan","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":"borrower","type":"address"},{"indexed":true,"internalType":"address","name":"liquidator","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"address","name":"collateralTokenAddr","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"LiquidateBorrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"RedeemQTokens","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"bool","name":"withQTokens","type":"bool"}],"name":"RepayBorrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"quoteManagerAddress","type":"address"}],"name":"SetQuoteManager","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"quoteManagerAddress","type":"address"}],"name":"_setQuoteManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"accountBorrows","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountPV","type":"uint256"},{"internalType":"uint64","name":"maxAPR","type":"uint64"}],"name":"borrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountPV","type":"uint256"},{"internalType":"uint64","name":"maxAPR","type":"uint64"}],"name":"borrowETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"side","type":"uint8"},{"internalType":"uint64","name":"id","type":"uint64"}],"name":"cancelQuote","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"side","type":"uint8"},{"internalType":"uint8","name":"quoteType","type":"uint8"},{"internalType":"uint64","name":"APR","type":"uint64"},{"internalType":"uint256","name":"cashflow","type":"uint256"}],"name":"createQuote","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"side","type":"uint8"},{"internalType":"address","name":"account","type":"address"}],"name":"getAccountQuotes","outputs":[{"internalType":"uint64[]","name":"","type":"uint64[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"quoteType","type":"uint8"},{"internalType":"uint64","name":"APR","type":"uint64"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"sTime","type":"uint256"},{"internalType":"uint256","name":"eTime","type":"uint256"}],"name":"getFV","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"side","type":"uint8"}],"name":"getNumQuotes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"quoteType","type":"uint8"},{"internalType":"uint64","name":"APR","type":"uint64"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"sTime","type":"uint256"},{"internalType":"uint256","name":"eTime","type":"uint256"}],"name":"getPV","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"side","type":"uint8"},{"internalType":"uint64","name":"id","type":"uint64"}],"name":"getQuote","outputs":[{"components":[{"internalType":"uint64","name":"id","type":"uint64"},{"internalType":"uint64","name":"next","type":"uint64"},{"internalType":"uint64","name":"prev","type":"uint64"},{"internalType":"address","name":"quoter","type":"address"},{"internalType":"uint8","name":"quoteType","type":"uint8"},{"internalType":"uint64","name":"APR","type":"uint64"},{"internalType":"uint256","name":"cashflow","type":"uint256"},{"internalType":"uint256","name":"filled","type":"uint256"}],"internalType":"struct QTypes.Quote","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"side","type":"uint8"}],"name":"getQuoteHead","outputs":[{"components":[{"internalType":"uint64","name":"id","type":"uint64"},{"internalType":"uint64","name":"next","type":"uint64"},{"internalType":"uint64","name":"prev","type":"uint64"},{"internalType":"address","name":"quoter","type":"address"},{"internalType":"uint8","name":"quoteType","type":"uint8"},{"internalType":"uint64","name":"APR","type":"uint64"},{"internalType":"uint256","name":"cashflow","type":"uint256"},{"internalType":"uint256","name":"filled","type":"uint256"}],"internalType":"struct QTypes.Quote","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"side","type":"uint8"}],"name":"getQuoteHeadId","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"hypotheticalMaxLendPV","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"qAdminAddr_","type":"address"},{"internalType":"address","name":"underlyingAddr_","type":"address"},{"internalType":"uint256","name":"maturity_","type":"uint256"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountPV","type":"uint256"},{"internalType":"uint64","name":"minAPR","type":"uint64"}],"name":"lend","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"minAPR","type":"uint64"}],"name":"lendETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"contract IERC20","name":"collateralToken","type":"address"}],"name":"liquidateBorrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"maturity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minQuoteSize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"proratedProtocolFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"proratedProtocolFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"qAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"qollateralManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"quoteManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"redeemAllQTokensByRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"redeemAllQTokensByRatioWithETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"redeemQTokensByRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"redeemQTokensByRatioWithETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"redeemableQTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"redeemableQTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"redemptionRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"repayBorrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"repayBorrowWithETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokensRedeemedTotal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAccruedFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"underlyingToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]

0x608060405234801561001057600080fd5b50615feb80620000216000396000f3fe6080604052600436106102b15760003560e01c80638082a0b211610175578063c188063e116100dc578063d897c5a011610095578063e7675c511161006f578063e7675c511461084e578063eb0ca4551461086e578063f5e3c4621461088e578063fe5bb3f9146108ae57600080fd5b8063d897c5a0146107f9578063dd62ed3e14610819578063de987d501461083957600080fd5b8063c188063e1461074a578063cc774e9414610752578063ce0746c414610772578063ce40130814610787578063d40e8f4a146107a5578063d6329955146107db57600080fd5b80639c5bf6331161012e5780639c5bf633146106b6578063a457c2d7146106cb578063a9059cbb146106eb578063ae9f4cd91461070b578063b0e21e8a14610720578063ba95534c1461073557600080fd5b80638082a0b2146106015780638a7af74e146106215780638c88f42b146106415780638cf226c01461066157806395d89b41146106815780639ab8367e1461069657600080fd5b8063260122e3116102195780633f1f4155116101d25780633f1f41551461053457806342c806ed146105545780634b57a8d1146105815780635f2ead68146105a15780635fac60b8146105b657806370a08231146105cb57600080fd5b8063260122e314610448578063313ce567146104685780633288b2ec1461048f57806333f5419b146104bc578063370ed288146104dc578063395093511461051457600080fd5b80631264bfbf1161026b5780631264bfbf1461038c5780631639f418146103ac57806318160ddd146103cc578063204f83f9146103e157806323b872dd146103f65780632495a5991461041657600080fd5b8062ec04cd146102bd57806302dcd07f146102d257806303d930f6146102fa57806306fdde031461031a578063095ea7b31461033c5780630e7527021461036c57600080fd5b366102b857005b600080fd5b6102d06102cb366004615546565b6108ce565b005b3480156102de57600080fd5b506102e7610a7a565b6040519081526020015b60405180910390f35b34801561030657600080fd5b506102d0610315366004615572565b610a8a565b34801561032657600080fd5b5061032f610b14565b6040516102f191906155e7565b34801561034857600080fd5b5061035c61035736600461562f565b610ba6565b60405190151581526020016102f1565b34801561037857600080fd5b506102e761038736600461565b565b610c4f565b34801561039857600080fd5b506102e76103a7366004615674565b610d23565b3480156103b857600080fd5b506102e76103c736600461565b565b610dc2565b3480156103d857600080fd5b506035546102e7565b3480156103ed57600080fd5b506099546102e7565b34801561040257600080fd5b5061035c6104113660046156c5565b610f2c565b34801561042257600080fd5b506098546001600160a01b03165b6040516001600160a01b0390911681526020016102f1565b34801561045457600080fd5b506102e7610463366004615706565b610fd7565b34801561047457600080fd5b5061047d61104d565b60405160ff90911681526020016102f1565b34801561049b57600080fd5b506104af6104aa366004615723565b6110bb565b6040516102f1919061575c565b3480156104c857600080fd5b506102e76104d73660046157a9565b61113e565b3480156104e857600080fd5b506104fc6104f7366004615706565b611237565b6040516001600160401b0390911681526020016102f1565b34801561052057600080fd5b5061035c61052f36600461562f565b6112a7565b34801561054057600080fd5b506102d061054f3660046157cb565b611348565b34801561056057600080fd5b5061057461056f366004615706565b6114ad565b6040516102f19190615852565b34801561058d57600080fd5b506102e761059c3660046157cb565b611525565b3480156105ad57600080fd5b50610430611530565b3480156105c257600080fd5b506102e761159e565b3480156105d757600080fd5b506102e76105e63660046157cb565b6001600160a01b031660009081526033602052604090205490565b34801561060d57600080fd5b506102e761061c366004615674565b61160b565b34801561062d57600080fd5b506102d061063c366004615861565b611663565b34801561064d57600080fd5b506102d061065c366004615861565b6117cf565b34801561066d57600080fd5b506102e761067c36600461565b565b611897565b34801561068d57600080fd5b5061032f6118cc565b3480156106a257600080fd5b506102d06106b136600461593b565b6118db565b3480156106c257600080fd5b50609c546102e7565b3480156106d757600080fd5b5061035c6106e636600461562f565b611a28565b3480156106f757600080fd5b5061035c61070636600461562f565b611ac9565b34801561071757600080fd5b506102e7611b6b565b34801561072c57600080fd5b506102e7611ce8565b34801561074157600080fd5b50609d546102e7565b6102e7611daf565b34801561075e57600080fd5b506102d061076d3660046159cd565b611f47565b34801561077e57600080fd5b506102e7611fac565b34801561079357600080fd5b506097546001600160a01b0316610430565b3480156107b157600080fd5b506102e76107c03660046157cb565b6001600160a01b03166000908152609a602052604090205490565b3480156107e757600080fd5b50609e546001600160a01b0316610430565b34801561080557600080fd5b506102d0610814366004615861565b61207a565b34801561082557600080fd5b506102e76108343660046159fb565b612142565b34801561084557600080fd5b506102e761216d565b34801561085a57600080fd5b506102e761086936600461565b565b6121ee565b34801561087a57600080fd5b506105746108893660046159cd565b6122b4565b34801561089a57600080fd5b506102d06108a9366004615a19565b61233b565b3480156108ba57600080fd5b506102e76108c936600461565b565b61240d565b6002609f54036108f95760405162461bcd60e51b81526004016108f090615a5b565b60405180910390fd5b6002609f556097546040516361a2ee1f60e01b815261012e916001600160a01b0316906361a2ee1f906109329030908590600401615a7a565b602060405180830381865afa15801561094f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109739190615a93565b156109905760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109e3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a079190615ae4565b6098546001600160a01b03908116911614610a345760405162461bcd60e51b81526004016108f090615b01565b6000610a3f34611897565b90506000610a5260003384876001612419565b9050610a6f610a608261240d565b610a6a9083615b67565b61288f565b50506001609f555050565b6000610a853361293b565b905090565b609e5460405163cebcf96f60e01b815260ff8087166004830152336024830152851660448201526001600160401b0384166064820152608481018390526001600160a01b039091169063cebcf96f9060a401600060405180830381600087803b158015610af657600080fd5b505af1158015610b0a573d6000803e3d6000fd5b5050505050505050565b606060368054610b2390615b7a565b80601f0160208091040260200160405190810160405280929190818152602001828054610b4f90615b7a565b8015610b9c5780601f10610b7157610100808354040283529160200191610b9c565b820191906000526020600020905b815481529060010190602001808311610b7f57829003601f168201915b5050505050905090565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f90610bdf9030908590600401615a7a565b602060405180830381865afa158015610bfc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c209190615a93565b15610c3d5760405162461bcd60e51b81526004016108f090615ab5565b610c4784846129a6565b949350505050565b60006002609f5403610c735760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012f916001600160a01b0316906361a2ee1f90610cac9030908590600401615a7a565b602060405180830381865afa158015610cc9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ced9190615a93565b15610d0a5760405162461bcd60e51b81526004016108f090615ab5565b610d1733846000806129be565b6001609f559392505050565b609e54604051631264bfbf60e01b815260ff871660048201526001600160401b03861660248201526044810185905260648101849052608481018390526000916001600160a01b031690631264bfbf9060a4015b602060405180830381865afa158015610d94573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db89190615bb4565b9695505050505050565b60006002609f5403610de65760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610130916001600160a01b0316906361a2ee1f90610e1f9030908590600401615a7a565b602060405180830381865afa158015610e3c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e609190615a93565b15610e7d5760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ed0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef49190615ae4565b6098546001600160a01b03908116911614610f215760405162461bcd60e51b81526004016108f090615b01565b610d17836001612adf565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f90610f659030908590600401615a7a565b602060405180830381865afa158015610f82573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fa69190615a93565b15610fc35760405162461bcd60e51b81526004016108f090615ab5565b610fce858585612ce7565b95945050505050565b609e5460405163260122e360e01b815260ff831660048201526000916001600160a01b03169063260122e390602401602060405180830381865afa158015611023573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110479190615bb4565b92915050565b6098546040805163313ce56760e01b815290516000926001600160a01b03169163313ce5679160048083019260209291908290030181865afa158015611097573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a859190615bd8565b609e54604051630ca22cbb60e21b815260ff841660048201526001600160a01b0383811660248301526060921690633288b2ec90604401600060405180830381865afa15801561110f573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526111379190810190615c00565b9392505050565b600060995482106111885760405162461bcd60e51b81526020600482015260146024820152731194934c4c481b585c9ad95d08195e1c1a5c995960621b60448201526064016108f0565b60975460408051630b637aa760e21b815290516301e13380926001600160a01b031691632d8dea9c9160048083019260209291908290030181865afa1580156111d5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111f99190615bb4565b836099546112079190615cb1565b61120f611ce8565b6112199087615cc4565b6112239190615cc4565b61122d9190615cdb565b6111379190615cdb565b609e546040516306e1da5160e31b815260ff831660048201526000916001600160a01b03169063370ed28890602401602060405180830381865afa158015611283573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110479190615cfd565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f906112e09030908590600401615a7a565b602060405180830381865afa1580156112fd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113219190615a93565b1561133e5760405162461bcd60e51b81526004016108f090615ab5565b610c478484612e78565b60975460408051631d6c8e3f60e21b815290516001600160a01b03909216916391d148549183916375b238fc916004808201926020929091908290030181865afa15801561139a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113be9190615bb4565b6040516001600160e01b031960e084901b1681526004810191909152336024820152604401602060405180830381865afa158015611400573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114249190615a93565b6114595760405162461bcd60e51b81526004016108f090602080825260049082015263046524d360e41b604082015260600190565b609e80546001600160a01b0319166001600160a01b0383169081179091556040519081527fa7f4849aca702f6bead45e7075d9db5a5d4f5e123280ca2bff648e65197b6e5c9060200160405180910390a150565b6114b56154ed565b609e546040516342c806ed60e01b815260ff841660048201526001600160a01b03909116906342c806ed9060240161010060405180830381865afa158015611501573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110479190615d1a565b60006110478261293b565b60975460408051630be5d5ad60e31b815290516000926001600160a01b031691635f2ead689160048083019260209291908290030181865afa15801561157a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a859190615ae4565b60975460405162827f6760e21b81523060048201526000916001600160a01b031690630209fd9c906024015b602060405180830381865afa1580156115e7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a859190615bb4565b609e54604051634041505960e11b815260ff871660048201526001600160401b03861660248201526044810185905260648101849052608481018390526000916001600160a01b031690638082a0b29060a401610d77565b6002609f54036116855760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012d916001600160a01b0316906361a2ee1f906116be9030908590600401615a7a565b602060405180830381865afa1580156116db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116ff9190615a93565b1561171c5760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa15801561176f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117939190615ae4565b6098546001600160a01b039081169116146117c05760405162461bcd60e51b81526004016108f090615b01565b610a6f60013385856001612419565b6002609f54036117f15760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012e916001600160a01b0316906361a2ee1f9061182a9030908590600401615a7a565b602060405180830381865afa158015611847573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061186b9190615a93565b156118885760405162461bcd60e51b81526004016108f090615ab5565b610a6f60003385856000612419565b60006118a66305f5e10061240d565b6118b4906305f5e100615b67565b6118c2836305f5e100615cc4565b6110479190615cdb565b606060378054610b2390615b7a565b600054610100900460ff16158080156118fb5750600054600160ff909116105b806119155750303b158015611915575060005460ff166001145b6119785760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016108f0565b6000805460ff19166001179055801561199b576000805461ff0019166101001790555b6119a58383612e9a565b609780546001600160a01b038089166001600160a01b031992831617909255609880549288169290911691909117905560998490558015611a20576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f90611a619030908590600401615a7a565b602060405180830381865afa158015611a7e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611aa29190615a93565b15611abf5760405162461bcd60e51b81526004016108f090615ab5565b610c478484612ecb565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f90611b029030908590600401615a7a565b602060405180830381865afa158015611b1f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b439190615a93565b15611b605760405162461bcd60e51b81526004016108f090615ab5565b610c47338585612ce7565b60006002609f5403611b8f5760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610130916001600160a01b0316906361a2ee1f90611bc89030908590600401615a7a565b602060405180830381865afa158015611be5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c099190615a93565b15611c265760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015611c79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c9d9190615ae4565b6098546001600160a01b03908116911614611cca5760405162461bcd60e51b81526004016108f090615b01565b611cdd611cd63361293b565b6001612adf565b9150506001609f5590565b6000806001600160a01b0316609760009054906101000a90046001600160a01b03166001600160a01b031663791db0246040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d6b9190615ae4565b6001600160a01b031603611d7f5750600090565b609754604051632d8acc7960e21b81523060048201526001600160a01b039091169063b62b31e4906024016115ca565b60006002609f5403611dd35760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012f916001600160a01b0316906361a2ee1f90611e0c9030908590600401615a7a565b602060405180830381865afa158015611e29573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e4d9190615a93565b15611e6a5760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ebd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ee19190615ae4565b6098546001600160a01b03908116911614611f0e5760405162461bcd60e51b81526004016108f090615b01565b336000818152609a602052604081205491611f2c90346001846129be565b9050611f3b610a6a8284615cb1565b925050506001609f5590565b609e5460405163179ad3d960e01b81526001600160a01b039091169063179ad3d990611f7e90600190869033908790600401615dd8565b600060405180830381600087803b158015611f9857600080fd5b505af1158015611a20573d6000803e3d6000fd5b60006002609f5403611fd05760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610130916001600160a01b0316906361a2ee1f906120099030908590600401615a7a565b602060405180830381865afa158015612026573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061204a9190615a93565b156120675760405162461bcd60e51b81526004016108f090615ab5565b611cdd6120733361293b565b6000612adf565b6002609f540361209c5760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012d916001600160a01b0316906361a2ee1f906120d59030908590600401615a7a565b602060405180830381865afa1580156120f2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121169190615a93565b156121335760405162461bcd60e51b81526004016108f090615ab5565b610a6f60013385856000612419565b6001600160a01b03918216600090815260346020908152604080832093909416825291909152205490565b6000610a85609760009054906101000a90046001600160a01b03166001600160a01b0316630df09d256040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121e99190615bb4565b612f51565b60006002609f54036122125760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610130916001600160a01b0316906361a2ee1f9061224b9030908590600401615a7a565b602060405180830381865afa158015612268573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061228c9190615a93565b156122a95760405162461bcd60e51b81526004016108f090615ab5565b610d17836000612adf565b6122bc6154ed565b609e5460405163eb0ca45560e01b815260ff851660048201526001600160401b03841660248201526001600160a01b039091169063eb0ca4559060440161010060405180830381865afa158015612317573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111379190615d1a565b6002609f540361235d5760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610131916001600160a01b0316906361a2ee1f906123969030908590600401615a7a565b602060405180830381865afa1580156123b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123d79190615a93565b156123f45760405162461bcd60e51b81526004016108f090615ab5565b6124018484846000613010565b50506001609f55505050565b6000611047824261113e565b600080841161243a5760405162461bcd60e51b81526004016108f090615e0a565b609e546040516342c806ed60e01b815260ff8816600482015285916000916001600160a01b03909116906342c806ed9060240161010060405180830381865afa15801561248b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124af9190615d1a565b90506000805b83156128325760ff8a1660011480156124e357508260a001516001600160401b0316876001600160401b0316105b8061250f575060ff8a1615801561250f57508260a001516001600160401b0316876001600160401b0316115b6128325782516001600160401b0316156128325782606001516001600160a01b0316896001600160a01b0316036125cc57609e54602084015160405163eb0ca45560e01b815260ff8d1660048201526001600160401b0390911660248201526001600160a01b039091169063eb0ca4559060440161010060405180830381865afa1580156125a1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125c59190615d1a565b92506124b5565b609e54604051635188831b60e01b81526001600160a01b0390911690635188831b906125fe908d908790600401615e31565b602060405180830381865afa15801561261b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061263f9190615a93565b61275557600083602001519050609e60009054906101000a90046001600160a01b03166001600160a01b031663179ad3d960008d876060015188600001516040518563ffffffff1660e01b815260040161269c9493929190615dd8565b600060405180830381600087803b1580156126b657600080fd5b505af11580156126ca573d6000803e3d6000fd5b5050609e5460405163eb0ca45560e01b815260ff8f1660048201526001600160401b03851660248201526001600160a01b03909116925063eb0ca455915060440161010060405180830381865afa158015612729573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061274d9190615d1a565b9350506124b5565b6000806127698c86600001518d898c6137ad565b90925090506127788285615b67565b93506127848184615b67565b92508186111561279f576127988287615cb1565b95506127a4565b600095505b609e54602086015160405163eb0ca45560e01b815260ff8f1660048201526001600160401b0390911660248201526001600160a01b039091169063eb0ca4559060440161010060405180830381865afa158015612805573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128299190615d1a565b945050506124b5565b81156128825760408051838152602081018390526001600160a01b038b169160ff8d16917fe6eb67287c05f17552781a0a3623f567d8f7d652cea44b265174c97f54e180c4910160405180910390a35b5098975050505050505050565b34811015612938576000336128a48334615cb1565b604051600081818185875af1925050503d80600081146128e0576040519150601f19603f3d011682016040523d82523d6000602084013e6128e5565b606091505b50509050806129365760405162461bcd60e51b815260206004820152601f60248201527f46524d323520756e7375636365737366756c20455448207472616e736665720060448201526064016108f0565b505b50565b6001600160a01b038116600090815260336020526040812054600081116129655750600092915050565b6001600160a01b0383166000908152609b60205260408120549061298c6121e98385615b67565b905081811161299c576000610fce565b610fce8282615cb1565b6000336129b4818585613c50565b5060019392505050565b6001600160a01b0384166000908152609a60205260408120546129e2908590613d74565b93508115612a205783600003612a1157506001600160a01b0384166000908152609a6020526040902054610c47565b612a1b8585613d8a565b612a4e565b60008411612a405760405162461bcd60e51b81526004016108f090615e0a565b612a4e853086866000613ef0565b6001600160a01b0385166000908152609a602052604081208054869290612a76908490615cb1565b90915550506040805185815283151560208201526001600160a01b038716917f23e1d46573bb38c46bc3f95d3028aa9650e1e3a45659e5be95ab7a82caefd6f5910160405180910390a2505050506001600160a01b03166000908152609a602052604090205490565b6000808311612b305760405162461bcd60e51b815260206004820152601e60248201527f46524d3233207461726765742072656465656d20616d6f756e74203d2030000060448201526064016108f0565b609760009054906101000a90046001600160a01b03166001600160a01b031663c8b82f5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b83573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ba79190615bb4565b609954612bb49190615b67565b4211612bfd5760405162461bcd60e51b815260206004820152601860248201527746524d342063616e6e6f742072656465656d206561726c7960401b60448201526064016108f0565b612c063361293b565b831115612c555760405162461bcd60e51b815260206004820152601f60248201527f46524d323020616d6f756e74203e2072656465656d61626c65546f6b656e730060448201526064016108f0565b612c5f3384613d8a565b336000908152609b602052604081208054859290612c7e908490615b67565b9250508190555082609c6000828254612c979190615b67565b90915550612cab9050303385600086613ef0565b60405183815233907fe60e13e1fa5509002572aab753f3f827f7796b5c22d3d93fdcfba50881e997ed9060200160405180910390a25090919050565b6000609954421115612e4c57609760009054906101000a90046001600160a01b03166001600160a01b031663c8b82f5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612d46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d6a9190615bb4565b609954612d779190615b67565b4211612dc05760405162461bcd60e51b815260206004820152601860248201527746524d342063616e6e6f742072656465656d206561726c7960401b60448201526064016108f0565b6000612dcb8561293b565b905080831115612e1d5760405162461bcd60e51b815260206004820152601f60248201527f46524d323020616d6f756e74203e2072656465656d61626c65546f6b656e730060448201526064016108f0565b6001600160a01b0385166000908152609b602052604081208054859290612e45908490615b67565b9091555050505b336001600160a01b03851603612e6d57612e668383614195565b9050611137565b610c478484846141a3565b6000336129b4818585612e8b8383612142565b612e959190615b67565b613c50565b600054610100900460ff16612ec15760405162461bcd60e51b81526004016108f090615e49565b61293682826141bc565b60003381612ed98286612142565b905083811015612f395760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016108f0565b612f468286868403613c50565b506001949350505050565b609c546098546040516370a0823160e01b8152306004820152600092839290916001600160a01b03909116906370a0823190602401602060405180830381865afa158015612fa3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fc79190615bb4565b612fd19190615b67565b90506000609c54612fe160355490565b612feb9190615b67565b9050600081612ffa8685615cc4565b6130049190615cdb565b9050610fce8186613d74565b600080609760009054906101000a90046001600160a01b03166001600160a01b0316635f2ead686040518163ffffffff1660e01b8152600401602060405180830381865afa158015613066573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061308a9190615ae4565b90506000609760009054906101000a90046001600160a01b03166001600160a01b031663982a08726040518163ffffffff1660e01b8152600401602060405180830381865afa1580156130e1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131059190615bb4565b609754604051630392abf160e11b81526001600160a01b038a8116600483015292935091169063072557e290602401602060405180830381865afa158015613151573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131759190615bb4565b6040516332901d0b60e21b81526001600160a01b03898116600483015284169063ca40742c90602401602060405180830381865afa1580156131bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131df9190615bb4565b10806131f75750806099546131f49190615b67565b42115b61323b5760405162461bcd60e51b815260206004820152601560248201527446524d35206e6f74206c6971756964617461626c6560581b60448201526064016108f0565b6000826001600160a01b03166305308b9f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561327b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061329f9190615bb4565b905060995442111561332557609760009054906101000a90046001600160a01b03166001600160a01b031663de01c9cb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156132fe573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133229190615bb4565b90505b6097546040805163de01c9cb60e01b815290516000926001600160a01b03169163de01c9cb9160048083019260209291908290030181865afa15801561336f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133939190615bb4565b6001600160a01b038a166000908152609a60205260409020546133b7908490615cc4565b6133c19190615cdb565b90506133cd8882613d74565b9750600088116133ef5760405162461bcd60e51b81526004016108f090615e0a565b609854604051637dee6c4760e01b81526000916001600160a01b0380881692637dee6c47926134249216908d90600401615a7a565b602060405180830381865afa158015613441573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134659190615bb4565b90506000609760009054906101000a90046001600160a01b03166001600160a01b031663de01c9cb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156134bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134e09190615bb4565b609760009054906101000a90046001600160a01b03166001600160a01b0316638c765e946040518163ffffffff1660e01b8152600401602060405180830381865afa158015613533573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135579190615bb4565b6135619084615cc4565b61356b9190615cdb565b90506000866001600160a01b0316632a7225818b846040518363ffffffff1660e01b815260040161359d929190615a7a565b602060405180830381865afa1580156135ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135de9190615bb4565b60405163e7602b9d60e01b81526001600160a01b038e811660048301528c811660248301529192509088169063e7602b9d90604401602060405180830381865afa158015613630573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136549190615bb4565b8111156136a35760405162461bcd60e51b815260206004820152601a60248201527f46524d37206e6f7420656e6f75676820636f6c6c61746572616c00000000000060448201526064016108f0565b6136b133308d8c6000613ef0565b6001600160a01b038c166000908152609a6020526040812080548d92906136d9908490615cb1565b9091555050604080518c81526001600160a01b038c8116602083015291810183905233918e16907f298637f684da70674f26509b10f07ec2fbc77a335ab1e7d6215a4b2484d8bb529060600160405180910390a36040516352a494eb60e01b81526001600160a01b038b811660048301528d81166024830152336044830152606482018390528816906352a494eb90608401600060405180830381600087803b15801561378557600080fd5b505af1158015613799573d6000803e3d6000fd5b509c9e9d5050505050505050505050505050565b609e5460405163eb0ca45560e01b815260ff871660048201526001600160401b0386166024820152600091829182916001600160a01b03169063eb0ca4559060440161010060405180830381865afa15801561380d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138319190615d1a565b9050600080826080015160ff1660000361397f57613862878460e001518560c0015161385d9190615cb1565b613d74565b91506138ed8360a001518342609954609760009054906101000a90046001600160a01b03166001600160a01b0316632d8dea9c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138e89190615bb4565b6141fc565b9050818360e0018181516139019190615b67565b905250609e546040516368aab36f60e01b815260ff8c1660048201526001600160401b038b166024820152604481018490526001600160a01b03909116906368aab36f90606401600060405180830381600087803b15801561396257600080fd5b505af1158015613976573d6000803e3d6000fd5b50505050613b15565b60006139e18460a001518942609954609760009054906101000a90046001600160a01b03166001600160a01b0316632d8dea9c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138c4573d6000803e3d6000fd5b90506139fb818560e001518660c0015161385d9190615cb1565b9150613a868460a001518342609954609760009054906101000a90046001600160a01b03166001600160a01b0316632d8dea9c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613a5d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a819190615bb4565b6142a7565b9250818460e001818151613a9a9190615b67565b905250609e546040516368aab36f60e01b815260ff8d1660048201526001600160401b038c166024820152604481018490526001600160a01b03909116906368aab36f90606401600060405180830381600087803b158015613afb57600080fd5b505af1158015613b0f573d6000803e3d6000fd5b50505050505b606083015160a084015160e085015160c0860151606491613b3591615cb1565b1015613bbe57609e60009054906101000a90046001600160a01b03166001600160a01b031663179ad3d960008e886060015189600001516040518563ffffffff1660e01b8152600401613b8b9493929190615dd8565b600060405180830381600087803b158015613ba557600080fd5b505af1158015613bb9573d6000803e3d6000fd5b505050505b60ff8c16613bec57613bde8c838c8787613bd78a61240d565b878f61435f565b965096505050505050613c46565b60001960ff8d1601613c0957613bde8c8b848787613bd78a61240d565b60405162461bcd60e51b815260206004820152601260248201527146524d313420696e76616c6964207369646560701b60448201526064016108f0565b9550959350505050565b6001600160a01b038316613cb25760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016108f0565b6001600160a01b038216613d135760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016108f0565b6001600160a01b0383811660008181526034602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6000818310613d835781611137565b5090919050565b6001600160a01b038216613dea5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b60648201526084016108f0565b613df6826000836148fc565b6001600160a01b03821660009081526033602052604090205481811015613e6a5760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b60648201526084016108f0565b6001600160a01b0383166000908152603360205260408120838303905560358054849290613e99908490615cb1565b90915550506040518281526000906001600160a01b038516907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a3613eeb83600084614a03565b505050565b84848315613efc573091505b8215613f055750305b8315613fd157609754604080516315ab88c960e31b815290516000926001600160a01b03169163ad5c46489160048083019260209291908290030181865afa158015613f55573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f799190615ae4565b9050806001600160a01b031663d0e30db0876040518263ffffffff1660e01b81526004016000604051808303818588803b158015613fb657600080fd5b505af1158015613fca573d6000803e3d6000fd5b5050505050505b306001600160a01b03831603613ffd57609854613ff8906001600160a01b03168287614a3e565b614015565b609854614015906001600160a01b0316838388614a94565b821561418c57609754604080516315ab88c960e31b815290516000926001600160a01b03169163ad5c46489160048083019260209291908290030181865afa158015614065573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140899190615ae4565b604051632e1a7d4d60e01b8152600481018890529091506001600160a01b03821690632e1a7d4d90602401600060405180830381600087803b1580156140ce57600080fd5b505af11580156140e2573d6000803e3d6000fd5b505050506000876001600160a01b03168760405160006040518083038185875af1925050503d8060008114614133576040519150601f19603f3d011682016040523d82523d6000602084013e614138565b606091505b50509050806141895760405162461bcd60e51b815260206004820152601f60248201527f46524d323520756e7375636365737366756c20455448207472616e736665720060448201526064016108f0565b50505b50505050505050565b6000336129b4818585614acc565b6000336141b1858285614cab565b612f46858585614acc565b600054610100900460ff166141e35760405162461bcd60e51b81526004016108f090615e49565b60366141ef8382615eda565b506037613eeb8282615eda565b60008284106142455760405162461bcd60e51b81526020600482015260156024820152741a5b9d985b1a59081d1a5b59481a5b9d195c9d985b605a1b60448201526064016108f0565b6301e1338060006142568686615cb1565b905060008285836142706001600160401b038d168c615cc4565b61427a9190615cc4565b6142849190615cdb565b61428e9190615cdb565b905061429a8189615b67565b9998505050505050505050565b60008284106142f05760405162461bcd60e51b81526020600482015260156024820152741a5b9d985b1a59081d1a5b59481a5b9d195c9d985b605a1b60448201526064016108f0565b6301e1338060006143018686615cb1565b9050600082614310868a615cc4565b61431a9190615cc4565b90506000614331836001600160401b038c16615cc4565b61433b8588615cc4565b6143459190615b67565b90506143518183615cdb565b9a9950505050505050505050565b600080600087116143825760405162461bcd60e51b81526004016108f090615e0a565b8587106143c55760405162461bcd60e51b8152602060048201526011602482015270232926989b1034b73b30b634b21020a82960791b60448201526064016108f0565b8487116144145760405162461bcd60e51b815260206004820152601960248201527f46524d3920616d6f756e74203c2070726f746f636f6c4665650000000000000060448201526064016108f0565b886001600160a01b0316886001600160a01b0316036144755760405162461bcd60e51b815260206004820152601a60248201527f46524d313720696e76616c696420636f756e746572706172747900000000000060448201526064016108f0565b60995442106144bf5760405162461bcd60e51b815260206004820152601660248201527546524d313820696e76616c6964206d6174757269747960501b60448201526064016108f0565b60ff8a161515806144ce575082155b15614665576144dd8588615b67565b609854604051636eb1769f60e11b81526001600160a01b038b811660048301523060248301529091169063dd62ed3e90604401602060405180830381865afa15801561452d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906145519190615bb4565b101561459f5760405162461bcd60e51b815260206004820152601960248201527f46524d32206e6f7420656e6f75676820616c6c6f77616e63650000000000000060448201526064016108f0565b6145a98588615b67565b6098546040516370a0823160e01b81526001600160a01b038b81166004830152909116906370a0823190602401602060405180830381865afa1580156145f3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906146179190615bb4565b10156146655760405162461bcd60e51b815260206004820152601760248201527f46524d33206e6f7420656e6f7567682062616c616e636500000000000000000060448201526064016108f0565b614670898988614d1f565b6001600160a01b0389166000908152609a602052604081208054889290614698908490615b67565b909155506146ca9050896146c1816001600160a01b031660009081526033602052604090205490565b600060016129be565b5060975460408051631e476c0960e21b815290516000926001600160a01b03169163791db0249160048083019260209291908290030181865afa158015614715573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906147399190615ae4565b905060ff8b16156001600160a01b0382166147735761476e8a8c8b88801561475e5750845b898015614769575085155b613ef0565b61484c565b6147948a836147838a6002615cc4565b88801561478d5750845b6000613ef0565b6147bb8a8c6147a38a8d615cb1565b88801561475e57508489801561476957508515613ef0565b6147c6876002615cc4565b609d60008282546147d79190615b67565b90915550506098546001600160a01b038084169162b129a491166147fc8a6002615cc4565b6040518363ffffffff1660e01b8152600401614819929190615a7a565b600060405180830381600087803b15801561483357600080fd5b505af1158015614847573d6000803e3d6000fd5b505050505b6148568a89615028565b6148798a6146c18c6001600160a01b031660009081526033602052604090205490565b506148858b8b8b61511b565b604080518a8152602081018a90529081018890526001600160401b03871660608201526001600160a01b03808c1691908d169060ff8f16907fef2f771df63195427dca9bbc404e2b6fcc9fe9e2c8c3bba8ba8d7a8da192c3469060800160405180910390a450969a95995094975050505050505050565b6001600160a01b038316158061491957506001600160a01b038216155b1561492357505050565b6001600160a01b0383166000908152609a60209081526040808320546033909252909120541161498c5760405162461bcd60e51b815260206004820152601460248201527346524d3820626f72726f7773203e206c656e647360601b60448201526064016108f0565b6001600160a01b0383166000908152609a60209081526040808320546033909252909120546149bb9190615cb1565b811115613eeb5760405162461bcd60e51b815260206004820152601660248201527546524d323120616d6f756e74203e20626f72726f777360501b60448201526064016108f0565b6001600160a01b0383161580614a2057506001600160a01b038216155b15614a2a57505050565b614a388282600060016129be565b50505050565b613eeb8363a9059cbb60e01b8484604051602401614a5d929190615a7a565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152615307565b6040516001600160a01b0380851660248301528316604482015260648101829052614a389085906323b872dd60e01b90608401614a5d565b6001600160a01b038316614b305760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016108f0565b6001600160a01b038216614b925760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016108f0565b614b9d8383836148fc565b6001600160a01b03831660009081526033602052604090205481811015614c155760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016108f0565b6001600160a01b03808516600090815260336020526040808220858503905591851681529081208054849290614c4c908490615b67565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051614c9891815260200190565b60405180910390a3614a38848484614a03565b6000614cb78484612142565b90506000198114614a385781811015614d125760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016108f0565b614a388484848403613c50565b60975460408051630be5d5ad60e31b815290516000926001600160a01b031691635f2ead689160048083019260209291908290030181865afa158015614d69573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614d8d9190615ae4565b604051630c876ce960e31b81526001600160a01b03868116600483015230602483018190529293506000919084169063643b674890604401602060405180830381865afa158015614de2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614e069190615bb4565b905080841115614e6d5760405162461bcd60e51b815260206004820152602c60248201527f46524d3232207065726d697474656420616d6f756e742065786365656465642060448201526b3337b9103137b93937bbb2b960a11b60648201526084016108f0565b60405163064198ed60e31b81526001600160a01b038681166004830152838116602483015284169063320cc76890604401602060405180830381865afa158015614ebb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614edf9190615a93565b614f4757604051633d85eee160e21b81526001600160a01b038681166004830152838116602483015284169063f617bb8490604401600060405180830381600087803b158015614f2e57600080fd5b505af1158015614f42573d6000803e3d6000fd5b505050505b60405163064198ed60e31b81526001600160a01b038781166004830152838116602483015284169063320cc76890604401602060405180830381865afa158015614f95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614fb99190615a93565b611a2057604051633d85eee160e21b81526001600160a01b038781166004830152838116602483015284169063f617bb8490604401600060405180830381600087803b15801561500857600080fd5b505af115801561501c573d6000803e3d6000fd5b50505050505050505050565b6001600160a01b03821661507e5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f20616464726573730060448201526064016108f0565b61508a600083836148fc565b806035600082825461509c9190615b67565b90915550506001600160a01b038216600090815260336020526040812080548392906150c9908490615b67565b90915550506040518181526001600160a01b038316906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a361293660008383614a03565b60975460408051635db5813b60e11b815290516000926001600160a01b03169163bb6b02769160048083019260209291908290030181865afa158015615165573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906151899190615ae4565b90506001600160a01b03811615614a38576097546040805163050774ab60e51b815290516000926001600160a01b03169163a0ee95609160048083019260209291908290030181865afa1580156151e4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906152089190615ae4565b905060006152158461240d565b609854604051637dee6c4760e01b81529192506000916001600160a01b0385811692637dee6c479261524f92909116908690600401615a7a565b602060405180830381865afa15801561526c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906152909190615bb4565b60405163fd43683160e01b81526001600160a01b0389811660048301528881166024830152604482018390529192509085169063fd43683190606401600060405180830381600087803b1580156152e657600080fd5b505af11580156152fa573d6000803e3d6000fd5b5050505050505050505050565b600061535c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166153d99092919063ffffffff16565b805190915015613eeb578080602001905181019061537a9190615a93565b613eeb5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016108f0565b6060610c478484600085856001600160a01b0385163b61543b5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016108f0565b600080866001600160a01b031685876040516154579190615f99565b60006040518083038185875af1925050503d8060008114615494576040519150601f19603f3d011682016040523d82523d6000602084013e615499565b606091505b50915091506154a98282866154b4565b979650505050505050565b606083156154c3575081611137565b8251156154d35782518084602001fd5b8160405162461bcd60e51b81526004016108f091906155e7565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915290565b6001600160401b038116811461293857600080fd5b60006020828403121561555857600080fd5b813561113781615531565b60ff8116811461293857600080fd5b6000806000806080858703121561558857600080fd5b843561559381615563565b935060208501356155a381615563565b925060408501356155b381615531565b9396929550929360600135925050565b60005b838110156155de5781810151838201526020016155c6565b50506000910152565b60208152600082518060208401526156068160408501602087016155c3565b601f01601f19169190910160400192915050565b6001600160a01b038116811461293857600080fd5b6000806040838503121561564257600080fd5b823561564d8161561a565b946020939093013593505050565b60006020828403121561566d57600080fd5b5035919050565b600080600080600060a0868803121561568c57600080fd5b853561569781615563565b945060208601356156a781615531565b94979496505050506040830135926060810135926080909101359150565b6000806000606084860312156156da57600080fd5b83356156e58161561a565b925060208401356156f58161561a565b929592945050506040919091013590565b60006020828403121561571857600080fd5b813561113781615563565b6000806040838503121561573657600080fd5b823561574181615563565b915060208301356157518161561a565b809150509250929050565b6020808252825182820181905260009190848201906040850190845b8181101561579d5783516001600160401b031683529284019291840191600101615778565b50909695505050505050565b600080604083850312156157bc57600080fd5b50508035926020909101359150565b6000602082840312156157dd57600080fd5b81356111378161561a565b6001600160401b0380825116835280602083015116602084015280604083015116604084015260018060a01b03606083015116606084015260ff60808301511660808401528060a08301511660a08401525060c081015160c083015260e081015160e08301525050565b610100810161104782846157e8565b6000806040838503121561587457600080fd5b82359150602083013561575181615531565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b03811182821017156158c4576158c4615886565b604052919050565b600082601f8301126158dd57600080fd5b81356001600160401b038111156158f6576158f6615886565b615909601f8201601f191660200161589c565b81815284602083860101111561591e57600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080600060a0868803121561595357600080fd5b853561595e8161561a565b9450602086013561596e8161561a565b93506040860135925060608601356001600160401b038082111561599157600080fd5b61599d89838a016158cc565b935060808801359150808211156159b357600080fd5b506159c0888289016158cc565b9150509295509295909350565b600080604083850312156159e057600080fd5b82356159eb81615563565b9150602083013561575181615531565b60008060408385031215615a0e57600080fd5b82356157418161561a565b600080600060608486031215615a2e57600080fd5b8335615a398161561a565b9250602084013591506040840135615a508161561a565b809150509250925092565b60208082526005908201526408ca49a64760db1b604082015260600190565b6001600160a01b03929092168252602082015260400190565b600060208284031215615aa557600080fd5b8151801515811461113757600080fd5b60208082526005908201526446524d323760d81b604082015260600190565b8051615adf8161561a565b919050565b600060208284031215615af657600080fd5b81516111378161561a565b60208082526030908201527f46524d323420455448206f7065726174696f6e206e6f74207065726d6974746560408201526f19081a5b881d1a1a5cc81b585c9ad95d60821b606082015260800190565b634e487b7160e01b600052601160045260246000fd5b8082018082111561104757611047615b51565b600181811c90821680615b8e57607f821691505b602082108103615bae57634e487b7160e01b600052602260045260246000fd5b50919050565b600060208284031215615bc657600080fd5b5051919050565b8051615adf81615563565b600060208284031215615bea57600080fd5b815161113781615563565b8051615adf81615531565b60006020808385031215615c1357600080fd5b82516001600160401b0380821115615c2a57600080fd5b818501915085601f830112615c3e57600080fd5b815181811115615c5057615c50615886565b8060051b9150615c6184830161589c565b8181529183018401918481019088841115615c7b57600080fd5b938501935b83851015615ca55784519250615c9583615531565b8282529385019390850190615c80565b98975050505050505050565b8181038181111561104757611047615b51565b808202811582820484141761104757611047615b51565b600082615cf857634e487b7160e01b600052601260045260246000fd5b500490565b600060208284031215615d0f57600080fd5b815161113781615531565b6000610100808385031215615d2e57600080fd5b604051908101906001600160401b0382118183101715615d5057615d50615886565b8160405283519150615d6182615531565b818152615d7060208501615bf5565b6020820152615d8160408501615bf5565b6040820152615d9260608501615ad4565b6060820152615da360808501615bcd565b6080820152615db460a08501615bf5565b60a082015260c084015160c082015260e084015160e0820152809250505092915050565b931515845260ff9290921660208401526001600160a01b031660408301526001600160401b0316606082015260800190565b6020808252600d908201526c046524d3120616d6f756e743d3609c1b604082015260600190565b60ff83168152610120810161113760208301846157e8565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b601f821115613eeb57600081815260208120601f850160051c81016020861015615ebb5750805b601f850160051c820191505b81811015611a2057828155600101615ec7565b81516001600160401b03811115615ef357615ef3615886565b615f0781615f018454615b7a565b84615e94565b602080601f831160018114615f3c5760008415615f245750858301515b600019600386901b1c1916600185901b178555611a20565b600085815260208120601f198616915b82811015615f6b57888601518255948401946001909101908401615f4c565b5085821015615f895787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60008251615fab8184602087016155c3565b919091019291505056fea2646970667358221220d8e4d4011ef0fbd8beaf2c70f89fed43b8031e662fee709319735f3e2335eff564736f6c63430008120033

Deployed Bytecode

0x6080604052600436106102b15760003560e01c80638082a0b211610175578063c188063e116100dc578063d897c5a011610095578063e7675c511161006f578063e7675c511461084e578063eb0ca4551461086e578063f5e3c4621461088e578063fe5bb3f9146108ae57600080fd5b8063d897c5a0146107f9578063dd62ed3e14610819578063de987d501461083957600080fd5b8063c188063e1461074a578063cc774e9414610752578063ce0746c414610772578063ce40130814610787578063d40e8f4a146107a5578063d6329955146107db57600080fd5b80639c5bf6331161012e5780639c5bf633146106b6578063a457c2d7146106cb578063a9059cbb146106eb578063ae9f4cd91461070b578063b0e21e8a14610720578063ba95534c1461073557600080fd5b80638082a0b2146106015780638a7af74e146106215780638c88f42b146106415780638cf226c01461066157806395d89b41146106815780639ab8367e1461069657600080fd5b8063260122e3116102195780633f1f4155116101d25780633f1f41551461053457806342c806ed146105545780634b57a8d1146105815780635f2ead68146105a15780635fac60b8146105b657806370a08231146105cb57600080fd5b8063260122e314610448578063313ce567146104685780633288b2ec1461048f57806333f5419b146104bc578063370ed288146104dc578063395093511461051457600080fd5b80631264bfbf1161026b5780631264bfbf1461038c5780631639f418146103ac57806318160ddd146103cc578063204f83f9146103e157806323b872dd146103f65780632495a5991461041657600080fd5b8062ec04cd146102bd57806302dcd07f146102d257806303d930f6146102fa57806306fdde031461031a578063095ea7b31461033c5780630e7527021461036c57600080fd5b366102b857005b600080fd5b6102d06102cb366004615546565b6108ce565b005b3480156102de57600080fd5b506102e7610a7a565b6040519081526020015b60405180910390f35b34801561030657600080fd5b506102d0610315366004615572565b610a8a565b34801561032657600080fd5b5061032f610b14565b6040516102f191906155e7565b34801561034857600080fd5b5061035c61035736600461562f565b610ba6565b60405190151581526020016102f1565b34801561037857600080fd5b506102e761038736600461565b565b610c4f565b34801561039857600080fd5b506102e76103a7366004615674565b610d23565b3480156103b857600080fd5b506102e76103c736600461565b565b610dc2565b3480156103d857600080fd5b506035546102e7565b3480156103ed57600080fd5b506099546102e7565b34801561040257600080fd5b5061035c6104113660046156c5565b610f2c565b34801561042257600080fd5b506098546001600160a01b03165b6040516001600160a01b0390911681526020016102f1565b34801561045457600080fd5b506102e7610463366004615706565b610fd7565b34801561047457600080fd5b5061047d61104d565b60405160ff90911681526020016102f1565b34801561049b57600080fd5b506104af6104aa366004615723565b6110bb565b6040516102f1919061575c565b3480156104c857600080fd5b506102e76104d73660046157a9565b61113e565b3480156104e857600080fd5b506104fc6104f7366004615706565b611237565b6040516001600160401b0390911681526020016102f1565b34801561052057600080fd5b5061035c61052f36600461562f565b6112a7565b34801561054057600080fd5b506102d061054f3660046157cb565b611348565b34801561056057600080fd5b5061057461056f366004615706565b6114ad565b6040516102f19190615852565b34801561058d57600080fd5b506102e761059c3660046157cb565b611525565b3480156105ad57600080fd5b50610430611530565b3480156105c257600080fd5b506102e761159e565b3480156105d757600080fd5b506102e76105e63660046157cb565b6001600160a01b031660009081526033602052604090205490565b34801561060d57600080fd5b506102e761061c366004615674565b61160b565b34801561062d57600080fd5b506102d061063c366004615861565b611663565b34801561064d57600080fd5b506102d061065c366004615861565b6117cf565b34801561066d57600080fd5b506102e761067c36600461565b565b611897565b34801561068d57600080fd5b5061032f6118cc565b3480156106a257600080fd5b506102d06106b136600461593b565b6118db565b3480156106c257600080fd5b50609c546102e7565b3480156106d757600080fd5b5061035c6106e636600461562f565b611a28565b3480156106f757600080fd5b5061035c61070636600461562f565b611ac9565b34801561071757600080fd5b506102e7611b6b565b34801561072c57600080fd5b506102e7611ce8565b34801561074157600080fd5b50609d546102e7565b6102e7611daf565b34801561075e57600080fd5b506102d061076d3660046159cd565b611f47565b34801561077e57600080fd5b506102e7611fac565b34801561079357600080fd5b506097546001600160a01b0316610430565b3480156107b157600080fd5b506102e76107c03660046157cb565b6001600160a01b03166000908152609a602052604090205490565b3480156107e757600080fd5b50609e546001600160a01b0316610430565b34801561080557600080fd5b506102d0610814366004615861565b61207a565b34801561082557600080fd5b506102e76108343660046159fb565b612142565b34801561084557600080fd5b506102e761216d565b34801561085a57600080fd5b506102e761086936600461565b565b6121ee565b34801561087a57600080fd5b506105746108893660046159cd565b6122b4565b34801561089a57600080fd5b506102d06108a9366004615a19565b61233b565b3480156108ba57600080fd5b506102e76108c936600461565b565b61240d565b6002609f54036108f95760405162461bcd60e51b81526004016108f090615a5b565b60405180910390fd5b6002609f556097546040516361a2ee1f60e01b815261012e916001600160a01b0316906361a2ee1f906109329030908590600401615a7a565b602060405180830381865afa15801561094f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109739190615a93565b156109905760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109e3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a079190615ae4565b6098546001600160a01b03908116911614610a345760405162461bcd60e51b81526004016108f090615b01565b6000610a3f34611897565b90506000610a5260003384876001612419565b9050610a6f610a608261240d565b610a6a9083615b67565b61288f565b50506001609f555050565b6000610a853361293b565b905090565b609e5460405163cebcf96f60e01b815260ff8087166004830152336024830152851660448201526001600160401b0384166064820152608481018390526001600160a01b039091169063cebcf96f9060a401600060405180830381600087803b158015610af657600080fd5b505af1158015610b0a573d6000803e3d6000fd5b5050505050505050565b606060368054610b2390615b7a565b80601f0160208091040260200160405190810160405280929190818152602001828054610b4f90615b7a565b8015610b9c5780601f10610b7157610100808354040283529160200191610b9c565b820191906000526020600020905b815481529060010190602001808311610b7f57829003601f168201915b5050505050905090565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f90610bdf9030908590600401615a7a565b602060405180830381865afa158015610bfc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c209190615a93565b15610c3d5760405162461bcd60e51b81526004016108f090615ab5565b610c4784846129a6565b949350505050565b60006002609f5403610c735760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012f916001600160a01b0316906361a2ee1f90610cac9030908590600401615a7a565b602060405180830381865afa158015610cc9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ced9190615a93565b15610d0a5760405162461bcd60e51b81526004016108f090615ab5565b610d1733846000806129be565b6001609f559392505050565b609e54604051631264bfbf60e01b815260ff871660048201526001600160401b03861660248201526044810185905260648101849052608481018390526000916001600160a01b031690631264bfbf9060a4015b602060405180830381865afa158015610d94573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db89190615bb4565b9695505050505050565b60006002609f5403610de65760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610130916001600160a01b0316906361a2ee1f90610e1f9030908590600401615a7a565b602060405180830381865afa158015610e3c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e609190615a93565b15610e7d5760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ed0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef49190615ae4565b6098546001600160a01b03908116911614610f215760405162461bcd60e51b81526004016108f090615b01565b610d17836001612adf565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f90610f659030908590600401615a7a565b602060405180830381865afa158015610f82573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fa69190615a93565b15610fc35760405162461bcd60e51b81526004016108f090615ab5565b610fce858585612ce7565b95945050505050565b609e5460405163260122e360e01b815260ff831660048201526000916001600160a01b03169063260122e390602401602060405180830381865afa158015611023573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110479190615bb4565b92915050565b6098546040805163313ce56760e01b815290516000926001600160a01b03169163313ce5679160048083019260209291908290030181865afa158015611097573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a859190615bd8565b609e54604051630ca22cbb60e21b815260ff841660048201526001600160a01b0383811660248301526060921690633288b2ec90604401600060405180830381865afa15801561110f573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526111379190810190615c00565b9392505050565b600060995482106111885760405162461bcd60e51b81526020600482015260146024820152731194934c4c481b585c9ad95d08195e1c1a5c995960621b60448201526064016108f0565b60975460408051630b637aa760e21b815290516301e13380926001600160a01b031691632d8dea9c9160048083019260209291908290030181865afa1580156111d5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111f99190615bb4565b836099546112079190615cb1565b61120f611ce8565b6112199087615cc4565b6112239190615cc4565b61122d9190615cdb565b6111379190615cdb565b609e546040516306e1da5160e31b815260ff831660048201526000916001600160a01b03169063370ed28890602401602060405180830381865afa158015611283573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110479190615cfd565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f906112e09030908590600401615a7a565b602060405180830381865afa1580156112fd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113219190615a93565b1561133e5760405162461bcd60e51b81526004016108f090615ab5565b610c478484612e78565b60975460408051631d6c8e3f60e21b815290516001600160a01b03909216916391d148549183916375b238fc916004808201926020929091908290030181865afa15801561139a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113be9190615bb4565b6040516001600160e01b031960e084901b1681526004810191909152336024820152604401602060405180830381865afa158015611400573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114249190615a93565b6114595760405162461bcd60e51b81526004016108f090602080825260049082015263046524d360e41b604082015260600190565b609e80546001600160a01b0319166001600160a01b0383169081179091556040519081527fa7f4849aca702f6bead45e7075d9db5a5d4f5e123280ca2bff648e65197b6e5c9060200160405180910390a150565b6114b56154ed565b609e546040516342c806ed60e01b815260ff841660048201526001600160a01b03909116906342c806ed9060240161010060405180830381865afa158015611501573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110479190615d1a565b60006110478261293b565b60975460408051630be5d5ad60e31b815290516000926001600160a01b031691635f2ead689160048083019260209291908290030181865afa15801561157a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a859190615ae4565b60975460405162827f6760e21b81523060048201526000916001600160a01b031690630209fd9c906024015b602060405180830381865afa1580156115e7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a859190615bb4565b609e54604051634041505960e11b815260ff871660048201526001600160401b03861660248201526044810185905260648101849052608481018390526000916001600160a01b031690638082a0b29060a401610d77565b6002609f54036116855760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012d916001600160a01b0316906361a2ee1f906116be9030908590600401615a7a565b602060405180830381865afa1580156116db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116ff9190615a93565b1561171c5760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa15801561176f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117939190615ae4565b6098546001600160a01b039081169116146117c05760405162461bcd60e51b81526004016108f090615b01565b610a6f60013385856001612419565b6002609f54036117f15760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012e916001600160a01b0316906361a2ee1f9061182a9030908590600401615a7a565b602060405180830381865afa158015611847573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061186b9190615a93565b156118885760405162461bcd60e51b81526004016108f090615ab5565b610a6f60003385856000612419565b60006118a66305f5e10061240d565b6118b4906305f5e100615b67565b6118c2836305f5e100615cc4565b6110479190615cdb565b606060378054610b2390615b7a565b600054610100900460ff16158080156118fb5750600054600160ff909116105b806119155750303b158015611915575060005460ff166001145b6119785760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016108f0565b6000805460ff19166001179055801561199b576000805461ff0019166101001790555b6119a58383612e9a565b609780546001600160a01b038089166001600160a01b031992831617909255609880549288169290911691909117905560998490558015611a20576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f90611a619030908590600401615a7a565b602060405180830381865afa158015611a7e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611aa29190615a93565b15611abf5760405162461bcd60e51b81526004016108f090615ab5565b610c478484612ecb565b6097546040516361a2ee1f60e01b8152600091610132916001600160a01b03909116906361a2ee1f90611b029030908590600401615a7a565b602060405180830381865afa158015611b1f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b439190615a93565b15611b605760405162461bcd60e51b81526004016108f090615ab5565b610c47338585612ce7565b60006002609f5403611b8f5760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610130916001600160a01b0316906361a2ee1f90611bc89030908590600401615a7a565b602060405180830381865afa158015611be5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c099190615a93565b15611c265760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015611c79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c9d9190615ae4565b6098546001600160a01b03908116911614611cca5760405162461bcd60e51b81526004016108f090615b01565b611cdd611cd63361293b565b6001612adf565b9150506001609f5590565b6000806001600160a01b0316609760009054906101000a90046001600160a01b03166001600160a01b031663791db0246040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d6b9190615ae4565b6001600160a01b031603611d7f5750600090565b609754604051632d8acc7960e21b81523060048201526001600160a01b039091169063b62b31e4906024016115ca565b60006002609f5403611dd35760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012f916001600160a01b0316906361a2ee1f90611e0c9030908590600401615a7a565b602060405180830381865afa158015611e29573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e4d9190615a93565b15611e6a5760405162461bcd60e51b81526004016108f090615ab5565b609760009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ebd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ee19190615ae4565b6098546001600160a01b03908116911614611f0e5760405162461bcd60e51b81526004016108f090615b01565b336000818152609a602052604081205491611f2c90346001846129be565b9050611f3b610a6a8284615cb1565b925050506001609f5590565b609e5460405163179ad3d960e01b81526001600160a01b039091169063179ad3d990611f7e90600190869033908790600401615dd8565b600060405180830381600087803b158015611f9857600080fd5b505af1158015611a20573d6000803e3d6000fd5b60006002609f5403611fd05760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610130916001600160a01b0316906361a2ee1f906120099030908590600401615a7a565b602060405180830381865afa158015612026573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061204a9190615a93565b156120675760405162461bcd60e51b81526004016108f090615ab5565b611cdd6120733361293b565b6000612adf565b6002609f540361209c5760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b815261012d916001600160a01b0316906361a2ee1f906120d59030908590600401615a7a565b602060405180830381865afa1580156120f2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121169190615a93565b156121335760405162461bcd60e51b81526004016108f090615ab5565b610a6f60013385856000612419565b6001600160a01b03918216600090815260346020908152604080832093909416825291909152205490565b6000610a85609760009054906101000a90046001600160a01b03166001600160a01b0316630df09d256040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121e99190615bb4565b612f51565b60006002609f54036122125760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610130916001600160a01b0316906361a2ee1f9061224b9030908590600401615a7a565b602060405180830381865afa158015612268573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061228c9190615a93565b156122a95760405162461bcd60e51b81526004016108f090615ab5565b610d17836000612adf565b6122bc6154ed565b609e5460405163eb0ca45560e01b815260ff851660048201526001600160401b03841660248201526001600160a01b039091169063eb0ca4559060440161010060405180830381865afa158015612317573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111379190615d1a565b6002609f540361235d5760405162461bcd60e51b81526004016108f090615a5b565b6002609f556097546040516361a2ee1f60e01b8152610131916001600160a01b0316906361a2ee1f906123969030908590600401615a7a565b602060405180830381865afa1580156123b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123d79190615a93565b156123f45760405162461bcd60e51b81526004016108f090615ab5565b6124018484846000613010565b50506001609f55505050565b6000611047824261113e565b600080841161243a5760405162461bcd60e51b81526004016108f090615e0a565b609e546040516342c806ed60e01b815260ff8816600482015285916000916001600160a01b03909116906342c806ed9060240161010060405180830381865afa15801561248b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124af9190615d1a565b90506000805b83156128325760ff8a1660011480156124e357508260a001516001600160401b0316876001600160401b0316105b8061250f575060ff8a1615801561250f57508260a001516001600160401b0316876001600160401b0316115b6128325782516001600160401b0316156128325782606001516001600160a01b0316896001600160a01b0316036125cc57609e54602084015160405163eb0ca45560e01b815260ff8d1660048201526001600160401b0390911660248201526001600160a01b039091169063eb0ca4559060440161010060405180830381865afa1580156125a1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125c59190615d1a565b92506124b5565b609e54604051635188831b60e01b81526001600160a01b0390911690635188831b906125fe908d908790600401615e31565b602060405180830381865afa15801561261b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061263f9190615a93565b61275557600083602001519050609e60009054906101000a90046001600160a01b03166001600160a01b031663179ad3d960008d876060015188600001516040518563ffffffff1660e01b815260040161269c9493929190615dd8565b600060405180830381600087803b1580156126b657600080fd5b505af11580156126ca573d6000803e3d6000fd5b5050609e5460405163eb0ca45560e01b815260ff8f1660048201526001600160401b03851660248201526001600160a01b03909116925063eb0ca455915060440161010060405180830381865afa158015612729573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061274d9190615d1a565b9350506124b5565b6000806127698c86600001518d898c6137ad565b90925090506127788285615b67565b93506127848184615b67565b92508186111561279f576127988287615cb1565b95506127a4565b600095505b609e54602086015160405163eb0ca45560e01b815260ff8f1660048201526001600160401b0390911660248201526001600160a01b039091169063eb0ca4559060440161010060405180830381865afa158015612805573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128299190615d1a565b945050506124b5565b81156128825760408051838152602081018390526001600160a01b038b169160ff8d16917fe6eb67287c05f17552781a0a3623f567d8f7d652cea44b265174c97f54e180c4910160405180910390a35b5098975050505050505050565b34811015612938576000336128a48334615cb1565b604051600081818185875af1925050503d80600081146128e0576040519150601f19603f3d011682016040523d82523d6000602084013e6128e5565b606091505b50509050806129365760405162461bcd60e51b815260206004820152601f60248201527f46524d323520756e7375636365737366756c20455448207472616e736665720060448201526064016108f0565b505b50565b6001600160a01b038116600090815260336020526040812054600081116129655750600092915050565b6001600160a01b0383166000908152609b60205260408120549061298c6121e98385615b67565b905081811161299c576000610fce565b610fce8282615cb1565b6000336129b4818585613c50565b5060019392505050565b6001600160a01b0384166000908152609a60205260408120546129e2908590613d74565b93508115612a205783600003612a1157506001600160a01b0384166000908152609a6020526040902054610c47565b612a1b8585613d8a565b612a4e565b60008411612a405760405162461bcd60e51b81526004016108f090615e0a565b612a4e853086866000613ef0565b6001600160a01b0385166000908152609a602052604081208054869290612a76908490615cb1565b90915550506040805185815283151560208201526001600160a01b038716917f23e1d46573bb38c46bc3f95d3028aa9650e1e3a45659e5be95ab7a82caefd6f5910160405180910390a2505050506001600160a01b03166000908152609a602052604090205490565b6000808311612b305760405162461bcd60e51b815260206004820152601e60248201527f46524d3233207461726765742072656465656d20616d6f756e74203d2030000060448201526064016108f0565b609760009054906101000a90046001600160a01b03166001600160a01b031663c8b82f5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b83573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ba79190615bb4565b609954612bb49190615b67565b4211612bfd5760405162461bcd60e51b815260206004820152601860248201527746524d342063616e6e6f742072656465656d206561726c7960401b60448201526064016108f0565b612c063361293b565b831115612c555760405162461bcd60e51b815260206004820152601f60248201527f46524d323020616d6f756e74203e2072656465656d61626c65546f6b656e730060448201526064016108f0565b612c5f3384613d8a565b336000908152609b602052604081208054859290612c7e908490615b67565b9250508190555082609c6000828254612c979190615b67565b90915550612cab9050303385600086613ef0565b60405183815233907fe60e13e1fa5509002572aab753f3f827f7796b5c22d3d93fdcfba50881e997ed9060200160405180910390a25090919050565b6000609954421115612e4c57609760009054906101000a90046001600160a01b03166001600160a01b031663c8b82f5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612d46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d6a9190615bb4565b609954612d779190615b67565b4211612dc05760405162461bcd60e51b815260206004820152601860248201527746524d342063616e6e6f742072656465656d206561726c7960401b60448201526064016108f0565b6000612dcb8561293b565b905080831115612e1d5760405162461bcd60e51b815260206004820152601f60248201527f46524d323020616d6f756e74203e2072656465656d61626c65546f6b656e730060448201526064016108f0565b6001600160a01b0385166000908152609b602052604081208054859290612e45908490615b67565b9091555050505b336001600160a01b03851603612e6d57612e668383614195565b9050611137565b610c478484846141a3565b6000336129b4818585612e8b8383612142565b612e959190615b67565b613c50565b600054610100900460ff16612ec15760405162461bcd60e51b81526004016108f090615e49565b61293682826141bc565b60003381612ed98286612142565b905083811015612f395760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016108f0565b612f468286868403613c50565b506001949350505050565b609c546098546040516370a0823160e01b8152306004820152600092839290916001600160a01b03909116906370a0823190602401602060405180830381865afa158015612fa3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fc79190615bb4565b612fd19190615b67565b90506000609c54612fe160355490565b612feb9190615b67565b9050600081612ffa8685615cc4565b6130049190615cdb565b9050610fce8186613d74565b600080609760009054906101000a90046001600160a01b03166001600160a01b0316635f2ead686040518163ffffffff1660e01b8152600401602060405180830381865afa158015613066573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061308a9190615ae4565b90506000609760009054906101000a90046001600160a01b03166001600160a01b031663982a08726040518163ffffffff1660e01b8152600401602060405180830381865afa1580156130e1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131059190615bb4565b609754604051630392abf160e11b81526001600160a01b038a8116600483015292935091169063072557e290602401602060405180830381865afa158015613151573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131759190615bb4565b6040516332901d0b60e21b81526001600160a01b03898116600483015284169063ca40742c90602401602060405180830381865afa1580156131bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131df9190615bb4565b10806131f75750806099546131f49190615b67565b42115b61323b5760405162461bcd60e51b815260206004820152601560248201527446524d35206e6f74206c6971756964617461626c6560581b60448201526064016108f0565b6000826001600160a01b03166305308b9f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561327b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061329f9190615bb4565b905060995442111561332557609760009054906101000a90046001600160a01b03166001600160a01b031663de01c9cb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156132fe573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133229190615bb4565b90505b6097546040805163de01c9cb60e01b815290516000926001600160a01b03169163de01c9cb9160048083019260209291908290030181865afa15801561336f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133939190615bb4565b6001600160a01b038a166000908152609a60205260409020546133b7908490615cc4565b6133c19190615cdb565b90506133cd8882613d74565b9750600088116133ef5760405162461bcd60e51b81526004016108f090615e0a565b609854604051637dee6c4760e01b81526000916001600160a01b0380881692637dee6c47926134249216908d90600401615a7a565b602060405180830381865afa158015613441573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134659190615bb4565b90506000609760009054906101000a90046001600160a01b03166001600160a01b031663de01c9cb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156134bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134e09190615bb4565b609760009054906101000a90046001600160a01b03166001600160a01b0316638c765e946040518163ffffffff1660e01b8152600401602060405180830381865afa158015613533573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135579190615bb4565b6135619084615cc4565b61356b9190615cdb565b90506000866001600160a01b0316632a7225818b846040518363ffffffff1660e01b815260040161359d929190615a7a565b602060405180830381865afa1580156135ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135de9190615bb4565b60405163e7602b9d60e01b81526001600160a01b038e811660048301528c811660248301529192509088169063e7602b9d90604401602060405180830381865afa158015613630573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136549190615bb4565b8111156136a35760405162461bcd60e51b815260206004820152601a60248201527f46524d37206e6f7420656e6f75676820636f6c6c61746572616c00000000000060448201526064016108f0565b6136b133308d8c6000613ef0565b6001600160a01b038c166000908152609a6020526040812080548d92906136d9908490615cb1565b9091555050604080518c81526001600160a01b038c8116602083015291810183905233918e16907f298637f684da70674f26509b10f07ec2fbc77a335ab1e7d6215a4b2484d8bb529060600160405180910390a36040516352a494eb60e01b81526001600160a01b038b811660048301528d81166024830152336044830152606482018390528816906352a494eb90608401600060405180830381600087803b15801561378557600080fd5b505af1158015613799573d6000803e3d6000fd5b509c9e9d5050505050505050505050505050565b609e5460405163eb0ca45560e01b815260ff871660048201526001600160401b0386166024820152600091829182916001600160a01b03169063eb0ca4559060440161010060405180830381865afa15801561380d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138319190615d1a565b9050600080826080015160ff1660000361397f57613862878460e001518560c0015161385d9190615cb1565b613d74565b91506138ed8360a001518342609954609760009054906101000a90046001600160a01b03166001600160a01b0316632d8dea9c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138e89190615bb4565b6141fc565b9050818360e0018181516139019190615b67565b905250609e546040516368aab36f60e01b815260ff8c1660048201526001600160401b038b166024820152604481018490526001600160a01b03909116906368aab36f90606401600060405180830381600087803b15801561396257600080fd5b505af1158015613976573d6000803e3d6000fd5b50505050613b15565b60006139e18460a001518942609954609760009054906101000a90046001600160a01b03166001600160a01b0316632d8dea9c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138c4573d6000803e3d6000fd5b90506139fb818560e001518660c0015161385d9190615cb1565b9150613a868460a001518342609954609760009054906101000a90046001600160a01b03166001600160a01b0316632d8dea9c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613a5d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a819190615bb4565b6142a7565b9250818460e001818151613a9a9190615b67565b905250609e546040516368aab36f60e01b815260ff8d1660048201526001600160401b038c166024820152604481018490526001600160a01b03909116906368aab36f90606401600060405180830381600087803b158015613afb57600080fd5b505af1158015613b0f573d6000803e3d6000fd5b50505050505b606083015160a084015160e085015160c0860151606491613b3591615cb1565b1015613bbe57609e60009054906101000a90046001600160a01b03166001600160a01b031663179ad3d960008e886060015189600001516040518563ffffffff1660e01b8152600401613b8b9493929190615dd8565b600060405180830381600087803b158015613ba557600080fd5b505af1158015613bb9573d6000803e3d6000fd5b505050505b60ff8c16613bec57613bde8c838c8787613bd78a61240d565b878f61435f565b965096505050505050613c46565b60001960ff8d1601613c0957613bde8c8b848787613bd78a61240d565b60405162461bcd60e51b815260206004820152601260248201527146524d313420696e76616c6964207369646560701b60448201526064016108f0565b9550959350505050565b6001600160a01b038316613cb25760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016108f0565b6001600160a01b038216613d135760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016108f0565b6001600160a01b0383811660008181526034602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6000818310613d835781611137565b5090919050565b6001600160a01b038216613dea5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b60648201526084016108f0565b613df6826000836148fc565b6001600160a01b03821660009081526033602052604090205481811015613e6a5760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b60648201526084016108f0565b6001600160a01b0383166000908152603360205260408120838303905560358054849290613e99908490615cb1565b90915550506040518281526000906001600160a01b038516907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a3613eeb83600084614a03565b505050565b84848315613efc573091505b8215613f055750305b8315613fd157609754604080516315ab88c960e31b815290516000926001600160a01b03169163ad5c46489160048083019260209291908290030181865afa158015613f55573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f799190615ae4565b9050806001600160a01b031663d0e30db0876040518263ffffffff1660e01b81526004016000604051808303818588803b158015613fb657600080fd5b505af1158015613fca573d6000803e3d6000fd5b5050505050505b306001600160a01b03831603613ffd57609854613ff8906001600160a01b03168287614a3e565b614015565b609854614015906001600160a01b0316838388614a94565b821561418c57609754604080516315ab88c960e31b815290516000926001600160a01b03169163ad5c46489160048083019260209291908290030181865afa158015614065573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140899190615ae4565b604051632e1a7d4d60e01b8152600481018890529091506001600160a01b03821690632e1a7d4d90602401600060405180830381600087803b1580156140ce57600080fd5b505af11580156140e2573d6000803e3d6000fd5b505050506000876001600160a01b03168760405160006040518083038185875af1925050503d8060008114614133576040519150601f19603f3d011682016040523d82523d6000602084013e614138565b606091505b50509050806141895760405162461bcd60e51b815260206004820152601f60248201527f46524d323520756e7375636365737366756c20455448207472616e736665720060448201526064016108f0565b50505b50505050505050565b6000336129b4818585614acc565b6000336141b1858285614cab565b612f46858585614acc565b600054610100900460ff166141e35760405162461bcd60e51b81526004016108f090615e49565b60366141ef8382615eda565b506037613eeb8282615eda565b60008284106142455760405162461bcd60e51b81526020600482015260156024820152741a5b9d985b1a59081d1a5b59481a5b9d195c9d985b605a1b60448201526064016108f0565b6301e1338060006142568686615cb1565b905060008285836142706001600160401b038d168c615cc4565b61427a9190615cc4565b6142849190615cdb565b61428e9190615cdb565b905061429a8189615b67565b9998505050505050505050565b60008284106142f05760405162461bcd60e51b81526020600482015260156024820152741a5b9d985b1a59081d1a5b59481a5b9d195c9d985b605a1b60448201526064016108f0565b6301e1338060006143018686615cb1565b9050600082614310868a615cc4565b61431a9190615cc4565b90506000614331836001600160401b038c16615cc4565b61433b8588615cc4565b6143459190615b67565b90506143518183615cdb565b9a9950505050505050505050565b600080600087116143825760405162461bcd60e51b81526004016108f090615e0a565b8587106143c55760405162461bcd60e51b8152602060048201526011602482015270232926989b1034b73b30b634b21020a82960791b60448201526064016108f0565b8487116144145760405162461bcd60e51b815260206004820152601960248201527f46524d3920616d6f756e74203c2070726f746f636f6c4665650000000000000060448201526064016108f0565b886001600160a01b0316886001600160a01b0316036144755760405162461bcd60e51b815260206004820152601a60248201527f46524d313720696e76616c696420636f756e746572706172747900000000000060448201526064016108f0565b60995442106144bf5760405162461bcd60e51b815260206004820152601660248201527546524d313820696e76616c6964206d6174757269747960501b60448201526064016108f0565b60ff8a161515806144ce575082155b15614665576144dd8588615b67565b609854604051636eb1769f60e11b81526001600160a01b038b811660048301523060248301529091169063dd62ed3e90604401602060405180830381865afa15801561452d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906145519190615bb4565b101561459f5760405162461bcd60e51b815260206004820152601960248201527f46524d32206e6f7420656e6f75676820616c6c6f77616e63650000000000000060448201526064016108f0565b6145a98588615b67565b6098546040516370a0823160e01b81526001600160a01b038b81166004830152909116906370a0823190602401602060405180830381865afa1580156145f3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906146179190615bb4565b10156146655760405162461bcd60e51b815260206004820152601760248201527f46524d33206e6f7420656e6f7567682062616c616e636500000000000000000060448201526064016108f0565b614670898988614d1f565b6001600160a01b0389166000908152609a602052604081208054889290614698908490615b67565b909155506146ca9050896146c1816001600160a01b031660009081526033602052604090205490565b600060016129be565b5060975460408051631e476c0960e21b815290516000926001600160a01b03169163791db0249160048083019260209291908290030181865afa158015614715573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906147399190615ae4565b905060ff8b16156001600160a01b0382166147735761476e8a8c8b88801561475e5750845b898015614769575085155b613ef0565b61484c565b6147948a836147838a6002615cc4565b88801561478d5750845b6000613ef0565b6147bb8a8c6147a38a8d615cb1565b88801561475e57508489801561476957508515613ef0565b6147c6876002615cc4565b609d60008282546147d79190615b67565b90915550506098546001600160a01b038084169162b129a491166147fc8a6002615cc4565b6040518363ffffffff1660e01b8152600401614819929190615a7a565b600060405180830381600087803b15801561483357600080fd5b505af1158015614847573d6000803e3d6000fd5b505050505b6148568a89615028565b6148798a6146c18c6001600160a01b031660009081526033602052604090205490565b506148858b8b8b61511b565b604080518a8152602081018a90529081018890526001600160401b03871660608201526001600160a01b03808c1691908d169060ff8f16907fef2f771df63195427dca9bbc404e2b6fcc9fe9e2c8c3bba8ba8d7a8da192c3469060800160405180910390a450969a95995094975050505050505050565b6001600160a01b038316158061491957506001600160a01b038216155b1561492357505050565b6001600160a01b0383166000908152609a60209081526040808320546033909252909120541161498c5760405162461bcd60e51b815260206004820152601460248201527346524d3820626f72726f7773203e206c656e647360601b60448201526064016108f0565b6001600160a01b0383166000908152609a60209081526040808320546033909252909120546149bb9190615cb1565b811115613eeb5760405162461bcd60e51b815260206004820152601660248201527546524d323120616d6f756e74203e20626f72726f777360501b60448201526064016108f0565b6001600160a01b0383161580614a2057506001600160a01b038216155b15614a2a57505050565b614a388282600060016129be565b50505050565b613eeb8363a9059cbb60e01b8484604051602401614a5d929190615a7a565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152615307565b6040516001600160a01b0380851660248301528316604482015260648101829052614a389085906323b872dd60e01b90608401614a5d565b6001600160a01b038316614b305760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016108f0565b6001600160a01b038216614b925760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016108f0565b614b9d8383836148fc565b6001600160a01b03831660009081526033602052604090205481811015614c155760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016108f0565b6001600160a01b03808516600090815260336020526040808220858503905591851681529081208054849290614c4c908490615b67565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051614c9891815260200190565b60405180910390a3614a38848484614a03565b6000614cb78484612142565b90506000198114614a385781811015614d125760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016108f0565b614a388484848403613c50565b60975460408051630be5d5ad60e31b815290516000926001600160a01b031691635f2ead689160048083019260209291908290030181865afa158015614d69573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614d8d9190615ae4565b604051630c876ce960e31b81526001600160a01b03868116600483015230602483018190529293506000919084169063643b674890604401602060405180830381865afa158015614de2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614e069190615bb4565b905080841115614e6d5760405162461bcd60e51b815260206004820152602c60248201527f46524d3232207065726d697474656420616d6f756e742065786365656465642060448201526b3337b9103137b93937bbb2b960a11b60648201526084016108f0565b60405163064198ed60e31b81526001600160a01b038681166004830152838116602483015284169063320cc76890604401602060405180830381865afa158015614ebb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614edf9190615a93565b614f4757604051633d85eee160e21b81526001600160a01b038681166004830152838116602483015284169063f617bb8490604401600060405180830381600087803b158015614f2e57600080fd5b505af1158015614f42573d6000803e3d6000fd5b505050505b60405163064198ed60e31b81526001600160a01b038781166004830152838116602483015284169063320cc76890604401602060405180830381865afa158015614f95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614fb99190615a93565b611a2057604051633d85eee160e21b81526001600160a01b038781166004830152838116602483015284169063f617bb8490604401600060405180830381600087803b15801561500857600080fd5b505af115801561501c573d6000803e3d6000fd5b50505050505050505050565b6001600160a01b03821661507e5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f20616464726573730060448201526064016108f0565b61508a600083836148fc565b806035600082825461509c9190615b67565b90915550506001600160a01b038216600090815260336020526040812080548392906150c9908490615b67565b90915550506040518181526001600160a01b038316906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a361293660008383614a03565b60975460408051635db5813b60e11b815290516000926001600160a01b03169163bb6b02769160048083019260209291908290030181865afa158015615165573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906151899190615ae4565b90506001600160a01b03811615614a38576097546040805163050774ab60e51b815290516000926001600160a01b03169163a0ee95609160048083019260209291908290030181865afa1580156151e4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906152089190615ae4565b905060006152158461240d565b609854604051637dee6c4760e01b81529192506000916001600160a01b0385811692637dee6c479261524f92909116908690600401615a7a565b602060405180830381865afa15801561526c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906152909190615bb4565b60405163fd43683160e01b81526001600160a01b0389811660048301528881166024830152604482018390529192509085169063fd43683190606401600060405180830381600087803b1580156152e657600080fd5b505af11580156152fa573d6000803e3d6000fd5b5050505050505050505050565b600061535c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166153d99092919063ffffffff16565b805190915015613eeb578080602001905181019061537a9190615a93565b613eeb5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016108f0565b6060610c478484600085856001600160a01b0385163b61543b5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016108f0565b600080866001600160a01b031685876040516154579190615f99565b60006040518083038185875af1925050503d8060008114615494576040519150601f19603f3d011682016040523d82523d6000602084013e615499565b606091505b50915091506154a98282866154b4565b979650505050505050565b606083156154c3575081611137565b8251156154d35782518084602001fd5b8160405162461bcd60e51b81526004016108f091906155e7565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915290565b6001600160401b038116811461293857600080fd5b60006020828403121561555857600080fd5b813561113781615531565b60ff8116811461293857600080fd5b6000806000806080858703121561558857600080fd5b843561559381615563565b935060208501356155a381615563565b925060408501356155b381615531565b9396929550929360600135925050565b60005b838110156155de5781810151838201526020016155c6565b50506000910152565b60208152600082518060208401526156068160408501602087016155c3565b601f01601f19169190910160400192915050565b6001600160a01b038116811461293857600080fd5b6000806040838503121561564257600080fd5b823561564d8161561a565b946020939093013593505050565b60006020828403121561566d57600080fd5b5035919050565b600080600080600060a0868803121561568c57600080fd5b853561569781615563565b945060208601356156a781615531565b94979496505050506040830135926060810135926080909101359150565b6000806000606084860312156156da57600080fd5b83356156e58161561a565b925060208401356156f58161561a565b929592945050506040919091013590565b60006020828403121561571857600080fd5b813561113781615563565b6000806040838503121561573657600080fd5b823561574181615563565b915060208301356157518161561a565b809150509250929050565b6020808252825182820181905260009190848201906040850190845b8181101561579d5783516001600160401b031683529284019291840191600101615778565b50909695505050505050565b600080604083850312156157bc57600080fd5b50508035926020909101359150565b6000602082840312156157dd57600080fd5b81356111378161561a565b6001600160401b0380825116835280602083015116602084015280604083015116604084015260018060a01b03606083015116606084015260ff60808301511660808401528060a08301511660a08401525060c081015160c083015260e081015160e08301525050565b610100810161104782846157e8565b6000806040838503121561587457600080fd5b82359150602083013561575181615531565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b03811182821017156158c4576158c4615886565b604052919050565b600082601f8301126158dd57600080fd5b81356001600160401b038111156158f6576158f6615886565b615909601f8201601f191660200161589c565b81815284602083860101111561591e57600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080600060a0868803121561595357600080fd5b853561595e8161561a565b9450602086013561596e8161561a565b93506040860135925060608601356001600160401b038082111561599157600080fd5b61599d89838a016158cc565b935060808801359150808211156159b357600080fd5b506159c0888289016158cc565b9150509295509295909350565b600080604083850312156159e057600080fd5b82356159eb81615563565b9150602083013561575181615531565b60008060408385031215615a0e57600080fd5b82356157418161561a565b600080600060608486031215615a2e57600080fd5b8335615a398161561a565b9250602084013591506040840135615a508161561a565b809150509250925092565b60208082526005908201526408ca49a64760db1b604082015260600190565b6001600160a01b03929092168252602082015260400190565b600060208284031215615aa557600080fd5b8151801515811461113757600080fd5b60208082526005908201526446524d323760d81b604082015260600190565b8051615adf8161561a565b919050565b600060208284031215615af657600080fd5b81516111378161561a565b60208082526030908201527f46524d323420455448206f7065726174696f6e206e6f74207065726d6974746560408201526f19081a5b881d1a1a5cc81b585c9ad95d60821b606082015260800190565b634e487b7160e01b600052601160045260246000fd5b8082018082111561104757611047615b51565b600181811c90821680615b8e57607f821691505b602082108103615bae57634e487b7160e01b600052602260045260246000fd5b50919050565b600060208284031215615bc657600080fd5b5051919050565b8051615adf81615563565b600060208284031215615bea57600080fd5b815161113781615563565b8051615adf81615531565b60006020808385031215615c1357600080fd5b82516001600160401b0380821115615c2a57600080fd5b818501915085601f830112615c3e57600080fd5b815181811115615c5057615c50615886565b8060051b9150615c6184830161589c565b8181529183018401918481019088841115615c7b57600080fd5b938501935b83851015615ca55784519250615c9583615531565b8282529385019390850190615c80565b98975050505050505050565b8181038181111561104757611047615b51565b808202811582820484141761104757611047615b51565b600082615cf857634e487b7160e01b600052601260045260246000fd5b500490565b600060208284031215615d0f57600080fd5b815161113781615531565b6000610100808385031215615d2e57600080fd5b604051908101906001600160401b0382118183101715615d5057615d50615886565b8160405283519150615d6182615531565b818152615d7060208501615bf5565b6020820152615d8160408501615bf5565b6040820152615d9260608501615ad4565b6060820152615da360808501615bcd565b6080820152615db460a08501615bf5565b60a082015260c084015160c082015260e084015160e0820152809250505092915050565b931515845260ff9290921660208401526001600160a01b031660408301526001600160401b0316606082015260800190565b6020808252600d908201526c046524d3120616d6f756e743d3609c1b604082015260600190565b60ff83168152610120810161113760208301846157e8565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b601f821115613eeb57600081815260208120601f850160051c81016020861015615ebb5750805b601f850160051c820191505b81811015611a2057828155600101615ec7565b81516001600160401b03811115615ef357615ef3615886565b615f0781615f018454615b7a565b84615e94565b602080601f831160018114615f3c5760008415615f245750858301515b600019600386901b1c1916600185901b178555611a20565b600085815260208120601f198616915b82811015615f6b57888601518255948401946001909101908401615f4c565b5085821015615f895787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60008251615fab8184602087016155c3565b919091019291505056fea2646970667358221220d8e4d4011ef0fbd8beaf2c70f89fed43b8031e662fee709319735f3e2335eff564736f6c63430008120033

Block Transaction Gas Used Reward
view all blocks collator

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

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