ETH Price: $2,219.89 (+1.00%)

Transaction Decoder

Block:
9898176 at Apr-18-2020 07:06:34 PM +UTC
Transaction Fee:
0.000905965 ETH $2.01
Gas Used:
181,193 Gas / 5 Gwei

Emitted Events:

161 WETH9.Transfer( src=BZxVault, dst=0x7BC672A622620D531F9eB30dE89DAEC31a4240FA, wad=16776240792245480 )
162 WETH9.Transfer( src=0x7BC672A622620D531F9eB30dE89DAEC31a4240FA, dst=[Receiver] LoanToken, wad=15098616713020932 )
163 WETH9.Deposit( dst=[Receiver] LoanToken, wad=117000000000000000 )
164 LoanToken.Mint( minter=[Sender] 0x5eb366650afc512bf8b8b4ecc0e012e93651a34e, tokenAmount=113678343610294149, assetAmount=117000000000000000, price=1029219781747462560 )
165 LoanToken.Transfer( from=0x0000000000000000000000000000000000000000, to=[Sender] 0x5eb366650afc512bf8b8b4ecc0e012e93651a34e, value=113678343610294149 )

Account State Difference:

  Address   Before After State Difference Code
0x1Cf226E9...dE44AF002
(Spark Pool)
14.639625452674140448 Eth14.640531417674140448 Eth0.000905965
0x5eb36665...93651a34e
0.128693 Eth
Nonce: 0
0.010787035 Eth
Nonce: 1
0.117905965
0x77f973FC...3759281bC
0xC02aaA39...83C756Cc2 2,373,349.661762887774588657 Eth2,373,349.778762887774588657 Eth0.117

Execution Trace

ETH 0.117 LoanToken.8f6ede1f( )
  • ETH 0.117 LoanTokenLogicV4.mintWithEther( receiver=0x5eb366650Afc512Bf8B8b4ecC0E012e93651a34e ) => ( mintAmount=113678343610294149 )
    • BZxProxy.327ab639( )
      • 0x7d8bb0dcfb4f20115883050f45b517459735181b.327ab639( )
        • BZxVault.withdrawToken( token=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, to=0x7BC672A622620D531F9eB30dE89DAEC31a4240FA, tokenAmount=16776240792245480 ) => ( True )
          • WETH9.transfer( dst=0x7BC672A622620D531F9eB30dE89DAEC31a4240FA, wad=16776240792245480 ) => ( True )
          • 0x7bc672a622620d531f9eb30de89daec31a4240fa.daebc33e( )
            • WETH9.transfer( dst=0x77f973FCaF871459aa58cd81881Ce453759281bC, wad=15098616713020932 ) => ( True )
            • WETH9.balanceOf( 0x77f973FCaF871459aa58cd81881Ce453759281bC ) => ( 18194786023401839 )
            • ETH 0.117 WETH9.CALL( )
              File 1 of 5: LoanToken
              /**
               * Copyright 2017-2019, bZeroX, LLC. All Rights Reserved.
               * Licensed under the Apache License, Version 2.0.
               */
               
              pragma solidity 0.5.8;
              
              
              /**
               * @title ERC20Basic
               * @dev Simpler version of ERC20 interface
               * See https://github.com/ethereum/EIPs/issues/179
               */
              contract ERC20Basic {
                function totalSupply() public view returns (uint256);
                function balanceOf(address _who) public view returns (uint256);
                function transfer(address _to, uint256 _value) public returns (bool);
                event Transfer(address indexed from, address indexed to, uint256 value);
              }
              
              /**
               * @title ERC20 interface
               * @dev see https://github.com/ethereum/EIPs/issues/20
               */
              contract ERC20 is ERC20Basic {
                function allowance(address _owner, address _spender)
                  public view returns (uint256);
              
                function transferFrom(address _from, address _to, uint256 _value)
                  public returns (bool);
              
                function approve(address _spender, uint256 _value) public returns (bool);
                event Approval(
                  address indexed owner,
                  address indexed spender,
                  uint256 value
                );
              }
              
              contract WETHInterface is ERC20 {
                  function deposit() external payable;
                  function withdraw(uint256 wad) external;
              }
              
              /**
               * @title SafeMath
               * @dev Math operations with safety checks that throw on error
               */
              library SafeMath {
              
                /**
                * @dev Multiplies two numbers, throws on overflow.
                */
                function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                  // Gas optimization: this is cheaper than asserting 'a' not being zero, but the
                  // benefit is lost if 'b' is also tested.
                  // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                  if (_a == 0) {
                    return 0;
                  }
              
                  c = _a * _b;
                  assert(c / _a == _b);
                  return c;
                }
              
                /**
                * @dev Integer division of two numbers, truncating the quotient.
                */
                function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
                  // assert(_b > 0); // Solidity automatically throws when dividing by 0
                  // uint256 c = _a / _b;
                  // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
                  return _a / _b;
                }
              
                /**
                * @dev Integer division of two numbers, rounding up and truncating the quotient
                */
                function divCeil(uint256 _a, uint256 _b) internal pure returns (uint256) {
                  if (_a == 0) {
                    return 0;
                  }
              
                  return ((_a - 1) / _b) + 1;
                }
              
                /**
                * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
                */
                function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
                  assert(_b <= _a);
                  return _a - _b;
                }
              
                /**
                * @dev Adds two numbers, throws on overflow.
                */
                function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                  c = _a + _b;
                  assert(c >= _a);
                  return c;
                }
              }
              
              /**
               * @title Ownable
               * @dev The Ownable contract has an owner address, and provides basic authorization control
               * functions, this simplifies the implementation of "user permissions".
               */
              contract Ownable {
                address public owner;
              
              
                event OwnershipTransferred(
                  address indexed previousOwner,
                  address indexed newOwner
                );
              
              
                /**
                 * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                 * account.
                 */
                constructor() public {
                  owner = msg.sender;
                }
              
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                  require(msg.sender == owner);
                  _;
                }
              
                /**
                 * @dev Allows the current owner to transfer control of the contract to a newOwner.
                 * @param _newOwner The address to transfer ownership to.
                 */
                function transferOwnership(address _newOwner) public onlyOwner {
                  _transferOwnership(_newOwner);
                }
              
                /**
                 * @dev Transfers control of the contract to a newOwner.
                 * @param _newOwner The address to transfer ownership to.
                 */
                function _transferOwnership(address _newOwner) internal {
                  require(_newOwner != address(0));
                  emit OwnershipTransferred(owner, _newOwner);
                  owner = _newOwner;
                }
              }
              
              /**
               * @title Helps contracts guard against reentrancy attacks.
               * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
               * @dev If you mark a function `nonReentrant`, you should also
               * mark it `external`.
               */
              contract ReentrancyGuard {
              
                /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs.
                /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056
                uint256 internal constant REENTRANCY_GUARD_FREE = 1;
              
                /// @dev Constant for locked guard state
                uint256 internal constant REENTRANCY_GUARD_LOCKED = 2;
              
                /**
                 * @dev We use a single lock for the whole contract.
                 */
                uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE;
              
                /**
                 * @dev Prevents a contract from calling itself, directly or indirectly.
                 * If you mark a function `nonReentrant`, you should also
                 * mark it `external`. Calling one `nonReentrant` function from
                 * another is not supported. Instead, you can implement a
                 * `private` function doing the actual work, and an `external`
                 * wrapper marked as `nonReentrant`.
                 */
                modifier nonReentrant() {
                  require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant");
                  reentrancyLock = REENTRANCY_GUARD_LOCKED;
                  _;
                  reentrancyLock = REENTRANCY_GUARD_FREE;
                }
              
              }
              
              contract LoanTokenization is ReentrancyGuard, Ownable {
              
                  uint256 internal constant MAX_UINT = 2**256 - 1;
              
                  string public name;
                  string public symbol;
                  uint8 public decimals;
              
                  address public bZxContract;
                  address public bZxVault;
                  address public bZxOracle;
                  address public wethContract;
              
                  address public loanTokenAddress;
              
                  // price of token at last user checkpoint
                  mapping (address => uint256) internal checkpointPrices_;
              }
              
              contract LoanTokenStorage is LoanTokenization {
              
                  struct ListIndex {
                      uint256 index;
                      bool isSet;
                  }
              
                  struct LoanData {
                      bytes32 loanOrderHash;
                      uint256 leverageAmount;
                      uint256 initialMarginAmount;
                      uint256 maintenanceMarginAmount;
                      uint256 maxDurationUnixTimestampSec;
                      uint256 index;
                  }
              
                  struct TokenReserves {
                      address lender;
                      uint256 amount;
                  }
              
                  event Borrow(
                      address indexed borrower,
                      uint256 borrowAmount,
                      uint256 interestRate,
                      address collateralTokenAddress,
                      address tradeTokenToFillAddress,
                      bool withdrawOnOpen
                  );
              
                  event Claim(
                      address indexed claimant,
                      uint256 tokenAmount,
                      uint256 assetAmount,
                      uint256 remainingTokenAmount,
                      uint256 price
                  );
              
                  bool internal isInitialized_ = false;
              
                  address public tokenizedRegistry;
              
                  uint256 public baseRate = 1000000000000000000; // 1.0%
                  uint256 public rateMultiplier = 39000000000000000000; // 39%
              
                  // "fee percentage retained by the oracle" = SafeMath.sub(10**20, spreadMultiplier);
                  uint256 public spreadMultiplier;
              
                  mapping (uint256 => bytes32) public loanOrderHashes; // mapping of levergeAmount to loanOrderHash
                  mapping (bytes32 => LoanData) public loanOrderData; // mapping of loanOrderHash to LoanOrder
                  uint256[] public leverageList;
              
                  TokenReserves[] public burntTokenReserveList; // array of TokenReserves
                  mapping (address => ListIndex) public burntTokenReserveListIndex; // mapping of lender address to ListIndex objects
                  uint256 public burntTokenReserved; // total outstanding burnt token amount
                  address internal nextOwedLender_;
              
                  uint256 public totalAssetBorrow = 0; // current amount of loan token amount tied up in loans
              
                  uint256 internal checkpointSupply_;
              
                  uint256 internal lastSettleTime_;
              
                  uint256 public initialPrice;
              }
              
              contract AdvancedTokenStorage is LoanTokenStorage {
                  using SafeMath for uint256;
              
                  event Transfer(
                      address indexed from,
                      address indexed to,
                      uint256 value
                  );
                  event Approval(
                      address indexed owner,
                      address indexed spender,
                      uint256 value
                  );
                  event Mint(
                      address indexed minter,
                      uint256 tokenAmount,
                      uint256 assetAmount,
                      uint256 price
                  );
                  event Burn(
                      address indexed burner,
                      uint256 tokenAmount,
                      uint256 assetAmount,
                      uint256 price
                  );
              
                  mapping(address => uint256) internal balances;
                  mapping (address => mapping (address => uint256)) internal allowed;
                  uint256 internal totalSupply_;
              
                  function totalSupply()
                      public
                      view
                      returns (uint256)
                  {
                      return totalSupply_;
                  }
              
                  function balanceOf(
                      address _owner)
                      public
                      view
                      returns (uint256)
                  {
                      return balances[_owner];
                  }
              
                  function allowance(
                      address _owner,
                      address _spender)
                      public
                      view
                      returns (uint256)
                  {
                      return allowed[_owner][_spender];
                  }
              }
              
              contract LoanToken is AdvancedTokenStorage {
              
                  address internal target_;
              
                  constructor(
                      address _newTarget)
                      public
                  {
                      _setTarget(_newTarget);
                  }
              
                  function()
                      external
                      payable
                  {
                      address target = target_;
                      bytes memory data = msg.data;
                      assembly {
                          let result := delegatecall(gas, target, add(data, 0x20), mload(data), 0, 0)
                          let size := returndatasize
                          let ptr := mload(0x40)
                          returndatacopy(ptr, 0, size)
                          switch result
                          case 0 { revert(ptr, size) }
                          default { return(ptr, size) }
                      }
                  }
              
                  function setTarget(
                      address _newTarget)
                      public
                      onlyOwner
                  {
                      _setTarget(_newTarget);
                  }
              
                  function _setTarget(
                      address _newTarget)
                      internal
                  {
                      require(_isContract(_newTarget), "target not a contract");
                      target_ = _newTarget;
                  }
              
                  function _isContract(
                      address addr)
                      internal
                      view
                      returns (bool)
                  {
                      uint256 size;
                      assembly { size := extcodesize(addr) }
                      return size > 0;
                  }
              }

              File 2 of 5: BZxVault
              /**
               * Copyright 2017–2019, bZeroX, LLC. All Rights Reserved.
               * Licensed under the Apache License, Version 2.0.
               */
               
              pragma solidity 0.5.2;
              
              
              /**
               * @title Ownable
               * @dev The Ownable contract has an owner address, and provides basic authorization control
               * functions, this simplifies the implementation of "user permissions".
               */
              contract Ownable {
                address public owner;
              
              
                event OwnershipRenounced(address indexed previousOwner);
                event OwnershipTransferred(
                  address indexed previousOwner,
                  address indexed newOwner
                );
              
              
                /**
                 * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                 * account.
                 */
                constructor() public {
                  owner = msg.sender;
                }
              
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                  require(msg.sender == owner);
                  _;
                }
              
                /**
                 * @dev Allows the current owner to relinquish control of the contract.
                 * @notice Renouncing to ownership will leave the contract without an owner.
                 * It will not be possible to call the functions with the `onlyOwner`
                 * modifier anymore.
                 */
                function renounceOwnership() public onlyOwner {
                  emit OwnershipRenounced(owner);
                  owner = address(0);
                }
              
                /**
                 * @dev Allows the current owner to transfer control of the contract to a newOwner.
                 * @param _newOwner The address to transfer ownership to.
                 */
                function transferOwnership(address _newOwner) public onlyOwner {
                  _transferOwnership(_newOwner);
                }
              
                /**
                 * @dev Transfers control of the contract to a newOwner.
                 * @param _newOwner The address to transfer ownership to.
                 */
                function _transferOwnership(address _newOwner) internal {
                  require(_newOwner != address(0));
                  emit OwnershipTransferred(owner, _newOwner);
                  owner = _newOwner;
                }
              }
              
              contract BZxOwnable is Ownable {
              
                  address public bZxContractAddress;
              
                  event BZxOwnershipTransferred(address indexed previousBZxContract, address indexed newBZxContract);
              
                  // modifier reverts if bZxContractAddress isn't set
                  modifier onlyBZx() {
                      require(msg.sender == bZxContractAddress, "only bZx contracts can call this function");
                      _;
                  }
              
                  /**
                  * @dev Allows the current owner to transfer the bZx contract owner to a new contract address
                  * @param newBZxContractAddress The bZx contract address to transfer ownership to.
                  */
                  function transferBZxOwnership(address newBZxContractAddress) public onlyOwner {
                      require(newBZxContractAddress != address(0) && newBZxContractAddress != owner, "transferBZxOwnership::unauthorized");
                      emit BZxOwnershipTransferred(bZxContractAddress, newBZxContractAddress);
                      bZxContractAddress = newBZxContractAddress;
                  }
              
                  /**
                  * @dev Allows the current owner to transfer control of the contract to a newOwner.
                  * @param newOwner The address to transfer ownership to.
                  * This overrides transferOwnership in Ownable to prevent setting the new owner the same as the bZxContract
                  */
                  function transferOwnership(address newOwner) public onlyOwner {
                      require(newOwner != address(0) && newOwner != bZxContractAddress, "transferOwnership::unauthorized");
                      emit OwnershipTransferred(owner, newOwner);
                      owner = newOwner;
                  }
              }
              
              interface NonCompliantEIP20 {
                  function transfer(address _to, uint256 _value) external;
                  function transferFrom(address _from, address _to, uint256 _value) external;
                  function approve(address _spender, uint256 _value) external;
              }
              
              contract EIP20Wrapper {
              
                  function eip20Transfer(
                      address token,
                      address to,
                      uint256 value)
                      internal
                      returns (bool result) {
              
                      NonCompliantEIP20(token).transfer(to, value);
              
                      assembly {
                          switch returndatasize()   
                          case 0 {                        // non compliant ERC20
                              result := not(0)            // result is true
                          }
                          case 32 {                       // compliant ERC20
                              returndatacopy(0, 0, 32) 
                              result := mload(0)          // result == returndata of external call
                          }
                          default {                       // not an not an ERC20 token
                              revert(0, 0) 
                          }
                      }
              
                      require(result, "eip20Transfer failed");
                  }
              
                  function eip20TransferFrom(
                      address token,
                      address from,
                      address to,
                      uint256 value)
                      internal
                      returns (bool result) {
              
                      NonCompliantEIP20(token).transferFrom(from, to, value);
              
                      assembly {
                          switch returndatasize()   
                          case 0 {                        // non compliant ERC20
                              result := not(0)            // result is true
                          }
                          case 32 {                       // compliant ERC20
                              returndatacopy(0, 0, 32) 
                              result := mload(0)          // result == returndata of external call
                          }
                          default {                       // not an not an ERC20 token
                              revert(0, 0) 
                          }
                      }
              
                      require(result, "eip20TransferFrom failed");
                  }
              
                  function eip20Approve(
                      address token,
                      address spender,
                      uint256 value)
                      internal
                      returns (bool result) {
              
                      NonCompliantEIP20(token).approve(spender, value);
              
                      assembly {
                          switch returndatasize()   
                          case 0 {                        // non compliant ERC20
                              result := not(0)            // result is true
                          }
                          case 32 {                       // compliant ERC20
                              returndatacopy(0, 0, 32) 
                              result := mload(0)          // result == returndata of external call
                          }
                          default {                       // not an not an ERC20 token
                              revert(0, 0) 
                          }
                      }
              
                      require(result, "eip20Approve failed");
                  }
              }
              
              contract BZxVault is EIP20Wrapper, BZxOwnable {
              
                  // Only the bZx contract can directly deposit ether
                  function() external payable onlyBZx {}
              
                  function withdrawEther(
                      address payable to,
                      uint256 value)
                      public
                      onlyBZx
                      returns (bool)
                  {
                      uint256 amount = value;
                      if (amount > address(this).balance) {
                          amount = address(this).balance;
                      }
              
                      return (to.send(amount));
                  }
              
                  function depositToken(
                      address token,
                      address from,
                      uint256 tokenAmount)
                      public
                      onlyBZx
                      returns (bool)
                  {
                      if (tokenAmount == 0) {
                          return false;
                      }
              
                      eip20TransferFrom(
                          token,
                          from,
                          address(this),
                          tokenAmount);
              
                      return true;
                  }
              
                  function withdrawToken(
                      address token,
                      address to,
                      uint256 tokenAmount)
                      public
                      onlyBZx
                      returns (bool)
                  {
                      if (tokenAmount == 0) {
                          return false;
                      }
              
                      eip20Transfer(
                          token,
                          to,
                          tokenAmount);
              
                      return true;
                  }
              
                  function transferTokenFrom(
                      address token,
                      address from,
                      address to,
                      uint256 tokenAmount)
                      public
                      onlyBZx
                      returns (bool)
                  {
                      if (tokenAmount == 0) {
                          return false;
                      }
              
                      eip20TransferFrom(
                          token,
                          from,
                          to,
                          tokenAmount);
              
                      return true;
                  }
              }

              File 3 of 5: WETH9
              // Copyright (C) 2015, 2016, 2017 Dapphub
              
              // This program is free software: you can redistribute it and/or modify
              // it under the terms of the GNU General Public License as published by
              // the Free Software Foundation, either version 3 of the License, or
              // (at your option) any later version.
              
              // This program is distributed in the hope that it will be useful,
              // but WITHOUT ANY WARRANTY; without even the implied warranty of
              // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
              // GNU General Public License for more details.
              
              // You should have received a copy of the GNU General Public License
              // along with this program.  If not, see <http://www.gnu.org/licenses/>.
              
              pragma solidity ^0.4.18;
              
              contract WETH9 {
                  string public name     = "Wrapped Ether";
                  string public symbol   = "WETH";
                  uint8  public decimals = 18;
              
                  event  Approval(address indexed src, address indexed guy, uint wad);
                  event  Transfer(address indexed src, address indexed dst, uint wad);
                  event  Deposit(address indexed dst, uint wad);
                  event  Withdrawal(address indexed src, uint wad);
              
                  mapping (address => uint)                       public  balanceOf;
                  mapping (address => mapping (address => uint))  public  allowance;
              
                  function() public payable {
                      deposit();
                  }
                  function deposit() public payable {
                      balanceOf[msg.sender] += msg.value;
                      Deposit(msg.sender, msg.value);
                  }
                  function withdraw(uint wad) public {
                      require(balanceOf[msg.sender] >= wad);
                      balanceOf[msg.sender] -= wad;
                      msg.sender.transfer(wad);
                      Withdrawal(msg.sender, wad);
                  }
              
                  function totalSupply() public view returns (uint) {
                      return this.balance;
                  }
              
                  function approve(address guy, uint wad) public returns (bool) {
                      allowance[msg.sender][guy] = wad;
                      Approval(msg.sender, guy, wad);
                      return true;
                  }
              
                  function transfer(address dst, uint wad) public returns (bool) {
                      return transferFrom(msg.sender, dst, wad);
                  }
              
                  function transferFrom(address src, address dst, uint wad)
                      public
                      returns (bool)
                  {
                      require(balanceOf[src] >= wad);
              
                      if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                          require(allowance[src][msg.sender] >= wad);
                          allowance[src][msg.sender] -= wad;
                      }
              
                      balanceOf[src] -= wad;
                      balanceOf[dst] += wad;
              
                      Transfer(src, dst, wad);
              
                      return true;
                  }
              }
              
              
              /*
                                  GNU GENERAL PUBLIC LICENSE
                                     Version 3, 29 June 2007
              
               Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
               Everyone is permitted to copy and distribute verbatim copies
               of this license document, but changing it is not allowed.
              
                                          Preamble
              
                The GNU General Public License is a free, copyleft license for
              software and other kinds of works.
              
                The licenses for most software and other practical works are designed
              to take away your freedom to share and change the works.  By contrast,
              the GNU General Public License is intended to guarantee your freedom to
              share and change all versions of a program--to make sure it remains free
              software for all its users.  We, the Free Software Foundation, use the
              GNU General Public License for most of our software; it applies also to
              any other work released this way by its authors.  You can apply it to
              your programs, too.
              
                When we speak of free software, we are referring to freedom, not
              price.  Our General Public Licenses are designed to make sure that you
              have the freedom to distribute copies of free software (and charge for
              them if you wish), that you receive source code or can get it if you
              want it, that you can change the software or use pieces of it in new
              free programs, and that you know you can do these things.
              
                To protect your rights, we need to prevent others from denying you
              these rights or asking you to surrender the rights.  Therefore, you have
              certain responsibilities if you distribute copies of the software, or if
              you modify it: responsibilities to respect the freedom of others.
              
                For example, if you distribute copies of such a program, whether
              gratis or for a fee, you must pass on to the recipients the same
              freedoms that you received.  You must make sure that they, too, receive
              or can get the source code.  And you must show them these terms so they
              know their rights.
              
                Developers that use the GNU GPL protect your rights with two steps:
              (1) assert copyright on the software, and (2) offer you this License
              giving you legal permission to copy, distribute and/or modify it.
              
                For the developers' and authors' protection, the GPL clearly explains
              that there is no warranty for this free software.  For both users' and
              authors' sake, the GPL requires that modified versions be marked as
              changed, so that their problems will not be attributed erroneously to
              authors of previous versions.
              
                Some devices are designed to deny users access to install or run
              modified versions of the software inside them, although the manufacturer
              can do so.  This is fundamentally incompatible with the aim of
              protecting users' freedom to change the software.  The systematic
              pattern of such abuse occurs in the area of products for individuals to
              use, which is precisely where it is most unacceptable.  Therefore, we
              have designed this version of the GPL to prohibit the practice for those
              products.  If such problems arise substantially in other domains, we
              stand ready to extend this provision to those domains in future versions
              of the GPL, as needed to protect the freedom of users.
              
                Finally, every program is threatened constantly by software patents.
              States should not allow patents to restrict development and use of
              software on general-purpose computers, but in those that do, we wish to
              avoid the special danger that patents applied to a free program could
              make it effectively proprietary.  To prevent this, the GPL assures that
              patents cannot be used to render the program non-free.
              
                The precise terms and conditions for copying, distribution and
              modification follow.
              
                                     TERMS AND CONDITIONS
              
                0. Definitions.
              
                "This License" refers to version 3 of the GNU General Public License.
              
                "Copyright" also means copyright-like laws that apply to other kinds of
              works, such as semiconductor masks.
              
                "The Program" refers to any copyrightable work licensed under this
              License.  Each licensee is addressed as "you".  "Licensees" and
              "recipients" may be individuals or organizations.
              
                To "modify" a work means to copy from or adapt all or part of the work
              in a fashion requiring copyright permission, other than the making of an
              exact copy.  The resulting work is called a "modified version" of the
              earlier work or a work "based on" the earlier work.
              
                A "covered work" means either the unmodified Program or a work based
              on the Program.
              
                To "propagate" a work means to do anything with it that, without
              permission, would make you directly or secondarily liable for
              infringement under applicable copyright law, except executing it on a
              computer or modifying a private copy.  Propagation includes copying,
              distribution (with or without modification), making available to the
              public, and in some countries other activities as well.
              
                To "convey" a work means any kind of propagation that enables other
              parties to make or receive copies.  Mere interaction with a user through
              a computer network, with no transfer of a copy, is not conveying.
              
                An interactive user interface displays "Appropriate Legal Notices"
              to the extent that it includes a convenient and prominently visible
              feature that (1) displays an appropriate copyright notice, and (2)
              tells the user that there is no warranty for the work (except to the
              extent that warranties are provided), that licensees may convey the
              work under this License, and how to view a copy of this License.  If
              the interface presents a list of user commands or options, such as a
              menu, a prominent item in the list meets this criterion.
              
                1. Source Code.
              
                The "source code" for a work means the preferred form of the work
              for making modifications to it.  "Object code" means any non-source
              form of a work.
              
                A "Standard Interface" means an interface that either is an official
              standard defined by a recognized standards body, or, in the case of
              interfaces specified for a particular programming language, one that
              is widely used among developers working in that language.
              
                The "System Libraries" of an executable work include anything, other
              than the work as a whole, that (a) is included in the normal form of
              packaging a Major Component, but which is not part of that Major
              Component, and (b) serves only to enable use of the work with that
              Major Component, or to implement a Standard Interface for which an
              implementation is available to the public in source code form.  A
              "Major Component", in this context, means a major essential component
              (kernel, window system, and so on) of the specific operating system
              (if any) on which the executable work runs, or a compiler used to
              produce the work, or an object code interpreter used to run it.
              
                The "Corresponding Source" for a work in object code form means all
              the source code needed to generate, install, and (for an executable
              work) run the object code and to modify the work, including scripts to
              control those activities.  However, it does not include the work's
              System Libraries, or general-purpose tools or generally available free
              programs which are used unmodified in performing those activities but
              which are not part of the work.  For example, Corresponding Source
              includes interface definition files associated with source files for
              the work, and the source code for shared libraries and dynamically
              linked subprograms that the work is specifically designed to require,
              such as by intimate data communication or control flow between those
              subprograms and other parts of the work.
              
                The Corresponding Source need not include anything that users
              can regenerate automatically from other parts of the Corresponding
              Source.
              
                The Corresponding Source for a work in source code form is that
              same work.
              
                2. Basic Permissions.
              
                All rights granted under this License are granted for the term of
              copyright on the Program, and are irrevocable provided the stated
              conditions are met.  This License explicitly affirms your unlimited
              permission to run the unmodified Program.  The output from running a
              covered work is covered by this License only if the output, given its
              content, constitutes a covered work.  This License acknowledges your
              rights of fair use or other equivalent, as provided by copyright law.
              
                You may make, run and propagate covered works that you do not
              convey, without conditions so long as your license otherwise remains
              in force.  You may convey covered works to others for the sole purpose
              of having them make modifications exclusively for you, or provide you
              with facilities for running those works, provided that you comply with
              the terms of this License in conveying all material for which you do
              not control copyright.  Those thus making or running the covered works
              for you must do so exclusively on your behalf, under your direction
              and control, on terms that prohibit them from making any copies of
              your copyrighted material outside their relationship with you.
              
                Conveying under any other circumstances is permitted solely under
              the conditions stated below.  Sublicensing is not allowed; section 10
              makes it unnecessary.
              
                3. Protecting Users' Legal Rights From Anti-Circumvention Law.
              
                No covered work shall be deemed part of an effective technological
              measure under any applicable law fulfilling obligations under article
              11 of the WIPO copyright treaty adopted on 20 December 1996, or
              similar laws prohibiting or restricting circumvention of such
              measures.
              
                When you convey a covered work, you waive any legal power to forbid
              circumvention of technological measures to the extent such circumvention
              is effected by exercising rights under this License with respect to
              the covered work, and you disclaim any intention to limit operation or
              modification of the work as a means of enforcing, against the work's
              users, your or third parties' legal rights to forbid circumvention of
              technological measures.
              
                4. Conveying Verbatim Copies.
              
                You may convey verbatim copies of the Program's source code as you
              receive it, in any medium, provided that you conspicuously and
              appropriately publish on each copy an appropriate copyright notice;
              keep intact all notices stating that this License and any
              non-permissive terms added in accord with section 7 apply to the code;
              keep intact all notices of the absence of any warranty; and give all
              recipients a copy of this License along with the Program.
              
                You may charge any price or no price for each copy that you convey,
              and you may offer support or warranty protection for a fee.
              
                5. Conveying Modified Source Versions.
              
                You may convey a work based on the Program, or the modifications to
              produce it from the Program, in the form of source code under the
              terms of section 4, provided that you also meet all of these conditions:
              
                  a) The work must carry prominent notices stating that you modified
                  it, and giving a relevant date.
              
                  b) The work must carry prominent notices stating that it is
                  released under this License and any conditions added under section
                  7.  This requirement modifies the requirement in section 4 to
                  "keep intact all notices".
              
                  c) You must license the entire work, as a whole, under this
                  License to anyone who comes into possession of a copy.  This
                  License will therefore apply, along with any applicable section 7
                  additional terms, to the whole of the work, and all its parts,
                  regardless of how they are packaged.  This License gives no
                  permission to license the work in any other way, but it does not
                  invalidate such permission if you have separately received it.
              
                  d) If the work has interactive user interfaces, each must display
                  Appropriate Legal Notices; however, if the Program has interactive
                  interfaces that do not display Appropriate Legal Notices, your
                  work need not make them do so.
              
                A compilation of a covered work with other separate and independent
              works, which are not by their nature extensions of the covered work,
              and which are not combined with it such as to form a larger program,
              in or on a volume of a storage or distribution medium, is called an
              "aggregate" if the compilation and its resulting copyright are not
              used to limit the access or legal rights of the compilation's users
              beyond what the individual works permit.  Inclusion of a covered work
              in an aggregate does not cause this License to apply to the other
              parts of the aggregate.
              
                6. Conveying Non-Source Forms.
              
                You may convey a covered work in object code form under the terms
              of sections 4 and 5, provided that you also convey the
              machine-readable Corresponding Source under the terms of this License,
              in one of these ways:
              
                  a) Convey the object code in, or embodied in, a physical product
                  (including a physical distribution medium), accompanied by the
                  Corresponding Source fixed on a durable physical medium
                  customarily used for software interchange.
              
                  b) Convey the object code in, or embodied in, a physical product
                  (including a physical distribution medium), accompanied by a
                  written offer, valid for at least three years and valid for as
                  long as you offer spare parts or customer support for that product
                  model, to give anyone who possesses the object code either (1) a
                  copy of the Corresponding Source for all the software in the
                  product that is covered by this License, on a durable physical
                  medium customarily used for software interchange, for a price no
                  more than your reasonable cost of physically performing this
                  conveying of source, or (2) access to copy the
                  Corresponding Source from a network server at no charge.
              
                  c) Convey individual copies of the object code with a copy of the
                  written offer to provide the Corresponding Source.  This
                  alternative is allowed only occasionally and noncommercially, and
                  only if you received the object code with such an offer, in accord
                  with subsection 6b.
              
                  d) Convey the object code by offering access from a designated
                  place (gratis or for a charge), and offer equivalent access to the
                  Corresponding Source in the same way through the same place at no
                  further charge.  You need not require recipients to copy the
                  Corresponding Source along with the object code.  If the place to
                  copy the object code is a network server, the Corresponding Source
                  may be on a different server (operated by you or a third party)
                  that supports equivalent copying facilities, provided you maintain
                  clear directions next to the object code saying where to find the
                  Corresponding Source.  Regardless of what server hosts the
                  Corresponding Source, you remain obligated to ensure that it is
                  available for as long as needed to satisfy these requirements.
              
                  e) Convey the object code using peer-to-peer transmission, provided
                  you inform other peers where the object code and Corresponding
                  Source of the work are being offered to the general public at no
                  charge under subsection 6d.
              
                A separable portion of the object code, whose source code is excluded
              from the Corresponding Source as a System Library, need not be
              included in conveying the object code work.
              
                A "User Product" is either (1) a "consumer product", which means any
              tangible personal property which is normally used for personal, family,
              or household purposes, or (2) anything designed or sold for incorporation
              into a dwelling.  In determining whether a product is a consumer product,
              doubtful cases shall be resolved in favor of coverage.  For a particular
              product received by a particular user, "normally used" refers to a
              typical or common use of that class of product, regardless of the status
              of the particular user or of the way in which the particular user
              actually uses, or expects or is expected to use, the product.  A product
              is a consumer product regardless of whether the product has substantial
              commercial, industrial or non-consumer uses, unless such uses represent
              the only significant mode of use of the product.
              
                "Installation Information" for a User Product means any methods,
              procedures, authorization keys, or other information required to install
              and execute modified versions of a covered work in that User Product from
              a modified version of its Corresponding Source.  The information must
              suffice to ensure that the continued functioning of the modified object
              code is in no case prevented or interfered with solely because
              modification has been made.
              
                If you convey an object code work under this section in, or with, or
              specifically for use in, a User Product, and the conveying occurs as
              part of a transaction in which the right of possession and use of the
              User Product is transferred to the recipient in perpetuity or for a
              fixed term (regardless of how the transaction is characterized), the
              Corresponding Source conveyed under this section must be accompanied
              by the Installation Information.  But this requirement does not apply
              if neither you nor any third party retains the ability to install
              modified object code on the User Product (for example, the work has
              been installed in ROM).
              
                The requirement to provide Installation Information does not include a
              requirement to continue to provide support service, warranty, or updates
              for a work that has been modified or installed by the recipient, or for
              the User Product in which it has been modified or installed.  Access to a
              network may be denied when the modification itself materially and
              adversely affects the operation of the network or violates the rules and
              protocols for communication across the network.
              
                Corresponding Source conveyed, and Installation Information provided,
              in accord with this section must be in a format that is publicly
              documented (and with an implementation available to the public in
              source code form), and must require no special password or key for
              unpacking, reading or copying.
              
                7. Additional Terms.
              
                "Additional permissions" are terms that supplement the terms of this
              License by making exceptions from one or more of its conditions.
              Additional permissions that are applicable to the entire Program shall
              be treated as though they were included in this License, to the extent
              that they are valid under applicable law.  If additional permissions
              apply only to part of the Program, that part may be used separately
              under those permissions, but the entire Program remains governed by
              this License without regard to the additional permissions.
              
                When you convey a copy of a covered work, you may at your option
              remove any additional permissions from that copy, or from any part of
              it.  (Additional permissions may be written to require their own
              removal in certain cases when you modify the work.)  You may place
              additional permissions on material, added by you to a covered work,
              for which you have or can give appropriate copyright permission.
              
                Notwithstanding any other provision of this License, for material you
              add to a covered work, you may (if authorized by the copyright holders of
              that material) supplement the terms of this License with terms:
              
                  a) Disclaiming warranty or limiting liability differently from the
                  terms of sections 15 and 16 of this License; or
              
                  b) Requiring preservation of specified reasonable legal notices or
                  author attributions in that material or in the Appropriate Legal
                  Notices displayed by works containing it; or
              
                  c) Prohibiting misrepresentation of the origin of that material, or
                  requiring that modified versions of such material be marked in
                  reasonable ways as different from the original version; or
              
                  d) Limiting the use for publicity purposes of names of licensors or
                  authors of the material; or
              
                  e) Declining to grant rights under trademark law for use of some
                  trade names, trademarks, or service marks; or
              
                  f) Requiring indemnification of licensors and authors of that
                  material by anyone who conveys the material (or modified versions of
                  it) with contractual assumptions of liability to the recipient, for
                  any liability that these contractual assumptions directly impose on
                  those licensors and authors.
              
                All other non-permissive additional terms are considered "further
              restrictions" within the meaning of section 10.  If the Program as you
              received it, or any part of it, contains a notice stating that it is
              governed by this License along with a term that is a further
              restriction, you may remove that term.  If a license document contains
              a further restriction but permits relicensing or conveying under this
              License, you may add to a covered work material governed by the terms
              of that license document, provided that the further restriction does
              not survive such relicensing or conveying.
              
                If you add terms to a covered work in accord with this section, you
              must place, in the relevant source files, a statement of the
              additional terms that apply to those files, or a notice indicating
              where to find the applicable terms.
              
                Additional terms, permissive or non-permissive, may be stated in the
              form of a separately written license, or stated as exceptions;
              the above requirements apply either way.
              
                8. Termination.
              
                You may not propagate or modify a covered work except as expressly
              provided under this License.  Any attempt otherwise to propagate or
              modify it is void, and will automatically terminate your rights under
              this License (including any patent licenses granted under the third
              paragraph of section 11).
              
                However, if you cease all violation of this License, then your
              license from a particular copyright holder is reinstated (a)
              provisionally, unless and until the copyright holder explicitly and
              finally terminates your license, and (b) permanently, if the copyright
              holder fails to notify you of the violation by some reasonable means
              prior to 60 days after the cessation.
              
                Moreover, your license from a particular copyright holder is
              reinstated permanently if the copyright holder notifies you of the
              violation by some reasonable means, this is the first time you have
              received notice of violation of this License (for any work) from that
              copyright holder, and you cure the violation prior to 30 days after
              your receipt of the notice.
              
                Termination of your rights under this section does not terminate the
              licenses of parties who have received copies or rights from you under
              this License.  If your rights have been terminated and not permanently
              reinstated, you do not qualify to receive new licenses for the same
              material under section 10.
              
                9. Acceptance Not Required for Having Copies.
              
                You are not required to accept this License in order to receive or
              run a copy of the Program.  Ancillary propagation of a covered work
              occurring solely as a consequence of using peer-to-peer transmission
              to receive a copy likewise does not require acceptance.  However,
              nothing other than this License grants you permission to propagate or
              modify any covered work.  These actions infringe copyright if you do
              not accept this License.  Therefore, by modifying or propagating a
              covered work, you indicate your acceptance of this License to do so.
              
                10. Automatic Licensing of Downstream Recipients.
              
                Each time you convey a covered work, the recipient automatically
              receives a license from the original licensors, to run, modify and
              propagate that work, subject to this License.  You are not responsible
              for enforcing compliance by third parties with this License.
              
                An "entity transaction" is a transaction transferring control of an
              organization, or substantially all assets of one, or subdividing an
              organization, or merging organizations.  If propagation of a covered
              work results from an entity transaction, each party to that
              transaction who receives a copy of the work also receives whatever
              licenses to the work the party's predecessor in interest had or could
              give under the previous paragraph, plus a right to possession of the
              Corresponding Source of the work from the predecessor in interest, if
              the predecessor has it or can get it with reasonable efforts.
              
                You may not impose any further restrictions on the exercise of the
              rights granted or affirmed under this License.  For example, you may
              not impose a license fee, royalty, or other charge for exercise of
              rights granted under this License, and you may not initiate litigation
              (including a cross-claim or counterclaim in a lawsuit) alleging that
              any patent claim is infringed by making, using, selling, offering for
              sale, or importing the Program or any portion of it.
              
                11. Patents.
              
                A "contributor" is a copyright holder who authorizes use under this
              License of the Program or a work on which the Program is based.  The
              work thus licensed is called the contributor's "contributor version".
              
                A contributor's "essential patent claims" are all patent claims
              owned or controlled by the contributor, whether already acquired or
              hereafter acquired, that would be infringed by some manner, permitted
              by this License, of making, using, or selling its contributor version,
              but do not include claims that would be infringed only as a
              consequence of further modification of the contributor version.  For
              purposes of this definition, "control" includes the right to grant
              patent sublicenses in a manner consistent with the requirements of
              this License.
              
                Each contributor grants you a non-exclusive, worldwide, royalty-free
              patent license under the contributor's essential patent claims, to
              make, use, sell, offer for sale, import and otherwise run, modify and
              propagate the contents of its contributor version.
              
                In the following three paragraphs, a "patent license" is any express
              agreement or commitment, however denominated, not to enforce a patent
              (such as an express permission to practice a patent or covenant not to
              sue for patent infringement).  To "grant" such a patent license to a
              party means to make such an agreement or commitment not to enforce a
              patent against the party.
              
                If you convey a covered work, knowingly relying on a patent license,
              and the Corresponding Source of the work is not available for anyone
              to copy, free of charge and under the terms of this License, through a
              publicly available network server or other readily accessible means,
              then you must either (1) cause the Corresponding Source to be so
              available, or (2) arrange to deprive yourself of the benefit of the
              patent license for this particular work, or (3) arrange, in a manner
              consistent with the requirements of this License, to extend the patent
              license to downstream recipients.  "Knowingly relying" means you have
              actual knowledge that, but for the patent license, your conveying the
              covered work in a country, or your recipient's use of the covered work
              in a country, would infringe one or more identifiable patents in that
              country that you have reason to believe are valid.
              
                If, pursuant to or in connection with a single transaction or
              arrangement, you convey, or propagate by procuring conveyance of, a
              covered work, and grant a patent license to some of the parties
              receiving the covered work authorizing them to use, propagate, modify
              or convey a specific copy of the covered work, then the patent license
              you grant is automatically extended to all recipients of the covered
              work and works based on it.
              
                A patent license is "discriminatory" if it does not include within
              the scope of its coverage, prohibits the exercise of, or is
              conditioned on the non-exercise of one or more of the rights that are
              specifically granted under this License.  You may not convey a covered
              work if you are a party to an arrangement with a third party that is
              in the business of distributing software, under which you make payment
              to the third party based on the extent of your activity of conveying
              the work, and under which the third party grants, to any of the
              parties who would receive the covered work from you, a discriminatory
              patent license (a) in connection with copies of the covered work
              conveyed by you (or copies made from those copies), or (b) primarily
              for and in connection with specific products or compilations that
              contain the covered work, unless you entered into that arrangement,
              or that patent license was granted, prior to 28 March 2007.
              
                Nothing in this License shall be construed as excluding or limiting
              any implied license or other defenses to infringement that may
              otherwise be available to you under applicable patent law.
              
                12. No Surrender of Others' Freedom.
              
                If conditions are imposed on you (whether by court order, agreement or
              otherwise) that contradict the conditions of this License, they do not
              excuse you from the conditions of this License.  If you cannot convey a
              covered work so as to satisfy simultaneously your obligations under this
              License and any other pertinent obligations, then as a consequence you may
              not convey it at all.  For example, if you agree to terms that obligate you
              to collect a royalty for further conveying from those to whom you convey
              the Program, the only way you could satisfy both those terms and this
              License would be to refrain entirely from conveying the Program.
              
                13. Use with the GNU Affero General Public License.
              
                Notwithstanding any other provision of this License, you have
              permission to link or combine any covered work with a work licensed
              under version 3 of the GNU Affero General Public License into a single
              combined work, and to convey the resulting work.  The terms of this
              License will continue to apply to the part which is the covered work,
              but the special requirements of the GNU Affero General Public License,
              section 13, concerning interaction through a network will apply to the
              combination as such.
              
                14. Revised Versions of this License.
              
                The Free Software Foundation may publish revised and/or new versions of
              the GNU General Public License from time to time.  Such new versions will
              be similar in spirit to the present version, but may differ in detail to
              address new problems or concerns.
              
                Each version is given a distinguishing version number.  If the
              Program specifies that a certain numbered version of the GNU General
              Public License "or any later version" applies to it, you have the
              option of following the terms and conditions either of that numbered
              version or of any later version published by the Free Software
              Foundation.  If the Program does not specify a version number of the
              GNU General Public License, you may choose any version ever published
              by the Free Software Foundation.
              
                If the Program specifies that a proxy can decide which future
              versions of the GNU General Public License can be used, that proxy's
              public statement of acceptance of a version permanently authorizes you
              to choose that version for the Program.
              
                Later license versions may give you additional or different
              permissions.  However, no additional obligations are imposed on any
              author or copyright holder as a result of your choosing to follow a
              later version.
              
                15. Disclaimer of Warranty.
              
                THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
              APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
              HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
              OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
              THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
              PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
              IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
              ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
              
                16. Limitation of Liability.
              
                IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
              WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
              THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
              GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
              USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
              DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
              PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
              EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
              SUCH DAMAGES.
              
                17. Interpretation of Sections 15 and 16.
              
                If the disclaimer of warranty and limitation of liability provided
              above cannot be given local legal effect according to their terms,
              reviewing courts shall apply local law that most closely approximates
              an absolute waiver of all civil liability in connection with the
              Program, unless a warranty or assumption of liability accompanies a
              copy of the Program in return for a fee.
              
                                   END OF TERMS AND CONDITIONS
              
                          How to Apply These Terms to Your New Programs
              
                If you develop a new program, and you want it to be of the greatest
              possible use to the public, the best way to achieve this is to make it
              free software which everyone can redistribute and change under these terms.
              
                To do so, attach the following notices to the program.  It is safest
              to attach them to the start of each source file to most effectively
              state the exclusion of warranty; and each file should have at least
              the "copyright" line and a pointer to where the full notice is found.
              
                  <one line to give the program's name and a brief idea of what it does.>
                  Copyright (C) <year>  <name of author>
              
                  This program is free software: you can redistribute it and/or modify
                  it under the terms of the GNU General Public License as published by
                  the Free Software Foundation, either version 3 of the License, or
                  (at your option) any later version.
              
                  This program is distributed in the hope that it will be useful,
                  but WITHOUT ANY WARRANTY; without even the implied warranty of
                  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                  GNU General Public License for more details.
              
                  You should have received a copy of the GNU General Public License
                  along with this program.  If not, see <http://www.gnu.org/licenses/>.
              
              Also add information on how to contact you by electronic and paper mail.
              
                If the program does terminal interaction, make it output a short
              notice like this when it starts in an interactive mode:
              
                  <program>  Copyright (C) <year>  <name of author>
                  This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
                  This is free software, and you are welcome to redistribute it
                  under certain conditions; type `show c' for details.
              
              The hypothetical commands `show w' and `show c' should show the appropriate
              parts of the General Public License.  Of course, your program's commands
              might be different; for a GUI interface, you would use an "about box".
              
                You should also get your employer (if you work as a programmer) or school,
              if any, to sign a "copyright disclaimer" for the program, if necessary.
              For more information on this, and how to apply and follow the GNU GPL, see
              <http://www.gnu.org/licenses/>.
              
                The GNU General Public License does not permit incorporating your program
              into proprietary programs.  If your program is a subroutine library, you
              may consider it more useful to permit linking proprietary applications with
              the library.  If this is what you want to do, use the GNU Lesser General
              Public License instead of this License.  But first, please read
              <http://www.gnu.org/philosophy/why-not-lgpl.html>.
              
              */

              File 4 of 5: LoanTokenLogicV4
              /**
               * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved.
               * Licensed under the Apache License, Version 2.0.
               */
              
              pragma solidity 0.5.8;
              pragma experimental ABIEncoderV2;
              
              
              /**
               * @title ERC20Basic
               * @dev Simpler version of ERC20 interface
               * See https://github.com/ethereum/EIPs/issues/179
               */
              contract ERC20Basic {
                function totalSupply() public view returns (uint256);
                function balanceOf(address _who) public view returns (uint256);
                function transfer(address _to, uint256 _value) public returns (bool);
                event Transfer(address indexed from, address indexed to, uint256 value);
              }
              
              /**
               * @title ERC20 interface
               * @dev see https://github.com/ethereum/EIPs/issues/20
               */
              contract ERC20 is ERC20Basic {
                function allowance(address _owner, address _spender)
                  public view returns (uint256);
              
                function transferFrom(address _from, address _to, uint256 _value)
                  public returns (bool);
              
                function approve(address _spender, uint256 _value) public returns (bool);
                event Approval(
                  address indexed owner,
                  address indexed spender,
                  uint256 value
                );
              }
              
              /**
               * @title EIP20/ERC20 interface
               * @dev see https://github.com/ethereum/EIPs/issues/20
               */
              contract EIP20 is ERC20 {
                  string public name;
                  uint8 public decimals;
                  string public symbol;
              }
              
              contract WETHInterface is EIP20 {
                  function deposit() external payable;
                  function withdraw(uint256 wad) external;
              }
              
              /**
               * @title SafeMath
               * @dev Math operations with safety checks that throw on error
               */
              library SafeMath {
              
                /**
                * @dev Multiplies two numbers, throws on overflow.
                */
                function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                  // Gas optimization: this is cheaper than asserting 'a' not being zero, but the
                  // benefit is lost if 'b' is also tested.
                  // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                  if (_a == 0) {
                    return 0;
                  }
              
                  c = _a * _b;
                  assert(c / _a == _b);
                  return c;
                }
              
                /**
                * @dev Integer division of two numbers, truncating the quotient.
                */
                function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
                  // assert(_b > 0); // Solidity automatically throws when dividing by 0
                  // uint256 c = _a / _b;
                  // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
                  return _a / _b;
                }
              
                /**
                * @dev Integer division of two numbers, rounding up and truncating the quotient
                */
                function divCeil(uint256 _a, uint256 _b) internal pure returns (uint256) {
                  if (_a == 0) {
                    return 0;
                  }
              
                  return ((_a - 1) / _b) + 1;
                }
              
                /**
                * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
                */
                function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
                  assert(_b <= _a);
                  return _a - _b;
                }
              
                /**
                * @dev Adds two numbers, throws on overflow.
                */
                function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                  c = _a + _b;
                  assert(c >= _a);
                  return c;
                }
              }
              
              /**
               * @title Ownable
               * @dev The Ownable contract has an owner address, and provides basic authorization control
               * functions, this simplifies the implementation of "user permissions".
               */
              contract Ownable {
                address public owner;
              
              
                event OwnershipTransferred(
                  address indexed previousOwner,
                  address indexed newOwner
                );
              
              
                /**
                 * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                 * account.
                 */
                constructor() public {
                  owner = msg.sender;
                }
              
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                  require(msg.sender == owner);
                  _;
                }
              
                /**
                 * @dev Allows the current owner to transfer control of the contract to a newOwner.
                 * @param _newOwner The address to transfer ownership to.
                 */
                function transferOwnership(address _newOwner) public onlyOwner {
                  _transferOwnership(_newOwner);
                }
              
                /**
                 * @dev Transfers control of the contract to a newOwner.
                 * @param _newOwner The address to transfer ownership to.
                 */
                function _transferOwnership(address _newOwner) internal {
                  require(_newOwner != address(0));
                  emit OwnershipTransferred(owner, _newOwner);
                  owner = _newOwner;
                }
              }
              
              /**
               * @title Helps contracts guard against reentrancy attacks.
               * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
               * @dev If you mark a function `nonReentrant`, you should also
               * mark it `external`.
               */
              contract ReentrancyGuard {
              
                /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs.
                /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056
                uint256 internal constant REENTRANCY_GUARD_FREE = 1;
              
                /// @dev Constant for locked guard state
                uint256 internal constant REENTRANCY_GUARD_LOCKED = 2;
              
                /**
                 * @dev We use a single lock for the whole contract.
                 */
                uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE;
              
                /**
                 * @dev Prevents a contract from calling itself, directly or indirectly.
                 * If you mark a function `nonReentrant`, you should also
                 * mark it `external`. Calling one `nonReentrant` function from
                 * another is not supported. Instead, you can implement a
                 * `private` function doing the actual work, and an `external`
                 * wrapper marked as `nonReentrant`.
                 */
                modifier nonReentrant() {
                  require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant");
                  reentrancyLock = REENTRANCY_GUARD_LOCKED;
                  _;
                  reentrancyLock = REENTRANCY_GUARD_FREE;
                }
              
              }
              
              contract LoanTokenization is ReentrancyGuard, Ownable {
              
                  uint256 internal constant MAX_UINT = 2**256 - 1;
              
                  string public name;
                  string public symbol;
                  uint8 public decimals;
              
                  address public bZxContract;
                  address public bZxVault;
                  address public bZxOracle;
                  address public wethContract;
              
                  address public loanTokenAddress;
              
                  // price of token at last user checkpoint
                  mapping (address => uint256) internal checkpointPrices_;
              }
              
              contract LoanTokenStorage is LoanTokenization {
              
                  struct ListIndex {
                      uint256 index;
                      bool isSet;
                  }
              
                  struct LoanData {
                      bytes32 loanOrderHash;
                      uint256 leverageAmount;
                      uint256 initialMarginAmount;
                      uint256 maintenanceMarginAmount;
                      uint256 maxDurationUnixTimestampSec;
                      uint256 index;
                      uint256 marginPremiumAmount;
                      address collateralTokenAddress;
                  }
              
                  struct TokenReserves {
                      address lender;
                      uint256 amount;
                  }
              
                  event Borrow(
                      address indexed borrower,
                      uint256 borrowAmount,
                      uint256 interestRate,
                      address collateralTokenAddress,
                      address tradeTokenToFillAddress,
                      bool withdrawOnOpen
                  );
              
                  event Repay(
                      bytes32 indexed loanOrderHash,
                      address indexed borrower,
                      address closer,
                      uint256 amount,
                      bool isLiquidation
                  );
              
                  event Claim(
                      address indexed claimant,
                      uint256 tokenAmount,
                      uint256 assetAmount,
                      uint256 remainingTokenAmount,
                      uint256 price
                  );
              
                  bool internal isInitialized_ = false;
              
                  address public tokenizedRegistry;
              
                  uint256 public baseRate = 1000000000000000000; // 1.0%
                  uint256 public rateMultiplier = 18750000000000000000; // 18.75%
              
                  // slot addition (non-sequential): lowUtilBaseRate = 8000000000000000000; // 8.0%
                  // slot addition (non-sequential): lowUtilRateMultiplier = 4750000000000000000; // 4.75%
              
                  // "fee percentage retained by the oracle" = SafeMath.sub(10**20, spreadMultiplier);
                  uint256 public spreadMultiplier;
              
                  mapping (uint256 => bytes32) public loanOrderHashes; // mapping of levergeAmount to loanOrderHash
                  mapping (bytes32 => LoanData) public loanOrderData; // mapping of loanOrderHash to LoanOrder
                  uint256[] public leverageList;
              
                  TokenReserves[] public burntTokenReserveList; // array of TokenReserves
                  mapping (address => ListIndex) public burntTokenReserveListIndex; // mapping of lender address to ListIndex objects
                  uint256 public burntTokenReserved; // total outstanding burnt token amount
                  address internal nextOwedLender_;
              
                  uint256 public totalAssetBorrow; // current amount of loan token amount tied up in loans
              
                  uint256 public checkpointSupply;
              
                  uint256 internal lastSettleTime_;
              
                  uint256 public initialPrice;
              }
              
              contract AdvancedTokenStorage is LoanTokenStorage {
                  using SafeMath for uint256;
              
                  event Transfer(
                      address indexed from,
                      address indexed to,
                      uint256 value
                  );
                  event Approval(
                      address indexed owner,
                      address indexed spender,
                      uint256 value
                  );
                  event Mint(
                      address indexed minter,
                      uint256 tokenAmount,
                      uint256 assetAmount,
                      uint256 price
                  );
                  event Burn(
                      address indexed burner,
                      uint256 tokenAmount,
                      uint256 assetAmount,
                      uint256 price
                  );
              
                  mapping(address => uint256) internal balances;
                  mapping (address => mapping (address => uint256)) internal allowed;
                  uint256 internal totalSupply_;
              
                  function totalSupply()
                      public
                      view
                      returns (uint256)
                  {
                      return totalSupply_;
                  }
              
                  function balanceOf(
                      address _owner)
                      public
                      view
                      returns (uint256)
                  {
                      return balances[_owner];
                  }
              
                  function allowance(
                      address _owner,
                      address _spender)
                      public
                      view
                      returns (uint256)
                  {
                      return allowed[_owner][_spender];
                  }
              }
              
              contract AdvancedToken is AdvancedTokenStorage {
                  using SafeMath for uint256;
              
                  function approve(
                      address _spender,
                      uint256 _value)
                      public
                      returns (bool)
                  {
                      allowed[msg.sender][_spender] = _value;
                      emit Approval(msg.sender, _spender, _value);
                      return true;
                  }
              
                  function _mint(
                      address _to,
                      uint256 _tokenAmount,
                      uint256 _assetAmount,
                      uint256 _price)
                      internal
                  {
                      require(_to != address(0), "15");
                      totalSupply_ = totalSupply_.add(_tokenAmount);
                      balances[_to] = balances[_to].add(_tokenAmount);
              
                      emit Mint(_to, _tokenAmount, _assetAmount, _price);
                      emit Transfer(address(0), _to, _tokenAmount);
                  }
              
                  function _burn(
                      address _who,
                      uint256 _tokenAmount,
                      uint256 _assetAmount,
                      uint256 _price)
                      internal
                  {
                      require(_tokenAmount <= balances[_who], "16");
                      // no need to require value <= totalSupply, since that would imply the
                      // sender's balance is greater than the totalSupply, which *should* be an assertion failure
              
                      balances[_who] = balances[_who].sub(_tokenAmount);
                      if (balances[_who] <= 10) { // we can't leave such small balance quantities
                          _tokenAmount = _tokenAmount.add(balances[_who]);
                          balances[_who] = 0;
                      }
              
                      totalSupply_ = totalSupply_.sub(_tokenAmount);
              
                      emit Burn(_who, _tokenAmount, _assetAmount, _price);
                      emit Transfer(_who, address(0), _tokenAmount);
                  }
              }
              
              contract BZxObjects {
              
                  struct LoanOrder {
                      address loanTokenAddress;
                      address interestTokenAddress;
                      address collateralTokenAddress;
                      address oracleAddress;
                      uint256 loanTokenAmount;
                      uint256 interestAmount;
                      uint256 initialMarginAmount;
                      uint256 maintenanceMarginAmount;
                      uint256 maxDurationUnixTimestampSec;
                      bytes32 loanOrderHash;
                  }
              
                  struct LoanPosition {
                      address trader;
                      address collateralTokenAddressFilled;
                      address positionTokenAddressFilled;
                      uint256 loanTokenAmountFilled;
                      uint256 loanTokenAmountUsed;
                      uint256 collateralTokenAmountFilled;
                      uint256 positionTokenAmountFilled;
                      uint256 loanStartUnixTimestampSec;
                      uint256 loanEndUnixTimestampSec;
                      bool active;
                      uint256 positionId;
                  }
              }
              
              contract OracleNotifierInterface {
              
                  function closeLoanNotifier(
                      BZxObjects.LoanOrder memory loanOrder,
                      BZxObjects.LoanPosition memory loanPosition,
                      address loanCloser,
                      uint256 closeAmount,
                      bool isLiquidation)
                      public
                      returns (bool);
              }
              
              interface IBZx {
                  function takeOrderFromiToken(
                      bytes32 loanOrderHash, // existing loan order hash
                      address[4] calldata sentAddresses,
                          // trader: borrower/trader
                          // collateralTokenAddress: collateral token
                          // tradeTokenAddress: trade token
                          // receiver: receiver of funds (address(0) assumes trader address)
                      uint256[7] calldata sentAmounts,
                          // newInterestRate: new loan interest rate
                          // newLoanAmount: new loan size (principal from lender)
                          // interestInitialAmount: interestAmount sent to determine initial loan length (this is included in one of the below)
                          // loanTokenSent: loanTokenAmount + interestAmount + any extra
                          // collateralTokenSent: collateralAmountRequired + any extra
                          // tradeTokenSent: tradeTokenAmount (optional)
                          // withdrawalAmount: Actual amount sent to borrower (can't exceed newLoanAmount)
                      bytes calldata loanDataBytes)
                      external
                      payable
                      returns (uint256);
              
                  function payInterestForOracle(
                      address oracleAddress,
                      address interestTokenAddress)
                      external
                      returns (uint256);
              
                  function getLenderInterestForOracle(
                      address lender,
                      address oracleAddress,
                      address interestTokenAddress)
                      external
                      view
                      returns (
                          uint256 interestPaid,
                          uint256 interestPaidDate,
                          uint256 interestOwedPerDay,
                          uint256 interestUnPaid);
              
                  function oracleAddresses(
                      address oracleAddress)
                      external
                      view
                      returns (address);
              
                  function getRequiredCollateral(
                      address loanTokenAddress,
                      address collateralTokenAddress,
                      address oracleAddress,
                      uint256 newLoanAmount,
                      uint256 marginAmount)
                      external
                      view
                      returns (uint256 collateralTokenAmount);
              
                  function getBorrowAmount(
                      address loanTokenAddress,
                      address collateralTokenAddress,
                      address oracleAddress,
                      uint256 collateralTokenAmount,
                      uint256 marginAmount)
                      external
                      view
                      returns (uint256 borrowAmount);
              }
              
              interface IBZxOracle {
                  function getTradeData(
                      address sourceTokenAddress,
                      address destTokenAddress,
                      uint256 sourceTokenAmount)
                      external
                      view
                      returns (
                          uint256 sourceToDestRate,
                          uint256 sourceToDestPrecision,
                          uint256 destTokenAmount
                      );
              }
              
              interface IWethHelper {
                  function claimEther(
                      address receiver,
                      uint256 amount)
                      external
                      returns (uint256 claimAmount);
              }
              
              contract LoanTokenLogicV4 is AdvancedToken, OracleNotifierInterface {
                  using SafeMath for uint256;
              
                  address internal target_;
              
                  //address internal constant arbitraryCaller = 0x000F400e6818158D541C3EBE45FE3AA0d47372FF;
              
                  modifier onlyOracle() {
                      require(msg.sender == IBZx(bZxContract).oracleAddresses(bZxOracle), "1");
                      _;
                  }
              
              
                  function()
                      external
                  {}
              
              
                  /* Public functions */
              
                  function mintWithEther(
                      address receiver)
                      external
                      payable
                      nonReentrant
                      returns (uint256 mintAmount)
                  {
                      require(loanTokenAddress == wethContract, "2");
                      return _mintToken(
                          receiver,
                          msg.value
                      );
                  }
              
                  function mint(
                      address receiver,
                      uint256 depositAmount)
                      external
                      nonReentrant
                      returns (uint256 mintAmount)
                  {
                      return _mintToken(
                          receiver,
                          depositAmount
                      );
                  }
              
                  function burnToEther(
                      address receiver,
                      uint256 burnAmount)
                      external
                      nonReentrant
                      returns (uint256 loanAmountPaid)
                  {
                      require(loanTokenAddress == wethContract, "3");
                      loanAmountPaid = _burnToken(
                          burnAmount
                      );
              
                      if (loanAmountPaid != 0) {
                          IWethHelper wethHelper = IWethHelper(0x3b5bDCCDFA2a0a1911984F203C19628EeB6036e0);
              
                          _transfer(loanTokenAddress, address(wethHelper), loanAmountPaid, "4");
                          require(loanAmountPaid == wethHelper.claimEther(receiver, loanAmountPaid), "4");
                      }
                  }
              
                  function burn(
                      address receiver,
                      uint256 burnAmount)
                      external
                      nonReentrant
                      returns (uint256 loanAmountPaid)
                  {
                      loanAmountPaid = _burnToken(
                          burnAmount
                      );
              
                      if (loanAmountPaid != 0) {
                          _transfer(loanTokenAddress, receiver, loanAmountPaid, "5");
                      }
                  }
              
                  function borrowTokenFromDeposit(
                      uint256 borrowAmount,
                      uint256 leverageAmount,
                      uint256 initialLoanDuration,    // duration in seconds
                      uint256 collateralTokenSent,    // set to 0 if sending ETH
                      address borrower,
                      address receiver,
                      address collateralTokenAddress, // address(0) means ETH and ETH must be sent with the call
                      bytes memory /*loanDataBytes*/) // arbitrary order data
                      public
                      onlyOwner
                      payable
                      returns (bytes32 loanOrderHash)
                  {
                      require(
                          ((msg.value == 0 && collateralTokenAddress != address(0) && collateralTokenSent != 0) ||
                          (msg.value != 0 && (collateralTokenAddress == address(0) || collateralTokenAddress == wethContract) && collateralTokenSent == 0)),
                          "6"
                      );
              
                      if (msg.value != 0) {
                          collateralTokenAddress = wethContract;
                          collateralTokenSent = msg.value;
                      }
              
                      uint256 _borrowAmount = borrowAmount;
              
                      leverageAmount = uint256(keccak256(abi.encodePacked(leverageAmount,collateralTokenAddress)));
                      loanOrderHash = loanOrderHashes[leverageAmount];
                      require(loanOrderHash != 0, "7");
              
                      _settleInterest();
              
                      uint256[7] memory sentAmounts;
              
                      LoanData memory loanOrder = loanOrderData[loanOrderHash];
                      bool useFixedInterestModel = loanOrder.maxDurationUnixTimestampSec == 0;
              
                      if (_borrowAmount == 0) {
                          _borrowAmount = _getBorrowAmountForDeposit(
                              collateralTokenSent,
                              leverageAmount,
                              initialLoanDuration,
                              collateralTokenAddress
                          );
                          require(_borrowAmount != 0, "35");
              
                          // withdrawalAmount
                          sentAmounts[6] = _borrowAmount;
                      } else {
                          // withdrawalAmount
                          sentAmounts[6] = _borrowAmount;
                      }
              
                      // interestRate, interestInitialAmount, borrowAmount (newBorrowAmount)
                      (sentAmounts[0], sentAmounts[2], _borrowAmount) = _getInterestRateAndAmount(
                          _borrowAmount,
                          _totalAssetSupply(0), // interest is settled above
                          initialLoanDuration,
                          useFixedInterestModel
                      );
              
                      sentAmounts[6] = _borrowTokenAndUseFinal(
                          loanOrderHash,
                          [
                              borrower,
                              collateralTokenAddress,
                              address(0), // tradeTokenAddress
                              receiver
                          ],
                          [
                              sentAmounts[0],         // interestRate
                              _borrowAmount,
                              sentAmounts[2],         // interestInitialAmount
                              0,                      // loanTokenSent
                              collateralTokenSent,
                              0,                      // tradeTokenSent
                              sentAmounts[6]          // withdrawalAmount
                          ],
                          ""                          // loanDataBytes
                      );
                      require(sentAmounts[6] == _borrowAmount, "8");
                  }
              
                  // Called to borrow and immediately get into a positions
                  // assumption: depositAmount is collateral + interest deposit and will be denominated in deposit token
                  // assumption: loan token and interest token are the same
                  // returns loanOrderHash for the base protocol loan
                  function marginTradeFromDeposit(
                      uint256 depositAmount,
                      uint256 leverageAmount,
                      uint256 loanTokenSent,
                      uint256 collateralTokenSent,
                      uint256 tradeTokenSent,
                      address trader,
                      address depositTokenAddress,
                      address collateralTokenAddress,
                      address tradeTokenAddress,
                      bytes memory loanDataBytes)
                      public
                      onlyOwner
                      payable
                      returns (bytes32 loanOrderHash)
                  {
                      require(tradeTokenAddress != address(0) &&
                          tradeTokenAddress != loanTokenAddress,
                          "10"
                      );
              
                      uint256 amount = depositAmount;
                      // To calculate borrow amount and interest owed to lender we need deposit amount to be represented as loan token
                      if (depositTokenAddress == tradeTokenAddress) {
                          (,,amount) = IBZxOracle(bZxOracle).getTradeData(
                              tradeTokenAddress,
                              loanTokenAddress,
                              amount
                          );
                      } else if (depositTokenAddress != loanTokenAddress) {
                          // depositTokenAddress can only be tradeTokenAddress or loanTokenAddress
                          revert("11");
                      }
              
                      loanOrderHash = _borrowTokenAndUse(
                          leverageAmount,
                          [
                              trader,
                              collateralTokenAddress,     // collateralTokenAddress
                              tradeTokenAddress,          // tradeTokenAddress
                              trader                      // receiver
                          ],
                          [
                              0,                      // interestRate (found later)
                              amount,                 // amount of deposit
                              0,                      // interestInitialAmount (interest is calculated based on fixed-term loan)
                              loanTokenSent,
                              collateralTokenSent,
                              tradeTokenSent,
                              0
                          ],
                          true,                       // amountIsADeposit
                          loanDataBytes
                      );
                  }
              
                  function transfer(
                      address _to,
                      uint256 _value)
                      public
                      returns (bool)
                  {
                      require(_value <= balances[msg.sender] &&
                          _to != address(0),
                          "13"
                      );
              
                      balances[msg.sender] = balances[msg.sender].sub(_value);
                      balances[_to] = balances[_to].add(_value);
              
                      // handle checkpoint update
                      uint256 currentPrice = tokenPrice();
                      if (balances[msg.sender] != 0) {
                          checkpointPrices_[msg.sender] = currentPrice;
                      } else {
                          checkpointPrices_[msg.sender] = 0;
                      }
                      if (balances[_to] != 0) {
                          checkpointPrices_[_to] = currentPrice;
                      } else {
                          checkpointPrices_[_to] = 0;
                      }
              
                      emit Transfer(msg.sender, _to, _value);
                      return true;
                  }
              
                  function transferFrom(
                      address _from,
                      address _to,
                      uint256 _value)
                      public
                      returns (bool)
                  {
                      uint256 allowanceAmount = allowed[_from][msg.sender];
                      require(_value <= balances[_from] &&
                          _value <= allowanceAmount &&
                          _to != address(0),
                          "14"
                      );
              
                      balances[_from] = balances[_from].sub(_value);
                      balances[_to] = balances[_to].add(_value);
                      if (allowanceAmount < MAX_UINT) {
                          allowed[_from][msg.sender] = allowanceAmount.sub(_value);
                      }
              
                      // handle checkpoint update
                      uint256 currentPrice = tokenPrice();
                      if (balances[_from] != 0) {
                          checkpointPrices_[_from] = currentPrice;
                      } else {
                          checkpointPrices_[_from] = 0;
                      }
                      if (balances[_to] != 0) {
                          checkpointPrices_[_to] = currentPrice;
                      } else {
                          checkpointPrices_[_to] = 0;
                      }
              
                      emit Transfer(_from, _to, _value);
                      return true;
                  }
              
              
                  /* Public View functions */
              
                  function tokenPrice()
                      public
                      view
                      returns (uint256 price)
                  {
                      uint256 interestUnPaid;
                      if (lastSettleTime_ != block.timestamp) {
                          (,interestUnPaid) = _getAllInterest();
                      }
              
                      return _tokenPrice(_totalAssetSupply(interestUnPaid));
                  }
              
                  function checkpointPrice(
                      address _user)
                      public
                      view
                      returns (uint256 price)
                  {
                      return checkpointPrices_[_user];
                  }
              
                  function marketLiquidity()
                      public
                      view
                      returns (uint256)
                  {
                      uint256 totalSupply = totalAssetSupply();
                      if (totalSupply > totalAssetBorrow) {
                          return totalSupply.sub(totalAssetBorrow);
                      }
                  }
              
                  function protocolInterestRate()
                      public
                      view
                      returns (uint256)
                  {
                      return _protocolInterestRate(totalAssetBorrow);
                  }
              
                  // the minimum rate the next base protocol borrower will receive for variable-rate loans
                  function borrowInterestRate()
                      public
                      view
                      returns (uint256)
                  {
                      return _nextBorrowInterestRate(
                          0,              // borrowAmount
                          false           // useFixedInterestModel
                      );
                  }
              
                  function nextBorrowInterestRate(
                      uint256 borrowAmount)
                      public
                      view
                      returns (uint256)
                  {
                      return _nextBorrowInterestRate(
                          borrowAmount,
                          false           // useFixedInterestModel
                      );
                  }
              
                  function nextBorrowInterestRateWithOption(
                      uint256 borrowAmount,
                      bool useFixedInterestModel)
                      public
                      view
                      returns (uint256)
                  {
                      return _nextBorrowInterestRate(
                          borrowAmount,
                          useFixedInterestModel
                      );
                  }
              
                  // the average interest that borrowers are currently paying for open loans
                  function avgBorrowInterestRate()
                      public
                      view
                      returns (uint256)
                  {
                      uint256 assetBorrow = totalAssetBorrow;
                      if (assetBorrow != 0) {
                          return _protocolInterestRate(assetBorrow)
                              .mul(checkpointSupply)
                              .div(totalAssetSupply());
                      } else {
                          return _getLowUtilBaseRate();
                      }
                  }
              
                  // interest that lenders are currently receiving when supplying to the pool
                  function supplyInterestRate()
                      public
                      view
                      returns (uint256)
                  {
                      return totalSupplyInterestRate(totalAssetSupply());
                  }
              
                  function nextSupplyInterestRate(
                      uint256 supplyAmount)
                      public
                      view
                      returns (uint256)
                  {
                      return totalSupplyInterestRate(totalAssetSupply().add(supplyAmount));
                  }
              
                  function totalSupplyInterestRate(
                      uint256 assetSupply)
                      public
                      view
                      returns (uint256)
                  {
                      uint256 assetBorrow = totalAssetBorrow;
                      if (assetBorrow != 0) {
                          return _supplyInterestRate(
                              assetBorrow,
                              assetSupply
                          );
                      }
                  }
              
                  function totalAssetSupply()
                      public
                      view
                      returns (uint256)
                  {
                      uint256 interestUnPaid;
                      if (lastSettleTime_ != block.timestamp) {
                          (,interestUnPaid) = _getAllInterest();
                      }
              
                      return _totalAssetSupply(interestUnPaid);
                  }
              
                  function getMaxEscrowAmount(
                      uint256 leverageAmount)
                      public
                      view
                      returns (uint256)
                  {
                      LoanData memory loanData = loanOrderData[loanOrderHashes[leverageAmount]];
                      if (loanData.initialMarginAmount == 0)
                          return 0;
              
                      return marketLiquidity()
                          .mul(loanData.initialMarginAmount)
                          .div(_adjustValue(
                              10**20, // maximum possible interest (100%)
                              loanData.maxDurationUnixTimestampSec,
                              loanData.initialMarginAmount));
                  }
              
                  function getLeverageList()
                      public
                      view
                      returns (uint256[] memory)
                  {
                      return leverageList;
                  }
              
                  function getLoanData(
                      bytes32 loanOrderHash)
                      public
                      view
                      returns (LoanData memory)
                  {
                      return loanOrderData[loanOrderHash];
                  }
              
                  // returns the user's balance of underlying token
                  function assetBalanceOf(
                      address _owner)
                      public
                      view
                      returns (uint256)
                  {
                      return balanceOf(_owner)
                          .mul(tokenPrice())
                          .div(10**18);
                  }
              
                  function getDepositAmountForBorrow(
                      uint256 borrowAmount,
                      uint256 leverageAmount,             // use 2000000000000000000 for 150% initial margin
                      uint256 initialLoanDuration,        // duration in seconds
                      address collateralTokenAddress)     // address(0) means ETH
                      public
                      view
                      returns (uint256 depositAmount)
                  {
                      if (borrowAmount != 0) {
                          leverageAmount = uint256(keccak256(abi.encodePacked(leverageAmount,collateralTokenAddress)));
                          LoanData memory loanOrder = loanOrderData[loanOrderHashes[leverageAmount]];
                          uint256 marginAmount = loanOrder.initialMarginAmount
                              .add(10**20); // adjust for over-collateralized loan
                              //.add(loanOrder.marginPremiumAmount);
              
                          // adjust value since interest is also borrowed
                          borrowAmount = borrowAmount
                              .mul(_getTargetNextRateMultiplierValue(initialLoanDuration))
                              .div(10**22);
              
                          if (borrowAmount <= ERC20(loanTokenAddress).balanceOf(address(this))) {
                              return IBZx(bZxContract).getRequiredCollateral(
                                  loanTokenAddress,
                                  collateralTokenAddress != address(0) ? collateralTokenAddress : wethContract,
                                  bZxOracle,
                                  borrowAmount,
                                  marginAmount
                              ).add(10); // add some dust to ensure enough is borrowed later
                          }
                      }
                  }
              
                  function getBorrowAmountForDeposit(
                      uint256 depositAmount,
                      uint256 leverageAmount,             // use 2000000000000000000 for 150% initial margin
                      uint256 initialLoanDuration,        // duration in seconds
                      address collateralTokenAddress)     // address(0) means ETH
                      public
                      view
                      returns (uint256 borrowAmount)
                  {
                      leverageAmount = uint256(keccak256(abi.encodePacked(leverageAmount,collateralTokenAddress)));
                      borrowAmount = _getBorrowAmountForDeposit(
                          depositAmount,
                          leverageAmount,
                          initialLoanDuration,
                          collateralTokenAddress
                      );
                  }
              
              
                  /* Internal functions */
              
                  function _mintToken(
                      address receiver,
                      uint256 depositAmount)
                      internal
                      returns (uint256 mintAmount)
                  {
                      require (depositAmount != 0, "17");
              
                      _settleInterest();
              
                      uint256 currentPrice = _tokenPrice(_totalAssetSupply(0));
                      mintAmount = depositAmount.mul(10**18).div(currentPrice);
              
                      if (msg.value == 0) {
                          _transferFrom(loanTokenAddress, msg.sender, address(this), depositAmount, "18");
                      } else {
                          WETHInterface(wethContract).deposit.value(depositAmount)();
                      }
              
                      _mint(receiver, mintAmount, depositAmount, currentPrice);
              
                      checkpointPrices_[receiver] = currentPrice;
                  }
              
                  function _burnToken(
                      uint256 burnAmount)
                      internal
                      returns (uint256 loanAmountPaid)
                  {
                      require(burnAmount != 0, "19");
              
                      if (burnAmount > balanceOf(msg.sender)) {
                          burnAmount = balanceOf(msg.sender);
                      }
              
                      _settleInterest();
              
                      uint256 currentPrice = _tokenPrice(_totalAssetSupply(0));
              
                      uint256 loanAmountOwed = burnAmount.mul(currentPrice).div(10**18);
                      uint256 loanAmountAvailableInContract = ERC20(loanTokenAddress).balanceOf(address(this));
              
                      loanAmountPaid = loanAmountOwed;
                      require(loanAmountPaid <= loanAmountAvailableInContract, "37");
              
                      _burn(msg.sender, burnAmount, loanAmountPaid, currentPrice);
              
                      if (balances[msg.sender] != 0) {
                          checkpointPrices_[msg.sender] = currentPrice;
                      } else {
                          checkpointPrices_[msg.sender] = 0;
                      }
                  }
              
                  function _settleInterest()
                      internal
                  {
                      if (lastSettleTime_ != block.timestamp) {
                          IBZx(bZxContract).payInterestForOracle(
                              bZxOracle, // (leave as original value)
                              loanTokenAddress // same as interestTokenAddress
                          );
              
                          lastSettleTime_ = block.timestamp;
                      }
                  }
              
                  function _getBorrowAmountForDeposit(
                      uint256 depositAmount,
                      uint256 leverageAmount,             // use 2000000000000000000 for 150% initial margin
                      uint256 initialLoanDuration,        // duration in seconds
                      address collateralTokenAddress)     // address(0) means ETH
                      internal
                      view
                      returns (uint256 borrowAmount)
                  {
                      if (depositAmount != 0) {
                          LoanData memory loanOrder = loanOrderData[loanOrderHashes[leverageAmount]];
                          uint256 marginAmount = loanOrder.initialMarginAmount
                              .add(10**20); // adjust for over-collateralized loan
                              //.add(loanOrder.marginPremiumAmount);
              
                          borrowAmount = IBZx(bZxContract).getBorrowAmount(
                              loanTokenAddress,
                              collateralTokenAddress != address(0) ? collateralTokenAddress : wethContract,
                              bZxOracle,
                              depositAmount,
                              marginAmount
                          );
              
                          // adjust value since interest is also borrowed
                          borrowAmount = borrowAmount
                              .mul(10**22)
                              .div(_getTargetNextRateMultiplierValue(initialLoanDuration));
              
                          if (borrowAmount > ERC20(loanTokenAddress).balanceOf(address(this))) {
                              borrowAmount = 0;
                          }
                      }
                  }
              
                  function _getTargetNextRateMultiplierValue(
                      uint256 initialLoanDuration)
                      internal
                      view
                      returns (uint256)
                  {
                      return rateMultiplier
                          .mul(80 ether)
                          .div(10**20)
                          .add(baseRate)
                          .mul(initialLoanDuration)
                          .div(315360) // 365 * 86400 / 100
                          .add(10**22);
                  }
              
                  function _getInterestRateAndAmount(
                      uint256 borrowAmount,
                      uint256 assetSupply,
                      uint256 initialLoanDuration,        // duration in seconds
                      bool useFixedInterestModel)         // False=variable interest, True=fixed interest
                      internal
                      view
                      returns (uint256 interestRate, uint256 interestInitialAmount, uint256 newBorrowAmount)
                  {
                      (,interestInitialAmount) = _getInterestRateAndAmount2(
                          borrowAmount,
                          assetSupply,
                          initialLoanDuration,
                          useFixedInterestModel
                      );
              
                      (interestRate, interestInitialAmount) = _getInterestRateAndAmount2(
                          borrowAmount
                              .add(interestInitialAmount),
                          assetSupply,
                          initialLoanDuration,
                          useFixedInterestModel
                      );
              
                      newBorrowAmount = borrowAmount
                          .add(interestInitialAmount);
                  }
              
                  function _getInterestRateAndAmount2(
                      uint256 borrowAmount,
                      uint256 assetSupply,
                      uint256 initialLoanDuration,
                      bool useFixedInterestModel)
                      internal
                      view
                      returns (uint256 interestRate, uint256 interestInitialAmount)
                  {
                      interestRate = _nextBorrowInterestRate2(
                          borrowAmount,
                          assetSupply,
                          useFixedInterestModel
                      );
              
                      // initial interestInitialAmount
                      interestInitialAmount = borrowAmount
                          .mul(interestRate)
                          .mul(initialLoanDuration)
                          .div(31536000 * 10**20); // 365 * 86400 * 10**20
                  }
              
                  function _borrowTokenAndUse(
                      uint256 leverageAmount,
                      address[4] memory sentAddresses,
                      uint256[7] memory sentAmounts,
                      bool amountIsADeposit,
                      bytes memory loanDataBytes)
                      internal
                      returns (bytes32 loanOrderHash)
                  {
                      require(sentAmounts[1] != 0, "21"); // amount
              
                      loanOrderHash = loanOrderHashes[leverageAmount];
                      require(loanOrderHash != 0, "22");
              
                      _settleInterest();
              
                      LoanData memory loanOrder = loanOrderData[loanOrderHash];
                      bool useFixedInterestModel = loanOrder.maxDurationUnixTimestampSec == 0;
                      //sentAmounts[7] = loanOrder.marginPremiumAmount;
              
                      if (amountIsADeposit) {
                          (sentAmounts[1], sentAmounts[0]) = _getBorrowAmountAndRate( // borrowAmount, interestRate
                              loanOrderHash,
                              sentAmounts[1], // amount
                              useFixedInterestModel
                          );
              
                          // update for borrowAmount
                          sentAmounts[6] = sentAmounts[1]; // borrowAmount
                      } else {
                          // amount is borrow amount
                          sentAmounts[0] = _nextBorrowInterestRate2( // interestRate
                              sentAmounts[1], // amount
                              _totalAssetSupply(0),
                              useFixedInterestModel
                          );
                      }
              
                      if (sentAddresses[2] == address(0)) { // tradeTokenAddress
                          // tradeTokenSent is ignored if trade token isn't specified
                          sentAmounts[5] = 0;
                      }
              
                      uint256 borrowAmount = _borrowTokenAndUseFinal(
                          loanOrderHash,
                          sentAddresses,
                          sentAmounts,
                          loanDataBytes
                      );
                      require(borrowAmount == sentAmounts[1], "23");
                  }
              
                  // returns borrowAmount
                  function _borrowTokenAndUseFinal(
                      bytes32 loanOrderHash,
                      address[4] memory sentAddresses,
                      uint256[7] memory sentAmounts,
                      bytes memory loanDataBytes)
                      internal
                      returns (uint256)
                  {
                      _checkPause();
              
                      require (sentAmounts[1] <= ERC20(loanTokenAddress).balanceOf(address(this)) && // borrowAmount
                          sentAddresses[0] != address(0), // borrower
                          "24"
                      );
              
              	    if (sentAddresses[3] == address(0)) {
                          sentAddresses[3] = sentAddresses[0]; // receiver = borrower
                      }
              
                      // handle transfers prior to adding borrowAmount to loanTokenSent
                      _verifyTransfers(
                          sentAddresses,
                          sentAmounts
                      );
              
                      // adding the loan token amount from the lender to loanTokenSent
                      sentAmounts[3] = sentAmounts[3]
                          .add(sentAmounts[1]); // borrowAmount
              
                      uint256 msgValue;
                      if (msg.value != 0) {
                          msgValue = address(this).balance;
                          if (msgValue > msg.value) {
                              msgValue = msg.value;
                          }
                      }
                      sentAmounts[1] = IBZx(bZxContract).takeOrderFromiToken.value(msgValue)( // borrowAmount
                          loanOrderHash,
                          sentAddresses,
                          sentAmounts,
                          loanDataBytes
                      );
                      require (sentAmounts[1] != 0, "25");
              
                      // update total borrowed amount outstanding in loans
                      totalAssetBorrow = totalAssetBorrow
                          .add(sentAmounts[1]); // borrowAmount
              
                      // checkpoint supply since the base protocol borrow stats have changed
                      checkpointSupply = _totalAssetSupply(0);
              
                      emit Borrow(
                          sentAddresses[0],               // borrower
                          sentAmounts[1],                 // borrowAmount
                          sentAmounts[0],                 // interestRate
                          sentAddresses[1],               // collateralTokenAddress
                          sentAddresses[2],               // tradeTokenAddress
                          sentAddresses[2] == address(0)  // withdrawOnOpen
                      );
              
                      return sentAmounts[1]; // borrowAmount;
                  }
              
                  // sentAddresses[0]: borrower
                  // sentAddresses[1]: collateralTokenAddress
                  // sentAddresses[2]: tradeTokenAddress
                  // sentAddresses[3]: receiver
                  // sentAmounts[0]: interestRate
                  // sentAmounts[1]: borrowAmount
                  // sentAmounts[2]: interestInitialAmount
                  // sentAmounts[3]: loanTokenSent
                  // sentAmounts[4]: collateralTokenSent
                  // sentAmounts[5]: tradeTokenSent
                  // sentAmounts[6]: withdrawalAmount
                  function _verifyTransfers(
                      address[4] memory sentAddresses,
                      uint256[7] memory sentAmounts)
                      internal
                  {
                      address collateralTokenAddress = sentAddresses[1];
                      address tradeTokenAddress = sentAddresses[2];
                      address receiver = sentAddresses[3];
                      uint256 borrowAmount = sentAmounts[1];
                      uint256 loanTokenSent = sentAmounts[3];
                      uint256 collateralTokenSent = sentAmounts[4];
                      uint256 tradeTokenSent = sentAmounts[5];
                      uint256 withdrawalAmount = sentAmounts[6];
              
                      bool success;
                      if (tradeTokenAddress == address(0)) { // withdrawOnOpen == true
                          if (loanTokenAddress == wethContract) {
                              IWethHelper wethHelper = IWethHelper(0x3b5bDCCDFA2a0a1911984F203C19628EeB6036e0);
              
                              _transfer(loanTokenAddress, address(wethHelper), withdrawalAmount, "");
                              success = withdrawalAmount == wethHelper.claimEther(receiver, withdrawalAmount);
                          } else {
                              _transfer(loanTokenAddress, receiver, withdrawalAmount, "");
                              success = true;
                          }
              
                          if (success && borrowAmount > withdrawalAmount) {
                              _transfer(loanTokenAddress, bZxVault, borrowAmount - withdrawalAmount, "");
                          }
                          require(success, "26");
                      } else {
                          _transfer(loanTokenAddress, bZxVault, borrowAmount, "26");
                      }
              
                      if (collateralTokenSent != 0) {
                          if (collateralTokenAddress == wethContract && msg.value != 0 && collateralTokenSent == msg.value) {
                              WETHInterface(wethContract).deposit.value(collateralTokenSent)();
                              _transfer(collateralTokenAddress, bZxVault, collateralTokenSent, "27");
                          } else {
                              if (collateralTokenAddress == loanTokenAddress) {
                                  loanTokenSent = loanTokenSent.add(collateralTokenSent);
                              } else if (collateralTokenAddress == tradeTokenAddress) {
                                  tradeTokenSent = tradeTokenSent.add(collateralTokenSent);
                              } else {
                                  _transferFrom(collateralTokenAddress, msg.sender, bZxVault, collateralTokenSent, "27");
                              }
                          }
                      }
              
                      if (loanTokenSent != 0) {
                          if (loanTokenAddress == tradeTokenAddress) {
                              tradeTokenSent = tradeTokenSent.add(loanTokenSent);
                          } else {
                              _transferFrom(loanTokenAddress, msg.sender, bZxVault, loanTokenSent, "31");
                          }
                      }
              
                      if (tradeTokenSent != 0) {
                          _transferFrom(tradeTokenAddress, msg.sender, bZxVault, tradeTokenSent, "32");
                      }
                  }
              
                  function _transfer(
                      address token,
                      address to,
                      uint256 amount,
                      string memory errorMsg)
                      internal
                  {
                      (bool success,) = token.call(
                          abi.encodeWithSelector(
                              0xa9059cbb, // transfer(address,uint256)
                              to,
                              amount
                          )
                      );
                      require(success, errorMsg);
                  }
              
                  function _transferFrom(
                      address token,
                      address from,
                      address to,
                      uint256 amount,
                      string memory errorMsg)
                      internal
                  {
                      (bool success,) = token.call(
                          abi.encodeWithSelector(
                              0x23b872dd, // transferFrom(address,address,uint256)
                              from,
                              to,
                              amount
                          )
                      );
                      require(success, errorMsg);
                  }
              
                  /* Internal View functions */
              
                  function _tokenPrice(
                      uint256 assetSupply)
                      internal
                      view
                      returns (uint256)
                  {
                      uint256 totalTokenSupply = totalSupply_;
              
                      return totalTokenSupply != 0 ?
                          assetSupply
                              .mul(10**18)
                              .div(totalTokenSupply) : initialPrice;
                  }
              
                  function _protocolInterestRate(
                      uint256 assetBorrow)
                      internal
                      view
                      returns (uint256)
                  {
                      if (assetBorrow != 0) {
                          (uint256 interestOwedPerDay,) = _getAllInterest();
                          return interestOwedPerDay
                              .mul(10**20)
                              .div(assetBorrow)
                              .mul(365);
                      }
                  }
              
                  // next supply interest adjustment
                  function _supplyInterestRate(
                      uint256 assetBorrow,
                      uint256 assetSupply)
                      public
                      view
                      returns (uint256)
                  {
                      if (assetBorrow != 0 && assetSupply >= assetBorrow) {
                          return _protocolInterestRate(assetBorrow)
                              .mul(_utilizationRate(assetBorrow, assetSupply))
                              .mul(spreadMultiplier)
                              .div(10**40);
                      }
                  }
              
                  function _nextBorrowInterestRate(
                      uint256 borrowAmount,
                      bool useFixedInterestModel)
                      internal
                      view
                      returns (uint256)
                  {
                      uint256 interestUnPaid;
                      if (borrowAmount != 0) {
                          if (lastSettleTime_ != block.timestamp) {
                              (,interestUnPaid) = _getAllInterest();
                          }
              
                          uint256 balance = ERC20(loanTokenAddress).balanceOf(address(this))
                              .add(interestUnPaid);
                          if (borrowAmount > balance) {
                              borrowAmount = balance;
                          }
                      }
              
                      return _nextBorrowInterestRate2(
                          borrowAmount,
                          _totalAssetSupply(interestUnPaid),
                          useFixedInterestModel
                      );
                  }
              
                  function _nextBorrowInterestRate2(
                      uint256 newBorrowAmount,
                      uint256 assetSupply,
                      bool useFixedInterestModel)
                      internal
                      view
                      returns (uint256 nextRate)
                  {
                      uint256 utilRate = _utilizationRate(
                          totalAssetBorrow.add(newBorrowAmount),
                          assetSupply
                      );
              
                      uint256 minRate;
                      uint256 maxRate;
                      uint256 thisBaseRate;
                      uint256 thisRateMultiplier;
              
                      if (useFixedInterestModel) {
                          if (utilRate < 80 ether) {
                              // target 80% utilization when loan is fixed-rate and utilization is under 80%
                              utilRate = 80 ether;
                          }
              
                          //keccak256("iToken_FixedInterestBaseRate")
                          //keccak256("iToken_FixedInterestRateMultiplier")
                          assembly {
                              thisBaseRate := sload(0x185a40c6b6d3f849f72c71ea950323d21149c27a9d90f7dc5e5ea2d332edcf7f)
                              thisRateMultiplier := sload(0x9ff54bc0049f5eab56ca7cd14591be3f7ed6355b856d01e3770305c74a004ea2)
                          }
                      } else if (utilRate < 50 ether) {
                          thisBaseRate = _getLowUtilBaseRate();
              
                          //keccak256("iToken_LowUtilRateMultiplier")
                          assembly {
                              thisRateMultiplier := sload(0x2b4858b1bc9e2d14afab03340ce5f6c81b703c86a0c570653ae586534e095fb1)
                          }
                      } else {
                          thisBaseRate = baseRate;
                          thisRateMultiplier = rateMultiplier;
                      }
              
                      if (utilRate > 90 ether) {
                          // scale rate proportionally up to 100%
              
                          utilRate = utilRate.sub(90 ether);
                          if (utilRate > 10 ether)
                              utilRate = 10 ether;
              
                          maxRate = thisRateMultiplier
                              .add(thisBaseRate)
                              .mul(90)
                              .div(100);
              
                          nextRate = utilRate
                              .mul(SafeMath.sub(100 ether, maxRate))
                              .div(10 ether)
                              .add(maxRate);
                      } else {
                          nextRate = utilRate
                              .mul(thisRateMultiplier)
                              .div(10**20)
                              .add(thisBaseRate);
              
                          minRate = thisBaseRate;
                          maxRate = thisRateMultiplier
                              .add(thisBaseRate);
              
                          if (nextRate < minRate)
                              nextRate = minRate;
                          else if (nextRate > maxRate)
                              nextRate = maxRate;
                      }
                  }
              
                  function _getAllInterest()
                      internal
                      view
                      returns (
                          uint256 interestOwedPerDay,
                          uint256 interestUnPaid)
                  {
                      (,,interestOwedPerDay,interestUnPaid) = IBZx(bZxContract).getLenderInterestForOracle(
                          address(this),
                          bZxOracle, // (leave as original value)
                          loanTokenAddress // same as interestTokenAddress
                      );
              
                      interestUnPaid = interestUnPaid
                          .mul(spreadMultiplier)
                          .div(10**20);
                  }
              
                  function _getBorrowAmountAndRate(
                      bytes32 loanOrderHash,
                      uint256 depositAmount,
                      bool useFixedInterestModel)
                      internal
                      view
                      returns (uint256 borrowAmount, uint256 interestRate)
                  {
                      LoanData memory loanData = loanOrderData[loanOrderHash];
                      require(loanData.initialMarginAmount != 0, "33");
              
                      interestRate = _nextBorrowInterestRate2(
                          depositAmount
                              .mul(10**20)
                              .div(loanData.initialMarginAmount),
                          totalAssetSupply(),
                          useFixedInterestModel
                      );
              
                      // assumes that loan, collateral, and interest token are the same
                      borrowAmount = depositAmount
                          .mul(10**40)
                          .div(_adjustValue(
                              interestRate,
                              loanData.maxDurationUnixTimestampSec,
                              loanData.initialMarginAmount))
                          .div(loanData.initialMarginAmount);
                  }
              
                  function _totalAssetSupply(
                      uint256 interestUnPaid)
                      internal
                      view
                      returns (uint256 assetSupply)
                  {
                      if (totalSupply_ != 0) {
                          uint256 assetsBalance = burntTokenReserved; // temporary holder when flash lending
                          if (assetsBalance == 0) {
                              assetsBalance = ERC20(loanTokenAddress).balanceOf(address(this))
                                  .add(totalAssetBorrow);
                          }
              
                          return assetsBalance
                              .add(interestUnPaid);
                      }
                  }
              
                  function _getLowUtilBaseRate()
                      internal
                      view
                      returns (uint256 lowUtilBaseRate)
                  {
                      //keccak256("iToken_LowUtilBaseRate")
                      assembly {
                          lowUtilBaseRate := sload(0x3d82e958c891799f357c1316ae5543412952ae5c423336f8929ed7458039c995)
                      }
                  }
              
                  function _checkPause()
                      internal
                      view
                  {
                      //keccak256("iToken_FunctionPause")
                      bytes32 slot = keccak256(abi.encodePacked(msg.sig, uint256(0xd46a704bc285dbd6ff5ad3863506260b1df02812f4f857c8cc852317a6ac64f2)));
                      bool isPaused;
                      assembly {
                          isPaused := sload(slot)
                      }
                      require(!isPaused, "unauthorized");
                  }
              
                  function _adjustValue(
                      uint256 interestRate,
                      uint256 maxDuration,
                      uint256 marginAmount)
                      internal
                      pure
                      returns (uint256)
                  {
                      return maxDuration != 0 ?
                          interestRate
                              .mul(10**20)
                              .div(31536000) // 86400 * 365
                              .mul(maxDuration)
                              .div(marginAmount)
                              .add(10**20) :
                          10**20;
                  }
              
                  function _utilizationRate(
                      uint256 assetBorrow,
                      uint256 assetSupply)
                      internal
                      pure
                      returns (uint256)
                  {
                      if (assetBorrow != 0 && assetSupply != 0) {
                          // U = total_borrow / total_supply
                          return assetBorrow
                              .mul(10**20)
                              .div(assetSupply);
                      }
                  }
              
              
                  /* Oracle-Only functions */
              
                  // called only by BZxOracle when a loan is partially or fully closed
                  function closeLoanNotifier(
                      BZxObjects.LoanOrder memory loanOrder,
                      BZxObjects.LoanPosition memory loanPosition,
                      address loanCloser,
                      uint256 closeAmount,
                      bool isLiquidation)
                      public
                      onlyOracle
                      returns (bool)
                  {
                      _settleInterest();
              
                      LoanData memory loanData = loanOrderData[loanOrder.loanOrderHash];
                      if (loanData.loanOrderHash == loanOrder.loanOrderHash) {
                          totalAssetBorrow = totalAssetBorrow > closeAmount ?
                              totalAssetBorrow.sub(closeAmount) : 0;
              
                          emit Repay(
                              loanOrder.loanOrderHash,    // loanOrderHash
                              loanPosition.trader,        // borrower
                              loanCloser,                 // closer
                              closeAmount,                // amount
                              isLiquidation               // isLiquidation
                          );
              
                          if (closeAmount == 0)
                              return true;
              
                          // checkpoint supply since the base protocol borrow stats have changed
                          checkpointSupply = _totalAssetSupply(0);
              
                          return true;
                      } else {
                          return false;
                      }
                  }
              
              
                  /* Owner-Only functions */
              
                  function updateSettings(
                      address settingsTarget,
                      bytes memory callData)
                      public
                  {
                      if (msg.sender != owner) {
                          address _lowerAdmin;
                          address _lowerAdminContract;
              
                          //keccak256("iToken_LowerAdminAddress")
                          //keccak256("iToken_LowerAdminContract")
                          assembly {
                              _lowerAdmin := sload(0x7ad06df6a0af6bd602d90db766e0d5f253b45187c3717a0f9026ea8b10ff0d4b)
                              _lowerAdminContract := sload(0x34b31cff1dbd8374124bd4505521fc29cab0f9554a5386ba7d784a4e611c7e31)
                          }
                          require(msg.sender == _lowerAdmin && settingsTarget == _lowerAdminContract);
                      }
              
                      address currentTarget = target_;
                      target_ = settingsTarget;
              
                      (bool result,) = address(this).call(callData);
              
                      uint256 size;
                      uint256 ptr;
                      assembly {
                          size := returndatasize
                          ptr := mload(0x40)
                          returndatacopy(ptr, 0, size)
                          if eq(result, 0) { revert(ptr, size) }
                      }
              
                      target_ = currentTarget;
              
                      assembly {
                          return(ptr, size)
                      }
                  }
              }

              File 5 of 5: BZxProxy
              /**
               * Copyright 2017–2018, bZeroX, LLC. All Rights Reserved.
               * Licensed under the Apache License, Version 2.0.
               */
               
              pragma solidity 0.5.3;
              
              
              /**
               * @title Ownable
               * @dev The Ownable contract has an owner address, and provides basic authorization control
               * functions, this simplifies the implementation of "user permissions".
               */
              contract Ownable {
                address public owner;
              
                event OwnershipTransferred(
                  address indexed previousOwner,
                  address indexed newOwner
                );
              
                /**
                 * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                 * account.
                 */
                constructor() public {
                  owner = msg.sender;
                }
              
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                  require(msg.sender == owner);
                  _;
                }
              
                /**
                 * @dev Allows the current owner to transfer control of the contract to a newOwner.
                 * @param _newOwner The address to transfer ownership to.
                 */
                function transferOwnership(address _newOwner) public onlyOwner {
                  _transferOwnership(_newOwner);
                }
              
                /**
                 * @dev Transfers control of the contract to a newOwner.
                 * @param _newOwner The address to transfer ownership to.
                 */
                function _transferOwnership(address _newOwner) internal {
                  require(_newOwner != address(0));
                  emit OwnershipTransferred(owner, _newOwner);
                  owner = _newOwner;
                }
              }
              
              /**
               * @title Helps contracts guard against reentrancy attacks.
               * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
               * @dev If you mark a function `nonReentrant`, you should also
               * mark it `external`.
               */
              contract ReentrancyGuard {
              
                /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs.
                /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056
                uint256 private constant REENTRANCY_GUARD_FREE = 1;
              
                /// @dev Constant for locked guard state
                uint256 private constant REENTRANCY_GUARD_LOCKED = 2;
              
                /**
                 * @dev We use a single lock for the whole contract.
                 */
                uint256 private reentrancyLock = REENTRANCY_GUARD_FREE;
              
                /**
                 * @dev Prevents a contract from calling itself, directly or indirectly.
                 * If you mark a function `nonReentrant`, you should also
                 * mark it `external`. Calling one `nonReentrant` function from
                 * another is not supported. Instead, you can implement a
                 * `private` function doing the actual work, and an `external`
                 * wrapper marked as `nonReentrant`.
                 */
                modifier nonReentrant() {
                  require(reentrancyLock == REENTRANCY_GUARD_FREE);
                  reentrancyLock = REENTRANCY_GUARD_LOCKED;
                  _;
                  reentrancyLock = REENTRANCY_GUARD_FREE;
                }
              
              }
              
              contract GasTracker {
              
                  uint256 internal gasUsed;
              
                  modifier tracksGas() {
                      // tx call 21k gas
                      gasUsed = gasleft() + 21000;
              
                      _; // modified function body inserted here
              
                      gasUsed = 0; // zero out the storage so we don't persist anything
                  }
              }
              
              contract BZxObjects {
              
                  struct ListIndex {
                      uint256 index;
                      bool isSet;
                  }
              
                  struct LoanOrder {
                      address loanTokenAddress;
                      address interestTokenAddress;
                      address collateralTokenAddress;
                      address oracleAddress;
                      uint256 loanTokenAmount;
                      uint256 interestAmount;
                      uint256 initialMarginAmount;
                      uint256 maintenanceMarginAmount;
                      uint256 maxDurationUnixTimestampSec;
                      bytes32 loanOrderHash;
                  }
              
                  struct LoanOrderAux {
                      address makerAddress;
                      address takerAddress;
                      address feeRecipientAddress;
                      address tradeTokenToFillAddress;
                      uint256 lenderRelayFee;
                      uint256 traderRelayFee;
                      uint256 makerRole;
                      uint256 expirationUnixTimestampSec;
                      bool withdrawOnOpen;
                      string description;
                  }
              
                  struct LoanPosition {
                      address trader;
                      address collateralTokenAddressFilled;
                      address positionTokenAddressFilled;
                      uint256 loanTokenAmountFilled;
                      uint256 loanTokenAmountUsed;
                      uint256 collateralTokenAmountFilled;
                      uint256 positionTokenAmountFilled;
                      uint256 loanStartUnixTimestampSec;
                      uint256 loanEndUnixTimestampSec;
                      bool active;
                      uint256 positionId;
                  }
              
                  struct PositionRef {
                      bytes32 loanOrderHash;
                      uint256 positionId;
                  }
              
                  struct LenderInterest {
                      uint256 interestOwedPerDay;
                      uint256 interestPaid;
                      uint256 interestPaidDate;
                  }
              
                  struct TraderInterest {
                      uint256 interestOwedPerDay;
                      uint256 interestPaid;
                      uint256 interestDepositTotal;
                      uint256 interestUpdatedDate;
                  }
              }
              
              contract BZxEvents {
              
                  event LogLoanAdded (
                      bytes32 indexed loanOrderHash,
                      address adderAddress,
                      address indexed makerAddress,
                      address indexed feeRecipientAddress,
                      uint256 lenderRelayFee,
                      uint256 traderRelayFee,
                      uint256 maxDuration,
                      uint256 makerRole
                  );
              
                  event LogLoanTaken (
                      address indexed lender,
                      address indexed trader,
                      address loanTokenAddress,
                      address collateralTokenAddress,
                      uint256 loanTokenAmount,
                      uint256 collateralTokenAmount,
                      uint256 loanEndUnixTimestampSec,
                      bool firstFill,
                      bytes32 indexed loanOrderHash,
                      uint256 positionId
                  );
              
                  event LogLoanCancelled(
                      address indexed makerAddress,
                      uint256 cancelLoanTokenAmount,
                      uint256 remainingLoanTokenAmount,
                      bytes32 indexed loanOrderHash
                  );
              
                  event LogLoanClosed(
                      address indexed lender,
                      address indexed trader,
                      address loanCloser,
                      bool isLiquidation,
                      bytes32 indexed loanOrderHash,
                      uint256 positionId
                  );
              
                  event LogPositionTraded(
                      bytes32 indexed loanOrderHash,
                      address indexed trader,
                      address sourceTokenAddress,
                      address destTokenAddress,
                      uint256 sourceTokenAmount,
                      uint256 destTokenAmount,
                      uint256 positionId
                  );
              
                  event LogWithdrawPosition(
                      bytes32 indexed loanOrderHash,
                      address indexed trader,
                      uint256 positionAmount,
                      uint256 remainingPosition,
                      uint256 positionId
                  );
              
                  event LogPayInterestForOracle(
                      address indexed lender,
                      address indexed oracleAddress,
                      address indexed interestTokenAddress,
                      uint256 amountPaid,
                      uint256 totalAccrued
                  );
              
                  event LogPayInterestForOrder(
                      bytes32 indexed loanOrderHash,
                      address indexed lender,
                      address indexed interestTokenAddress,
                      uint256 amountPaid,
                      uint256 totalAccrued,
                      uint256 loanCount
                  );
              
                  event LogChangeTraderOwnership(
                      bytes32 indexed loanOrderHash,
                      address indexed oldOwner,
                      address indexed newOwner
                  );
              
                  event LogChangeLenderOwnership(
                      bytes32 indexed loanOrderHash,
                      address indexed oldOwner,
                      address indexed newOwner
                  );
              
                  event LogUpdateLoanAsLender(
                      bytes32 indexed loanOrderHash,
                      address indexed lender,
                      uint256 loanTokenAmountAdded,
                      uint256 loanTokenAmountFillable,
                      uint256 expirationUnixTimestampSec
                  );
              }
              
              contract BZxStorage is BZxObjects, BZxEvents, ReentrancyGuard, Ownable, GasTracker {
                  uint256 internal constant MAX_UINT = 2**256 - 1;
              
                  address public bZRxTokenContract;
                  address public bZxEtherContract;
                  address public wethContract;
                  address payable public vaultContract;
                  address public oracleRegistryContract;
                  address public bZxTo0xContract;
                  address public bZxTo0xV2Contract;
                  bool public DEBUG_MODE = false;
              
                  // Loan Orders
                  mapping (bytes32 => LoanOrder) public orders; // mapping of loanOrderHash to on chain loanOrders
                  mapping (bytes32 => LoanOrderAux) public orderAux; // mapping of loanOrderHash to on chain loanOrder auxiliary parameters
                  mapping (bytes32 => uint256) public orderFilledAmounts; // mapping of loanOrderHash to loanTokenAmount filled
                  mapping (bytes32 => uint256) public orderCancelledAmounts; // mapping of loanOrderHash to loanTokenAmount cancelled
                  mapping (bytes32 => address) public orderLender; // mapping of loanOrderHash to lender (only one lender per order)
              
                  // Loan Positions
                  mapping (uint256 => LoanPosition) public loanPositions; // mapping of position ids to loanPositions
                  mapping (bytes32 => mapping (address => uint256)) public loanPositionsIds; // mapping of loanOrderHash to mapping of trader address to position id
              
                  // Lists
                  mapping (address => bytes32[]) public orderList; // mapping of lenders and trader addresses to array of loanOrderHashes
                  mapping (bytes32 => mapping (address => ListIndex)) public orderListIndex; // mapping of loanOrderHash to mapping of lenders and trader addresses to ListIndex objects
              
                  mapping (bytes32 => uint256[]) public orderPositionList; // mapping of loanOrderHash to array of order position ids
              
                  PositionRef[] public positionList; // array of loans that need to be checked for liquidation or expiration
                  mapping (uint256 => ListIndex) public positionListIndex; // mapping of position ids to ListIndex objects
              
                  // Interest
                  mapping (address => mapping (address => uint256)) public tokenInterestOwed; // mapping of lender address to mapping of interest token address to amount of interest owed for all loans (assuming they go to full term)
                  mapping (address => mapping (address => mapping (address => LenderInterest))) public lenderOracleInterest; // mapping of lender address to mapping of oracle to mapping of interest token to LenderInterest objects
                  mapping (bytes32 => LenderInterest) public lenderOrderInterest; // mapping of loanOrderHash to LenderInterest objects
                  mapping (uint256 => TraderInterest) public traderLoanInterest; // mapping of position ids to TraderInterest objects
              
                  // Other Storage
                  mapping (address => address) public oracleAddresses; // mapping of oracles to their current logic contract
                  mapping (bytes32 => mapping (address => bool)) public preSigned; // mapping of hash => signer => signed
                  mapping (address => mapping (address => bool)) public allowedValidators; // mapping of signer => validator => approved
              
                  // General Purpose
                  mapping (bytes => uint256) internal dbUint256;
                  mapping (bytes => uint256[]) internal dbUint256Array;
                  mapping (bytes => address) internal dbAddress;
                  mapping (bytes => address[]) internal dbAddressArray;
                  mapping (bytes => bool) internal dbBool;
                  mapping (bytes => bool[]) internal dbBoolArray;
                  mapping (bytes => bytes32) internal dbBytes32;
                  mapping (bytes => bytes32[]) internal dbBytes32Array;
                  mapping (bytes => bytes) internal dbBytes;
                  mapping (bytes => bytes[]) internal dbBytesArray;
              }
              
              contract BZxProxiable {
                  mapping (bytes4 => address) public targets;
              
                  mapping (bytes4 => bool) public targetIsPaused;
              
                  function initialize(address _target) public;
              }
              
              contract BZxProxy is BZxStorage, BZxProxiable {
                  
                  constructor(
                      address _settings) 
                      public
                  {
                      (bool result,) = _settings.delegatecall.gas(gasleft())(abi.encodeWithSignature("initialize(address)", _settings));
                      require(result, "BZxProxy::constructor: failed");
                  }
                  
                  function() 
                      external
                      payable 
                  {
                      require(!targetIsPaused[msg.sig], "BZxProxy::Function temporarily paused");
              
                      address target = targets[msg.sig];
                      require(target != address(0), "BZxProxy::Target not found");
              
                      bytes memory data = msg.data;
                      assembly {
                          let result := delegatecall(gas, target, add(data, 0x20), mload(data), 0, 0)
                          let size := returndatasize
                          let ptr := mload(0x40)
                          returndatacopy(ptr, 0, size)
                          switch result
                          case 0 { revert(ptr, size) }
                          default { return(ptr, size) }
                      }
                  }
              
                  function initialize(
                      address)
                      public
                  {
                      revert();
                  }
              }