Moonbase Alpha Testnet

Contract

0xd038039C11ae8F87A8c6f554f26f82ebE4F59075

Overview

DEV Balance

Moonbase Alpha LogoMoonbase Alpha LogoMoonbase Alpha Logo0 DEV

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Value
0x6080604029847522022-10-10 3:18:24536 days ago1665371904IN
 Contract Creation
0 DEV0.003595121

Latest 25 internal transactions (View All)

Parent Txn Hash Block From To Value
31037612022-11-01 16:22:36513 days ago1667319756
0xd038039C...bE4F59075
0 DEV
31037612022-11-01 16:22:36513 days ago1667319756
0xd038039C...bE4F59075
0 DEV
31037562022-11-01 16:21:24513 days ago1667319684
0xd038039C...bE4F59075
0 DEV
31037562022-11-01 16:21:24513 days ago1667319684
0xd038039C...bE4F59075
0 DEV
31037512022-11-01 16:19:48513 days ago1667319588
0xd038039C...bE4F59075
0 DEV
31037512022-11-01 16:19:48513 days ago1667319588
0xd038039C...bE4F59075
0 DEV
31037462022-11-01 16:18:12513 days ago1667319492
0xd038039C...bE4F59075
0 DEV
31037462022-11-01 16:18:12513 days ago1667319492
0xd038039C...bE4F59075
0 DEV
31037382022-11-01 16:15:18513 days ago1667319318
0xd038039C...bE4F59075
0 DEV
31037382022-11-01 16:15:18513 days ago1667319318
0xd038039C...bE4F59075
0 DEV
31037292022-11-01 16:12:00513 days ago1667319120
0xd038039C...bE4F59075
0 DEV
31037292022-11-01 16:12:00513 days ago1667319120
0xd038039C...bE4F59075
0 DEV
31037212022-11-01 16:10:12513 days ago1667319012
0xd038039C...bE4F59075
0 DEV
31037212022-11-01 16:10:12513 days ago1667319012
0xd038039C...bE4F59075
0 DEV
31037162022-11-01 16:08:48513 days ago1667318928
0xd038039C...bE4F59075
0 DEV
31037162022-11-01 16:08:48513 days ago1667318928
0xd038039C...bE4F59075
0 DEV
31037132022-11-01 16:07:24513 days ago1667318844
0xd038039C...bE4F59075
0 DEV
31037132022-11-01 16:07:24513 days ago1667318844
0xd038039C...bE4F59075
0 DEV
31037022022-11-01 16:04:54513 days ago1667318694
0xd038039C...bE4F59075
0 DEV
31037022022-11-01 16:04:54513 days ago1667318694
0xd038039C...bE4F59075
0 DEV
31036202022-11-01 15:42:54513 days ago1667317374
0xd038039C...bE4F59075
0 DEV
31036202022-11-01 15:42:54513 days ago1667317374
0xd038039C...bE4F59075
0 DEV
31036102022-11-01 15:40:24513 days ago1667317224
0xd038039C...bE4F59075
0 DEV
31036102022-11-01 15:40:24513 days ago1667317224
0xd038039C...bE4F59075
0 DEV
31036032022-11-01 15:38:48513 days ago1667317128
0xd038039C...bE4F59075
0 DEV
View All Internal Transactions
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0x753D5612...048a59923
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.10+commit.fc410830

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion

Contract Source Code (Solidity Standard Json-Input format)

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

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.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 "./interfaces/IFeeEmissionsQontroller.sol";
import "./interfaces/IFixedRateMarket.sol";
import "./interfaces/IQollateralManager.sol";
import "./interfaces/IQPriceOracle.sol";
import "./interfaces/ITradingEmissionsQontroller.sol";
import "./interfaces/IQAdmin.sol";
import "./libraries/ECDSA.sol";
import "./libraries/Interest.sol";

contract FixedRateMarket is Initializable, ERC20Upgradeable, IFixedRateMarket {

  using SafeERC20 for IERC20;

  /// @notice Contract storing all global Qoda parameters
  IQAdmin private _qAdmin;

  /// @notice Address of the ERC20 token which the loan will be denominated
  IERC20 private _underlyingToken;

  /// @notice UNIX timestamp (in seconds) when the market matures
  uint private _maturity;

  /// @notice True if a nonce for a Quote is void, false otherwise.
  /// Used for checking if a Quote is a duplicate, or cancelled.
  /// Note: We need to use a map of all nonces here instead of just storing
  /// latest nonce because: what if users have multiple live orders at once?
  /// account => nonce => bool
  mapping(address => mapping(uint => bool)) private _voidNonces;

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

  /// @notice Storage for the current total partial fill for a Quote
  /// quoteId => filled
  mapping(bytes32 => uint) private _quoteFill;

  /// @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 public constant ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60;

  /// @notice Constructor for upgradeable contracts
  /// @param qAdminAddress_ Address of the `QAdmin` contract
  /// @param underlyingTokenAddress_ 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 qAdminAddress_,
                      address underlyingTokenAddress_,
                      uint maturity_,
                      string memory name_,
                      string memory symbol_
                      ) public initializer {
    __ERC20_init(name_, symbol_);
    _qAdmin = IQAdmin(qAdminAddress_);
    _underlyingToken = IERC20(underlyingTokenAddress_);
    _maturity = maturity_;
  }

  /** USER INTERFACE **/

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

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

  /// @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){

    // Don't allow users to pay more than necessary
    amount = Math.min(amount, _accountBorrows[msg.sender]);

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

    // Check borrower has approved contract spend    
    require(_checkApproval(msg.sender, amount), "FRM2 not enough allowance");

    // Check borrower has enough balance
    require(_checkBalance(msg.sender, amount), "FRM3 not enough balance");

    // Effects: Deduct from the account's total debts
    // Guaranteed not to underflow due to the flooring on amount above
    _accountBorrows[msg.sender] -= amount;

    // Transfer amount from borrower to contract for escrow until maturity
    _underlyingToken.safeTransferFrom(msg.sender, address(this), amount);

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

    return _accountBorrows[msg.sender];
  }

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

    // Set the value to true for the `_voidNonces` mapping
    _voidNonces[msg.sender][nonce] = true;

    // Emit the event
    emit CancelQuote(msg.sender, nonce);
  }

  /// @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) {
    return _redeemQTokensByRatio(amount, block.timestamp);
  }

  /// @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) {
    return _redeemQTokensByRatio(_redeemableQTokens(msg.sender), block.timestamp);
  }

  /// @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 If an account is in danger of being undercollateralized (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 that is undercollateralized
  /// @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 {
    _liquidateBorrow(borrower, amount, collateralToken, block.timestamp);
  }

  /** VIEW FUNCTIONS **/

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

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

  /// @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(IFixedRateMarket(address(this)));
  }

  /// @notice True if a nonce for a Quote is voided, false otherwise.
  /// Used for checking if a Quote is a duplicated.
  /// @param account Account to query
  /// @param nonce Nonce to query
  /// @return bool True if used, false otherwise
  function isNonceVoid(address account, uint nonce) external view returns(bool){
    return _voidNonces[account][nonce];
  }

  /// @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 current total partial fill for a Quote
  /// @param quoteId ID of the Quote - this is the keccak256 hash of the signature
  /// @return uint Partial fill
  function quoteFill(bytes32 quoteId) external view returns(uint){
    return _quoteFill[quoteId];
  }

  /// @notice Gets the `protocolFee` associated with this market
  /// @return uint annualized protocol fee, scaled by 1e4
  function protocolFee() public view returns(uint) {
    return _qAdmin.protocolFee(IFixedRateMarket(address(this)));
  }

  /// @notice Gets the `protocolFee` associated with this market, prorated by time till maturity 
  /// @param amount loan amount
  /// @param timeNow block timestamp for calculating time till maturity, unit in second
  /// @return uint prorated protocol fee in local currency
  function proratedProtocolFee(uint amount, uint timeNow) public view returns(uint) {
    require(timeNow < _maturity, "FRM0 market expired");
    return amount * protocolFee() * (_maturity - timeNow) / _qAdmin.MANTISSA_BPS() / ONE_YEAR_IN_SECONDS;
  }

  /// @notice Gets the `protocolFee` associated with this market, prorated by time till maturity from now 
  /// @param amount loan amount
  /// @return uint prorated protocol fee, scaled by 1e4
  function proratedProtocolFeeNow(uint amount) external view returns(uint) {
    return proratedProtocolFee(amount, block.timestamp);
  }

  /// @notice Gets the current `redemptionRatio` where owned qTokens can be redeemed up to
  /// @return uint redemption ratio, 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;
  }

  /** INTERNAL FUNCTIONS **/

  /// @notice Internal function for executing quote as a borrower, please see `borrow()` for parameter and return value description 
  function _borrow(
                   uint amountPV,
                   address lender,
                   uint8 quoteType,
                   uint64 quoteExpiryTime,
                   uint64 APR,
                   uint cashflow,
                   uint nonce,
                   bytes memory signature,
                   uint timeNow
                   ) internal returns(uint, uint){
    require(timeNow < _maturity, "FRM0 market expired");

    QTypes.Quote memory quote = QTypes.Quote(
                                             keccak256(signature),
                                             address(this),
                                             lender,
                                             quoteType,
                                             1, // side=1 for lender
                                             quoteExpiryTime,
                                             APR,
                                             cashflow,
                                             nonce,
                                             signature
                                             );

    // Calculate the equivalent `amountFV`
    uint amountFV = Interest.PVToFV(
                                    APR,
                                    amountPV,
                                    timeNow,
                                    _maturity,
                                    _qAdmin.MANTISSA_BPS()
                                    );

    return _processLoan(amountPV, amountFV, quote, timeNow);
  }

  /// @notice Internal function for executing quote as a lender, please see `lend()` for parameter and return value description
  function _lend(
    uint amountPV,
    address borrower,
    uint8 quoteType,
    uint64 quoteExpiryTime,
    uint64 APR,
    uint cashflow,
    uint nonce,
    bytes memory signature,
    uint timeNow
  ) internal returns(uint, uint){
    require(timeNow < _maturity, "FRM0 market expired");

    QTypes.Quote memory quote = QTypes.Quote(
      keccak256(signature),
      address(this),
      borrower,
      quoteType,
      0, // side=0 for borrower
      quoteExpiryTime,
      APR,
      cashflow,
      nonce,
      signature
    );

    // Calculate the equivalent `amountFV`
    uint amountFV = Interest.PVToFV(
      APR,
      amountPV,
      timeNow,
      _maturity,
      _qAdmin.MANTISSA_BPS()
    );

    return _processLoan(amountPV, amountFV, quote, timeNow);
  }

  /// @notice Internal function for lender to redeem qTokens after maturity
  /// please see `redeemQTokensByRatio()` for parameter and return value description
  function _redeemQTokensByRatio(uint amount, uint timeNow) internal returns(uint) {
    // Enforce maturity + grace period before allowing redemptions
    require(timeNow > _maturity + _qAdmin.maturityGracePeriod(), "FRM4 cannot redeem early");

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

    // 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
    _underlyingToken.safeTransfer(msg.sender, amount);

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

    return amount;
  }

  /// @notice Internal function for any user to liquidate underwater or past maturity account, 
  /// please see `liquidateBorrow()` for parameter and return value description
  function _liquidateBorrow(
                            address borrower, 
                            uint amount,
                            IERC20 collateralToken,
                            uint timeNow
                            ) internal {
    IQollateralManager _qollateralManager = IQollateralManager(_qAdmin.qollateralManager());
    uint repaymentGracePeriod = _qAdmin.repaymentGracePeriod();

    // Ensure borrower is either undercollateralized or past payment due date.
    // These are the necessary conditions before borrower can be liquidated.
    require(
      _qollateralManager.collateralRatio(borrower) < _qAdmin.minCollateralRatio() ||
      timeNow > _maturity + repaymentGracePeriod,
      "FRM5 not liquidatable"
    );

    // For borrowers that are undercollateralized, liquidator can only repay up
    // to a percentage of the full loan balance determined by the `closeFactor`
    uint closeFactor = _qollateralManager.closeFactor();

    // For borrowers that are past due date, ignore the close factor - liquidator
    // can liquidate the entire sum
    if(timeNow > _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, "FRM6 amount = 0");

    // Get USD value of amount paid
    uint amountUSD = _qollateralManager.localToUSD(_underlyingToken, 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 = _qollateralManager.USDToLocal(collateralToken, rewardUSD);

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

    // Liquidator repays the loan on behalf of borrower
    _underlyingToken.safeTransferFrom(msg.sender, address(this), amount);

    // 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
    _qollateralManager._transferCollateral(
                                           collateralToken,
                                           borrower,
                                           msg.sender,
                                           rewardLocal
                                           );
  }

  /// @notice Intermediary function that handles some error handling, partial fills
  /// and managing uniqueness of nonces
  /// @param amountPV Size of the initial loan paid by lender
  /// @param amountFV Final amount that must be paid by borrower
  /// @param quote Quote struct for code simplicity / avoiding 'stack too deep' error
  /// @return uint, uint Loan amount (`amountPV`) and repayment amount (`amountFV`)
  function _processLoan(
                        uint amountPV,
                        uint amountFV,
                        QTypes.Quote memory quote,
                        uint timeNow
                        ) internal returns(uint, uint){

    address signer = ECDSA.getSigner(
                                     quote.marketAddress,
                                     quote.quoter,
                                     quote.quoteType,
                                     quote.side,
                                     quote.quoteExpiryTime,
                                     quote.APR,
                                     quote.cashflow,
                                     quote.nonce,
                                     quote.signature
                                     );

    // Check if signature is valid
    require(signer == quote.quoter, "FRM8 invalid signature");

    // Check if `Market` is already expired
    require(timeNow < _maturity, "FRM0 market expired");

    // Check that quote hasn't expired yet
    require(quote.quoteExpiryTime == 0 || quote.quoteExpiryTime > timeNow, "FRM9 quote expired");

    // Check that the quote meets the minimum size threshold or else it is invalid
    IFixedRateMarket market = IFixedRateMarket(quote.marketAddress);
    require(amountPV >= _qAdmin.minQuoteSize(market), "FRM10 size too small");

    // Check that the nonce hasn't already been used
    require(!_voidNonces[quote.quoter][quote.nonce], "FRM11 invalid nonce");    

    if(quote.quoteType == 0){ // Quote is in PV terms

      // `amountPV` cannot be greater than remaining quote size
      require(amountPV <= quote.cashflow - _quoteFill[quote.quoteId], "FRM12 size too large");

      // Update the partial fills for the quote
      _quoteFill[quote.quoteId] += amountPV;

    }else if(quote.quoteType == 1){ // Quote is in FV terms

      // `amountFV` cannot be greater than remaining quote size
      require(amountFV <= quote.cashflow - _quoteFill[quote.quoteId], "FRM12 size too large");

      // Update the partial fills for the quote
      _quoteFill[quote.quoteId] += amountFV;

    }else{
      revert("FRM13 invalid quote type"); 
    }

    // Nonce is used up once the partial fill equals the original amount
    if(_quoteFill[quote.quoteId] == quote.cashflow){
      _voidNonces[quote.quoter][quote.nonce] = true;
    }

    uint protocolFee_ = market.proratedProtocolFee(amountPV, timeNow);

    // Determine who is the lender and who is the borrower before instantiating loan
    if(quote.side == 1){
      // If quote.side = 1, the quoter is the lender
      return _createFixedRateLoan(quote.quoteId, msg.sender, quote.quoter, amountPV, amountFV, protocolFee_, timeNow);
    }else if (quote.side == 0){
      // If quote.side = 0, the quoter is the borrower
      return _createFixedRateLoan(quote.quoteId, quote.quoter, msg.sender, amountPV, amountFV, protocolFee_, timeNow);
    }else {
      revert("FRM14 invalid quote side"); //should not reach here
    }
  }

  /// @notice Mint the future payment tokens to the lender, add `amountFV` to
  /// the borrower's debts, and transfer `amountPV` from lender to borrower
  /// @param quoteId ID of the Quote - this is the keccak256 hash of the signature
  /// @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 timeNow Time in second since epoch when the loan is created
  /// @return uint, uint Loan amount (`amountPV`) and repayment amount (`amountFV`)
  function _createFixedRateLoan(
                                bytes32 quoteId,
                                address borrower,
                                address lender,
                                uint amountPV,
                                uint amountFV,
                                uint protocolFee_,
                                uint timeNow
                                ) internal returns(uint, uint){

    // Loan amount must be strictly positive
    require(amountPV > 0, "FRM15 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_, "FRM25 amount too small");

    require(lender != borrower, "FRM17 invalid counterparty");

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

    // Check lender has approved contract spend
    require(_checkApproval(lender, amountPV + protocolFee_), "FRM19 not enough allowance");

    // Check lender has enough balance
    require(_checkBalance(lender, amountPV + protocolFee_), "FRM20 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 borrower has sufficient collateral for loan. This should be
    // the `_initCollateralRatio` which should be a larger value than the
    // `_minCollateralRatio`. This protects users from taking loans at the
    // minimum threshold, putting them at risk of instant liquidation.
    IQollateralManager _qollateralManager = IQollateralManager(_qAdmin.qollateralManager());
    uint collateralRatio = _qollateralManager.hypotheticalCollateralRatio(
                                                                          borrower,
                                                                          IERC20(address(0)),
                                                                          0,
                                                                          0,
                                                                          IFixedRateMarket(address(this)),
                                                                          amountFV,
                                                                          0
                                                                          );
    require(collateralRatio >= _qollateralManager.initCollateralRatio(), "FRM21 not enough collateral");

    // 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
    _repayBorrowWithqToken(borrower, balanceOf(borrower));

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

    // Transfer `amountPV` from lender to borrower, and protocolFee from both lender and borrower to address holding it
    // Note that lender will pay `protocolFee_` from their account balance, when borrower will pay `protocolFee_` 
    // from their borrowed amount. So total amount involved in transfer = amountPV + protocolFee_  
    IFeeEmissionsQontroller feeEmissionsQontroller = IFeeEmissionsQontroller(_qAdmin.feeEmissionsQontroller());
    if (address(feeEmissionsQontroller) == address(0)) {
      _underlyingToken.safeTransferFrom(lender, borrower, amountPV);
    } else {
      _underlyingToken.safeTransferFrom(lender, address(feeEmissionsQontroller), protocolFee_ * 2);
      _underlyingToken.safeTransferFrom(lender, borrower, amountPV - protocolFee_);

      _totalAccruedFees += protocolFee_ * 2;
      feeEmissionsQontroller.receiveFees(_underlyingToken, 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
    _repayBorrowWithqToken(lender, balanceOf(lender));

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

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

    return (amountPV, amountFV);
  }

  /// @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)
  /// @param timeNow Block timestamp when trading reward update is requested 
  function _updateTradingRewards(address borrower, address lender, uint amountPV, uint timeNow) internal {

    // Instantiate interfaces
    ITradingEmissionsQontroller teq = ITradingEmissionsQontroller(_qAdmin.tradingEmissionsQontroller());
    IQPriceOracle oracle = IQPriceOracle(_qAdmin.qPriceOracle());

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

  /// @notice Borrower makes repayment with qTokens. The qTokens will automatically
  /// get burned and the accountBorrows deducted accordingly.
  /// @param account User account
  /// @return uint Remaining account borrow amount
  function _repayBorrowWithqToken(address account, uint amount) internal returns(uint){
    require(amount <= balanceOf(account), "FRM22 amount > QToken balance");

    // Don't allow users to pay more than necessary
    amount = Math.min(_accountBorrows[account], amount);
    
    if (amount > 0) {
      // Burn the qTokens from the account and subtract the amount for the user's borrows
      _burn(account, amount);
      _accountBorrows[account] -= amount;
  
      // Emit the repayment event
      emit RepayBorrow(account, amount, true);
    }

    // Return the remaining account borrow amount
    return _accountBorrows[account];
  }

  /// @notice Verify if the user has enough token balance
  /// @param userAddress Address of the account to check
  /// @param amount Balance must be greater than or equal to this amount
  /// @return bool true if sufficient balance otherwise false
  function _checkBalance(
                         address userAddress,
                         uint256 amount
                         ) internal view returns(bool){
    if(_underlyingToken.balanceOf(userAddress) >= amount) {
      return true;
    }
    return false;
  }

  /// @notice Verify if the user has approved the smart contract for spend
  /// @param userAddress Address of the account to check
  /// @param amount Allowance  must be greater than or equal to this amount
  /// @return bool true if sufficient allowance otherwise false
  function _checkApproval(
                          address userAddress,
                          uint256 amount
                          ) internal view returns(bool) {
    if(_underlyingToken.allowance(userAddress, address(this)) >= amount){
      return true;
    }
    return false;
  }

  /// @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
  function _redeemableQTokensByRatio(uint amount) internal view returns(uint) {
    uint repaidTotal = _underlyingToken.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 ratio;
  }




  /** 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(_underlyingToken)).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], "FRM23 borrows > qToken balance");

    // Safe from underflow after previous require statement
    uint maxTransferrable = balanceOf(from) - _accountBorrows[from];
    require(amount <= maxTransferrable, "FRM24 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;
    }

    _repayBorrowWithqToken(to, amount);
  }

  /// @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) returns (bool) {
    return _transferFrom(msg.sender, to, amount, block.timestamp);
  }

  /// @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) returns (bool) {
    return _transferFrom(from, to, amount, block.timestamp);
  }

  /// @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, uint timeNow) internal returns (bool) {
    // After maturity, amount to redeem must not exceed loan repayment ratio
    if (timeNow > _maturity) {
      require(timeNow > _maturity + _qAdmin.maturityGracePeriod(), "FRM4 cannot redeem early");
      uint redeemableTokens = _redeemableQTokens(from);
      require(amount <= redeemableTokens, "FRM23 amount > QToken redeemable balance");

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

}

File 2 of 23 : 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);
        }
    }
}

File 3 of 23 : ERC20Upgradeable.sol
// 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;
}

File 4 of 23 : MathUpgradeable.sol
// 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 MathUpgradeable {
    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;
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 6 of 23 : IERC20Metadata.sol
// 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);
}

File 7 of 23 : SafeERC20.sol
// 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");
        }
    }
}

File 8 of 23 : IFeeEmissionsQontroller.sol
//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 account, uint amount);

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

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

  /** 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(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 blocksTillRoundEnd() 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 totalFeesAccrued() external view returns (uint);

  function totalFeesClaimed() external view returns (uint);

}

File 9 of 23 : 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";

interface IFixedRateMarket is IERC20Upgradeable, IERC20MetadataUpgradeable {

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

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

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

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

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

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

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

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

  /// @notice This function allows net lenders to redeem qTokens for the
  /// underlying token. Redemptions may only be permitted after loan maturity
  /// plus `_maturityGracePeriod`. The public interface redeems 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 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 If an account is in danger of being undercollateralized (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 that is undercollateralized
  /// @param amount Amount to repay on behalf of account
  /// @param collateralToken Liquidator's choice of which currency to be paid in
  function liquidateBorrow(
                           address borrower,
                           uint amount,
                           IERC20 collateralToken
                           ) external;
  
  /** VIEW FUNCTIONS **/
  
  /// @notice Get the address of the `QollateralManager`
  /// @return address
  function qollateralManager() external view returns(address);

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

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

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

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

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

  /// @notice Get the `protocolFee` associated with this market
  /// @return uint annualized protocol fee, scaled by 1e4
  function protocolFee() external view returns(uint);

  /// @notice Get the `protocolFee` associated with this market, prorated by time till maturity 
  /// @param amount loan amount
  /// @param timeNow block timestamp for calculating time till maturity 
  /// @return uint prorated protocol fee, scaled by 1e4
  function proratedProtocolFee(uint amount, uint timeNow) external view returns(uint);

  /// @notice Get the `protocolFee` associated with this market, prorated by time till maturity from now 
  /// @param amount loan amount
  /// @return uint prorated protocol fee, scaled by 1e4
  function proratedProtocolFeeNow(uint amount) external view returns(uint);

  /// @notice Gets the current `redemptionRatio` where owned qTokens can be redeemed up to
  /// @return uint redemption ratio, scaled by 1e18
  function redemptionRatio() external view returns(uint);

  /// @notice Tokens redeemed across all users so far
  /// @return uint redeemed amount of qToken
  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);

}

File 10 of 23 : 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 withdraw collateral
  /// @param token ERC20 token
  /// @param amount Amount to withdraw (in local ccy)
  /// @return uint New collateral balance
  function withdrawCollateral(IERC20 token, uint amount) external returns(uint);

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

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

  /// @notice 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
  function virtualCollateralValue(address account) external view returns(uint);
  
  /// @notice Get the `collateralFactor` weighted value (in USD) for the tokens
  /// deposited for an account
  /// @param account Account to query
  /// @param token ERC20 token
  /// @return uint Value of token collateral of account in USD
  function virtualCollateralValueByToken(
                                         address account,
                                         IERC20 token
                                         ) external view returns(uint);

  /// @notice Get the `marketFactor` weighted net borrows (i.e. borrows - lends)
  /// in USD summed across all `Market`s participated in by the user
  /// @param account Account to query
  /// @return uint Borrow value of account in USD
  function virtualBorrowValue(address account) external view returns(uint);
  
  /// @notice Get the `marketFactor` weighted net borrows (i.e. borrows - lends)
  /// in USD for a particular `Market`
  /// @param account Account to query
  /// @param market `FixedRateMarket` contract
  /// @return uint Borrow value of account in USD
  function virtualBorrowValueByMarket(
                                      address account,
                                      IFixedRateMarket market
                                      ) external view returns(uint);

  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
  function realCollateralValue(address account) external view returns(uint);
  
  /// @notice Get the unweighted value (in USD) of the tokens deposited
  /// for an account
  /// @param account Account to query
  /// @param token ERC20 token
  /// @return uint Value of token collateral of account in USD
  function realCollateralValueByToken(
                                      address account,
                                      IERC20 token
                                      ) external view returns(uint);
  
  /// @notice Get the unweighted current net value borrowed (i.e. borrows - lends)
  /// in USD summed across all `Market`s participated in by the user
  /// @param account Account to query
  /// @return uint Borrow value of account in USD
  function realBorrowValue(address account) external view returns(uint);

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

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

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

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

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

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

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

File 11 of 23 : IQPriceOracle.sol
//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);  
}

File 12 of 23 : ITradingEmissionsQontroller.sol
//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 1e6)
  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);

  function qAdmin() external view returns(address);

  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 23 : 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 "./IFixedRateMarket.sol";
import "../libraries/QTypes.sol";

interface IQAdmin is IAccessControlUpgradeable {

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

  /// @notice Emitted when setting `_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 `collateralFactor`
  event SetCollateralFactor(address indexed tokenAddress, uint oldValue, uint newValue);

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

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

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

  /// @notice Emitted when `_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 `creditLimit` gets updated
  event SetCreditLimit(address accountAddress, uint oldValue, uint newValue); 
  
  /** ADMIN FUNCTIONS **/

  /// @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 to adjust allowed limit in USD for given address to do uncollateralized borrow
  /// Note that if credit limit is lowered, there might be chance where user's loan is subjected to 
  /// instant liquidations. So it's crucial to notify the user in advance before attempting the action.
  /// @param accountAddress accoutn for credit limit adjustment
  /// @param creditLimit_ new credit limit in USD, scaled by 1e6
  function _setCreditLimit(address accountAddress, 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 token ERC20 token corresponding to the Asset
  /// @param isYieldBearing True if token bears interest (eg aToken, cToken, mToken, etc)
  /// @param underlying Address of the underlying token
  /// @param oracleFeed Chainlink price feed address
  /// @param collateralFactor 0.0 to 1.0 (scaled to 1e8) for discounting risky assets
  /// @param marketFactor 0.0 to 1.0 (scaled to 1e8) for premium on risky borrows
  function _addAsset(
                     IERC20 token,
                     bool isYieldBearing,
                     address underlying,
                     address oracleFeed,
                     uint collateralFactor,
                     uint marketFactor
                     ) external;

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

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

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

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

  /// @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 market Address of the `FixedRateMarket` contract
  /// @param protocolFee_ New protocol fee value (scaled to 1e4)
  function _setProtocolFee(IFixedRateMarket market, 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;
  
  /** 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 `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 credit limit with associated address, scaled by 1e6
  function creditLimit(address accountAddress) 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 `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 IFixedRateMarket Address of `FixedRateMarket` contract
  function fixedRateMarkets(IERC20 token, uint maturity) external view returns(IFixedRateMarket);

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

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

  function initCollateralRatio() external view returns(uint);

  function closeFactor() external view returns(uint);

  function 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(IFixedRateMarket market) 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 2**256 - 1
  function UINT_MAX() external pure returns(uint);
  
  /// @notice Generic mantissa corresponding to ETH decimals
  function MANTISSA_DEFAULT() external pure returns(uint);

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

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

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

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

File 14 of 23 : ECDSA.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;

library ECDSA {

  /// @notice Recover the signer of a Quote given the plaintext inputs and signature
  /// @param marketAddress Address of `FixedRateMarket` contract
  /// @param quoter Account of the Quoter
  /// @param quoteType 0 for PV+APR, 1 for FV+APR
  /// @param side 0 if Quoter is borrowing, 1 if Quoter is lending
  /// @param quoteExpiryTime Timestamp after which the quote is no longer valid
  /// @param APR Annualized simple interest, scaled by 1e2
  /// @param cashflow Can be PV or FV depending on `quoteType`
  /// @param nonce For uniqueness of signature
  /// @param signature Signed hash of the Quote message
  /// @return address Signer of the message
  function getSigner(
                     address marketAddress,
                     address quoter,
                     uint8 quoteType,
                     uint8 side,
                     uint64 quoteExpiryTime,
                     uint64 APR,
                     uint cashflow,
                     uint nonce,
                     bytes memory signature
                     ) internal pure returns(address){
    bytes32 messageHash = getMessageHash(
                                         marketAddress,
                                         quoter,
                                         quoteType,
                                         side,
                                         quoteExpiryTime,
                                         APR,
                                         cashflow,
                                         nonce
                                         );
    return  _recoverSigner(messageHash, signature);    
  }

  /// @notice Hashes the fields of a Quote into an Ethereum message hash
  /// @param marketAddress Address of `FixedRateMarket` contract
  /// @param quoter Account of the Quoter
  /// @param quoteType 0 for PV+APR, 1 for FV+APR
  /// @param side 0 if Quoter is borrowing, 1 if Quoter is lending
  /// @param quoteExpiryTime Timestamp after which the quote is no longer valid
  /// @param APR Annualized simple interest, scaled by 1e2
  /// @param cashflow Can be PV or FV depending on `quoteType`
  /// @param nonce For uniqueness of signature
  /// @return bytes32 Message hash
  function getMessageHash(
                          address marketAddress,
                          address quoter,
                          uint8 quoteType,
                          uint8 side,
                          uint64 quoteExpiryTime,
                          uint64 APR,
                          uint cashflow,
                          uint nonce
                          ) internal pure returns(bytes32) {
    bytes32 unprefixedHash = keccak256(abi.encodePacked(
                                                        marketAddress,
                                                        quoter,
                                                        quoteType,
                                                        side,
                                                        quoteExpiryTime,
                                                        APR,
                                                        cashflow,
                                                        nonce
                                                        ));
    return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", unprefixedHash)); 
  }

  /// @notice Recovers the address of the signer of the `messageHash` from the
  /// signature. It should be used to check versus the cleartext address given
  /// to verify the message is indeed signed by the owner.
  /// @param messageHash Hash of the loan fields
  /// @param signature The candidate signature to recover the signer from
  /// @return address This is the recovered signer of the `messageHash` using the signature
  function _recoverSigner(
                          bytes32 messageHash,
                          bytes memory signature
                          ) private pure returns(address) {
    (bytes32 r, bytes32 s, uint8 v) = _splitSignature(signature);
    
    //built-in solidity function to recover the signer address using
    // the messageHash and signature
    return ecrecover(messageHash, v, r, s);
  }

  
  /// @notice Helper function that splits the signature into r,s,v components
  /// @param signature The candidate signature to recover the signer from
  /// @return r bytes32, s bytes32, v uint8
  function _splitSignature(bytes memory signature) private pure returns(
                                                                        bytes32 r,
                                                                        bytes32 s,
                                                                        uint8 v) {
    require(signature.length == 65, "invalid signature length");
    assembly {
      r := mload(add(signature, 32))
      s := mload(add(signature, 64))
      v := byte(0, mload(add(signature, 96)))
    }
  }
}

File 15 of 23 : Interest.sol
// 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 = 31563000;
    
    // elapsed time from now to maturity
    uint elapsed = eTime - sTime;

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

    return num / denom;
    
  }  
}

File 16 of 23 : AddressUpgradeable.sol
// 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);
            }
        }
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

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

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

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

File 19 of 23 : ContextUpgradeable.sol
// 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;
}

File 20 of 23 : draft-IERC20Permit.sol
// 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);
}

File 21 of 23 : Address.sol
// 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);
            }
        }
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

library QTypes {

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

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

}

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

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"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":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"nonce","type":"uint256"}],"name":"CancelQuote","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"quoteId","type":"bytes32"},{"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"}],"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":"collateralTokenAddress","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":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":[],"name":"ONE_YEAR_IN_SECONDS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","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":"address","name":"lender","type":"address"},{"internalType":"uint8","name":"quoteType","type":"uint8"},{"internalType":"uint64","name":"quoteExpiryTime","type":"uint64"},{"internalType":"uint64","name":"APR","type":"uint64"},{"internalType":"uint256","name":"cashflow","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"borrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"nonce","type":"uint256"}],"name":"cancelQuote","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":"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":"qAdminAddress_","type":"address"},{"internalType":"address","name":"underlyingTokenAddress_","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":"address","name":"account","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"}],"name":"isNonceVoid","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountPV","type":"uint256"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint8","name":"quoteType","type":"uint8"},{"internalType":"uint64","name":"quoteExpiryTime","type":"uint64"},{"internalType":"uint64","name":"APR","type":"uint64"},{"internalType":"uint256","name":"cashflow","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"lend","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","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":"timeNow","type":"uint256"}],"name":"proratedProtocolFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"proratedProtocolFeeNow","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":"qollateralManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"quoteId","type":"bytes32"}],"name":"quoteFill","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"redeemAllQTokensByRatio","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":[],"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":"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"}]

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106102065760003560e01c8063897819e01161011a578063c03eb805116100ad578063de987d501161007c578063de987d5014610462578063e6ac8f4c1461046a578063e7675c511461047d578063e7c8fed414610490578063f5e3c4621461049b57600080fd5b8063c03eb805146103e5578063ce0746c41461041e578063d40e8f4a14610426578063dd62ed3e1461044f57600080fd5b8063a457c2d7116100e9578063a457c2d7146103af578063a9059cbb146103c2578063b0e21e8a146103d5578063ba95534c146103dd57600080fd5b8063897819e01461036c57806395d89b411461038c5780639ab8367e146103945780639c5bf633146103a757600080fd5b8063284f7e121161019d5780634092bb9d1161016c5780634092bb9d146103215780635f2ead68146103365780635fac60b81461033e57806370a08231146103465780638194afbb1461035957600080fd5b8063284f7e12146102b9578063313ce567146102e157806333f5419b146102fb578063395093511461030e57600080fd5b806318160ddd116101d957806318160ddd14610271578063204f83f91461027957806323b872dd146102815780632495a5991461029457600080fd5b806302dcd07f1461020b57806306fdde0314610226578063095ea7b31461023b5780630e7527021461025e575b600080fd5b6102136104ae565b6040519081526020015b60405180910390f35b61022e6104be565b60405161021d9190613a21565b61024e610249366004613a6c565b610550565b604051901515815260200161021d565b61021361026c366004613a98565b61056a565b603554610213565b606754610213565b61024e61028f366004613ab1565b610704565b6066546001600160a01b03165b6040516001600160a01b03909116815260200161021d565b6102cc6102c7366004613baa565b61071c565b6040805192835260208301919091520161021d565b6102e9610741565b60405160ff909116815260200161021d565b610213610309366004613c5f565b6107af565b61024e61031c366004613a6c565b610881565b61033461032f366004613a98565b6108a3565b005b6102a16108fc565b61021361096a565b610213610354366004613c81565b6109d7565b610213610367366004613a98565b6109f2565b61021361037a366004613a98565b6000908152606a602052604090205490565b61022e6109fe565b6103346103a2366004613cbe565b610a0d565b606c54610213565b61024e6103bd366004613a6c565b610b5a565b61024e6103d0366004613a6c565b610be0565b610213610bee565b606d54610213565b61024e6103f3366004613a6c565b6001600160a01b03919091166000908152606860209081526040808320938352929052205460ff1690565b610213610c1f565b610213610434366004613c81565b6001600160a01b031660009081526069602052604090205490565b61021361045d366004613d51565b610c33565b610213610c5e565b6102cc610478366004613baa565b610cdf565b61021361048b366004613a98565b610cf3565b6102136301e1338081565b6103346104a9366004613d8a565b610cff565b60006104b933610d10565b905090565b6060603680546104cd90613dcc565b80601f01602080910402602001604051908101604052809291908181526020018280546104f990613dcc565b80156105465780601f1061051b57610100808354040283529160200191610546565b820191906000526020600020905b81548152906001019060200180831161052957829003601f168201915b5050505050905090565b60003361055e818585610d79565b60019150505b92915050565b33600090815260696020526040812054610585908390610e9d565b9150600082116105cc5760405162461bcd60e51b815260206004820152600d60248201526c046524d3120616d6f756e743d3609c1b60448201526064015b60405180910390fd5b6105d63383610eb3565b6106225760405162461bcd60e51b815260206004820152601960248201527f46524d32206e6f7420656e6f75676820616c6c6f77616e63650000000000000060448201526064016105c3565b61062c3383610f42565b6106785760405162461bcd60e51b815260206004820152601760248201527f46524d33206e6f7420656e6f7567682062616c616e636500000000000000000060448201526064016105c3565b3360009081526069602052604081208054849290610697908490613e1d565b90915550506066546106b4906001600160a01b0316333085610f78565b604080518381526000602082015233917f23e1d46573bb38c46bc3f95d3028aa9650e1e3a45659e5be95ab7a82caefd6f5910160405180910390a250503360009081526069602052604090205490565b600061071284848442610fe9565b90505b9392505050565b6000806107308a8a8a8a8a8a8a8a42611156565b915091509850989650505050505050565b6066546040805163313ce56760e01b815290516000926001600160a01b03169163313ce5679160048083019260209291908290030181865afa15801561078b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104b99190613e34565b600060675482106107d25760405162461bcd60e51b81526004016105c390613e51565b60655460408051630b637aa760e21b815290516301e13380926001600160a01b031691632d8dea9c9160048083019260209291908290030181865afa15801561081f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108439190613e7e565b836067546108519190613e1d565b610859610bee565b6108639087613e97565b61086d9190613e97565b6108779190613eb6565b6107159190613eb6565b60003361055e8185856108948383610c33565b61089e9190613ed8565b610d79565b336000818152606860209081526040808320858452825291829020805460ff1916600117905590518381527fca7b8417b9538e951786ee468654b646ac049daa30615f8b1eaf44d3f6635946910160405180910390a250565b60655460408051630be5d5ad60e31b815290516000926001600160a01b031691635f2ead689160048083019260209291908290030181865afa158015610946573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104b99190613ef0565b60655460405162827f6760e21b81523060048201526000916001600160a01b031690630209fd9c906024015b602060405180830381865afa1580156109b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104b99190613e7e565b6001600160a01b031660009081526033602052604090205490565b600061056482426107af565b6060603780546104cd90613dcc565b600054610100900460ff1615808015610a2d5750600054600160ff909116105b80610a475750303b158015610a47575060005460ff166001145b610aaa5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016105c3565b6000805460ff191660011790558015610acd576000805461ff0019166101001790555b610ad783836112a1565b606580546001600160a01b038089166001600160a01b031992831617909255606680549288169290911691909117905560678490558015610b52576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050565b60003381610b688286610c33565b905083811015610bc85760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016105c3565b610bd58286868403610d79565b506001949350505050565b600061071533848442610fe9565b606554604051632d8acc7960e21b81523060048201526000916001600160a01b03169063b62b31e490602401610996565b60006104b9610c2d33610d10565b426112d6565b6001600160a01b03918216600090815260346020908152604080832093909416825291909152205490565b60006104b9606560009054906101000a90046001600160a01b03166001600160a01b0316630df09d256040518163ffffffff1660e01b8152600401602060405180830381865afa158015610cb6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cda9190613e7e565b611462565b6000806107308a8a8a8a8a8a8a8a42611515565b600061056482426112d6565b610d0b83838342611615565b505050565b600080610d1c836109d7565b905060008111610d2f5750600092915050565b6001600160a01b0383166000908152606b602052604081205490610d56610cda8385613ed8565b9050818111610d66576000610d70565b610d708282613e1d565b95945050505050565b6001600160a01b038316610ddb5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016105c3565b6001600160a01b038216610e3c5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016105c3565b6001600160a01b0383811660008181526034602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6000818310610eac5781610715565b5090919050565b606654604051636eb1769f60e11b81526001600160a01b038481166004830152306024830152600092849291169063dd62ed3e906044015b602060405180830381865afa158015610f08573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f2c9190613e7e565b10610f3957506001610564565b50600092915050565b6066546040516370a0823160e01b81526001600160a01b03848116600483015260009284929116906370a0823190602401610eeb565b6040516001600160a01b0380851660248301528316604482015260648101829052610fe39085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152611de3565b50505050565b600060675482111561111e57606560009054906101000a90046001600160a01b03166001600160a01b031663c8b82f5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611048573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061106c9190613e7e565b6067546110799190613ed8565b82116110c25760405162461bcd60e51b815260206004820152601860248201527746524d342063616e6e6f742072656465656d206561726c7960401b60448201526064016105c3565b60006110cd86610d10565b9050808411156110ef5760405162461bcd60e51b81526004016105c390613f0d565b6001600160a01b0386166000908152606b602052604081208054869290611117908490613ed8565b9091555050505b6001600160a01b038516331415611140576111398484611eb5565b905061114e565b61114b858585611ec3565b90505b949350505050565b600080606754831061117a5760405162461bcd60e51b81526004016105c390613e51565b600060405180610140016040528086805190602001208152602001306001600160a01b031681526020018c6001600160a01b031681526020018b60ff168152602001600160ff1681526020018a67ffffffffffffffff1681526020018967ffffffffffffffff168152602001888152602001878152602001868152509050600061127f898e87606754606560009054906101000a90046001600160a01b03166001600160a01b0316632d8dea9c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611256573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061127a9190613e7e565b611edc565b905061128d8d828488611f88565b935093505050995099975050505050505050565b600054610100900460ff166112c85760405162461bcd60e51b81526004016105c390613f55565b6112d282826124be565b5050565b6065546040805163c8b82f5b60e01b815290516000926001600160a01b03169163c8b82f5b9160048083019260209291908290030181865afa158015611320573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113449190613e7e565b6067546113519190613ed8565b821161139a5760405162461bcd60e51b815260206004820152601860248201527746524d342063616e6e6f742072656465656d206561726c7960401b60448201526064016105c3565b60006113a533610d10565b9050808411156113c75760405162461bcd60e51b81526004016105c390613f0d565b6113d1338561250c565b336000908152606b6020526040812080548692906113f0908490613ed8565b9250508190555083606c60008282546114099190613ed8565b9091555050606654611425906001600160a01b0316338661266d565b60405184815233907fe60e13e1fa5509002572aab753f3f827f7796b5c22d3d93fdcfba50881e997ed9060200160405180910390a2509192915050565b606c546066546040516370a0823160e01b8152306004820152600092839290916001600160a01b03909116906370a0823190602401602060405180830381865afa1580156114b4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114d89190613e7e565b6114e29190613ed8565b90506000606c546114f260355490565b6114fc9190613ed8565b905060008161150b8685613e97565b610d709190613eb6565b60008060675483106115395760405162461bcd60e51b81526004016105c390613e51565b600060405180610140016040528086805190602001208152602001306001600160a01b031681526020018c6001600160a01b031681526020018b60ff168152602001600060ff1681526020018a67ffffffffffffffff1681526020018967ffffffffffffffff168152602001888152602001878152602001868152509050600061127f898e87606754606560009054906101000a90046001600160a01b03166001600160a01b0316632d8dea9c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611256573d6000803e3d6000fd5b60655460408051630be5d5ad60e31b815290516000926001600160a01b031691635f2ead689160048083019260209291908290030181865afa15801561165f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116839190613ef0565b90506000606560009054906101000a90046001600160a01b03166001600160a01b031663982a08726040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116da573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116fe9190613e7e565b9050606560009054906101000a90046001600160a01b03166001600160a01b03166384da26666040518163ffffffff1660e01b8152600401602060405180830381865afa158015611753573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117779190613e7e565b6040516332901d0b60e21b81526001600160a01b03888116600483015284169063ca40742c90602401602060405180830381865afa1580156117bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117e19190613e7e565b10806117f95750806067546117f69190613ed8565b83115b61183d5760405162461bcd60e51b815260206004820152601560248201527446524d35206e6f74206c6971756964617461626c6560581b60448201526064016105c3565b6000826001600160a01b03166305308b9f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561187d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118a19190613e7e565b905060675484111561192757606560009054906101000a90046001600160a01b03166001600160a01b031663de01c9cb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611900573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119249190613e7e565b90505b6065546040805163de01c9cb60e01b815290516000926001600160a01b03169163de01c9cb9160048083019260209291908290030181865afa158015611971573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119959190613e7e565b6001600160a01b0389166000908152606960205260409020546119b9908490613e97565b6119c39190613eb6565b90506119cf8782610e9d565b965060008711611a135760405162461bcd60e51b815260206004820152600f60248201526e046524d3620616d6f756e74203d203608c1b60448201526064016105c3565b606654604051637dee6c4760e01b81526001600160a01b03918216600482015260248101899052600091861690637dee6c4790604401602060405180830381865afa158015611a66573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a8a9190613e7e565b90506000606560009054906101000a90046001600160a01b03166001600160a01b031663de01c9cb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ae1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b059190613e7e565b606560009054906101000a90046001600160a01b03166001600160a01b0316638c765e946040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b58573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b7c9190613e7e565b611b869084613e97565b611b909190613eb6565b604051632a72258160e01b81526001600160a01b038a8116600483015260248201839052919250600091881690632a72258190604401602060405180830381865afa158015611be3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c079190613e7e565b60405163e7602b9d60e01b81526001600160a01b038d811660048301528b8116602483015291925060009189169063e7602b9d90604401602060405180830381865afa158015611c5b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c7f9190613e7e565b905080821115611cd15760405162461bcd60e51b815260206004820152601a60248201527f46524d37206e6f7420656e6f75676820636f6c6c61746572616c00000000000060448201526064016105c3565b606654611ce9906001600160a01b031633308e610f78565b6001600160a01b038c16600090815260696020526040812080548d9290611d11908490613e1d565b9091555050604080518c81526001600160a01b038c8116602083015291810184905233918e16907f298637f684da70674f26509b10f07ec2fbc77a335ab1e7d6215a4b2484d8bb529060600160405180910390a36040516352a494eb60e01b81526001600160a01b038b811660048301528d81166024830152336044830152606482018490528916906352a494eb90608401600060405180830381600087803b158015611dbd57600080fd5b505af1158015611dd1573d6000803e3d6000fd5b50505050505050505050505050505050565b6000611e38826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661269d9092919063ffffffff16565b805190915015610d0b5780806020019051810190611e569190613fa0565b610d0b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016105c3565b60003361055e8185856126ac565b600033611ed185828561288b565b610bd58585856126ac565b6000828410611f255760405162461bcd60e51b81526020600482015260156024820152741a5b9d985b1a59081d1a5b59481a5b9d195c9d985b605a1b60448201526064016105c3565b6301e133806000611f368686613e1d565b90506000828583611f5167ffffffffffffffff8d168c613e97565b611f5b9190613e97565b611f659190613eb6565b611f6f9190613eb6565b9050611f7b8189613ed8565b9998505050505050505050565b6000806000611fc485602001518660400151876060015188608001518960a001518a60c001518b60e001518c61010001518d61012001516128ff565b905084604001516001600160a01b0316816001600160a01b0316146120245760405162461bcd60e51b815260206004820152601660248201527546524d3820696e76616c6964207369676e617475726560501b60448201526064016105c3565b60675484106120455760405162461bcd60e51b81526004016105c390613e51565b60a085015167ffffffffffffffff16158061206d5750838560a0015167ffffffffffffffff16115b6120ae5760405162461bcd60e51b81526020600482015260126024820152711194934e481c5d5bdd1948195e1c1a5c995960721b60448201526064016105c3565b602085015160655460405162827f6760e21b81526001600160a01b03808416600483015290911690630209fd9c90602401602060405180830381865afa1580156120fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121209190613e7e565b8810156121665760405162461bcd60e51b81526020600482015260146024820152731194934c4c081cda5e99481d1bdbc81cdb585b1b60621b60448201526064016105c3565b6040808701516001600160a01b03166000908152606860209081528282206101008a015183529052205460ff16156121d65760405162461bcd60e51b815260206004820152601360248201527246524d313120696e76616c6964206e6f6e636560681b60448201526064016105c3565b606086015160ff166122735785516000908152606a602052604090205460e08701516122029190613e1d565b8811156122485760405162461bcd60e51b815260206004820152601460248201527346524d31322073697a6520746f6f206c6172676560601b60448201526064016105c3565b85516000908152606a6020526040812080548a9290612268908490613ed8565b909155506123519050565b856060015160ff16600114156123095785516000908152606a602052604090205460e08701516122a39190613e1d565b8711156122e95760405162461bcd60e51b815260206004820152601460248201527346524d31322073697a6520746f6f206c6172676560601b60448201526064016105c3565b85516000908152606a602052604081208054899290612268908490613ed8565b60405162461bcd60e51b815260206004820152601860248201527f46524d313320696e76616c69642071756f74652074797065000000000000000060448201526064016105c3565b60e086015186516000908152606a602052604090205414156123a2576040808701516001600160a01b03166000908152606860209081528282206101008a01518352905220805460ff191660011790555b6040516333f5419b60e01b815260048101899052602481018690526000906001600160a01b038316906333f5419b90604401602060405180830381865afa1580156123f1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124159190613e7e565b9050866080015160ff166001141561244a5761243e87600001513389604001518c8c868c6129f0565b945094505050506124b5565b608087015160ff1661246d5761243e87600001518860400151338c8c868c6129f0565b60405162461bcd60e51b815260206004820152601860248201527f46524d313420696e76616c69642071756f74652073696465000000000000000060448201526064016105c3565b94509492505050565b600054610100900460ff166124e55760405162461bcd60e51b81526004016105c390613f55565b81516124f890603690602085019061395c565b508051610d0b90603790602084019061395c565b6001600160a01b03821661256c5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b60648201526084016105c3565b612578826000836131c6565b6001600160a01b038216600090815260336020526040902054818110156125ec5760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b60648201526084016105c3565b6001600160a01b038316600090815260336020526040812083830390556035805484929061261b908490613e1d565b90915550506040518281526000906001600160a01b038516907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a3610d0b836000846132d3565b6040516001600160a01b038316602482015260448101829052610d0b90849063a9059cbb60e01b90606401610fac565b60606107128484600085613304565b6001600160a01b0383166127105760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016105c3565b6001600160a01b0382166127725760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016105c3565b61277d8383836131c6565b6001600160a01b038316600090815260336020526040902054818110156127f55760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016105c3565b6001600160a01b0380851660009081526033602052604080822085850390559185168152908120805484929061282c908490613ed8565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161287891815260200190565b60405180910390a3610fe38484846132d3565b60006128978484610c33565b90506000198114610fe357818110156128f25760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016105c3565b610fe38484848403610d79565b604080516bffffffffffffffffffffffff1960608c811b8216602080850191909152908c901b90911660348301526001600160f81b031960f88b811b821660488501528a901b1660498301526001600160c01b031960c089811b8216604a85015288901b166052830152605a8201869052607a80830186905283518084039091018152609a830184528051908201207f19457468657265756d205369676e6564204d6573736167653a0a33320000000060ba84015260d6808401919091528351808403909101815260f690920190925280519101206000906129e18184613435565b9b9a5050505050505050505050565b60008060008611612a345760405162461bcd60e51b815260206004820152600e60248201526d046524d313520616d6f756e743d360941b60448201526064016105c3565b848610612a775760405162461bcd60e51b8152602060048201526011602482015270232926989b1034b73b30b634b21020a82960791b60448201526064016105c3565b838611612abf5760405162461bcd60e51b81526020600482015260166024820152751194934c8d48185b5bdd5b9d081d1bdbc81cdb585b1b60521b60448201526064016105c3565b876001600160a01b0316876001600160a01b03161415612b215760405162461bcd60e51b815260206004820152601a60248201527f46524d313720696e76616c696420636f756e746572706172747900000000000060448201526064016105c3565b6067548310612b6b5760405162461bcd60e51b815260206004820152601660248201527546524d313820696e76616c6964206d6174757269747960501b60448201526064016105c3565b612b7e87612b798689613ed8565b610eb3565b612bca5760405162461bcd60e51b815260206004820152601a60248201527f46524d3139206e6f7420656e6f75676820616c6c6f77616e636500000000000060448201526064016105c3565b612bdd87612bd88689613ed8565b610f42565b612c295760405162461bcd60e51b815260206004820152601860248201527f46524d3230206e6f7420656e6f7567682062616c616e6365000000000000000060448201526064016105c3565b60655460408051630be5d5ad60e31b815290516000926001600160a01b031691635f2ead689160048083019260209291908290030181865afa158015612c73573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c979190613ef0565b60405163257041f360e01b81526001600160a01b038b81166004830152600060248301819052604483018190526064830181905230608484015260a483018a905260c4830181905292935083169063257041f39060e401602060405180830381865afa158015612d0b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d2f9190613e7e565b9050816001600160a01b031663b8f3ece16040518163ffffffff1660e01b8152600401602060405180830381865afa158015612d6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d939190613e7e565b811015612de25760405162461bcd60e51b815260206004820152601b60248201527f46524d3231206e6f7420656e6f75676820636f6c6c61746572616c000000000060448201526064016105c3565b6001600160a01b038a1660009081526069602052604081208054899290612e0a908490613ed8565b90915550612e2290508a612e1d816109d7565b6134b4565b5060405163064198ed60e31b81526001600160a01b038a8116600483015230602483015283169063320cc76890604401602060405180830381865afa158015612e6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e939190613fa0565b612ef957604051633d85eee160e21b81526001600160a01b038a8116600483015230602483015283169063f617bb8490604401600060405180830381600087803b158015612ee057600080fd5b505af1158015612ef4573d6000803e3d6000fd5b505050505b60405163064198ed60e31b81526001600160a01b038b8116600483015230602483015283169063320cc76890604401602060405180830381865afa158015612f45573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f699190613fa0565b612fcf57604051633d85eee160e21b81526001600160a01b038b8116600483015230602483015283169063f617bb8490604401600060405180830381600087803b158015612fb657600080fd5b505af1158015612fca573d6000803e3d6000fd5b505050505b60655460408051631e476c0960e21b815290516000926001600160a01b03169163791db0249160048083019260209291908290030181865afa158015613019573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061303d9190613ef0565b90506001600160a01b03811661306a57606654613065906001600160a01b03168b8d8c610f78565b61313d565b61308e8a8261307a8a6002613e97565b6066546001600160a01b0316929190610f78565b61309d8a8c61307a8a8d613e1d565b6130a8876002613e97565b606d60008282546130b99190613ed8565b90915550506066546001600160a01b038083169162b129a491166130de8a6002613e97565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604401600060405180830381600087803b15801561312457600080fd5b505af1158015613138573d6000803e3d6000fd5b505050505b6131478a896135d2565b6131548a612e1d8c6109d7565b506131618b8b8b896136c5565b604080518a8152602081018a90529081018890526001600160a01b03808c1691908d16908e907f814195afed760c4d1214915d81f055a44af981562a33c02cb7f9e544355f88059060600160405180910390a450969a95995094975050505050505050565b6001600160a01b03831615806131e357506001600160a01b038216155b156131ed57505050565b6001600160a01b03831660009081526069602052604090205461320f846109d7565b1161325c5760405162461bcd60e51b815260206004820152601e60248201527f46524d323320626f72726f7773203e2071546f6b656e2062616c616e6365000060448201526064016105c3565b6001600160a01b03831660009081526069602052604081205461327e856109d7565b6132889190613e1d565b905080821115610fe35760405162461bcd60e51b815260206004820152601660248201527546524d323420616d6f756e74203e20626f72726f777360501b60448201526064016105c3565b6001600160a01b03831615806132f057506001600160a01b038216155b156132fa57505050565b610fe382826134b4565b6060824710156133655760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016105c3565b6001600160a01b0385163b6133bc5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016105c3565b600080866001600160a01b031685876040516133d89190613fc2565b60006040518083038185875af1925050503d8060008114613415576040519150601f19603f3d011682016040523d82523d6000602084013e61341a565b606091505b509150915061342a8282866138af565b979650505050505050565b600080600080613444856138e8565b6040805160008152602081018083528b905260ff8316918101919091526060810184905260808101839052929550909350915060019060a0016020604051602081039080840390855afa15801561349f573d6000803e3d6000fd5b5050604051601f190151979650505050505050565b60006134bf836109d7565b82111561350e5760405162461bcd60e51b815260206004820152601d60248201527f46524d323220616d6f756e74203e2051546f6b656e2062616c616e636500000060448201526064016105c3565b6001600160a01b0383166000908152606960205260409020546135319083610e9d565b915081156135b557613543838361250c565b6001600160a01b0383166000908152606960205260408120805484929061356b908490613e1d565b909155505060408051838152600160208201526001600160a01b038516917f23e1d46573bb38c46bc3f95d3028aa9650e1e3a45659e5be95ab7a82caefd6f5910160405180910390a25b50506001600160a01b031660009081526069602052604090205490565b6001600160a01b0382166136285760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f20616464726573730060448201526064016105c3565b613634600083836131c6565b80603560008282546136469190613ed8565b90915550506001600160a01b03821660009081526033602052604081208054839290613673908490613ed8565b90915550506040518181526001600160a01b038316906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a36112d2600083836132d3565b60655460408051635db5813b60e11b815290516000926001600160a01b03169163bb6b02769160048083019260209291908290030181865afa15801561370f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137339190613ef0565b90506000606560009054906101000a90046001600160a01b03166001600160a01b031663a0ee95606040518163ffffffff1660e01b8152600401602060405180830381865afa15801561378a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137ae9190613ef0565b905060006137bc85856107af565b606654604051637dee6c4760e01b81526001600160a01b0391821660048201526024810183905291925060009190841690637dee6c4790604401602060405180830381865afa158015613813573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138379190613e7e565b60405163fd43683160e01b81526001600160a01b038a811660048301528981166024830152604482018390529192509085169063fd43683190606401600060405180830381600087803b15801561388d57600080fd5b505af11580156138a1573d6000803e3d6000fd5b505050505050505050505050565b606083156138be575081610715565b8251156138ce5782518084602001fd5b8160405162461bcd60e51b81526004016105c39190613a21565b6000806000835160411461393e5760405162461bcd60e51b815260206004820152601860248201527f696e76616c6964207369676e6174757265206c656e677468000000000000000060448201526064016105c3565b50505060208101516040820151606090920151909260009190911a90565b82805461396890613dcc565b90600052602060002090601f01602090048101928261398a57600085556139d0565b82601f106139a357805160ff19168380011785556139d0565b828001600101855582156139d0579182015b828111156139d05782518255916020019190600101906139b5565b506139dc9291506139e0565b5090565b5b808211156139dc57600081556001016139e1565b60005b83811015613a105781810151838201526020016139f8565b83811115610fe35750506000910152565b6020815260008251806020840152613a408160408501602087016139f5565b601f01601f19169190910160400192915050565b6001600160a01b0381168114613a6957600080fd5b50565b60008060408385031215613a7f57600080fd5b8235613a8a81613a54565b946020939093013593505050565b600060208284031215613aaa57600080fd5b5035919050565b600080600060608486031215613ac657600080fd5b8335613ad181613a54565b92506020840135613ae181613a54565b929592945050506040919091013590565b60ff81168114613a6957600080fd5b803567ffffffffffffffff81168114613b1957600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b600067ffffffffffffffff80841115613b4f57613b4f613b1e565b604051601f8501601f19908116603f01168101908282118183101715613b7757613b77613b1e565b81604052809350858152868686011115613b9057600080fd5b858560208301376000602087830101525050509392505050565b600080600080600080600080610100898b031215613bc757600080fd5b883597506020890135613bd981613a54565b96506040890135613be981613af2565b9550613bf760608a01613b01565b9450613c0560808a01613b01565b935060a0890135925060c0890135915060e089013567ffffffffffffffff811115613c2f57600080fd5b8901601f81018b13613c4057600080fd5b613c4f8b823560208401613b34565b9150509295985092959890939650565b60008060408385031215613c7257600080fd5b50508035926020909101359150565b600060208284031215613c9357600080fd5b813561071581613a54565b600082601f830112613caf57600080fd5b61071583833560208501613b34565b600080600080600060a08688031215613cd657600080fd5b8535613ce181613a54565b94506020860135613cf181613a54565b935060408601359250606086013567ffffffffffffffff80821115613d1557600080fd5b613d2189838a01613c9e565b93506080880135915080821115613d3757600080fd5b50613d4488828901613c9e565b9150509295509295909350565b60008060408385031215613d6457600080fd5b8235613d6f81613a54565b91506020830135613d7f81613a54565b809150509250929050565b600080600060608486031215613d9f57600080fd5b8335613daa81613a54565b9250602084013591506040840135613dc181613a54565b809150509250925092565b600181811c90821680613de057607f821691505b60208210811415613e0157634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b600082821015613e2f57613e2f613e07565b500390565b600060208284031215613e4657600080fd5b815161071581613af2565b6020808252601390820152721194934c081b585c9ad95d08195e1c1a5c9959606a1b604082015260600190565b600060208284031215613e9057600080fd5b5051919050565b6000816000190483118215151615613eb157613eb1613e07565b500290565b600082613ed357634e487b7160e01b600052601260045260246000fd5b500490565b60008219821115613eeb57613eeb613e07565b500190565b600060208284031215613f0257600080fd5b815161071581613a54565b60208082526028908201527f46524d323320616d6f756e74203e2051546f6b656e2072656465656d61626c656040820152672062616c616e636560c01b606082015260800190565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b600060208284031215613fb257600080fd5b8151801515811461071557600080fd5b60008251613fd48184602087016139f5565b919091019291505056fea2646970667358221220f8e2e160292ed357e758b09d1733c8460b469ef059d5252afe6da253d254e2d264736f6c634300080a0033

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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

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