ETH Price: $3,316.02 (-4.08%)
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

1 Internal Transaction and 4 Token Transfers found.

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block
From
To
127831262021-07-07 22:55:051280 days ago1625698505  Contract Creation0 ETH
Loading...
Loading

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

Contract Name:
Borrower

Compiler Version
v0.6.12+commit.27d51765

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion, MIT license
File 1 of 44 : Borrower.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "../core/BaseUpgradeablePausable.sol";
import "../core/ConfigHelper.sol";
import "../core/CreditLine.sol";
import "../../interfaces/IERC20withDec.sol";
import "@opengsn/gsn/contracts/BaseRelayRecipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";

/**
 * @title Goldfinch's Borrower contract
 * @notice These contracts represent the a convenient way for a borrower to interact with Goldfinch
 *  They are 100% optional. However, they let us add many sophisticated and convient features for borrowers
 *  while still keeping our core protocol small and secure. We therefore expect most borrowers will use them.
 *  This contract is the "official" borrower contract that will be maintained by Goldfinch governance. However,
 *  in theory, anyone can fork or create their own version, or not use any contract at all. The core functionality
 *  is completely agnostic to whether it is interacting with a contract or an externally owned account (EOA).
 * @author Goldfinch
 */

contract Borrower is BaseUpgradeablePausable, BaseRelayRecipient {
  using SafeMath for uint256;

  GoldfinchConfig public config;
  using ConfigHelper for GoldfinchConfig;

  address private constant USDT_ADDRESS = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
  address private constant BUSD_ADDRESS = address(0x4Fabb145d64652a948d72533023f6E7A623C7C53);

  function initialize(address owner, GoldfinchConfig _config) public initializer {
    require(owner != address(0), "Owner cannot be empty");
    __BaseUpgradeablePausable__init(owner);
    config = _config;

    trustedForwarder = config.trustedForwarderAddress();

    // Handle default approvals. Pool, and OneInch for maximum amounts
    address oneInch = config.oneInchAddress();
    IERC20withDec usdc = config.getUSDC();
    usdc.approve(config.poolAddress(), uint256(-1));
    usdc.approve(oneInch, uint256(-1));
    bytes memory data = abi.encodeWithSignature("approve(address,uint256)", oneInch, uint256(-1));
    invoke(USDT_ADDRESS, data);
    invoke(BUSD_ADDRESS, data);
  }

  /**
   * @notice Allows a borrower to drawdown on their creditline through the CreditDesk.
   * @param creditLineAddress The creditline from which they would like to drawdown
   * @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown
   * @param addressToSendTo The address where they would like the funds sent. If the zero address is passed,
   *  it will be defaulted to the contracts address (msg.sender). This is a convenience feature for when they would
   *  like the funds sent to an exchange or alternate wallet, different from the authentication address
   */
  function drawdown(
    address creditLineAddress,
    uint256 amount,
    address addressToSendTo
  ) external onlyAdmin {
    config.getCreditDesk().drawdown(creditLineAddress, amount);

    if (addressToSendTo == address(0) || addressToSendTo == address(this)) {
      addressToSendTo = _msgSender();
    }

    transferERC20(config.usdcAddress(), addressToSendTo, amount);
  }

  function drawdownWithSwapOnOneInch(
    address creditLineAddress,
    uint256 amount,
    address addressToSendTo,
    address toToken,
    uint256 minTargetAmount,
    uint256[] calldata exchangeDistribution
  ) public onlyAdmin {
    // Drawdown to the Borrower contract
    config.getCreditDesk().drawdown(creditLineAddress, amount);

    // Do the swap
    swapOnOneInch(config.usdcAddress(), toToken, amount, minTargetAmount, exchangeDistribution);

    // Default to sending to the owner, and don't let funds stay in this contract
    if (addressToSendTo == address(0) || addressToSendTo == address(this)) {
      addressToSendTo = _msgSender();
    }

    // Fulfill the send to
    bytes memory _data = abi.encodeWithSignature("balanceOf(address)", address(this));
    uint256 receivedAmount = toUint256(invoke(toToken, _data));
    transferERC20(toToken, addressToSendTo, receivedAmount);
  }

  function transferERC20(
    address token,
    address to,
    uint256 amount
  ) public onlyAdmin {
    bytes memory _data = abi.encodeWithSignature("transfer(address,uint256)", to, amount);
    invoke(token, _data);
  }

  /**
   * @notice Allows a borrower to payback loans by calling the `pay` function directly on the CreditDesk
   * @param creditLineAddress The credit line to be paid back
   * @param amount The amount, in USDC atomic units, that the borrower wishes to pay
   */
  function pay(address creditLineAddress, uint256 amount) external onlyAdmin {
    bool success = config.getUSDC().transferFrom(_msgSender(), address(this), amount);
    require(success, "Failed to transfer USDC");
    config.getCreditDesk().pay(creditLineAddress, amount);
  }

  function payMultiple(address[] calldata creditLines, uint256[] calldata amounts) external onlyAdmin {
    require(creditLines.length == amounts.length, "Creditlines and amounts must be the same length");

    uint256 totalAmount;
    for (uint256 i = 0; i < amounts.length; i++) {
      totalAmount = totalAmount.add(amounts[i]);
    }

    // Do a single transfer, which is cheaper
    bool success = config.getUSDC().transferFrom(_msgSender(), address(this), totalAmount);
    require(success, "Failed to transfer USDC");

    ICreditDesk creditDesk = config.getCreditDesk();
    for (uint256 i = 0; i < amounts.length; i++) {
      creditDesk.pay(creditLines[i], amounts[i]);
    }
  }

  function payInFull(address creditLineAddress, uint256 amount) external onlyAdmin {
    bool success = config.getUSDC().transferFrom(_msgSender(), creditLineAddress, amount);
    require(success, "Failed to transfer USDC");

    config.getCreditDesk().applyPayment(creditLineAddress, amount);
    require(CreditLine(creditLineAddress).balance() == 0, "Failed to fully pay off creditline");
  }

  function payWithSwapOnOneInch(
    address creditLineAddress,
    uint256 originAmount,
    address fromToken,
    uint256 minTargetAmount,
    uint256[] memory exchangeDistribution
  ) external onlyAdmin {
    transferFrom(fromToken, _msgSender(), address(this), originAmount);
    IERC20withDec usdc = config.getUSDC();
    swapOnOneInch(fromToken, address(usdc), originAmount, minTargetAmount, exchangeDistribution);
    uint256 usdcBalance = usdc.balanceOf(address(this));
    config.getCreditDesk().pay(creditLineAddress, usdcBalance);
  }

  function payMultipleWithSwapOnOneInch(
    address[] memory creditLines,
    uint256[] memory minAmounts,
    uint256 originAmount,
    address fromToken,
    uint256[] memory exchangeDistribution
  ) external onlyAdmin {
    require(creditLines.length == minAmounts.length, "Creditlines and amounts must be the same length");

    uint256 totalMinAmount = 0;
    for (uint256 i = 0; i < minAmounts.length; i++) {
      totalMinAmount = totalMinAmount.add(minAmounts[i]);
    }

    transferFrom(fromToken, _msgSender(), address(this), originAmount);

    IERC20withDec usdc = config.getUSDC();
    swapOnOneInch(fromToken, address(usdc), originAmount, totalMinAmount, exchangeDistribution);

    ICreditDesk creditDesk = config.getCreditDesk();
    for (uint256 i = 0; i < minAmounts.length; i++) {
      creditDesk.pay(creditLines[i], minAmounts[i]);
    }

    uint256 remainingUSDC = usdc.balanceOf(address(this));
    if (remainingUSDC > 0) {
      bool success = usdc.transfer(creditLines[0], remainingUSDC);
      require(success, "Failed to transfer USDC");
    }
  }

  function transferFrom(
    address erc20,
    address sender,
    address recipient,
    uint256 amount
  ) internal {
    bytes memory _data;
    // Do a low-level invoke on this transfer, since Tether fails if we use the normal IERC20 interface
    _data = abi.encodeWithSignature("transferFrom(address,address,uint256)", sender, recipient, amount);
    invoke(address(erc20), _data);
  }

  function swapOnOneInch(
    address fromToken,
    address toToken,
    uint256 originAmount,
    uint256 minTargetAmount,
    uint256[] memory exchangeDistribution
  ) internal {
    bytes memory _data = abi.encodeWithSignature(
      "swap(address,address,uint256,uint256,uint256[],uint256)",
      fromToken,
      toToken,
      originAmount,
      minTargetAmount,
      exchangeDistribution,
      0
    );
    invoke(config.oneInchAddress(), _data);
  }

  /**
   * @notice Performs a generic transaction.
   * @param _target The address for the transaction.
   * @param _data The data of the transaction.
   * Mostly copied from Argent:
   * https://github.com/argentlabs/argent-contracts/blob/develop/contracts/wallet/BaseWallet.sol#L111
   */
  function invoke(address _target, bytes memory _data) internal returns (bytes memory) {
    // External contracts can be compiled with different Solidity versions
    // which can cause "revert without reason" when called through,
    // for example, a standard IERC20 ABI compiled on the latest version.
    // This low-level call avoids that issue.

    bool success;
    bytes memory _res;
    // solhint-disable-next-line avoid-low-level-calls
    (success, _res) = _target.call(_data);
    if (!success && _res.length > 0) {
      // solhint-disable-next-line no-inline-assembly
      assembly {
        returndatacopy(0, 0, returndatasize())
        revert(0, returndatasize())
      }
    } else if (!success) {
      revert("VM: wallet invoke reverted");
    }
    return _res;
  }

  function toUint256(bytes memory _bytes) internal pure returns (uint256 value) {
    assembly {
      value := mload(add(_bytes, 0x20))
    }
  }

  // OpenZeppelin contracts come with support for GSN _msgSender() (which just defaults to msg.sender)
  // Since there are two different versions of the function in the hierarchy, we need to instruct solidity to
  // use the relay recipient version which can actually pull the real sender from the parameters.
  // https://www.notion.so/My-contract-is-using-OpenZeppelin-How-do-I-add-GSN-support-2bee7e9d5f774a0cbb60d3a8de03e9fb
  function _msgSender() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (address payable) {
    return BaseRelayRecipient._msgSender();
  }

  function _msgData() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (bytes memory ret) {
    return BaseRelayRecipient._msgData();
  }

  function versionRecipient() external view override returns (string memory) {
    return "2.0.0";
  }
}

File 2 of 44 : FixedPoint.sol
// solhint-disable
// Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol
pragma solidity 0.6.12;

import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol";


/**
 * @title Library for fixed point arithmetic on uints
 */
library FixedPoint {
    using SafeMath for uint256;
    using SignedSafeMath for int256;

    // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
    // For unsigned values:
    //   This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
    uint256 private constant FP_SCALING_FACTOR = 10**18;

    // --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
    struct Unsigned {
        uint256 rawValue;
    }

    /**
     * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`.
     * @param a uint to convert into a FixedPoint.
     * @return the converted FixedPoint.
     */
    function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
        return Unsigned(a.mul(FP_SCALING_FACTOR));
    }

    /**
     * @notice Whether `a` is equal to `b`.
     * @param a a FixedPoint.
     * @param b a uint256.
     * @return True if equal, or False.
     */
    function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
        return a.rawValue == fromUnscaledUint(b).rawValue;
    }

    /**
     * @notice Whether `a` is equal to `b`.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return True if equal, or False.
     */
    function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
        return a.rawValue == b.rawValue;
    }

    /**
     * @notice Whether `a` is greater than `b`.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return True if `a > b`, or False.
     */
    function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
        return a.rawValue > b.rawValue;
    }

    /**
     * @notice Whether `a` is greater than `b`.
     * @param a a FixedPoint.
     * @param b a uint256.
     * @return True if `a > b`, or False.
     */
    function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
        return a.rawValue > fromUnscaledUint(b).rawValue;
    }

    /**
     * @notice Whether `a` is greater than `b`.
     * @param a a uint256.
     * @param b a FixedPoint.
     * @return True if `a > b`, or False.
     */
    function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
        return fromUnscaledUint(a).rawValue > b.rawValue;
    }

    /**
     * @notice Whether `a` is greater than or equal to `b`.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return True if `a >= b`, or False.
     */
    function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
        return a.rawValue >= b.rawValue;
    }

    /**
     * @notice Whether `a` is greater than or equal to `b`.
     * @param a a FixedPoint.
     * @param b a uint256.
     * @return True if `a >= b`, or False.
     */
    function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
        return a.rawValue >= fromUnscaledUint(b).rawValue;
    }

    /**
     * @notice Whether `a` is greater than or equal to `b`.
     * @param a a uint256.
     * @param b a FixedPoint.
     * @return True if `a >= b`, or False.
     */
    function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
        return fromUnscaledUint(a).rawValue >= b.rawValue;
    }

    /**
     * @notice Whether `a` is less than `b`.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return True if `a < b`, or False.
     */
    function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
        return a.rawValue < b.rawValue;
    }

    /**
     * @notice Whether `a` is less than `b`.
     * @param a a FixedPoint.
     * @param b a uint256.
     * @return True if `a < b`, or False.
     */
    function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
        return a.rawValue < fromUnscaledUint(b).rawValue;
    }

    /**
     * @notice Whether `a` is less than `b`.
     * @param a a uint256.
     * @param b a FixedPoint.
     * @return True if `a < b`, or False.
     */
    function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
        return fromUnscaledUint(a).rawValue < b.rawValue;
    }

    /**
     * @notice Whether `a` is less than or equal to `b`.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return True if `a <= b`, or False.
     */
    function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
        return a.rawValue <= b.rawValue;
    }

    /**
     * @notice Whether `a` is less than or equal to `b`.
     * @param a a FixedPoint.
     * @param b a uint256.
     * @return True if `a <= b`, or False.
     */
    function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
        return a.rawValue <= fromUnscaledUint(b).rawValue;
    }

    /**
     * @notice Whether `a` is less than or equal to `b`.
     * @param a a uint256.
     * @param b a FixedPoint.
     * @return True if `a <= b`, or False.
     */
    function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
        return fromUnscaledUint(a).rawValue <= b.rawValue;
    }

    /**
     * @notice The minimum of `a` and `b`.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return the minimum of `a` and `b`.
     */
    function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
        return a.rawValue < b.rawValue ? a : b;
    }

    /**
     * @notice The maximum of `a` and `b`.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return the maximum of `a` and `b`.
     */
    function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
        return a.rawValue > b.rawValue ? a : b;
    }

    /**
     * @notice Adds two `Unsigned`s, reverting on overflow.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return the sum of `a` and `b`.
     */
    function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
        return Unsigned(a.rawValue.add(b.rawValue));
    }

    /**
     * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
     * @param a a FixedPoint.
     * @param b a uint256.
     * @return the sum of `a` and `b`.
     */
    function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
        return add(a, fromUnscaledUint(b));
    }

    /**
     * @notice Subtracts two `Unsigned`s, reverting on overflow.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return the difference of `a` and `b`.
     */
    function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
        return Unsigned(a.rawValue.sub(b.rawValue));
    }

    /**
     * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
     * @param a a FixedPoint.
     * @param b a uint256.
     * @return the difference of `a` and `b`.
     */
    function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
        return sub(a, fromUnscaledUint(b));
    }

    /**
     * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
     * @param a a uint256.
     * @param b a FixedPoint.
     * @return the difference of `a` and `b`.
     */
    function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
        return sub(fromUnscaledUint(a), b);
    }

    /**
     * @notice Multiplies two `Unsigned`s, reverting on overflow.
     * @dev This will "floor" the product.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return the product of `a` and `b`.
     */
    function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
        // There are two caveats with this computation:
        // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
        // stored internally as a uint256 ~10^59.
        // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
        // would round to 3, but this computation produces the result 2.
        // No need to use SafeMath because FP_SCALING_FACTOR != 0.
        return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
    }

    /**
     * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
     * @dev This will "floor" the product.
     * @param a a FixedPoint.
     * @param b a uint256.
     * @return the product of `a` and `b`.
     */
    function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
        return Unsigned(a.rawValue.mul(b));
    }

    /**
     * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return the product of `a` and `b`.
     */
    function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
        uint256 mulRaw = a.rawValue.mul(b.rawValue);
        uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
        uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
        if (mod != 0) {
            return Unsigned(mulFloor.add(1));
        } else {
            return Unsigned(mulFloor);
        }
    }

    /**
     * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
     * @param a a FixedPoint.
     * @param b a FixedPoint.
     * @return the product of `a` and `b`.
     */
    function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
        // Since b is an int, there is no risk of truncation and we can just mul it normally
        return Unsigned(a.rawValue.mul(b));
    }

    /**
     * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
     * @dev This will "floor" the quotient.
     * @param a a FixedPoint numerator.
     * @param b a FixedPoint denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
        // There are two caveats with this computation:
        // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
        // 10^41 is stored internally as a uint256 10^59.
        // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
        // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
        return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
    }

    /**
     * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
     * @dev This will "floor" the quotient.
     * @param a a FixedPoint numerator.
     * @param b a uint256 denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
        return Unsigned(a.rawValue.div(b));
    }

    /**
     * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
     * @dev This will "floor" the quotient.
     * @param a a uint256 numerator.
     * @param b a FixedPoint denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
        return div(fromUnscaledUint(a), b);
    }

    /**
     * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
     * @param a a FixedPoint numerator.
     * @param b a FixedPoint denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
        uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
        uint256 divFloor = aScaled.div(b.rawValue);
        uint256 mod = aScaled.mod(b.rawValue);
        if (mod != 0) {
            return Unsigned(divFloor.add(1));
        } else {
            return Unsigned(divFloor);
        }
    }

    /**
     * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
     * @param a a FixedPoint numerator.
     * @param b a uint256 denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
        // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
        // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
        // This creates the possibility of overflow if b is very large.
        return divCeil(a, fromUnscaledUint(b));
    }

    /**
     * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
     * @dev This will "floor" the result.
     * @param a a FixedPoint numerator.
     * @param b a uint256 denominator.
     * @return output is `a` to the power of `b`.
     */
    function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
        output = fromUnscaledUint(1);
        for (uint256 i = 0; i < b; i = i.add(1)) {
            output = mul(output, a);
        }
    }

    // ------------------------------------------------- SIGNED -------------------------------------------------------------
    // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
    // For signed values:
    //   This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
    int256 private constant SFP_SCALING_FACTOR = 10**18;

    struct Signed {
        int256 rawValue;
    }

    function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
        require(a.rawValue >= 0, "Negative value provided");
        return Unsigned(uint256(a.rawValue));
    }

    function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
        require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
        return Signed(int256(a.rawValue));
    }

    /**
     * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`.
     * @param a int to convert into a FixedPoint.Signed.
     * @return the converted FixedPoint.Signed.
     */
    function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
        return Signed(a.mul(SFP_SCALING_FACTOR));
    }

    /**
     * @notice Whether `a` is equal to `b`.
     * @param a a FixedPoint.Signed.
     * @param b a int256.
     * @return True if equal, or False.
     */
    function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
        return a.rawValue == fromUnscaledInt(b).rawValue;
    }

    /**
     * @notice Whether `a` is equal to `b`.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return True if equal, or False.
     */
    function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
        return a.rawValue == b.rawValue;
    }

    /**
     * @notice Whether `a` is greater than `b`.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return True if `a > b`, or False.
     */
    function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
        return a.rawValue > b.rawValue;
    }

    /**
     * @notice Whether `a` is greater than `b`.
     * @param a a FixedPoint.Signed.
     * @param b an int256.
     * @return True if `a > b`, or False.
     */
    function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
        return a.rawValue > fromUnscaledInt(b).rawValue;
    }

    /**
     * @notice Whether `a` is greater than `b`.
     * @param a an int256.
     * @param b a FixedPoint.Signed.
     * @return True if `a > b`, or False.
     */
    function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
        return fromUnscaledInt(a).rawValue > b.rawValue;
    }

    /**
     * @notice Whether `a` is greater than or equal to `b`.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return True if `a >= b`, or False.
     */
    function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
        return a.rawValue >= b.rawValue;
    }

    /**
     * @notice Whether `a` is greater than or equal to `b`.
     * @param a a FixedPoint.Signed.
     * @param b an int256.
     * @return True if `a >= b`, or False.
     */
    function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
        return a.rawValue >= fromUnscaledInt(b).rawValue;
    }

    /**
     * @notice Whether `a` is greater than or equal to `b`.
     * @param a an int256.
     * @param b a FixedPoint.Signed.
     * @return True if `a >= b`, or False.
     */
    function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
        return fromUnscaledInt(a).rawValue >= b.rawValue;
    }

    /**
     * @notice Whether `a` is less than `b`.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return True if `a < b`, or False.
     */
    function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
        return a.rawValue < b.rawValue;
    }

    /**
     * @notice Whether `a` is less than `b`.
     * @param a a FixedPoint.Signed.
     * @param b an int256.
     * @return True if `a < b`, or False.
     */
    function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
        return a.rawValue < fromUnscaledInt(b).rawValue;
    }

    /**
     * @notice Whether `a` is less than `b`.
     * @param a an int256.
     * @param b a FixedPoint.Signed.
     * @return True if `a < b`, or False.
     */
    function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
        return fromUnscaledInt(a).rawValue < b.rawValue;
    }

    /**
     * @notice Whether `a` is less than or equal to `b`.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return True if `a <= b`, or False.
     */
    function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
        return a.rawValue <= b.rawValue;
    }

    /**
     * @notice Whether `a` is less than or equal to `b`.
     * @param a a FixedPoint.Signed.
     * @param b an int256.
     * @return True if `a <= b`, or False.
     */
    function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
        return a.rawValue <= fromUnscaledInt(b).rawValue;
    }

    /**
     * @notice Whether `a` is less than or equal to `b`.
     * @param a an int256.
     * @param b a FixedPoint.Signed.
     * @return True if `a <= b`, or False.
     */
    function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
        return fromUnscaledInt(a).rawValue <= b.rawValue;
    }

    /**
     * @notice The minimum of `a` and `b`.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return the minimum of `a` and `b`.
     */
    function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
        return a.rawValue < b.rawValue ? a : b;
    }

    /**
     * @notice The maximum of `a` and `b`.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return the maximum of `a` and `b`.
     */
    function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
        return a.rawValue > b.rawValue ? a : b;
    }

    /**
     * @notice Adds two `Signed`s, reverting on overflow.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return the sum of `a` and `b`.
     */
    function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
        return Signed(a.rawValue.add(b.rawValue));
    }

    /**
     * @notice Adds an `Signed` to an unscaled int, reverting on overflow.
     * @param a a FixedPoint.Signed.
     * @param b an int256.
     * @return the sum of `a` and `b`.
     */
    function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
        return add(a, fromUnscaledInt(b));
    }

    /**
     * @notice Subtracts two `Signed`s, reverting on overflow.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return the difference of `a` and `b`.
     */
    function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
        return Signed(a.rawValue.sub(b.rawValue));
    }

    /**
     * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
     * @param a a FixedPoint.Signed.
     * @param b an int256.
     * @return the difference of `a` and `b`.
     */
    function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
        return sub(a, fromUnscaledInt(b));
    }

    /**
     * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
     * @param a an int256.
     * @param b a FixedPoint.Signed.
     * @return the difference of `a` and `b`.
     */
    function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
        return sub(fromUnscaledInt(a), b);
    }

    /**
     * @notice Multiplies two `Signed`s, reverting on overflow.
     * @dev This will "floor" the product.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return the product of `a` and `b`.
     */
    function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
        // There are two caveats with this computation:
        // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
        // stored internally as an int256 ~10^59.
        // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
        // would round to 3, but this computation produces the result 2.
        // No need to use SafeMath because SFP_SCALING_FACTOR != 0.
        return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
    }

    /**
     * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
     * @dev This will "floor" the product.
     * @param a a FixedPoint.Signed.
     * @param b an int256.
     * @return the product of `a` and `b`.
     */
    function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
        return Signed(a.rawValue.mul(b));
    }

    /**
     * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return the product of `a` and `b`.
     */
    function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
        int256 mulRaw = a.rawValue.mul(b.rawValue);
        int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
        // Manual mod because SignedSafeMath doesn't support it.
        int256 mod = mulRaw % SFP_SCALING_FACTOR;
        if (mod != 0) {
            bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
            int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
            return Signed(mulTowardsZero.add(valueToAdd));
        } else {
            return Signed(mulTowardsZero);
        }
    }

    /**
     * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
     * @param a a FixedPoint.Signed.
     * @param b a FixedPoint.Signed.
     * @return the product of `a` and `b`.
     */
    function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
        // Since b is an int, there is no risk of truncation and we can just mul it normally
        return Signed(a.rawValue.mul(b));
    }

    /**
     * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
     * @dev This will "floor" the quotient.
     * @param a a FixedPoint numerator.
     * @param b a FixedPoint denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
        // There are two caveats with this computation:
        // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
        // 10^41 is stored internally as an int256 10^59.
        // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
        // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
        return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
    }

    /**
     * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
     * @dev This will "floor" the quotient.
     * @param a a FixedPoint numerator.
     * @param b an int256 denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
        return Signed(a.rawValue.div(b));
    }

    /**
     * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
     * @dev This will "floor" the quotient.
     * @param a an int256 numerator.
     * @param b a FixedPoint denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
        return div(fromUnscaledInt(a), b);
    }

    /**
     * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
     * @param a a FixedPoint numerator.
     * @param b a FixedPoint denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
        int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
        int256 divTowardsZero = aScaled.div(b.rawValue);
        // Manual mod because SignedSafeMath doesn't support it.
        int256 mod = aScaled % b.rawValue;
        if (mod != 0) {
            bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
            int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
            return Signed(divTowardsZero.add(valueToAdd));
        } else {
            return Signed(divTowardsZero);
        }
    }

    /**
     * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
     * @param a a FixedPoint numerator.
     * @param b an int256 denominator.
     * @return the quotient of `a` divided by `b`.
     */
    function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
        // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
        // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
        // This creates the possibility of overflow if b is very large.
        return divAwayFromZero(a, fromUnscaledInt(b));
    }

    /**
     * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
     * @dev This will "floor" the result.
     * @param a a FixedPoint.Signed.
     * @param b a uint256 (negative exponents are not allowed).
     * @return output is `a` to the power of `b`.
     */
    function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
        output = fromUnscaledInt(1);
        for (uint256 i = 0; i < b; i = i.add(1)) {
            output = mul(output, a);
        }
    }
}

File 3 of 44 : SafeMath.sol
pragma solidity ^0.6.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        // Solidity only automatically asserts when dividing by 0
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

File 4 of 44 : SignedSafeMath.sol
pragma solidity ^0.6.0;

/**
 * @title SignedSafeMath
 * @dev Signed math operations with safety checks that revert on error.
 */
library SignedSafeMath {
    int256 constant private _INT256_MIN = -2**255;

    /**
     * @dev Multiplies two signed integers, reverts on overflow.
     */
    function mul(int256 a, int256 b) internal pure returns (int256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");

        int256 c = a * b;
        require(c / a == b, "SignedSafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
     */
    function div(int256 a, int256 b) internal pure returns (int256) {
        require(b != 0, "SignedSafeMath: division by zero");
        require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");

        int256 c = a / b;

        return c;
    }

    /**
     * @dev Subtracts two signed integers, reverts on overflow.
     */
    function sub(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a - b;
        require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");

        return c;
    }

    /**
     * @dev Adds two signed integers, reverts on overflow.
     */
    function add(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a + b;
        require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");

        return c;
    }
}

File 5 of 44 : Accountant.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "./CreditLine.sol";
import "../../external/FixedPoint.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";

/**
 * @title The Accountant
 * @notice Library for handling key financial calculations, such as interest and principal accrual.
 * @author Goldfinch
 */

library Accountant {
  using SafeMath for uint256;
  using FixedPoint for FixedPoint.Signed;
  using FixedPoint for FixedPoint.Unsigned;
  using FixedPoint for int256;
  using FixedPoint for uint256;

  // Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled
  uint256 public constant FP_SCALING_FACTOR = 10**18;
  uint256 public constant INTEREST_DECIMALS = 1e8;
  uint256 public constant BLOCKS_PER_DAY = 5760;
  uint256 public constant BLOCKS_PER_YEAR = (BLOCKS_PER_DAY * 365);

  struct PaymentAllocation {
    uint256 interestPayment;
    uint256 principalPayment;
    uint256 additionalBalancePayment;
  }

  function calculateInterestAndPrincipalAccrued(
    CreditLine cl,
    uint256 blockNumber,
    uint256 lateFeeGracePeriod
  ) public view returns (uint256, uint256) {
    uint256 balance = cl.balance(); // gas optimization
    uint256 interestAccrued = calculateInterestAccrued(cl, balance, blockNumber, lateFeeGracePeriod);
    uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, blockNumber);
    return (interestAccrued, principalAccrued);
  }

  function calculatePrincipalAccrued(
    CreditLine cl,
    uint256 balance,
    uint256 blockNumber
  ) public view returns (uint256) {
    if (blockNumber >= cl.termEndBlock()) {
      return balance;
    } else {
      return 0;
    }
  }

  function calculateWritedownFor(
    CreditLine cl,
    uint256 blockNumber,
    uint256 gracePeriodInDays,
    uint256 maxDaysLate
  ) public view returns (uint256, uint256) {
    FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
    if (amountOwedPerDay.isEqual(0)) {
      return (0, 0);
    }
    FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays);
    FixedPoint.Unsigned memory daysLate;

    // Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30,
    // Before the term end block, we use the interestOwed to calculate the periods late. However, after the loan term
    // has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to
    // calculate the periods later.
    uint256 totalOwed = cl.interestOwed().add(cl.principalOwed());
    daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
    if (blockNumber > cl.termEndBlock()) {
      uint256 blocksLate = blockNumber.sub(cl.termEndBlock());
      daysLate = daysLate.add(FixedPoint.fromUnscaledUint(blocksLate).div(BLOCKS_PER_DAY));
    }

    FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
    FixedPoint.Unsigned memory writedownPercent;
    if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
      // Within the grace period, we don't have to write down, so assume 0%
      writedownPercent = FixedPoint.fromUnscaledUint(0);
    } else {
      writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
    }

    FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(cl.balance()).div(FP_SCALING_FACTOR);
    // This will return a number between 0-100 representing the write down percent with no decimals
    uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue;
    return (unscaledWritedownPercent, writedownAmount.rawValue);
  }

  function calculateAmountOwedForOneDay(CreditLine cl) public view returns (FixedPoint.Unsigned memory) {
    // Determine theoretical interestOwed for one full day
    uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
    FixedPoint.Unsigned memory interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365);

    return interestOwed;
  }

  function calculateInterestAccrued(
    CreditLine cl,
    uint256 balance,
    uint256 blockNumber,
    uint256 lateFeeGracePeriodInDays
  ) public view returns (uint256) {
    // We use Math.min here to prevent integer overflow (ie. go negative) when calculating
    // numBlocksElapsed. Typically this shouldn't be possible, because
    // the interestAccruedAsOfBlock couldn't be *after* the current blockNumber. However, when assessing
    // we allow this function to be called with a past block number, which raises the possibility
    // of overflow.
    // This use of min should not generate incorrect interest calculations, since
    // this functions purpose is just to normalize balances, and  will be called any time
    // a balance affecting action takes place (eg. drawdown, repayment, assessment)
    uint256 interestAccruedAsOfBlock = Math.min(blockNumber, cl.interestAccruedAsOfBlock());
    uint256 numBlocksElapsed = blockNumber.sub(interestAccruedAsOfBlock);
    uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS);
    uint256 interestOwed = totalInterestPerYear.mul(numBlocksElapsed).div(BLOCKS_PER_YEAR);

    if (lateFeeApplicable(cl, blockNumber, lateFeeGracePeriodInDays)) {
      uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);
      uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(numBlocksElapsed).div(BLOCKS_PER_YEAR);
      interestOwed = interestOwed.add(additionalLateFeeInterest);
    }

    return interestOwed;
  }

  function lateFeeApplicable(
    CreditLine cl,
    uint256 blockNumber,
    uint256 gracePeriodInDays
  ) public view returns (bool) {
    uint256 blocksLate = blockNumber.sub(cl.lastFullPaymentBlock());
    return cl.lateFeeApr() > 0 && blocksLate > gracePeriodInDays.mul(BLOCKS_PER_DAY);
  }

  function allocatePayment(
    uint256 paymentAmount,
    uint256 balance,
    uint256 interestOwed,
    uint256 principalOwed
  ) public pure returns (PaymentAllocation memory) {
    uint256 paymentRemaining = paymentAmount;
    uint256 interestPayment = Math.min(interestOwed, paymentRemaining);
    paymentRemaining = paymentRemaining.sub(interestPayment);

    uint256 principalPayment = Math.min(principalOwed, paymentRemaining);
    paymentRemaining = paymentRemaining.sub(principalPayment);

    uint256 balanceRemaining = balance.sub(principalPayment);
    uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);

    return
      PaymentAllocation({
        interestPayment: interestPayment,
        principalPayment: principalPayment,
        additionalBalancePayment: additionalBalancePayment
      });
  }
}

File 6 of 44 : CreditLine.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "./GoldfinchConfig.sol";
import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IERC20withDec.sol";

/**
 * @title CreditLine
 * @notice A "dumb" state container that represents the agreement between an Underwriter and
 *  the borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed.
 *  This contract purposefully has essentially no business logic. Really just setters and getters.
 * @author Goldfinch
 */

// solhint-disable-next-line max-states-count
contract CreditLine is BaseUpgradeablePausable {
  // Credit line terms
  address public borrower;
  address public underwriter;
  uint256 public limit;
  uint256 public interestApr;
  uint256 public paymentPeriodInDays;
  uint256 public termInDays;
  uint256 public lateFeeApr;

  // Accounting variables
  uint256 public balance;
  uint256 public interestOwed;
  uint256 public principalOwed;
  uint256 public termEndBlock;
  uint256 public nextDueBlock;
  uint256 public interestAccruedAsOfBlock;
  uint256 public writedownAmount;
  uint256 public lastFullPaymentBlock;

  function initialize(
    address owner,
    address _borrower,
    address _underwriter,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _paymentPeriodInDays,
    uint256 _termInDays,
    uint256 _lateFeeApr
  ) public initializer {
    require(owner != address(0) && _borrower != address(0) && _underwriter != address(0), "Zero address passed in");
    __BaseUpgradeablePausable__init(owner);
    borrower = _borrower;
    underwriter = _underwriter;
    limit = _limit;
    interestApr = _interestApr;
    paymentPeriodInDays = _paymentPeriodInDays;
    termInDays = _termInDays;
    lateFeeApr = _lateFeeApr;
    interestAccruedAsOfBlock = block.number;
  }

  function setTermEndBlock(uint256 newTermEndBlock) external onlyAdmin {
    termEndBlock = newTermEndBlock;
  }

  function setNextDueBlock(uint256 newNextDueBlock) external onlyAdmin {
    nextDueBlock = newNextDueBlock;
  }

  function setBalance(uint256 newBalance) external onlyAdmin {
    balance = newBalance;
  }

  function setInterestOwed(uint256 newInterestOwed) external onlyAdmin {
    interestOwed = newInterestOwed;
  }

  function setPrincipalOwed(uint256 newPrincipalOwed) external onlyAdmin {
    principalOwed = newPrincipalOwed;
  }

  function setInterestAccruedAsOfBlock(uint256 newInterestAccruedAsOfBlock) external onlyAdmin {
    interestAccruedAsOfBlock = newInterestAccruedAsOfBlock;
  }

  function setWritedownAmount(uint256 newWritedownAmount) external onlyAdmin {
    writedownAmount = newWritedownAmount;
  }

  function setLastFullPaymentBlock(uint256 newLastFullPaymentBlock) external onlyAdmin {
    lastFullPaymentBlock = newLastFullPaymentBlock;
  }

  function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin {
    lateFeeApr = newLateFeeApr;
  }

  function setLimit(uint256 newAmount) external onlyAdminOrUnderwriter {
    limit = newAmount;
  }

  function authorizePool(address configAddress) external onlyAdmin {
    GoldfinchConfig config = GoldfinchConfig(configAddress);
    address poolAddress = config.getAddress(uint256(ConfigOptions.Addresses.Pool));
    address usdcAddress = config.getAddress(uint256(ConfigOptions.Addresses.USDC));
    // Approve the pool for an infinite amount
    bool success = IERC20withDec(usdcAddress).approve(poolAddress, uint256(-1));
    require(success, "Failed to approve USDC");
  }

  modifier onlyAdminOrUnderwriter() {
    require(isAdmin() || _msgSender() == underwriter, "Restricted to owner or underwriter");
    _;
  }
}

File 7 of 44 : Math.sol
pragma solidity ^0.6.0;

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

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

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

File 8 of 44 : GoldfinchConfig.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./BaseUpgradeablePausable.sol";
import "./ConfigOptions.sol";

/**
 * @title GoldfinchConfig
 * @notice This contract stores mappings of useful "protocol config state", giving a central place
 *  for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars
 *  are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol.
 * @author Goldfinch
 */

contract GoldfinchConfig is BaseUpgradeablePausable {
  mapping(uint256 => address) public addresses;
  mapping(uint256 => uint256) public numbers;

  event AddressUpdated(address owner, uint256 index, address oldValue, address newValue);
  event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue);

  function initialize(address owner) public initializer {
    __BaseUpgradeablePausable__init(owner);
  }

  function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin {
    require(addresses[addressIndex] == address(0), "Address has already been initialized");

    emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress);
    addresses[addressIndex] = newAddress;
  }

  function setNumber(uint256 index, uint256 newNumber) public onlyAdmin {
    emit NumberUpdated(msg.sender, index, numbers[index], newNumber);
    numbers[index] = newNumber;
  }

  function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin {
    uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve);
    emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve);
    addresses[key] = newTreasuryReserve;
  }

  /*
    Using custom getters incase we want to change underlying implementation later,
    or add checks or validations later on.
  */
  function getAddress(uint256 addressKey) public view returns (address) {
    return addresses[addressKey];
  }

  function getNumber(uint256 number) public view returns (uint256) {
    return numbers[number];
  }
}

File 9 of 44 : BaseUpgradeablePausable.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./PauserPausable.sol";

/**
 * @title BaseUpgradeablePausable contract
 * @notice This is our Base contract that most other contracts inherit from. It includes many standard
 *  useful abilities like ugpradeability, pausability, access control, and re-entrancy guards.
 * @author Goldfinch
 */

contract BaseUpgradeablePausable is
  Initializable,
  AccessControlUpgradeSafe,
  PauserPausable,
  ReentrancyGuardUpgradeSafe
{
  bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
  using SafeMath for uint256;
  // Pre-reserving a few slots in the base contract in case we need to add things in the future.
  // This does not actually take up gas cost or storage cost, but it does reserve the storage slots.
  // See OpenZeppelin's use of this pattern here:
  // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37
  uint256[50] private __gap1;
  uint256[50] private __gap2;
  uint256[50] private __gap3;
  uint256[50] private __gap4;

  // solhint-disable-next-line func-name-mixedcase
  function __BaseUpgradeablePausable__init(address owner) public initializer {
    require(owner != address(0), "Owner cannot be the zero address");
    __AccessControl_init_unchained();
    __Pausable_init_unchained();
    __ReentrancyGuard_init_unchained();

    _setupRole(OWNER_ROLE, owner);
    _setupRole(PAUSER_ROLE, owner);

    _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
    _setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
  }

  function isAdmin() public view returns (bool) {
    return hasRole(OWNER_ROLE, _msgSender());
  }

  modifier onlyAdmin() {
    require(isAdmin(), "Must have admin role to perform this action");
    _;
  }
}

File 10 of 44 : IERC20withDec.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

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

/*
Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's.
*/

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20withDec is IERC20 {
  /**
   * @dev Returns the number of decimals used for the token
   */
  function decimals() external view returns (uint8);
}

File 11 of 44 : ConfigOptions.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

/**
 * @title ConfigOptions
 * @notice A central place for enumerating the configurable options of our GoldfinchConfig contract
 * @author Goldfinch
 */

library ConfigOptions {
  // NEVER EVER CHANGE THE ORDER OF THESE!
  // You can rename or append. But NEVER change the order.
  enum Numbers {
    TransactionLimit,
    TotalFundsLimit,
    MaxUnderwriterLimit,
    ReserveDenominator,
    WithdrawFeeDenominator,
    LatenessGracePeriodInDays,
    LatenessMaxDays
  }
  enum Addresses {
    Pool,
    CreditLineImplementation,
    CreditLineFactory,
    CreditDesk,
    Fidu,
    USDC,
    TreasuryReserve,
    ProtocolAdmin,
    OneInch,
    TrustedForwarder,
    CUSDCContract,
    GoldfinchConfig
  }

  function getNumberName(uint256 number) public pure returns (string memory) {
    Numbers numberName = Numbers(number);
    if (Numbers.TransactionLimit == numberName) {
      return "TransactionLimit";
    }
    if (Numbers.TotalFundsLimit == numberName) {
      return "TotalFundsLimit";
    }
    if (Numbers.MaxUnderwriterLimit == numberName) {
      return "MaxUnderwriterLimit";
    }
    if (Numbers.ReserveDenominator == numberName) {
      return "ReserveDenominator";
    }
    if (Numbers.WithdrawFeeDenominator == numberName) {
      return "WithdrawFeeDenominator";
    }
    if (Numbers.LatenessGracePeriodInDays == numberName) {
      return "LatenessGracePeriodInDays";
    }
    if (Numbers.LatenessMaxDays == numberName) {
      return "LatenessMaxDays";
    }
    revert("Unknown value passed to getNumberName");
  }

  function getAddressName(uint256 addressKey) public pure returns (string memory) {
    Addresses addressName = Addresses(addressKey);
    if (Addresses.Pool == addressName) {
      return "Pool";
    }
    if (Addresses.CreditLineImplementation == addressName) {
      return "CreditLineImplementation";
    }
    if (Addresses.CreditLineFactory == addressName) {
      return "CreditLineFactory";
    }
    if (Addresses.CreditDesk == addressName) {
      return "CreditDesk";
    }
    if (Addresses.Fidu == addressName) {
      return "Fidu";
    }
    if (Addresses.USDC == addressName) {
      return "USDC";
    }
    if (Addresses.TreasuryReserve == addressName) {
      return "TreasuryReserve";
    }
    if (Addresses.ProtocolAdmin == addressName) {
      return "ProtocolAdmin";
    }
    if (Addresses.OneInch == addressName) {
      return "OneInch";
    }
    if (Addresses.TrustedForwarder == addressName) {
      return "TrustedForwarder";
    }
    if (Addresses.CUSDCContract == addressName) {
      return "CUSDCContract";
    }
    revert("Unknown value passed to getAddressName");
  }
}

File 12 of 44 : AccessControl.sol
pragma solidity ^0.6.0;

import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, _msgSender()));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 */
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
    function __AccessControl_init() internal initializer {
        __Context_init_unchained();
        __AccessControl_init_unchained();
    }

    function __AccessControl_init_unchained() internal initializer {


    }

    using EnumerableSet for EnumerableSet.AddressSet;
    using Address for address;

    struct RoleData {
        EnumerableSet.AddressSet members;
        bytes32 adminRole;
    }

    mapping (bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

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

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

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view returns (bool) {
        return _roles[role].members.contains(account);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view returns (uint256) {
        return _roles[role].members.length();
    }

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
        return _roles[role].members.at(index);
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) public virtual {
        require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");

        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) public virtual {
        require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");

        _revokeRole(role, account);
    }

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

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        _roles[role].adminRole = adminRole;
    }

    function _grantRole(bytes32 role, address account) private {
        if (_roles[role].members.add(account)) {
            emit RoleGranted(role, account, _msgSender());
        }
    }

    function _revokeRole(bytes32 role, address account) private {
        if (_roles[role].members.remove(account)) {
            emit RoleRevoked(role, account, _msgSender());
        }
    }

    uint256[49] private __gap;
}

File 13 of 44 : ReentrancyGuard.sol
pragma solidity ^0.6.0;
import "../Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
contract ReentrancyGuardUpgradeSafe is Initializable {
    bool private _notEntered;


    function __ReentrancyGuard_init() internal initializer {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal initializer {


        // Storing an initial non-zero value makes deployment a bit more
        // expensive, but in exchange the refund on every call to nonReentrant
        // will be lower in amount. Since refunds are capped to a percetange of
        // the total transaction's gas, it is best to keep them low in cases
        // like this one, to increase the likelihood of the full refund coming
        // into effect.
        _notEntered = true;

    }


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

        // Any calls to nonReentrant after this point will fail
        _notEntered = false;

        _;

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

    uint256[49] private __gap;
}

File 14 of 44 : Initializable.sol
pragma solidity >=0.4.24 <0.7.0;


/**
 * @title Initializable
 *
 * @dev Helper contract to support initializer functions. To use it, replace
 * the constructor with a function that has the `initializer` modifier.
 * WARNING: Unlike constructors, initializer functions must be manually
 * invoked. This applies both to deploying an Initializable contract, as well
 * as extending an Initializable contract via inheritance.
 * WARNING: When used with inheritance, manual care must be taken to not invoke
 * a parent initializer twice, or ensure that all initializers are idempotent,
 * because this is not dealt with automatically as with constructors.
 */
contract Initializable {

  /**
   * @dev Indicates that the contract has been initialized.
   */
  bool private initialized;

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

  /**
   * @dev Modifier to use in the initializer function of a contract.
   */
  modifier initializer() {
    require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");

    bool isTopLevelCall = !initializing;
    if (isTopLevelCall) {
      initializing = true;
      initialized = true;
    }

    _;

    if (isTopLevelCall) {
      initializing = false;
    }
  }

  /// @dev Returns true if and only if the function is running in the constructor
  function isConstructor() private view returns (bool) {
    // extcodesize checks the size of the code stored in an address, and
    // address returns the current address. Since the code is still not
    // deployed when running a constructor, any checks on its code size will
    // yield zero, making it an effective way to detect if a contract is
    // under construction or not.
    address self = address(this);
    uint256 cs;
    assembly { cs := extcodesize(self) }
    return cs == 0;
  }

  // Reserved storage space to allow for layout changes in the future.
  uint256[50] private ______gap;
}

File 15 of 44 : PauserPausable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;

import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";

/**
 * @title PauserPausable
 * @notice Inheriting from OpenZeppelin's Pausable contract, this does small
 *  augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract.
 *  It is meant to be inherited.
 * @author Goldfinch
 */

contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe {
  bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

  // solhint-disable-next-line func-name-mixedcase
  function __PauserPausable__init() public initializer {
    __Pausable_init_unchained();
  }

  /**
   * @dev Pauses all functions guarded by Pause
   *
   * See {Pausable-_pause}.
   *
   * Requirements:
   *
   * - the caller must have the PAUSER_ROLE.
   */

  function pause() public onlyPauserRole {
    _pause();
  }

  /**
   * @dev Unpauses the contract
   *
   * See {Pausable-_unpause}.
   *
   * Requirements:
   *
   * - the caller must have the Pauser role
   */
  function unpause() public onlyPauserRole {
    _unpause();
  }

  modifier onlyPauserRole() {
    require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action");
    _;
  }
}

File 16 of 44 : EnumerableSet.sol
pragma solidity ^0.6.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
 * (`UintSet`) are supported.
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;

        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping (bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) { // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
            // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.

            bytes32 lastvalue = set._values[lastIndex];

            // Move the last value to the index where the value to delete is
            set._values[toDeleteIndex] = lastvalue;
            // Update the index for the moved value
            set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        require(set._values.length > index, "EnumerableSet: index out of bounds");
        return set._values[index];
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(value)));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(value)));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(value)));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint256(_at(set._inner, index)));
    }


    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }
}

File 17 of 44 : Address.sol
pragma solidity ^0.6.2;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != accountHash && codehash != 0x0);
    }

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

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }
}

File 18 of 44 : Context.sol
pragma solidity ^0.6.0;
import "../Initializable.sol";

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with GSN meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
contract ContextUpgradeSafe is Initializable {
    // Empty internal constructor, to prevent people from mistakenly deploying
    // an instance of this contract, which should be used via inheritance.

    function __Context_init() internal initializer {
        __Context_init_unchained();
    }

    function __Context_init_unchained() internal initializer {


    }


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

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }

    uint256[50] private __gap;
}

File 19 of 44 : Pausable.sol
pragma solidity ^0.6.0;

import "../GSN/Context.sol";
import "../Initializable.sol";

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

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

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */

    function __Pausable_init() internal initializer {
        __Context_init_unchained();
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal initializer {


        _paused = false;

    }


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

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     */
    modifier whenNotPaused() {
        require(!_paused, "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     */
    modifier whenPaused() {
        require(_paused, "Pausable: not paused");
        _;
    }

    /**
     * @dev Triggers stopped state.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }

    uint256[49] private __gap;
}

File 20 of 44 : IERC20.sol
pragma solidity ^0.6.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

File 21 of 44 : TestAccountant.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "../protocol/core/Accountant.sol";
import "../protocol/core/CreditLine.sol";

contract TestAccountant {
  function calculateInterestAndPrincipalAccrued(
    address creditLineAddress,
    uint256 blockNumber,
    uint256 lateFeeGracePeriod
  ) public view returns (uint256, uint256) {
    CreditLine cl = CreditLine(creditLineAddress);
    return Accountant.calculateInterestAndPrincipalAccrued(cl, blockNumber, lateFeeGracePeriod);
  }

  function calculateWritedownFor(
    address creditLineAddress,
    uint256 blockNumber,
    uint256 gracePeriod,
    uint256 maxLatePeriods
  ) public view returns (uint256, uint256) {
    CreditLine cl = CreditLine(creditLineAddress);
    return Accountant.calculateWritedownFor(cl, blockNumber, gracePeriod, maxLatePeriods);
  }

  function calculateAmountOwedForOneDay(address creditLineAddress) public view returns (FixedPoint.Unsigned memory) {
    CreditLine cl = CreditLine(creditLineAddress);
    return Accountant.calculateAmountOwedForOneDay(cl);
  }
}

File 22 of 44 : FakeV2CreditDesk.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../protocol/core/Pool.sol";
import "../protocol/core/Accountant.sol";
import "../protocol/core/CreditLine.sol";
import "../protocol/core/GoldfinchConfig.sol";

contract FakeV2CreditDesk is BaseUpgradeablePausable {
  uint256 public totalWritedowns;
  uint256 public totalLoansOutstanding;
  // Approximate number of blocks
  uint256 public constant BLOCKS_PER_DAY = 5760;
  GoldfinchConfig public config;

  struct Underwriter {
    uint256 governanceLimit;
    address[] creditLines;
  }

  struct Borrower {
    address[] creditLines;
  }

  event PaymentMade(
    address indexed payer,
    address indexed creditLine,
    uint256 interestAmount,
    uint256 principalAmount,
    uint256 remainingAmount
  );
  event PrepaymentMade(address indexed payer, address indexed creditLine, uint256 prepaymentAmount);
  event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
  event CreditLineCreated(address indexed borrower, address indexed creditLine);
  event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress);
  event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);
  event LimitChanged(address indexed owner, string limitType, uint256 amount);

  mapping(address => Underwriter) public underwriters;
  mapping(address => Borrower) private borrowers;

  function initialize(address owner, GoldfinchConfig _config) public initializer {
    owner;
    _config;
    return;
  }

  function someBrandNewFunction() public pure returns (uint256) {
    return 5;
  }

  function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
    return underwriters[underwriterAddress].creditLines;
  }
}

File 23 of 44 : Pool.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";

/**
 * @title Goldfinch's Pool contract
 * @notice Main entry point for LP's (a.k.a. capital providers)
 *  Handles key logic for depositing and withdrawing funds from the Pool
 * @author Goldfinch
 */

contract Pool is BaseUpgradeablePausable, IPool {
  GoldfinchConfig public config;
  using ConfigHelper for GoldfinchConfig;

  uint256 public compoundBalance;

  event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);
  event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);
  event TransferMade(address indexed from, address indexed to, uint256 amount);
  event InterestCollected(address indexed payer, uint256 poolAmount, uint256 reserveAmount);
  event PrincipalCollected(address indexed payer, uint256 amount);
  event ReserveFundsCollected(address indexed user, uint256 amount);
  event PrincipalWrittendown(address indexed creditline, int256 amount);

  /**
   * @notice Run only once, on initialization
   * @param owner The address of who should have the "OWNER_ROLE" of this contract
   * @param _config The address of the GoldfinchConfig contract
   */
  function initialize(address owner, GoldfinchConfig _config) public initializer {
    __BaseUpgradeablePausable__init(owner);

    config = _config;
    sharePrice = fiduMantissa();
    IERC20withDec usdc = config.getUSDC();
    // Sanity check the address
    usdc.totalSupply();

    // Unlock self for infinite amount
    bool success = usdc.approve(address(this), uint256(-1));
    require(success, "Failed to approve USDC");
  }

  /**
   * @notice Deposits `amount` USDC from msg.sender into the Pool, and returns you the equivalent value of FIDU tokens
   * @param amount The amount of USDC to deposit
   */
  function deposit(uint256 amount) external override whenNotPaused withinTransactionLimit(amount) nonReentrant {
    require(amount > 0, "Must deposit more than zero");
    // Check if the amount of new shares to be added is within limits
    uint256 depositShares = getNumShares(amount);
    uint256 potentialNewTotalShares = totalShares().add(depositShares);
    require(poolWithinLimit(potentialNewTotalShares), "Deposit would put the Pool over the total limit.");
    emit DepositMade(msg.sender, amount, depositShares);
    bool success = doUSDCTransfer(msg.sender, address(this), amount);
    require(success, "Failed to transfer for deposit");

    config.getFidu().mintTo(msg.sender, depositShares);
  }

  /**
   * @notice Withdraws USDC from the Pool to msg.sender, and burns the equivalent value of FIDU tokens
   * @param usdcAmount The amount of USDC to withdraw
   */
  function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant {
    require(usdcAmount > 0, "Must withdraw more than zero");
    uint256 withdrawShares = getNumShares(usdcAmount);
    _withdraw(usdcAmount, withdrawShares);
  }

  /**
   * @notice Withdraws USDC (denominated in FIDU terms) from the Pool to msg.sender
   * @param fiduAmount The amount of USDC to withdraw in terms of fidu shares
   */
  function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant {
    require(fiduAmount > 0, "Must withdraw more than zero");
    uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount);
    uint256 withdrawShares = fiduAmount;
    _withdraw(usdcAmount, withdrawShares);
  }

  /**
   * @notice Collects `interest` USDC in interest and `principal` in principal from `from` and sends it to the Pool.
   *  This also increases the share price accordingly. A portion is sent to the Goldfinch Reserve address
   * @param from The address to take the USDC from. Implicitly, the Pool
   *  must be authorized to move USDC on behalf of `from`.
   * @param interest the interest amount of USDC to move to the Pool
   * @param principal the principal amount of USDC to move to the Pool
   *
   * Requirements:
   *  - The caller must be the Credit Desk. Not even the owner can call this function.
   */
  function collectInterestAndPrincipal(
    address from,
    uint256 interest,
    uint256 principal
  ) public override onlyCreditDesk whenNotPaused {
    _collectInterestAndPrincipal(from, interest, principal);
  }

  function distributeLosses(address creditlineAddress, int256 writedownDelta)
    external
    override
    onlyCreditDesk
    whenNotPaused
  {
    if (writedownDelta > 0) {
      uint256 delta = usdcToSharePrice(uint256(writedownDelta));
      sharePrice = sharePrice.add(delta);
    } else {
      // If delta is negative, convert to positive uint, and sub from sharePrice
      uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1));
      sharePrice = sharePrice.sub(delta);
    }
    emit PrincipalWrittendown(creditlineAddress, writedownDelta);
  }

  /**
   * @notice Moves `amount` USDC from `from`, to `to`.
   * @param from The address to take the USDC from. Implicitly, the Pool
   *  must be authorized to move USDC on behalf of `from`.
   * @param to The address that the USDC should be moved to
   * @param amount the amount of USDC to move to the Pool
   *
   * Requirements:
   *  - The caller must be the Credit Desk. Not even the owner can call this function.
   */
  function transferFrom(
    address from,
    address to,
    uint256 amount
  ) public override onlyCreditDesk whenNotPaused returns (bool) {
    bool result = doUSDCTransfer(from, to, amount);
    require(result, "USDC Transfer failed");
    emit TransferMade(from, to, amount);
    return result;
  }

  /**
   * @notice Moves `amount` USDC from the pool, to `to`. This is similar to transferFrom except we sweep any
   * balance we have from compound first and recognize interest. Meant to be called only by the credit desk on drawdown
   * @param to The address that the USDC should be moved to
   * @param amount the amount of USDC to move to the Pool
   *
   * Requirements:
   *  - The caller must be the Credit Desk. Not even the owner can call this function.
   */
  function drawdown(address to, uint256 amount) public override onlyCreditDesk whenNotPaused returns (bool) {
    if (compoundBalance > 0) {
      _sweepFromCompound();
    }
    return transferFrom(address(this), to, amount);
  }

  function assets() public view override returns (uint256) {
    ICreditDesk creditDesk = config.getCreditDesk();
    return
      compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(creditDesk.totalLoansOutstanding()).sub(
        creditDesk.totalWritedowns()
      );
  }

  /**
   * @notice Moves any USDC still in the Pool to Compound, and tracks the amount internally.
   * This is done to earn interest on latent funds until we have other borrowers who can use it.
   *
   * Requirements:
   *  - The caller must be an admin.
   */
  function sweepToCompound() public override onlyAdmin whenNotPaused {
    IERC20 usdc = config.getUSDC();
    uint256 usdcBalance = usdc.balanceOf(address(this));

    ICUSDCContract cUSDC = config.getCUSDCContract();
    // Approve compound to the exact amount
    bool success = usdc.approve(address(cUSDC), usdcBalance);
    require(success, "Failed to approve USDC for compound");

    sweepToCompound(cUSDC, usdcBalance);

    // Remove compound approval to be extra safe
    success = config.getUSDC().approve(address(cUSDC), 0);
    require(success, "Failed to approve USDC for compound");
  }

  /**
   * @notice Moves any USDC from Compound back to the Pool, and recognizes interest earned.
   * This is done automatically on drawdown or withdraw, but can be called manually if necessary.
   *
   * Requirements:
   *  - The caller must be an admin.
   */
  function sweepFromCompound() public override onlyAdmin whenNotPaused {
    _sweepFromCompound();
  }

  /* Internal Functions */

  function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal withinTransactionLimit(usdcAmount) {
    IFidu fidu = config.getFidu();
    // Determine current shares the address has and the shares requested to withdraw
    uint256 currentShares = fidu.balanceOf(msg.sender);
    // Ensure the address has enough value in the pool
    require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns");

    if (compoundBalance > 0) {
      _sweepFromCompound();
    }

    uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator());
    uint256 userAmount = usdcAmount.sub(reserveAmount);

    emit WithdrawalMade(msg.sender, userAmount, reserveAmount);
    // Send the amounts
    bool success = doUSDCTransfer(address(this), msg.sender, userAmount);
    require(success, "Failed to transfer for withdraw");
    sendToReserve(address(this), reserveAmount, msg.sender);

    // Burn the shares
    fidu.burnFrom(msg.sender, withdrawShares);
  }

  function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal {
    // Our current design requires we re-normalize by withdrawing everything and recognizing interest gains
    // before we can add additional capital to Compound
    require(compoundBalance == 0, "Cannot sweep when we already have a compound balance");
    require(usdcAmount != 0, "Amount to sweep cannot be zero");
    uint256 error = cUSDC.mint(usdcAmount);
    require(error == 0, "Sweep to compound failed");
    compoundBalance = usdcAmount;
  }

  function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal {
    uint256 cBalance = compoundBalance;
    require(cBalance != 0, "No funds on compound");
    require(cUSDCAmount != 0, "Amount to sweep cannot be zero");

    IERC20 usdc = config.getUSDC();
    uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this));
    uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent();
    uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount);

    uint256 error = cUSDC.redeem(cUSDCAmount);
    uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this));
    require(error == 0, "Sweep from compound failed");
    require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount");

    uint256 interestAccrued = redeemedUSDC.sub(cBalance);
    _collectInterestAndPrincipal(address(this), interestAccrued, 0);
    compoundBalance = 0;
  }

  function _collectInterestAndPrincipal(
    address from,
    uint256 interest,
    uint256 principal
  ) internal {
    uint256 reserveAmount = interest.div(config.getReserveDenominator());
    uint256 poolAmount = interest.sub(reserveAmount);
    uint256 increment = usdcToSharePrice(poolAmount);
    sharePrice = sharePrice.add(increment);

    if (poolAmount > 0) {
      emit InterestCollected(from, poolAmount, reserveAmount);
    }
    if (principal > 0) {
      emit PrincipalCollected(from, principal);
    }
    if (reserveAmount > 0) {
      sendToReserve(from, reserveAmount, from);
    }
    // Gas savings: No need to transfer to yourself, which happens in sweepFromCompound
    if (from != address(this)) {
      bool success = doUSDCTransfer(from, address(this), principal.add(poolAmount));
      require(success, "Failed to collect principal repayment");
    }
  }

  function _sweepFromCompound() internal {
    ICUSDCContract cUSDC = config.getCUSDCContract();
    sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this)));
  }

  function updateGoldfinchConfig() external onlyAdmin {
    config = GoldfinchConfig(config.configAddress());
  }

  function fiduMantissa() internal pure returns (uint256) {
    return uint256(10)**uint256(18);
  }

  function usdcMantissa() internal pure returns (uint256) {
    return uint256(10)**uint256(6);
  }

  function usdcToFidu(uint256 amount) internal pure returns (uint256) {
    return amount.mul(fiduMantissa()).div(usdcMantissa());
  }

  function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) {
    // See https://compound.finance/docs#protocol-math
    // But note, the docs and reality do not agree. Docs imply that that exchange rate is
    // scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16
    // 1e16 is also what Sheraz at Certik said.
    uint256 usdcDecimals = 6;
    uint256 cUSDCDecimals = 8;
    return
      amount // Amount in cToken (1e8)
        .mul(exchangeRate) // Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are)
        .div(10**(18 + usdcDecimals - cUSDCDecimals)) // Downscale to cToken decimals (1e8)
        .div(10**2); // Downscale from cToken to USDC decimals (8 to 6)
  }

  function totalShares() internal view returns (uint256) {
    return config.getFidu().totalSupply();
  }

  function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) {
    return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares());
  }

  function poolWithinLimit(uint256 _totalShares) internal view returns (bool) {
    return
      _totalShares.mul(sharePrice).div(fiduMantissa()) <=
      usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit)));
  }

  function transactionWithinLimit(uint256 amount) internal view returns (bool) {
    return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
  }

  function getNumShares(uint256 amount) internal view returns (uint256) {
    return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice);
  }

  function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) {
    return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa()));
  }

  function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
    return amount.div(fiduMantissa().div(usdcMantissa()));
  }

  function sendToReserve(
    address from,
    uint256 amount,
    address userForEvent
  ) internal {
    emit ReserveFundsCollected(userForEvent, amount);
    bool success = doUSDCTransfer(from, config.reserveAddress(), amount);
    require(success, "Reserve transfer was not successful");
  }

  function doUSDCTransfer(
    address from,
    address to,
    uint256 amount
  ) internal returns (bool) {
    require(to != address(0), "Can't send to zero address");
    IERC20withDec usdc = config.getUSDC();
    return usdc.transferFrom(from, to, amount);
  }

  modifier withinTransactionLimit(uint256 amount) {
    require(transactionWithinLimit(amount), "Amount is over the per-transaction limit");
    _;
  }

  modifier onlyCreditDesk() {
    require(msg.sender == config.creditDeskAddress(), "Only the credit desk is allowed to call this function");
    _;
  }
}

File 24 of 44 : ConfigHelper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "./GoldfinchConfig.sol";
import "../../interfaces/IPool.sol";
import "../../interfaces/IFidu.sol";
import "../../interfaces/ICreditDesk.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICUSDCContract.sol";

/**
 * @title ConfigHelper
 * @notice A convenience library for getting easy access to other contracts and constants within the
 *  protocol, through the use of the GoldfinchConfig contract
 * @author Goldfinch
 */

library ConfigHelper {
  function getPool(GoldfinchConfig config) internal view returns (IPool) {
    return IPool(poolAddress(config));
  }

  function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) {
    return IERC20withDec(usdcAddress(config));
  }

  function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) {
    return ICreditDesk(creditDeskAddress(config));
  }

  function getFidu(GoldfinchConfig config) internal view returns (IFidu) {
    return IFidu(fiduAddress(config));
  }

  function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) {
    return ICUSDCContract(cusdcContractAddress(config));
  }

  function oneInchAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.OneInch));
  }

  function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder));
  }

  function configAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig));
  }

  function poolAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.Pool));
  }

  function creditDeskAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk));
  }

  function fiduAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.Fidu));
  }

  function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract));
  }

  function usdcAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.USDC));
  }

  function reserveAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve));
  }

  function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin));
  }

  function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) {
    return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator));
  }

  function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) {
    return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator));
  }

  function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
    return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays));
  }

  function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) {
    return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays));
  }
}

File 25 of 44 : IPool.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

abstract contract IPool {
  uint256 public sharePrice;

  function deposit(uint256 amount) external virtual;

  function withdraw(uint256 usdcAmount) external virtual;

  function withdrawInFidu(uint256 fiduAmount) external virtual;

  function collectInterestAndPrincipal(
    address from,
    uint256 interest,
    uint256 principal
  ) public virtual;

  function transferFrom(
    address from,
    address to,
    uint256 amount
  ) public virtual returns (bool);

  function drawdown(address to, uint256 amount) public virtual returns (bool);

  function sweepToCompound() public virtual;

  function sweepFromCompound() public virtual;

  function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual;

  function assets() public view virtual returns (uint256);
}

File 26 of 44 : IFidu.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./IERC20withDec.sol";

interface IFidu is IERC20withDec {
  function mintTo(address to, uint256 amount) external;

  function burnFrom(address to, uint256 amount) external;
}

File 27 of 44 : ICreditDesk.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

abstract contract ICreditDesk {
  uint256 public totalWritedowns;
  uint256 public totalLoansOutstanding;

  function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual;

  function createCreditLine(
    address _borrower,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _paymentPeriodInDays,
    uint256 _termInDays,
    uint256 _lateFeeApr
  ) public virtual returns (address);

  function drawdown(address creditLineAddress, uint256 amount) external virtual;

  function pay(address creditLineAddress, uint256 amount) external virtual;

  function assessCreditLine(address creditLineAddress) external virtual;

  function applyPayment(address creditLineAddress, uint256 amount) external virtual;

  function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256);
}

File 28 of 44 : ICUSDCContract.sol
// SPDX-License-Identifier: MIT
// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
pragma solidity 0.6.12;

import "./IERC20withDec.sol";

interface ICUSDCContract is IERC20withDec {
  /*** User Interface ***/

  function mint(uint256 mintAmount) external returns (uint256);

  function redeem(uint256 redeemTokens) external returns (uint256);

  function redeemUnderlying(uint256 redeemAmount) external returns (uint256);

  function borrow(uint256 borrowAmount) external returns (uint256);

  function repayBorrow(uint256 repayAmount) external returns (uint256);

  function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);

  function liquidateBorrow(
    address borrower,
    uint256 repayAmount,
    address cTokenCollateral
  ) external returns (uint256);

  function getAccountSnapshot(address account)
    external
    view
    returns (
      uint256,
      uint256,
      uint256,
      uint256
    );

  function balanceOfUnderlying(address owner) external returns (uint256);

  function exchangeRateCurrent() external returns (uint256);

  /*** Admin Functions ***/

  function _addReserves(uint256 addAmount) external returns (uint256);
}

File 29 of 44 : TestTheConfig.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "../protocol/core/GoldfinchConfig.sol";

contract TestTheConfig {
  address public poolAddress = 0xBAc2781706D0aA32Fb5928c9a5191A13959Dc4AE;
  address public clImplAddress = 0xc783df8a850f42e7F7e57013759C285caa701eB6;
  address public clFactoryAddress = 0x0afFE1972479c386A2Ab21a27a7f835361B6C0e9;
  address public fiduAddress = 0xf3c9B38c155410456b5A98fD8bBf5E35B87F6d96;
  address public creditDeskAddress = 0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4;
  address public treasuryReserveAddress = 0xECd9C93B79AE7C1591b1fB5323BD777e86E150d5;
  address public trustedForwarderAddress = 0x956868751Cc565507B3B58E53a6f9f41B56bed74;
  address public cUSDCAddress = 0x5B281A6DdA0B271e91ae35DE655Ad301C976edb1;
  address public goldfinchConfigAddress = address(8);

  function testTheEnums(address configAddress) public {
    GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransactionLimit), 1);
    GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit), 2);
    GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit), 3);
    GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.ReserveDenominator), 4);
    GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator), 5);
    GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays), 6);
    GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays), 7);

    GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Fidu), fiduAddress);
    GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Pool), poolAddress);
    GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CreditDesk), creditDeskAddress);
    GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CreditLineFactory), clFactoryAddress);
    GoldfinchConfig(configAddress).setAddress(
      uint256(ConfigOptions.Addresses.TrustedForwarder),
      trustedForwarderAddress
    );
    GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CUSDCContract), cUSDCAddress);
    GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig), goldfinchConfigAddress);

    GoldfinchConfig(configAddress).setTreasuryReserve(treasuryReserveAddress);
  }
}

File 30 of 44 : TestGoldfinchConfig.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "../protocol/core/GoldfinchConfig.sol";

contract TestGoldfinchConfig is GoldfinchConfig {
  function setAddressForTest(uint256 addressKey, address newAddress) public {
    addresses[addressKey] = newAddress;
  }
}

File 31 of 44 : CreditLineFactory.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "./GoldfinchConfig.sol";
import "./BaseUpgradeablePausable.sol";
import "../periphery/Borrower.sol";
import "./CreditLine.sol";
import "./ConfigHelper.sol";

/**
 * @title CreditLineFactory
 * @notice Contract that allows us to create other contracts, such as CreditLines and BorrowerContracts
 * @author Goldfinch
 */

contract CreditLineFactory is BaseUpgradeablePausable {
  GoldfinchConfig public config;
  using ConfigHelper for GoldfinchConfig;

  event BorrowerCreated(address indexed borrower, address indexed owner);

  function initialize(address owner, GoldfinchConfig _config) public initializer {
    __BaseUpgradeablePausable__init(owner);
    config = _config;
  }

  function createCreditLine() external returns (address) {
    CreditLine newCreditLine = new CreditLine();
    return address(newCreditLine);
  }

  /**
   * @notice Allows anyone to create a Borrower contract instance
   * @param owner The address that will own the new Borrower instance
   */
  function createBorrower(address owner) external returns (address) {
    Borrower borrower = new Borrower();
    borrower.initialize(owner, config);
    emit BorrowerCreated(address(borrower), owner);
    return address(borrower);
  }

  function updateGoldfinchConfig() external onlyAdmin {
    config = GoldfinchConfig(config.configAddress());
  }
}

File 32 of 44 : BaseRelayRecipient.sol
// SPDX-License-Identifier:MIT
// solhint-disable no-inline-assembly
pragma solidity ^0.6.2;

import "./interfaces/IRelayRecipient.sol";

/**
 * A base contract to be inherited by any contract that want to receive relayed transactions
 * A subclass must use "_msgSender()" instead of "msg.sender"
 */
abstract contract BaseRelayRecipient is IRelayRecipient {

    /*
     * Forwarder singleton we accept calls from
     */
    address public trustedForwarder;

    function isTrustedForwarder(address forwarder) public override view returns(bool) {
        return forwarder == trustedForwarder;
    }

    /**
     * return the sender of this call.
     * if the call came through our trusted forwarder, return the original sender.
     * otherwise, return `msg.sender`.
     * should be used in the contract anywhere instead of msg.sender
     */
    function _msgSender() internal override virtual view returns (address payable ret) {
        if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
            // At this point we know that the sender is a trusted forwarder,
            // so we trust that the last bytes of msg.data are the verified sender address.
            // extract sender address from the end of msg.data
            assembly {
                ret := shr(96,calldataload(sub(calldatasize(),20)))
            }
        } else {
            return msg.sender;
        }
    }

    /**
     * return the msg.data of this call.
     * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
     * of the msg.data - so this method will strip those 20 bytes off.
     * otherwise, return `msg.data`
     * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
     * signing or hashing the
     */
    function _msgData() internal override virtual view returns (bytes memory ret) {
        if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
            // At this point we know that the sender is a trusted forwarder,
            // we copy the msg.data , except the last 20 bytes (and update the total length)
            assembly {
                let ptr := mload(0x40)
                // copy only size-20 bytes
                let size := sub(calldatasize(),20)
                // structure RLP data as <offset> <length> <bytes>
                mstore(ptr, 0x20)
                mstore(add(ptr,32), size)
                calldatacopy(add(ptr,64), 0, size)
                return(ptr, add(size,64))
            }
        } else {
            return msg.data;
        }
    }
}

File 33 of 44 : IRelayRecipient.sol
// SPDX-License-Identifier:MIT
pragma solidity ^0.6.2;

/**
 * a contract must implement this interface in order to support relayed transaction.
 * It is better to inherit the BaseRelayRecipient as its implementation.
 */
abstract contract IRelayRecipient {

    /**
     * return if the forwarder is trusted to forward relayed transactions to us.
     * the forwarder is required to verify the sender's signature, and verify
     * the call is not a replay.
     */
    function isTrustedForwarder(address forwarder) public virtual view returns(bool);

    /**
     * return the sender of this call.
     * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
     * of the msg.data.
     * otherwise, return `msg.sender`
     * should be used in the contract anywhere instead of msg.sender
     */
    function _msgSender() internal virtual view returns (address payable);

    /**
     * return the msg.data of this call.
     * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
     * of the msg.data - so this method will strip those 20 bytes off.
     * otherwise, return `msg.data`
     * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
     * signing or hashing the
     */
    function _msgData() internal virtual view returns (bytes memory);

    function versionRecipient() external virtual view returns (string memory);
}

File 34 of 44 : TestPool.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "../protocol/core/Pool.sol";

contract TestPool is Pool {
  function _getNumShares(uint256 amount) public view returns (uint256) {
    return getNumShares(amount);
  }

  function _usdcMantissa() public pure returns (uint256) {
    return usdcMantissa();
  }

  function _fiduMantissa() public pure returns (uint256) {
    return fiduMantissa();
  }

  function _usdcToFidu(uint256 amount) public pure returns (uint256) {
    return usdcToFidu(amount);
  }

  function _setSharePrice(uint256 newSharePrice) public returns (uint256) {
    sharePrice = newSharePrice;
  }
}

File 35 of 44 : FakeV2CreditLine.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;

import "../protocol/core/Pool.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";

contract FakeV2CreditLine is BaseUpgradeablePausable {
  // Credit line terms
  address public borrower;
  address public underwriter;
  uint256 public limit;
  uint256 public interestApr;
  uint256 public paymentPeriodInDays;
  uint256 public termInDays;
  uint256 public lateFeeApr;

  // Accounting variables
  uint256 public balance;
  uint256 public interestOwed;
  uint256 public principalOwed;
  uint256 public termEndBlock;
  uint256 public nextDueBlock;
  uint256 public interestAccruedAsOfBlock;
  uint256 public writedownAmount;
  uint256 public lastFullPaymentBlock;

  function initialize(
    address owner,
    address _borrower,
    address _underwriter,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _paymentPeriodInDays,
    uint256 _termInDays,
    uint256 _lateFeeApr
  ) public initializer {
    __BaseUpgradeablePausable__init(owner);
    borrower = _borrower;
    underwriter = _underwriter;
    limit = _limit;
    interestApr = _interestApr;
    paymentPeriodInDays = _paymentPeriodInDays;
    termInDays = _termInDays;
    lateFeeApr = _lateFeeApr;
    interestAccruedAsOfBlock = block.number;
  }

  function anotherNewFunction() external pure returns (uint256) {
    return 42;
  }

  function authorizePool(address) external view onlyAdmin {
    // no-op
    return;
  }
}

File 36 of 44 : ERC20.sol
pragma solidity ^0.6.0;

import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../Initializable.sol";

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

    mapping (address => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    /**
     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
     * a default value of 18.
     *
     * To select a different value for {decimals}, use {_setupDecimals}.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */

    function __ERC20_init(string memory name, string memory symbol) internal initializer {
        __Context_init_unchained();
        __ERC20_init_unchained(name, symbol);
    }

    function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {


        _name = name;
        _symbol = symbol;
        _decimals = 18;

    }


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

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

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

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

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

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

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

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20};
     *
     * Requirements:
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
        return true;
    }

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

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

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

        _beforeTokenTransfer(sender, recipient, amount);

        _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(sender, recipient, amount);
    }

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

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

        _totalSupply = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }

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

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

        _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
        _totalSupply = _totalSupply.sub(amount);
        emit Transfer(account, address(0), amount);
    }

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

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

    /**
     * @dev Sets {decimals} to a value other than the default one of 18.
     *
     * WARNING: This function should only be called from the constructor. Most
     * applications that interact with token contracts will not expect
     * {decimals} to ever change, and may work incorrectly if it does.
     */
    function _setupDecimals(uint8 decimals_) internal {
        _decimals = decimals_;
    }

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

    uint256[44] private __gap;
}

File 37 of 44 : TestERC20.sol
// contracts/GLDToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;

import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";

contract TestERC20 is ERC20UpgradeSafe {
  constructor(uint256 initialSupply, uint8 decimals) public {
    __ERC20_init("USDC", "USDC");
    _setupDecimals(decimals);
    _mint(msg.sender, initialSupply);
  }
}

File 38 of 44 : ERC20Pausable.sol
pragma solidity ^0.6.0;

import "./ERC20.sol";
import "../../utils/Pausable.sol";
import "../../Initializable.sol";

/**
 * @dev ERC20 token with pausable token transfers, minting and burning.
 *
 * Useful for scenarios such as preventing trades until the end of an evaluation
 * period, or having an emergency switch for freezing all token transfers in the
 * event of a large bug.
 */
abstract contract ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe {
    function __ERC20Pausable_init() internal initializer {
        __Context_init_unchained();
        __Pausable_init_unchained();
        __ERC20Pausable_init_unchained();
    }

    function __ERC20Pausable_init_unchained() internal initializer {


    }

    /**
     * @dev See {ERC20-_beforeTokenTransfer}.
     *
     * Requirements:
     *
     * - the contract must not be paused.
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
        super._beforeTokenTransfer(from, to, amount);

        require(!paused(), "ERC20Pausable: token transfer while paused");
    }

    uint256[50] private __gap;
}

File 39 of 44 : ERC20Burnable.sol
pragma solidity ^0.6.0;

import "../../GSN/Context.sol";
import "./ERC20.sol";
import "../../Initializable.sol";

/**
 * @dev Extension of {ERC20} that allows token holders to destroy both their own
 * tokens and those that they have an allowance for, in a way that can be
 * recognized off-chain (via event analysis).
 */
abstract contract ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe {
    function __ERC20Burnable_init() internal initializer {
        __Context_init_unchained();
        __ERC20Burnable_init_unchained();
    }

    function __ERC20Burnable_init_unchained() internal initializer {


    }

    /**
     * @dev Destroys `amount` tokens from the caller.
     *
     * See {ERC20-_burn}.
     */
    function burn(uint256 amount) public virtual {
        _burn(_msgSender(), amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, deducting from the caller's
     * allowance.
     *
     * See {ERC20-_burn} and {ERC20-allowance}.
     *
     * Requirements:
     *
     * - the caller must have allowance for ``accounts``'s tokens of at least
     * `amount`.
     */
    function burnFrom(address account, uint256 amount) public virtual {
        uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");

        _approve(account, _msgSender(), decreasedAllowance);
        _burn(account, amount);
    }

    uint256[50] private __gap;
}

File 40 of 44 : ERC20PresetMinterPauser.sol
pragma solidity ^0.6.0;

import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
import "../Initializable.sol";

/**
 * @dev {ERC20} token, including:
 *
 *  - ability for holders to burn (destroy) their tokens
 *  - a minter role that allows for token minting (creation)
 *  - a pauser role that allows to stop all token transfers
 *
 * This contract uses {AccessControl} to lock permissioned functions using the
 * different roles - head to its documentation for details.
 *
 * The account that deploys the contract will be granted the minter and pauser
 * roles, as well as the default admin role, which will let it grant both minter
 * and pauser roles to aother accounts
 */
contract ERC20PresetMinterPauserUpgradeSafe is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC20BurnableUpgradeSafe, ERC20PausableUpgradeSafe {
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

    /**
     * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
     * account that deploys the contract.
     *
     * See {ERC20-constructor}.
     */

    function initialize(string memory name, string memory symbol) public {
        __ERC20PresetMinterPauser_init(name, symbol);
    }

    function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer {
        __Context_init_unchained();
        __AccessControl_init_unchained();
        __ERC20_init_unchained(name, symbol);
        __ERC20Burnable_init_unchained();
        __Pausable_init_unchained();
        __ERC20Pausable_init_unchained();
        __ERC20PresetMinterPauser_init_unchained(name, symbol);
    }

    function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer {


        _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());

        _setupRole(MINTER_ROLE, _msgSender());
        _setupRole(PAUSER_ROLE, _msgSender());

    }


    /**
     * @dev Creates `amount` new tokens for `to`.
     *
     * See {ERC20-_mint}.
     *
     * Requirements:
     *
     * - the caller must have the `MINTER_ROLE`.
     */
    function mint(address to, uint256 amount) public {
        require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
        _mint(to, amount);
    }

    /**
     * @dev Pauses all token transfers.
     *
     * See {ERC20Pausable} and {Pausable-_pause}.
     *
     * Requirements:
     *
     * - the caller must have the `PAUSER_ROLE`.
     */
    function pause() public {
        require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
        _pause();
    }

    /**
     * @dev Unpauses all token transfers.
     *
     * See {ERC20Pausable} and {Pausable-_unpause}.
     *
     * Requirements:
     *
     * - the caller must have the `PAUSER_ROLE`.
     */
    function unpause() public {
        require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
        _unpause();
    }

    function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20UpgradeSafe, ERC20PausableUpgradeSafe) {
        super._beforeTokenTransfer(from, to, amount);
    }

    uint256[50] private __gap;
}

File 41 of 44 : Fidu.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;

import "@openzeppelin/contracts-ethereum-package/contracts/presets/ERC20PresetMinterPauser.sol";
import "./ConfigHelper.sol";

/**
 * @title Fidu
 * @notice Fidu (symbol: FIDU) is Goldfinch's liquidity token, representing shares
 *  in the Pool. When you deposit, we mint a corresponding amount of Fidu, and when you withdraw, we
 *  burn Fidu. The share price of the Pool implicitly represents the "exchange rate" between Fidu
 *  and USDC (or whatever currencies the Pool may allow withdraws in during the future)
 * @author Goldfinch
 */

contract Fidu is ERC20PresetMinterPauserUpgradeSafe {
  bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
  // $1 threshold to handle potential rounding errors, from differing decimals on Fidu and USDC;
  uint256 public constant ASSET_LIABILITY_MATCH_THRESHOLD = 1e6;
  GoldfinchConfig public config;
  using ConfigHelper for GoldfinchConfig;

  /*
    We are using our own initializer function so we can set the owner by passing it in.
    I would override the regular "initializer" function, but I can't because it's not marked
    as "virtual" in the parent contract
  */
  // solhint-disable-next-line func-name-mixedcase
  function __initialize__(
    address owner,
    string calldata name,
    string calldata symbol,
    GoldfinchConfig _config
  ) external initializer {
    __Context_init_unchained();
    __AccessControl_init_unchained();
    __ERC20_init_unchained(name, symbol);

    __ERC20Burnable_init_unchained();
    __Pausable_init_unchained();
    __ERC20Pausable_init_unchained();

    config = _config;

    _setupRole(MINTER_ROLE, owner);
    _setupRole(PAUSER_ROLE, owner);
    _setupRole(OWNER_ROLE, owner);

    _setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
    _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
    _setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
  }

  /**
   * @dev Creates `amount` new tokens for `to`.
   *
   * See {ERC20-_mint}.
   *
   * Requirements:
   *
   * - the caller must have the `MINTER_ROLE`.
   */
  function mintTo(address to, uint256 amount) public {
    require(canMint(amount), "Cannot mint: it would create an asset/liability mismatch");
    // This will lock the function down to only the minter
    super.mint(to, amount);
  }

  /**
   * @dev Destroys `amount` tokens from `account`, deducting from the caller's
   * allowance.
   *
   * See {ERC20-_burn} and {ERC20-allowance}.
   *
   * Requirements:
   *
   * - the caller must have the MINTER_ROLE
   */
  function burnFrom(address from, uint256 amount) public override {
    require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to burn");
    require(canBurn(amount), "Cannot burn: it would create an asset/liability mismatch");
    _burn(from, amount);
  }

  // Internal functions

  // canMint assumes that the USDC that backs the new shares has already been sent to the Pool
  function canMint(uint256 newAmount) internal view returns (bool) {
    IPool pool = config.getPool();
    uint256 liabilities = totalSupply().add(newAmount).mul(pool.sharePrice()).div(fiduMantissa());
    uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
    uint256 _assets = pool.assets();
    if (_assets >= liabilitiesInDollars) {
      return _assets.sub(liabilitiesInDollars) <= ASSET_LIABILITY_MATCH_THRESHOLD;
    } else {
      return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
    }
  }

  // canBurn assumes that the USDC that backed these shares has already been moved out the Pool
  function canBurn(uint256 amountToBurn) internal view returns (bool) {
    IPool pool = config.getPool();
    uint256 liabilities = totalSupply().sub(amountToBurn).mul(pool.sharePrice()).div(fiduMantissa());
    uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
    uint256 _assets = pool.assets();
    if (_assets >= liabilitiesInDollars) {
      return _assets.sub(liabilitiesInDollars) <= ASSET_LIABILITY_MATCH_THRESHOLD;
    } else {
      return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
    }
  }

  function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
    return amount.div(fiduMantissa().div(usdcMantissa()));
  }

  function fiduMantissa() internal pure returns (uint256) {
    return uint256(10)**uint256(18);
  }

  function usdcMantissa() internal pure returns (uint256) {
    return uint256(10)**uint256(6);
  }

  function updateGoldfinchConfig() external {
    require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to change config");
    config = GoldfinchConfig(config.configAddress());
  }
}

File 42 of 44 : IOneSplit.sol
// SPDX-License-Identifier: MIT
// solhint-disable

pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;

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

// contract IOneSplitConsts {
//     // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
//     uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
//     uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
//     uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
//     uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
//     uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
//     uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
//     uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
//     uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
//     uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
//     uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
//     uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
//     uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
//     uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
//     uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
//     uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
//     uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
//     uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
//     uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
//     uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
//     uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
//     uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
//     uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
//     uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
//     uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
//     uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
//     uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
//     uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
//     uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
//     uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
//     uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
//     uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
//     uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
//     uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
//     uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
//     uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
//     uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
//     uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
//     uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
//     uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
//     uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
//     uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
//     uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
//     uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
//     uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
//     uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
//     uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
//     uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
//     uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
//     uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
//     uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
//     uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
//     uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
//     uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
//     uint256 internal constant FLAG_DISABLE_MOONISWAP_ALL = 0x8000000000000000;
//     uint256 internal constant FLAG_DISABLE_MOONISWAP_ETH = 0x10000000000000000;
//     uint256 internal constant FLAG_DISABLE_MOONISWAP_DAI = 0x20000000000000000;
//     uint256 internal constant FLAG_DISABLE_MOONISWAP_USDC = 0x40000000000000000;
//     uint256 internal constant FLAG_DISABLE_MOONISWAP_POOL_TOKEN = 0x80000000000000000;
// }

interface IOneSplit {
  function getExpectedReturn(
    IERC20 fromToken,
    IERC20 destToken,
    uint256 amount,
    uint256 parts,
    uint256 flags // See constants in IOneSplit.sol
  ) external view returns (uint256 returnAmount, uint256[] memory distribution);

  function getExpectedReturnWithGas(
    IERC20 fromToken,
    IERC20 destToken,
    uint256 amount,
    uint256 parts,
    uint256 flags, // See constants in IOneSplit.sol
    uint256 destTokenEthPriceTimesGasPrice
  )
    external
    view
    returns (
      uint256 returnAmount,
      uint256 estimateGasAmount,
      uint256[] memory distribution
    );

  function swap(
    IERC20 fromToken,
    IERC20 destToken,
    uint256 amount,
    uint256 minReturn,
    uint256[] memory distribution,
    uint256 flags
  ) external payable returns (uint256 returnAmount);
}

File 43 of 44 : CreditDesk.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./Accountant.sol";
import "./CreditLine.sol";
import "./CreditLineFactory.sol";

/**
 * @title Goldfinch's CreditDesk contract
 * @notice Main entry point for borrowers and underwriters.
 *  Handles key logic for creating CreditLine's, borrowing money, repayment, etc.
 * @author Goldfinch
 */

contract CreditDesk is BaseUpgradeablePausable, ICreditDesk {
  // Approximate number of blocks per day
  uint256 public constant BLOCKS_PER_DAY = 5760;
  GoldfinchConfig public config;
  using ConfigHelper for GoldfinchConfig;

  struct Underwriter {
    uint256 governanceLimit;
    address[] creditLines;
  }

  struct Borrower {
    address[] creditLines;
  }

  event PaymentApplied(
    address indexed payer,
    address indexed creditLine,
    uint256 interestAmount,
    uint256 principalAmount,
    uint256 remainingAmount
  );
  event PaymentCollected(address indexed payer, address indexed creditLine, uint256 paymentAmount);
  event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
  event CreditLineCreated(address indexed borrower, address indexed creditLine);
  event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);

  mapping(address => Underwriter) public underwriters;
  mapping(address => Borrower) private borrowers;
  mapping(address => address) private creditLines;

  /**
   * @notice Run only once, on initialization
   * @param owner The address of who should have the "OWNER_ROLE" of this contract
   * @param _config The address of the GoldfinchConfig contract
   */
  function initialize(address owner, GoldfinchConfig _config) public initializer {
    __BaseUpgradeablePausable__init(owner);
    config = _config;
  }

  /**
   * @notice Sets a particular underwriter's limit of how much credit the DAO will allow them to "create"
   * @param underwriterAddress The address of the underwriter for whom the limit shall change
   * @param limit What the new limit will be set to
   * Requirements:
   *
   * - the caller must have the `OWNER_ROLE`.
   */
  function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit)
    external
    override
    onlyAdmin
    whenNotPaused
  {
    require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol");
    underwriters[underwriterAddress].governanceLimit = limit;
    emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit);
  }

  /**
   * @notice Allows an underwriter to create a new CreditLine for a single borrower
   * @param _borrower The borrower for whom the CreditLine will be created
   * @param _limit The maximum amount a borrower can drawdown from this CreditLine
   * @param _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer.
   *  We assume 8 digits of precision. For example, to submit 15.34%, you would pass up 15340000,
   *  and 5.34% would be 5340000
   * @param _paymentPeriodInDays How many days in each payment period.
   *  ie. the frequency with which they need to make payments.
   * @param _termInDays Number of days in the credit term. It is used to set the `termEndBlock` upon first drawdown.
   *  ie. The credit line should be fully paid off {_termIndays} days after the first drawdown.
   * @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your
   *  normal rate is 15%, then you will pay 18% while you are late.
   *
   * Requirements:
   *
   * - the caller must be an underwriter with enough limit (see `setUnderwriterGovernanceLimit`)
   */
  function createCreditLine(
    address _borrower,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _paymentPeriodInDays,
    uint256 _termInDays,
    uint256 _lateFeeApr
  ) public override whenNotPaused returns (address) {
    Underwriter storage underwriter = underwriters[msg.sender];
    Borrower storage borrower = borrowers[_borrower];
    require(underwriterCanCreateThisCreditLine(_limit, underwriter), "The underwriter cannot create this credit line");

    address clAddress = getCreditLineFactory().createCreditLine();
    CreditLine cl = CreditLine(clAddress);
    cl.initialize(
      address(this),
      _borrower,
      msg.sender,
      _limit,
      _interestApr,
      _paymentPeriodInDays,
      _termInDays,
      _lateFeeApr
    );

    underwriter.creditLines.push(clAddress);
    borrower.creditLines.push(clAddress);
    creditLines[clAddress] = clAddress;
    emit CreditLineCreated(_borrower, clAddress);

    cl.grantRole(keccak256("OWNER_ROLE"), config.protocolAdminAddress());
    cl.authorizePool(address(config));
    return clAddress;
  }

  /**
   * @notice Allows a borrower to drawdown on their creditline.
   *  `amount` USDC is sent to the borrower, and the credit line accounting is updated.
   * @param creditLineAddress The creditline from which they would like to drawdown
   * @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown
   *
   * Requirements:
   *
   * - the caller must be the borrower on the creditLine
   */
  function drawdown(address creditLineAddress, uint256 amount)
    external
    override
    whenNotPaused
    onlyValidCreditLine(creditLineAddress)
  {
    CreditLine cl = CreditLine(creditLineAddress);
    Borrower storage borrower = borrowers[msg.sender];
    require(borrower.creditLines.length > 0, "No credit lines exist for this borrower");
    require(amount > 0, "Must drawdown more than zero");
    require(cl.borrower() == msg.sender, "You are not the borrower of this credit line");
    require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
    uint256 unappliedBalance = getUSDCBalance(creditLineAddress);
    require(
      withinCreditLimit(amount, unappliedBalance, cl),
      "The borrower does not have enough credit limit for this drawdown"
    );

    uint256 balance = cl.balance();

    if (balance == 0) {
      cl.setInterestAccruedAsOfBlock(blockNumber());
      cl.setLastFullPaymentBlock(blockNumber());
    }

    IPool pool = config.getPool();

    // If there is any balance on the creditline that has not been applied yet, then use that first before
    // drawing down from the pool. This is to support cases where the borrower partially pays back the
    // principal before the due date, but then decides to drawdown again
    uint256 amountToTransferFromCL;
    if (unappliedBalance > 0) {
      if (amount > unappliedBalance) {
        amountToTransferFromCL = unappliedBalance;
        amount = amount.sub(unappliedBalance);
      } else {
        amountToTransferFromCL = amount;
        amount = 0;
      }
      bool success = pool.transferFrom(creditLineAddress, msg.sender, amountToTransferFromCL);
      require(success, "Failed to drawdown");
    }

    (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, blockNumber());
    balance = balance.add(amount);

    updateCreditLineAccounting(cl, balance, interestOwed, principalOwed);

    // Must put this after we update the credit line accounting, so we're using the latest
    // interestOwed
    require(!isLate(cl), "Cannot drawdown when payments are past due");
    emit DrawdownMade(msg.sender, address(cl), amount.add(amountToTransferFromCL));

    if (amount > 0) {
      bool success = pool.drawdown(msg.sender, amount);
      require(success, "Failed to drawdown");
    }
  }

  /**
   * @notice Allows a borrower to repay their loan. Payment is *collected* immediately (by sending it to
   *  the individual CreditLine), but it is not *applied* unless it is after the nextDueBlock, or until we assess
   *  the credit line (ie. payment period end).
   *  Any amounts over the minimum payment will be applied to outstanding principal (reducing the effective
   *  interest rate). If there is still any left over, it will remain in the USDC Balance
   *  of the CreditLine, which is held distinct from the Pool amounts, and can not be withdrawn by LP's.
   * @param creditLineAddress The credit line to be paid back
   * @param amount The amount, in USDC atomic units, that a borrower wishes to pay
   */
  function pay(address creditLineAddress, uint256 amount)
    external
    override
    whenNotPaused
    onlyValidCreditLine(creditLineAddress)
  {
    require(amount > 0, "Must pay more than zero");
    CreditLine cl = CreditLine(creditLineAddress);

    collectPayment(cl, amount);
    assessCreditLine(creditLineAddress);
  }

  /**
   * @notice Assesses a particular creditLine. This will apply payments, which will update accounting and
   *  distribute gains or losses back to the pool accordingly. This function is idempotent, and anyone
   *  is allowed to call it.
   * @param creditLineAddress The creditline that should be assessed.
   */
  function assessCreditLine(address creditLineAddress)
    public
    override
    whenNotPaused
    onlyValidCreditLine(creditLineAddress)
  {
    CreditLine cl = CreditLine(creditLineAddress);
    // Do not assess until a full period has elapsed or past due
    require(cl.balance() > 0, "Must have balance to assess credit line");

    // Don't assess credit lines early!
    if (blockNumber() < cl.nextDueBlock() && !isLate(cl)) {
      return;
    }

    uint256 blockToAssess = calculateNextDueBlock(cl);
    cl.setNextDueBlock(blockToAssess);

    // We always want to assess for the most recently *past* nextDueBlock.
    // So if the recalculation above sets the nextDueBlock into the future,
    // then ensure we pass in the one just before this.
    if (blockToAssess > blockNumber()) {
      uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY);
      blockToAssess = blockToAssess.sub(blocksPerPeriod);
    }
    _applyPayment(cl, getUSDCBalance(address(cl)), blockToAssess);
  }

  function applyPayment(address creditLineAddress, uint256 amount)
    external
    override
    whenNotPaused
    onlyValidCreditLine(creditLineAddress)
  {
    CreditLine cl = CreditLine(creditLineAddress);
    require(cl.borrower() == msg.sender, "You do not belong to this credit line");
    _applyPayment(cl, amount, blockNumber());
  }

  function migrateCreditLine(
    CreditLine clToMigrate,
    address borrower,
    uint256 limit,
    uint256 interestApr,
    uint256 paymentPeriodInDays,
    uint256 termInDays,
    uint256 lateFeeApr
  ) public {
    require(clToMigrate.underwriter() == msg.sender, "Caller must be the underwriter");
    require(clToMigrate.limit() > 0, "Can't migrate empty credit line");
    address newClAddress = createCreditLine(borrower, limit, interestApr, paymentPeriodInDays, termInDays, lateFeeApr);

    CreditLine newCl = CreditLine(newClAddress);

    // Set accounting state vars.
    newCl.setBalance(clToMigrate.balance());
    newCl.setInterestOwed(clToMigrate.interestOwed());
    newCl.setPrincipalOwed(clToMigrate.principalOwed());
    newCl.setTermEndBlock(clToMigrate.termEndBlock());
    newCl.setNextDueBlock(clToMigrate.nextDueBlock());
    newCl.setInterestAccruedAsOfBlock(clToMigrate.interestAccruedAsOfBlock());
    newCl.setWritedownAmount(clToMigrate.writedownAmount());
    newCl.setLastFullPaymentBlock(clToMigrate.lastFullPaymentBlock());

    // Close out the original credit line
    clToMigrate.setLimit(0);
    clToMigrate.setBalance(0);
    bool success = config.getPool().transferFrom(
      address(clToMigrate),
      address(newCl),
      config.getUSDC().balanceOf(address(clToMigrate))
    );
    require(success, "Failed to transfer funds");
  }

  // Public View Functions (Getters)

  /**
   * @notice Simple getter for the creditlines of a given underwriter
   * @param underwriterAddress The underwriter address you would like to see the credit lines of.
   */
  function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
    return underwriters[underwriterAddress].creditLines;
  }

  /**
   * @notice Simple getter for the creditlines of a given borrower
   * @param borrowerAddress The borrower address you would like to see the credit lines of.
   */
  function getBorrowerCreditLines(address borrowerAddress) public view returns (address[] memory) {
    return borrowers[borrowerAddress].creditLines;
  }

  /**
   * @notice This function is only meant to be used by frontends. It returns the total
   * payment due for a given creditLine as of the provided blocknumber. Returns 0 if no
   * payment is due (e.g. asOfBLock is before the nextDueBlock)
   * @param creditLineAddress The creditLine to calculate the payment for
   * @param asOfBLock The block to use for the payment calculation, if it is set to 0, uses the current block number
   */
  function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock)
    external
    view
    override
    onlyValidCreditLine(creditLineAddress)
    returns (uint256)
  {
    if (asOfBLock == 0) {
      asOfBLock = blockNumber();
    }
    CreditLine cl = CreditLine(creditLineAddress);

    if (asOfBLock < cl.nextDueBlock() && !isLate(cl)) {
      return 0;
    }

    (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
      cl,
      asOfBLock,
      config.getLatenessGracePeriodInDays()
    );
    return cl.interestOwed().add(interestAccrued).add(cl.principalOwed().add(principalAccrued));
  }

  function updateGoldfinchConfig() external onlyAdmin {
    config = GoldfinchConfig(config.configAddress());
  }

  /*
   * Internal Functions
   */

  /**
   * @notice Collects `amount` of payment for a given credit line. This sends money from the payer to the credit line.
   *  Note that payment is not *applied* when calling this function. Only collected (ie. held) for later application.
   * @param cl The CreditLine the payment will be collected for.
   * @param amount The amount, in USDC atomic units, to be collected
   */
  function collectPayment(CreditLine cl, uint256 amount) internal {
    require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");

    emit PaymentCollected(msg.sender, address(cl), amount);

    bool success = config.getPool().transferFrom(msg.sender, address(cl), amount);
    require(success, "Failed to collect payment");
  }

  /**
   * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.
   *  It also updates all the accounting variables. Note that interest is always paid back first, then principal.
   *  Any extra after paying the minimum will go towards existing principal (reducing the
   *  effective interest rate). Any extra after the full loan has been paid off will remain in the
   *  USDC Balance of the creditLine, where it will be automatically used for the next drawdown.
   * @param cl The CreditLine the payment will be collected for.
   * @param amount The amount, in USDC atomic units, to be applied
   * @param blockNumber The blockNumber on which accrual calculations should be based. This allows us
   *  to be precise when we assess a Credit Line
   */
  function _applyPayment(
    CreditLine cl,
    uint256 amount,
    uint256 blockNumber
  ) internal {
    (uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = handlePayment(
      cl,
      amount,
      blockNumber
    );

    IPool pool = config.getPool();
    updateWritedownAmounts(cl, pool);

    if (interestPayment > 0 || principalPayment > 0) {
      emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining);
      pool.collectInterestAndPrincipal(address(cl), interestPayment, principalPayment);
    }
  }

  function handlePayment(
    CreditLine cl,
    uint256 paymentAmount,
    uint256 asOfBlock
  )
    internal
    returns (
      uint256,
      uint256,
      uint256
    )
  {
    (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, asOfBlock);
    Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(
      paymentAmount,
      cl.balance(),
      interestOwed,
      principalOwed
    );

    uint256 newBalance = cl.balance().sub(pa.principalPayment);
    // Apply any additional payment towards the balance
    newBalance = newBalance.sub(pa.additionalBalancePayment);

    uint256 totalPrincipalPayment = cl.balance().sub(newBalance);
    uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);

    updateCreditLineAccounting(
      cl,
      newBalance,
      interestOwed.sub(pa.interestPayment),
      principalOwed.sub(pa.principalPayment)
    );

    assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);

    return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
  }

  function updateWritedownAmounts(CreditLine cl, IPool pool) internal {
    (uint256 writedownPercent, uint256 writedownAmount) = Accountant.calculateWritedownFor(
      cl,
      blockNumber(),
      config.getLatenessGracePeriodInDays(),
      config.getLatenessMaxDays()
    );

    if (writedownPercent == 0 && cl.writedownAmount() == 0) {
      return;
    }
    int256 writedownDelta = int256(cl.writedownAmount()) - int256(writedownAmount);
    cl.setWritedownAmount(writedownAmount);
    if (writedownDelta > 0) {
      // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns.
      totalWritedowns = totalWritedowns.sub(uint256(writedownDelta));
    } else {
      totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1));
    }
    pool.distributeLosses(address(cl), writedownDelta);
  }

  function isLate(CreditLine cl) internal view returns (bool) {
    uint256 blocksElapsedSinceFullPayment = blockNumber().sub(cl.lastFullPaymentBlock());
    return blocksElapsedSinceFullPayment > cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY);
  }

  function getCreditLineFactory() internal view returns (CreditLineFactory) {
    return CreditLineFactory(config.getAddress(uint256(ConfigOptions.Addresses.CreditLineFactory)));
  }

  function updateAndGetInterestAndPrincipalOwedAsOf(CreditLine cl, uint256 blockNumber)
    internal
    returns (uint256, uint256)
  {
    (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
      cl,
      blockNumber,
      config.getLatenessGracePeriodInDays()
    );
    if (interestAccrued > 0) {
      // If we've accrued any interest, update interestAccruedAsOfBLock to the block that we've
      // calculated interest for. If we've not accrued any interest, then we keep the old value so the next
      // time the entire period is taken into account.
      cl.setInterestAccruedAsOfBlock(blockNumber);
    }
    return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued));
  }

  function withinCreditLimit(
    uint256 amount,
    uint256 unappliedBalance,
    CreditLine cl
  ) internal view returns (bool) {
    return cl.balance().add(amount).sub(unappliedBalance) <= cl.limit();
  }

  function withinTransactionLimit(uint256 amount) internal view returns (bool) {
    return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
  }

  function calculateNewTermEndBlock(CreditLine cl, uint256 balance) internal view returns (uint256) {
    // If there's no balance, there's no loan, so there's no term end block
    if (balance == 0) {
      return 0;
    }
    // Don't allow any weird bugs where we add to your current end block. This
    // function should only be used on new credit lines, when we are setting them up
    if (cl.termEndBlock() != 0) {
      return cl.termEndBlock();
    }
    return blockNumber().add(BLOCKS_PER_DAY.mul(cl.termInDays()));
  }

  function calculateNextDueBlock(CreditLine cl) internal view returns (uint256) {
    uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY);
    uint256 balance = cl.balance();
    uint256 nextDueBlock = cl.nextDueBlock();
    uint256 curBlockNumber = blockNumber();
    // You must have just done your first drawdown
    if (nextDueBlock == 0 && balance > 0) {
      return curBlockNumber.add(blocksPerPeriod);
    }

    // Active loan that has entered a new period, so return the *next* nextDueBlock.
    // But never return something after the termEndBlock
    if (balance > 0 && curBlockNumber >= nextDueBlock) {
      uint256 blocksToAdvance = (curBlockNumber.sub(nextDueBlock).div(blocksPerPeriod)).add(1).mul(blocksPerPeriod);
      nextDueBlock = nextDueBlock.add(blocksToAdvance);
      return Math.min(nextDueBlock, cl.termEndBlock());
    }

    // Your paid off, or have not taken out a loan yet, so no next due block.
    if (balance == 0 && nextDueBlock != 0) {
      return 0;
    }
    // Active loan in current period, where we've already set the nextDueBlock correctly, so should not change.
    if (balance > 0 && curBlockNumber < nextDueBlock) {
      return nextDueBlock;
    }
    revert("Error: could not calculate next due block.");
  }

  function blockNumber() internal view virtual returns (uint256) {
    return block.number;
  }

  function underwriterCanCreateThisCreditLine(uint256 newAmount, Underwriter storage underwriter)
    internal
    view
    returns (bool)
  {
    uint256 underwriterLimit = underwriter.governanceLimit;
    require(underwriterLimit != 0, "underwriter does not have governance limit");
    uint256 creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter);
    uint256 totalToBeExtended = creditCurrentlyExtended.add(newAmount);
    return totalToBeExtended <= underwriterLimit;
  }

  function withinMaxUnderwriterLimit(uint256 amount) internal view returns (bool) {
    return amount <= config.getNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit));
  }

  function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint256) {
    uint256 creditExtended;
    uint256 length = underwriter.creditLines.length;
    for (uint256 i = 0; i < length; i++) {
      CreditLine cl = CreditLine(underwriter.creditLines[i]);
      creditExtended = creditExtended.add(cl.limit());
    }
    return creditExtended;
  }

  function updateCreditLineAccounting(
    CreditLine cl,
    uint256 balance,
    uint256 interestOwed,
    uint256 principalOwed
  ) internal nonReentrant {
    // subtract cl from total loans outstanding
    totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance());

    cl.setBalance(balance);
    cl.setInterestOwed(interestOwed);
    cl.setPrincipalOwed(principalOwed);

    // This resets lastFullPaymentBlock. These conditions assure that they have
    // indeed paid off all their interest and they have a real nextDueBlock. (ie. creditline isn't pre-drawdown)
    uint256 nextDueBlock = cl.nextDueBlock();
    if (interestOwed == 0 && nextDueBlock != 0) {
      // If interest was fully paid off, then set the last full payment as the previous due block
      uint256 mostRecentLastDueBlock;
      if (blockNumber() < nextDueBlock) {
        uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY);
        mostRecentLastDueBlock = nextDueBlock.sub(blocksPerPeriod);
      } else {
        mostRecentLastDueBlock = nextDueBlock;
      }
      cl.setLastFullPaymentBlock(mostRecentLastDueBlock);
    }

    // Add new amount back to total loans outstanding
    totalLoansOutstanding = totalLoansOutstanding.add(balance);

    cl.setTermEndBlock(calculateNewTermEndBlock(cl, balance)); // pass in balance as a gas optimization
    cl.setNextDueBlock(calculateNextDueBlock(cl));
  }

  function getUSDCBalance(address _address) internal view returns (uint256) {
    return config.getUSDC().balanceOf(_address);
  }

  modifier onlyValidCreditLine(address clAddress) {
    require(creditLines[clAddress] != address(0), "Unknown credit line");
    _;
  }
}

File 44 of 44 : TestCreditDesk.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "../protocol/core/CreditDesk.sol";

contract TestCreditDesk is CreditDesk {
  uint256 _blockNumberForTest;

  function _setTotalLoansOutstanding(uint256 amount) public {
    totalLoansOutstanding = amount;
  }

  function _setBlockNumberForTest(uint256 blockNumber) public {
    _blockNumberForTest = blockNumber;
  }

  function blockNumber() internal view override returns (uint256) {
    if (_blockNumberForTest == 0) {
      return super.blockNumber();
    } else {
      return _blockNumberForTest;
    }
  }

  function blockNumberForTest() public view returns (uint256) {
    return blockNumber();
  }
}

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

Contract Security Audit

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"OWNER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"__BaseUpgradeablePausable__init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"__PauserPausable__init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"config","outputs":[{"internalType":"contract GoldfinchConfig","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creditLineAddress","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"addressToSendTo","type":"address"}],"name":"drawdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"creditLineAddress","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"addressToSendTo","type":"address"},{"internalType":"address","name":"toToken","type":"address"},{"internalType":"uint256","name":"minTargetAmount","type":"uint256"},{"internalType":"uint256[]","name":"exchangeDistribution","type":"uint256[]"}],"name":"drawdownWithSwapOnOneInch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"contract GoldfinchConfig","name":"_config","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isAdmin","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"isTrustedForwarder","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creditLineAddress","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"pay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"creditLineAddress","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"payInFull","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"creditLines","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"payMultiple","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"creditLines","type":"address[]"},{"internalType":"uint256[]","name":"minAmounts","type":"uint256[]"},{"internalType":"uint256","name":"originAmount","type":"uint256"},{"internalType":"address","name":"fromToken","type":"address"},{"internalType":"uint256[]","name":"exchangeDistribution","type":"uint256[]"}],"name":"payMultipleWithSwapOnOneInch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"creditLineAddress","type":"address"},{"internalType":"uint256","name":"originAmount","type":"uint256"},{"internalType":"address","name":"fromToken","type":"address"},{"internalType":"uint256","name":"minTargetAmount","type":"uint256"},{"internalType":"uint256[]","name":"exchangeDistribution","type":"uint256[]"}],"name":"payWithSwapOnOneInch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"trustedForwarder","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"versionRecipient","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}]

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101cf5760003560e01c806379502c5511610104578063a217fddf116100a2578063ca15c87311610071578063ca15c8731461038b578063d547741f1461039e578063e58378bb146103b1578063e63ab1e9146103b9576101cf565b8063a217fddf14610355578063b6db75a01461035d578063c407687614610365578063c8bc38ae14610378576101cf565b80638b032c64116100de5780638b032c64146103095780639010d07c1461031c57806391d148541461032f5780639db5dbe414610342576101cf565b806379502c55146102e45780637da0a877146102f95780638456cb5914610301576101cf565b8063486ff0cd11610171578063572b6c051161014b578063572b6c05146102965780635c975abb146102b65780635e3e9fad146102be5780636cbbbbc2146102d1576101cf565b8063486ff0cd14610266578063526d81f61461027b57806356b7b73a14610283576101cf565b806336568abe116101ad57806336568abe146102255780633f17474a146102385780633f4ba83a1461024b578063485cc95514610253576101cf565b8063097616a3146101d4578063248a9ca3146101e95780632f2ff15d14610212575b600080fd5b6101e76101e2366004611f80565b6103c1565b005b6101fc6101f736600461231a565b6104fa565b6040516102099190612485565b60405180910390f35b6101e7610220366004612332565b61050f565b6101e7610233366004612332565b610553565b6101e761024636600461209c565b610595565b6101e761071d565b6101e7610261366004611ff8565b61075d565b61026e610a24565b604051610209919061248e565b6101e7610a44565b6101e7610291366004612129565b610acf565b6102a96102a4366004611f80565b610c2e565b604051610209919061247a565b6102a9610c43565b6101e76102cc36600461205b565b610c4c565b6101e76102df366004612206565b610d34565b6102ec610fed565b60405161020991906123ab565b6102ec610ffd565b6101e761100d565b6101e7610317366004612030565b61104b565b6102ec61032a366004612356565b611232565b6102a961033d366004612332565b611253565b6101e7610350366004611fb8565b61126b565b6101fc6112e1565b6102a96112e6565b6101e7610373366004612030565b611307565b6101e761038636600461219d565b611465565b6101fc61039936600461231a565b611672565b6101e76103ac366004612332565b611689565b6101fc6116c3565b6101fc6116d5565b600054610100900460ff16806103da57506103da6116e7565b806103e8575060005460ff16155b61040d5760405162461bcd60e51b8152600401610404906127a9565b60405180910390fd5b600054610100900460ff16158015610438576000805460ff1961ff0019909116610100171660011790555b6001600160a01b03821661045e5760405162461bcd60e51b815260040161040490612703565b6104666116ed565b61046e61176e565b6104766117fa565b61048e60008051602061295583398151915283610549565b6104a660008051602061297583398151915283610549565b6104cc600080516020612975833981519152600080516020612955833981519152611889565b6104e460008051602061295583398151915280611889565b80156104f6576000805461ff00191690555b5050565b60009081526065602052604090206002015490565b60008281526065602052604090206002015461052d9061033d61189e565b6105495760405162461bcd60e51b815260040161040490612503565b6104f682826118a8565b61055b61189e565b6001600160a01b0316816001600160a01b03161461058b5760405162461bcd60e51b815260040161040490612879565b6104f68282611911565b61059d6112e6565b6105b95760405162461bcd60e51b81526004016104049061282e565b6101c4546105cf906001600160a01b031661197a565b6001600160a01b0316636acab9da88886040518363ffffffff1660e01b81526004016105fc929190612461565b600060405180830381600087803b15801561061657600080fd5b505af115801561062a573d6000803e3d6000fd5b50506101c454610684925061064891506001600160a01b0316611985565b858886868680806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250611a0592505050565b6001600160a01b03851615806106a257506001600160a01b03851630145b156106b2576106af61189e565b94505b6060306040516024016106c591906123ab565b60408051601f198184030181529190526020810180516001600160e01b03166370a0823160e01b179052905060006107056107008784611a6c565b611b15565b905061071286888361126b565b505050505050505050565b61073760008051602061297583398151915261033d61189e565b6107535760405162461bcd60e51b815260040161040490612580565b61075b611b1c565b565b600054610100900460ff168061077657506107766116e7565b80610784575060005460ff16155b6107a05760405162461bcd60e51b8152600401610404906127a9565b600054610100900460ff161580156107cb576000805460ff1961ff0019909116610100171660011790555b6001600160a01b0383166107f15760405162461bcd60e51b815260040161040490612738565b6107fa836103c1565b6101c480546001600160a01b0319166001600160a01b0384811691909117918290556108269116611b88565b6101c380546001600160a01b0319166001600160a01b039283161790556101c4546000916108549116611ba0565b6101c454909150600090610870906001600160a01b0316611bb8565b6101c4549091506001600160a01b038083169163095ea7b3916108939116611bc3565b6000196040518363ffffffff1660e01b81526004016108b3929190612461565b602060405180830381600087803b1580156108cd57600080fd5b505af11580156108e1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061090591906122fa565b5060405163095ea7b360e01b81526001600160a01b0382169063095ea7b39061093690859060001990600401612461565b602060405180830381600087803b15801561095057600080fd5b505af1158015610964573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061098891906122fa565b506060826000196040516024016109a0929190612461565b60408051601f198184030181529190526020810180516001600160e01b031663095ea7b360e01b17905290506109ea73dac17f958d2ee523a2206206994597c13d831ec782611a6c565b50610a09734fabb145d64652a948d72533023f6e7a623c7c5382611a6c565b505050508015610a1f576000805461ff00191690555b505050565b6040805180820190915260058152640322e302e360dc1b60208201525b90565b600054610100900460ff1680610a5d5750610a5d6116e7565b80610a6b575060005460ff16155b610a875760405162461bcd60e51b8152600401610404906127a9565b600054610100900460ff16158015610ab2576000805460ff1961ff0019909116610100171660011790555b610aba61176e565b8015610acc576000805461ff00191690555b50565b610ad76112e6565b610af35760405162461bcd60e51b81526004016104049061282e565b610b0683610aff61189e565b3087611bda565b6101c454600090610b1f906001600160a01b0316611bb8565b9050610b2e8482878686611a05565b6040516370a0823160e01b81526000906001600160a01b038316906370a0823190610b5d9030906004016123ab565b60206040518083038186803b158015610b7557600080fd5b505afa158015610b89573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bad9190612377565b6101c454909150610bc6906001600160a01b031661197a565b6001600160a01b031663c407687688836040518363ffffffff1660e01b8152600401610bf3929190612461565b600060405180830381600087803b158015610c0d57600080fd5b505af1158015610c21573d6000803e3d6000fd5b5050505050505050505050565b6101c3546001600160a01b0390811691161490565b60975460ff1690565b610c546112e6565b610c705760405162461bcd60e51b81526004016104049061282e565b6101c454610c86906001600160a01b031661197a565b6001600160a01b0316636acab9da84846040518363ffffffff1660e01b8152600401610cb3929190612461565b600060405180830381600087803b158015610ccd57600080fd5b505af1158015610ce1573d6000803e3d6000fd5b505050506001600160a01b0381161580610d0357506001600160a01b03811630145b15610d1357610d1061189e565b90505b6101c454610a1f90610d2d906001600160a01b0316611985565b828461126b565b610d3c6112e6565b610d585760405162461bcd60e51b81526004016104049061282e565b8351855114610d795760405162461bcd60e51b815260040161040490612603565b6000805b8551811015610db657610dac868281518110610d9557fe5b602002602001015183611c2f90919063ffffffff16565b9150600101610d7d565b50610dc383610aff61189e565b6101c454600090610ddc906001600160a01b0316611bb8565b9050610deb8482878587611a05565b6101c454600090610e04906001600160a01b031661197a565b905060005b8751811015610ea457816001600160a01b031663c40768768a8381518110610e2d57fe5b60200260200101518a8481518110610e4157fe5b60200260200101516040518363ffffffff1660e01b8152600401610e66929190612461565b600060405180830381600087803b158015610e8057600080fd5b505af1158015610e94573d6000803e3d6000fd5b505060019092019150610e099050565b506040516370a0823160e01b81526000906001600160a01b038416906370a0823190610ed49030906004016123ab565b60206040518083038186803b158015610eec57600080fd5b505afa158015610f00573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f249190612377565b90508015610712576000836001600160a01b031663a9059cbb8b600081518110610f4a57fe5b6020026020010151846040518363ffffffff1660e01b8152600401610f70929190612461565b602060405180830381600087803b158015610f8a57600080fd5b505af1158015610f9e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fc291906122fa565b905080610fe15760405162461bcd60e51b8152600401610404906127f7565b50505050505050505050565b6101c4546001600160a01b031681565b6101c3546001600160a01b031681565b61102760008051602061297583398151915261033d61189e565b6110435760405162461bcd60e51b815260040161040490612580565b61075b611c54565b6110536112e6565b61106f5760405162461bcd60e51b81526004016104049061282e565b6101c454600090611088906001600160a01b0316611bb8565b6001600160a01b03166323b872dd61109e61189e565b85856040518463ffffffff1660e01b81526004016110be939291906123bf565b602060405180830381600087803b1580156110d857600080fd5b505af11580156110ec573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061111091906122fa565b90508061112f5760405162461bcd60e51b8152600401610404906127f7565b6101c454611145906001600160a01b031661197a565b6001600160a01b0316632e0c6cfe84846040518363ffffffff1660e01b8152600401611172929190612461565b600060405180830381600087803b15801561118c57600080fd5b505af11580156111a0573d6000803e3d6000fd5b50505050826001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b1580156111dd57600080fd5b505afa1580156111f1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112159190612377565b15610a1f5760405162461bcd60e51b815260040161040490612767565b600082815260656020526040812061124a9083611cad565b90505b92915050565b600082815260656020526040812061124a9083611cb9565b6112736112e6565b61128f5760405162461bcd60e51b81526004016104049061282e565b606082826040516024016112a4929190612461565b60408051601f198184030181529190526020810180516001600160e01b031663a9059cbb60e01b17905290506112da8482611a6c565b5050505050565b600081565b600061130260008051602061295583398151915261033d61189e565b905090565b61130f6112e6565b61132b5760405162461bcd60e51b81526004016104049061282e565b6101c454600090611344906001600160a01b0316611bb8565b6001600160a01b03166323b872dd61135a61189e565b30856040518463ffffffff1660e01b815260040161137a939291906123bf565b602060405180830381600087803b15801561139457600080fd5b505af11580156113a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113cc91906122fa565b9050806113eb5760405162461bcd60e51b8152600401610404906127f7565b6101c454611401906001600160a01b031661197a565b6001600160a01b031663c407687684846040518363ffffffff1660e01b815260040161142e929190612461565b600060405180830381600087803b15801561144857600080fd5b505af115801561145c573d6000803e3d6000fd5b50505050505050565b61146d6112e6565b6114895760405162461bcd60e51b81526004016104049061282e565b8281146114a85760405162461bcd60e51b815260040161040490612603565b6000805b828110156114e3576114d98484838181106114c357fe5b9050602002013583611c2f90919063ffffffff16565b91506001016114ac565b506101c4546000906114fd906001600160a01b0316611bb8565b6001600160a01b03166323b872dd61151361189e565b30856040518463ffffffff1660e01b8152600401611533939291906123bf565b602060405180830381600087803b15801561154d57600080fd5b505af1158015611561573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061158591906122fa565b9050806115a45760405162461bcd60e51b8152600401610404906127f7565b6101c4546000906115bd906001600160a01b031661197a565b905060005b8481101561166857816001600160a01b031663c40768768989848181106115e557fe5b90506020020160208101906115fa9190611f80565b88888581811061160657fe5b905060200201356040518363ffffffff1660e01b815260040161162a929190612461565b600060405180830381600087803b15801561164457600080fd5b505af1158015611658573d6000803e3d6000fd5b5050600190920191506115c29050565b5050505050505050565b600081815260656020526040812061124d90611cce565b6000828152606560205260409020600201546116a79061033d61189e565b61058b5760405162461bcd60e51b815260040161040490612689565b60008051602061295583398151915281565b60008051602061297583398151915281565b303b1590565b600054610100900460ff168061170657506117066116e7565b80611714575060005460ff16155b6117305760405162461bcd60e51b8152600401610404906127a9565b600054610100900460ff16158015610aba576000805460ff1961ff0019909116610100171660011790558015610acc576000805461ff001916905550565b600054610100900460ff168061178757506117876116e7565b80611795575060005460ff16155b6117b15760405162461bcd60e51b8152600401610404906127a9565b600054610100900460ff161580156117dc576000805460ff1961ff0019909116610100171660011790555b6097805460ff191690558015610acc576000805461ff001916905550565b600054610100900460ff168061181357506118136116e7565b80611821575060005460ff16155b61183d5760405162461bcd60e51b8152600401610404906127a9565b600054610100900460ff16158015611868576000805460ff1961ff0019909116610100171660011790555b60c9805460ff191660011790558015610acc576000805461ff001916905550565b60009182526065602052604090912060020155565b6000611302611cd9565b60008281526065602052604090206118c09082611d0b565b156104f6576118cd61189e565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60008281526065602052604090206119299082611d20565b156104f65761193661189e565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b600061124d82611d35565b60006001600160a01b03821663b93f9b0a60055b6040518263ffffffff1660e01b81526004016119b59190612485565b60206040518083038186803b1580156119cd57600080fd5b505afa1580156119e1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124d9190611f9c565b606085858585856000604051602401611a23969594939291906123e3565b60408051601f198184030181529190526020810180516001600160e01b0316637153a8af60e11b1790526101c45490915061145c90611a6a906001600160a01b0316611ba0565b825b606060006060846001600160a01b031684604051611a8a919061238f565b6000604051808303816000865af19150503d8060008114611ac7576040519150601f19603f3d011682016040523d82523d6000602084013e611acc565b606091505b50909250905081158015611ae1575060008151115b15611af0573d6000803e3d6000fd5b81611b0d5760405162461bcd60e51b815260040161040490612652565b949350505050565b6020015190565b60975460ff16611b3e5760405162461bcd60e51b815260040161040490612552565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa611b7161189e565b604051611b7e91906123ab565b60405180910390a1565b60006001600160a01b03821663b93f9b0a6009611999565b60006001600160a01b03821663b93f9b0a6008611999565b600061124d82611985565b60006001600160a01b03821663b93f9b0a82611999565b6060838383604051602401611bf1939291906123bf565b60408051601f198184030181529190526020810180516001600160e01b03166323b872dd60e01b1790529050611c278582611a6c565b505050505050565b60008282018381101561124a5760405162461bcd60e51b8152600401610404906125cc565b60975460ff1615611c775760405162461bcd60e51b8152600401610404906126d9565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611b7161189e565b600061124a8383611d4d565b600061124a836001600160a01b038416611d92565b600061124d82611daa565b600060183610801590611cf05750611cf033610c2e565b15611d04575060131936013560601c610a41565b5033610a41565b600061124a836001600160a01b038416611dae565b600061124a836001600160a01b038416611df8565b60006001600160a01b03821663b93f9b0a6003611999565b81546000908210611d705760405162461bcd60e51b8152600401610404906124c1565b826000018281548110611d7f57fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b5490565b6000611dba8383611d92565b611df05750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561124d565b50600061124d565b60008181526001830160205260408120548015611eb45783546000198083019190810190600090879083908110611e2b57fe5b9060005260206000200154905080876000018481548110611e4857fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080611e7857fe5b6001900381819060005260206000200160009055905586600101600087815260200190815260200160002060009055600194505050505061124d565b600091505061124d565b803561124d8161293f565b60008083601f840112611eda578182fd5b50813567ffffffffffffffff811115611ef1578182fd5b6020830191508360208083028501011115611f0b57600080fd5b9250929050565b600082601f830112611f22578081fd5b8135611f35611f30826128ef565b6128c8565b818152915060208083019084810181840286018201871015611f5657600080fd5b60005b84811015611f7557813584529282019290820190600101611f59565b505050505092915050565b600060208284031215611f91578081fd5b813561124a8161293f565b600060208284031215611fad578081fd5b815161124a8161293f565b600080600060608486031215611fcc578182fd5b8335611fd78161293f565b92506020840135611fe78161293f565b929592945050506040919091013590565b6000806040838503121561200a578182fd5b82356120158161293f565b915060208301356120258161293f565b809150509250929050565b60008060408385031215612042578182fd5b823561204d8161293f565b946020939093013593505050565b60008060006060848603121561206f578283fd5b833561207a8161293f565b92506020840135915060408401356120918161293f565b809150509250925092565b600080600080600080600060c0888a0312156120b6578283fd5b87356120c18161293f565b96506020880135955060408801356120d88161293f565b945060608801356120e88161293f565b93506080880135925060a088013567ffffffffffffffff81111561210a578283fd5b6121168a828b01611ec9565b989b979a50959850939692959293505050565b600080600080600060a08688031215612140578081fd5b853561214b8161293f565b94506020860135935060408601356121628161293f565b925060608601359150608086013567ffffffffffffffff811115612184578182fd5b61219088828901611f12565b9150509295509295909350565b600080600080604085870312156121b2578384fd5b843567ffffffffffffffff808211156121c9578586fd5b6121d588838901611ec9565b909650945060208701359150808211156121ed578384fd5b506121fa87828801611ec9565b95989497509550505050565b600080600080600060a0868803121561221d578283fd5b853567ffffffffffffffff80821115612234578485fd5b818801915088601f830112612247578485fd5b8135612255611f30826128ef565b80828252602080830192508086018d82838702890101111561227557898afd5b8996505b8487101561229f5761228b8e82611ebe565b845260019690960195928101928101612279565b509099508a013593505050808211156122b6578485fd5b6122c289838a01611f12565b9550604088013594506122d88960608a01611ebe565b935060808801359150808211156122ed578283fd5b5061219088828901611f12565b60006020828403121561230b578081fd5b8151801515811461124a578182fd5b60006020828403121561232b578081fd5b5035919050565b60008060408385031215612344578182fd5b8235915060208301356120258161293f565b60008060408385031215612368578182fd5b50508035926020909101359150565b600060208284031215612388578081fd5b5051919050565b600082516123a181846020870161290f565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b0387811682528616602080830191909152604082018690526060820185905260c06080830181905284519083018190526000918581019160e085019190845b8181101561244557845184529382019392820192600101612429565b505050809250505060ff831660a0830152979650505050505050565b6001600160a01b03929092168252602082015260400190565b901515815260200190565b90815260200190565b60006020825282518060208401526124ad81604085016020870161290f565b601f01601f19169190910160400192915050565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b60208082526014908201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604082015260600190565b6020808252602c908201527f4d75737420686176652070617573657220726f6c6520746f20706572666f726d60408201526b103a3434b99030b1ba34b7b760a11b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252602f908201527f4372656469746c696e657320616e6420616d6f756e7473206d7573742062652060408201526e0e8d0ca40e6c2daca40d8cadccee8d608b1b606082015260800190565b6020808252601a908201527f564d3a2077616c6c657420696e766f6b65207265766572746564000000000000604082015260600190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b6020808252818101527f4f776e65722063616e6e6f7420626520746865207a65726f2061646472657373604082015260600190565b6020808252601590820152744f776e65722063616e6e6f7420626520656d70747960581b604082015260600190565b60208082526022908201527f4661696c656420746f2066756c6c7920706179206f6666206372656469746c696040820152616e6560f01b606082015260800190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b60208082526017908201527f4661696c656420746f207472616e736665722055534443000000000000000000604082015260600190565b6020808252602b908201527f4d75737420686176652061646d696e20726f6c6520746f20706572666f726d2060408201526a3a3434b99030b1ba34b7b760a91b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b60405181810167ffffffffffffffff811182821017156128e757600080fd5b604052919050565b600067ffffffffffffffff821115612905578081fd5b5060209081020190565b60005b8381101561292a578181015183820152602001612912565b83811115612939576000848401525b50505050565b6001600160a01b0381168114610acc57600080fdfeb19546dff01e856fb3f010c267a7b1c60363cf8a4664e21cc89c26224620214e65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862aa264697066735822122089d425cc3f11864e9755ea9a5b456a5a7330c9e704a89cc1038a1c1b0c6e981d64736f6c634300060c0033

Deployed Bytecode Sourcemap

1112:9374:34:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1457:421:24;;;;;;:::i;:::-;;:::i;:::-;;3920:112:4;;;;;;:::i;:::-;;:::i;:::-;;;;;;;:::i;:::-;;;;;;;;4282:223;;;;;;:::i;:::-;;:::i;5456:205::-;;;;;;:::i;:::-;;:::i;3151:902:34:-;;;;;;:::i;:::-;;:::i;1154:62:32:-;;;:::i;1479:685:34:-;;;;;;:::i;:::-;;:::i;10384:100::-;;;:::i;:::-;;;;;;;:::i;677:91:32:-;;;:::i;5913:544:34:-;;;;;;:::i;:::-;;:::i;465:135:0:-;;;;;;:::i;:::-;;:::i;:::-;;;;;;;:::i;1248:76:15:-;;;:::i;2768:379:34:-;;;;;;:::i;:::-;;:::i;6461:1075::-;;;;;;:::i;:::-;;:::i;1212:29::-;;;:::i;:::-;;;;;;;:::i;427:31:0:-;;;:::i;940:58:32:-;;;:::i;5517:392:34:-;;;;;;:::i;:::-;;:::i;3603:136:4:-;;;;;;:::i;:::-;;:::i;2588:137::-;;;;;;:::i;:::-;;:::i;4057:221:34:-;;;;;;:::i;:::-;;:::i;1778:49:4:-;;;:::i;1882:97:24:-;;;:::i;4546:275:34:-;;;;;;:::i;:::-;;:::i;4825:688::-;;;;;;:::i;:::-;;:::i;2893:125:4:-;;;;;;:::i;:::-;;:::i;4739:226::-;;;;;;:::i;:::-;;:::i;824:60:24:-;;;:::i;559:62:32:-;;;:::i;1457:421:24:-;1024:12:3;;;;;;;;:31;;;1040:15;:13;:15::i;:::-;1024:47;;;-1:-1:-1;1060:11:3;;;;1059:12;1024:47;1016:106;;;;-1:-1:-1;;;1016:106:3;;;;;;;:::i;:::-;;;;;;;;;1129:19;1152:12;;;;;;1151:13;1170:80;;;;1198:12;:19;;-1:-1:-1;;;;1198:19:3;;;;;1225:18;1213:4;1225:18;;;1170:80;-1:-1:-1;;;;;1546:19:24;::::1;1538:64;;;::::0;-1:-1:-1;;;1538:64:24;;::::1;::::0;::::1;;;:::i;:::-;1608:32;:30;:32::i;:::-;1646:27;:25;:27::i;:::-;1679:34;:32;:34::i;:::-;1720:29;-1:-1:-1::0;;;;;;;;;;;1743:5:24::1;1720:10;:29::i;:::-;1755:30;-1:-1:-1::0;;;;;;;;;;;1779:5:24::1;1755:10;:30::i;:::-;1792:38;-1:-1:-1::0;;;;;;;;;;;;;;;;;;;;;;1792:13:24::1;:38::i;:::-;1836:37;-1:-1:-1::0;;;;;;;;;;;861:23:24;1836:13:::1;:37::i;:::-;1268:14:3::0;1264:55;;;1307:5;1292:20;;-1:-1:-1;;1292:20:3;;;1264:55;1457:421:24;;:::o;3920:112:4:-;3977:7;4003:12;;;:6;:12;;;;;:22;;;;3920:112::o;4282:223::-;4373:12;;;;:6;:12;;;;;:22;;;4365:45;;4397:12;:10;:12::i;4365:45::-;4357:105;;;;-1:-1:-1;;;4357:105:4;;;;;;;:::i;:::-;4473:25;4484:4;4490:7;4473:10;:25::i;5456:205::-;5553:12;:10;:12::i;:::-;-1:-1:-1;;;;;5542:23:4;;;;;;5534:83;;;;-1:-1:-1;;;5534:83:4;;;;;;;:::i;:::-;5628:26;5640:4;5646:7;5628:11;:26::i;3151:902:34:-;2018:9:24;:7;:9::i;:::-;2010:65;;;;-1:-1:-1;;;2010:65:24;;;;;;;:::i;:::-;3429:6:34::1;::::0;:22:::1;::::0;-1:-1:-1;;;;;3429:6:34::1;:20;:22::i;:::-;:58;::::0;-1:-1:-1;;;3429:58:34;;-1:-1:-1;;;;;3429:31:34;;;::::1;::::0;::::1;::::0;:58:::1;::::0;3461:17;;3480:6;;3429:58:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;-1:-1:-1::0;;3527:6:34::1;::::0;3513:91:::1;::::0;-1:-1:-1;3527:20:34::1;::::0;-1:-1:-1;;;;;;3527:6:34::1;:18;:20::i;:::-;3549:7;3558:6;3566:15;3583:20;;3513:91;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;::::0;;;;-1:-1:-1;3513:13:34::1;::::0;-1:-1:-1;;;3513:91:34:i:1;:::-;-1:-1:-1::0;;;;;3697:29:34;::::1;::::0;;:65:::1;;-1:-1:-1::0;3757:4:34::1;-1:-1:-1::0;;;;;3730:32:34;::::1;;3697:65;3693:116;;;3790:12;:10;:12::i;:::-;3772:30;;3693:116;3842:18;3917:4;3863:60;;;;;;;;:::i;:::-;;::::0;;-1:-1:-1;;3863:60:34;;::::1;::::0;;;;;;::::1;::::0;::::1;::::0;;-1:-1:-1;;;;;3863:60:34::1;-1:-1:-1::0;;;3863:60:34::1;::::0;;;-1:-1:-1;;3954:33:34::1;3964:22;3971:7:::0;3863:60;3964:6:::1;:22::i;:::-;3954:9;:33::i;:::-;3929:58;;3993:55;4007:7;4016:15;4033:14;3993:13;:55::i;:::-;2081:1:24;;3151:902:34::0;;;;;;;:::o;1154:62:32:-;1260:34;-1:-1:-1;;;;;;;;;;;1281:12:32;:10;:12::i;1260:34::-;1252:91;;;;-1:-1:-1;;;1252:91:32;;;;;;;:::i;:::-;1201:10:::1;:8;:10::i;:::-;1154:62::o:0;1479:685:34:-;1024:12:3;;;;;;;;:31;;;1040:15;:13;:15::i;:::-;1024:47;;;-1:-1:-1;1060:11:3;;;;1059:12;1024:47;1016:106;;;;-1:-1:-1;;;1016:106:3;;;;;;;:::i;:::-;1129:19;1152:12;;;;;;1151:13;1170:80;;;;1198:12;:19;;-1:-1:-1;;;;1198:19:3;;;;;1225:18;1213:4;1225:18;;;1170:80;-1:-1:-1;;;;;1572:19:34;::::1;1564:53;;;::::0;-1:-1:-1;;;1564:53:34;;::::1;::::0;::::1;;;:::i;:::-;1623:38;1655:5;1623:31;:38::i;:::-;1667:6;:16:::0;;-1:-1:-1;;;;;;1667:16:34::1;-1:-1:-1::0;;;;;1667:16:34;;::::1;::::0;;;::::1;::::0;;;;1709:32:::1;::::0;:6:::1;:30;:32::i;:::-;1690:16;:51:::0;;-1:-1:-1;;;;;;1690:51:34::1;-1:-1:-1::0;;;;;1690:51:34;;::::1;;::::0;;1837:6:::1;::::0;-1:-1:-1;;1837:23:34::1;::::0;:6:::1;:21;:23::i;:::-;1887:6;::::0;1819:41;;-1:-1:-1;1866:18:34::1;::::0;1887:16:::1;::::0;-1:-1:-1;;;;;1887:6:34::1;:14;:16::i;:::-;1922:6;::::0;1866:37;;-1:-1:-1;;;;;;1909:12:34;;::::1;::::0;::::1;::::0;1922:20:::1;::::0;:6:::1;:18;:20::i;:::-;-1:-1:-1::0;;1909:47:34::1;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1::0;1962:34:34::1;::::0;-1:-1:-1;;;1962:34:34;;-1:-1:-1;;;;;1962:12:34;::::1;::::0;-1:-1:-1;;1962:34:34::1;::::0;1975:7;;-1:-1:-1;;;1962:34:34::1;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;;2002:17;2074:7;-1:-1:-1::0;;2022:73:34::1;;;;;;;;;:::i;:::-;;::::0;;-1:-1:-1;;2022:73:34;;::::1;::::0;;;;;;::::1;::::0;::::1;::::0;;-1:-1:-1;;;;;2022:73:34::1;-1:-1:-1::0;;;2022:73:34::1;::::0;;;-1:-1:-1;2101:26:34::1;1336:42;2022:73:::0;2101:6:::1;:26::i;:::-;;2133;1431:42;2154:4;2133:6;:26::i;:::-;;1256:1:3;;;1268:14:::0;1264:55;;;1307:5;1292:20;;-1:-1:-1;;1292:20:3;;;1264:55;1479:685:34;;;:::o;10384:100::-;10465:14;;;;;;;;;;;;-1:-1:-1;;;10465:14:34;;;;10384:100;;:::o;677:91:32:-;1024:12:3;;;;;;;;:31;;;1040:15;:13;:15::i;:::-;1024:47;;;-1:-1:-1;1060:11:3;;;;1059:12;1024:47;1016:106;;;;-1:-1:-1;;;1016:106:3;;;;;;;:::i;:::-;1129:19;1152:12;;;;;;1151:13;1170:80;;;;1198:12;:19;;-1:-1:-1;;;;1198:19:3;;;;;1225:18;1213:4;1225:18;;;1170:80;736:27:32::1;:25;:27::i;:::-;1268:14:3::0;1264:55;;;1307:5;1292:20;;-1:-1:-1;;1292:20:3;;;1264:55;677:91:32;:::o;5913:544:34:-;2018:9:24;:7;:9::i;:::-;2010:65;;;;-1:-1:-1;;;2010:65:24;;;;;;;:::i;:::-;6124:66:34::1;6137:9;6148:12;:10;:12::i;:::-;6170:4;6177:12;6124;:66::i;:::-;6217:6;::::0;6196:18:::1;::::0;6217:16:::1;::::0;-1:-1:-1;;;;;6217:6:34::1;:14;:16::i;:::-;6196:37;;6239:92;6253:9;6272:4;6279:12;6293:15;6310:20;6239:13;:92::i;:::-;6359:29;::::0;-1:-1:-1;;;6359:29:34;;6337:19:::1;::::0;-1:-1:-1;;;;;6359:14:34;::::1;::::0;-1:-1:-1;;6359:29:34::1;::::0;6382:4:::1;::::0;6359:29:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;6394:6;::::0;6337:51;;-1:-1:-1;6394:22:34::1;::::0;-1:-1:-1;;;;;6394:6:34::1;:20;:22::i;:::-;:58;::::0;-1:-1:-1;;;6394:58:34;;-1:-1:-1;;;;;6394:26:34;;;::::1;::::0;::::1;::::0;:58:::1;::::0;6421:17;;6440:11;;6394:58:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;2081:1:24;;5913:544:34::0;;;;;:::o;465:135:0:-;577:16;;-1:-1:-1;;;;;564:29:0;;;577:16;;564:29;;465:135::o;1248:76:15:-;1310:7;;;;1248:76;:::o;2768:379:34:-;2018:9:24;:7;:9::i;:::-;2010:65;;;;-1:-1:-1;;;2010:65:24;;;;;;;:::i;:::-;2895:6:34::1;::::0;:22:::1;::::0;-1:-1:-1;;;;;2895:6:34::1;:20;:22::i;:::-;:58;::::0;-1:-1:-1;;;2895:58:34;;-1:-1:-1;;;;;2895:31:34;;;::::1;::::0;::::1;::::0;:58:::1;::::0;2927:17;;2946:6;;2895:58:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;-1:-1:-1::0;;;;;;;;;2964:29:34;::::1;::::0;;:65:::1;;-1:-1:-1::0;3024:4:34::1;-1:-1:-1::0;;;;;2997:32:34;::::1;;2964:65;2960:116;;;3057:12;:10;:12::i;:::-;3039:30;;2960:116;3096:6;::::0;3082:60:::1;::::0;3096:20:::1;::::0;-1:-1:-1;;;;;3096:6:34::1;:18;:20::i;:::-;3118:15;3135:6;3082:13;:60::i;6461:1075::-:0;2018:9:24;:7;:9::i;:::-;2010:65;;;;-1:-1:-1;;;2010:65:24;;;;;;;:::i;:::-;6717:10:34::1;:17;6695:11;:18;:39;6687:99;;;::::0;-1:-1:-1;;;6687:99:34;;::::1;::::0;::::1;;;:::i;:::-;6793:22;6830:9:::0;6825:113:::1;6849:10;:17;6845:1;:21;6825:113;;;6898:33;6917:10;6928:1;6917:13;;;;;;;;;;;;;;6898:14;:18;;:33;;;;:::i;:::-;6881:50:::0;-1:-1:-1;6868:3:34::1;;6825:113;;;;6944:66;6957:9;6968:12;:10;:12::i;6944:66::-;7038:6;::::0;7017:18:::1;::::0;7038:16:::1;::::0;-1:-1:-1;;;;;7038:6:34::1;:14;:16::i;:::-;7017:37;;7060:91;7074:9;7093:4;7100:12;7114:14;7130:20;7060:13;:91::i;:::-;7183:6;::::0;7158:22:::1;::::0;7183::::1;::::0;-1:-1:-1;;;;;7183:6:34::1;:20;:22::i;:::-;7158:47;;7216:9;7211:108;7235:10;:17;7231:1;:21;7211:108;;;7267:10;-1:-1:-1::0;;;;;7267:14:34::1;;7282:11;7294:1;7282:14;;;;;;;;;;;;;;7298:10;7309:1;7298:13;;;;;;;;;;;;;;7267:45;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;-1:-1:-1::0;;7254:3:34::1;::::0;;::::1;::::0;-1:-1:-1;7211:108:34::1;::::0;-1:-1:-1;7211:108:34::1;;-1:-1:-1::0;7349:29:34::1;::::0;-1:-1:-1;;;7349:29:34;;7325:21:::1;::::0;-1:-1:-1;;;;;7349:14:34;::::1;::::0;-1:-1:-1;;7349:29:34::1;::::0;7372:4:::1;::::0;7349:29:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;7325:53:::0;-1:-1:-1;7388:17:34;;7384:148:::1;;7415:12;7430:4;-1:-1:-1::0;;;;;7430:13:34::1;;7444:11;7456:1;7444:14;;;;;;;;;;;;;;7460:13;7430:44;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;7415:59;;7490:7;7482:43;;;::::0;-1:-1:-1;;;7482:43:34;;::::1;::::0;::::1;;;:::i;:::-;7384:148;2081:1:24;;;;6461:1075:34::0;;;;;:::o;1212:29::-;;;-1:-1:-1;;;;;1212:29:34;;:::o;427:31:0:-;;;-1:-1:-1;;;;;427:31:0;;:::o;940:58:32:-;1260:34;-1:-1:-1;;;;;;;;;;;1281:12:32;:10;:12::i;1260:34::-;1252:91;;;;-1:-1:-1;;;1252:91:32;;;;;;;:::i;:::-;985:8:::1;:6;:8::i;5517:392:34:-:0;2018:9:24;:7;:9::i;:::-;2010:65;;;;-1:-1:-1;;;2010:65:24;;;;;;;:::i;:::-;5619:6:34::1;::::0;5604:12:::1;::::0;5619:16:::1;::::0;-1:-1:-1;;;;;5619:6:34::1;:14;:16::i;:::-;-1:-1:-1::0;;;;;5619:29:34::1;;5649:12;:10;:12::i;:::-;5663:17;5682:6;5619:70;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;5604:85;;5703:7;5695:43;;;::::0;-1:-1:-1;;;5695:43:34;;::::1;::::0;::::1;;;:::i;:::-;5745:6;::::0;:22:::1;::::0;-1:-1:-1;;;;;5745:6:34::1;:20;:22::i;:::-;:62;::::0;-1:-1:-1;;;5745:62:34;;-1:-1:-1;;;;;5745:35:34;;;::::1;::::0;::::1;::::0;:62:::1;::::0;5781:17;;5800:6;;5745:62:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;5832:17;-1:-1:-1::0;;;;;5821:37:34::1;;:39;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;:44:::0;5813:91:::1;;;::::0;-1:-1:-1;;;5813:91:34;;::::1;::::0;::::1;;;:::i;3603:136:4:-:0;3676:7;3702:12;;;:6;:12;;;;;:30;;3726:5;3702:23;:30::i;:::-;3695:37;;3603:136;;;;;:::o;2588:137::-;2657:4;2680:12;;;:6;:12;;;;;:38;;2710:7;2680:29;:38::i;4057:221:34:-;2018:9:24;:7;:9::i;:::-;2010:65;;;;-1:-1:-1;;;2010:65:24;;;;;;;:::i;:::-;4162:18:34::1;4236:2;4240:6;4183:64;;;;;;;;;:::i;:::-;;::::0;;-1:-1:-1;;4183:64:34;;::::1;::::0;;;;;;::::1;::::0;::::1;::::0;;-1:-1:-1;;;;;4183:64:34::1;-1:-1:-1::0;;;4183:64:34::1;::::0;;;-1:-1:-1;4253:20:34::1;4260:5:::0;4183:64;4253:6:::1;:20::i;:::-;;2081:1:24;4057:221:34::0;;;:::o;1778:49:4:-;1823:4;1778:49;:::o;1882:97:24:-;1922:4;1941:33;-1:-1:-1;;;;;;;;;;;1961:12:24;:10;:12::i;1941:33::-;1934:40;;1882:97;:::o;4546:275:34:-;2018:9:24;:7;:9::i;:::-;2010:65;;;;-1:-1:-1;;;2010:65:24;;;;;;;:::i;:::-;4642:6:34::1;::::0;4627:12:::1;::::0;4642:16:::1;::::0;-1:-1:-1;;;;;4642:6:34::1;:14;:16::i;:::-;-1:-1:-1::0;;;;;4642:29:34::1;;4672:12;:10;:12::i;:::-;4694:4;4701:6;4642:66;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;4627:81;;4722:7;4714:43;;;::::0;-1:-1:-1;;;4714:43:34;;::::1;::::0;::::1;;;:::i;:::-;4763:6;::::0;:22:::1;::::0;-1:-1:-1;;;;;4763:6:34::1;:20;:22::i;:::-;:53;::::0;-1:-1:-1;;;4763:53:34;;-1:-1:-1;;;;;4763:26:34;;;::::1;::::0;::::1;::::0;:53:::1;::::0;4790:17;;4809:6;;4763:53:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;2081:1:24;4546:275:34::0;;:::o;4825:688::-;2018:9:24;:7;:9::i;:::-;2010:65;;;;-1:-1:-1;;;2010:65:24;;;;;;;:::i;:::-;4939:36:34;;::::1;4931:96;;;::::0;-1:-1:-1;;;4931:96:34;;::::1;::::0;::::1;;;:::i;:::-;5034:19;::::0;5059:101:::1;5079:18:::0;;::::1;5059:101;;;5126:27;5142:7;;5150:1;5142:10;;;;;;;;;;;;;5126:11;:15;;:27;;;;:::i;:::-;5112:41:::0;-1:-1:-1;5099:3:34::1;;5059:101;;;-1:-1:-1::0;5227:6:34::1;::::0;5212:12:::1;::::0;5227:16:::1;::::0;-1:-1:-1;;;;;5227:6:34::1;:14;:16::i;:::-;-1:-1:-1::0;;;;;5227:29:34::1;;5257:12;:10;:12::i;:::-;5279:4;5286:11;5227:71;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;5212:86;;5312:7;5304:43;;;::::0;-1:-1:-1;;;5304:43:34;;::::1;::::0;::::1;;;:::i;:::-;5379:6;::::0;5354:22:::1;::::0;5379::::1;::::0;-1:-1:-1;;;;;5379:6:34::1;:20;:22::i;:::-;5354:47;;5412:9;5407:102;5427:18:::0;;::::1;5407:102;;;-1:-1:-1::0;;;;;5460:14:34;::::1;;5475:11:::0;;5487:1;5475:14;;::::1;;;;;;;;;;;;;;;;;;:::i;:::-;5491:7;;5499:1;5491:10;;;;;;;;;;;;;5460:42;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;-1:-1:-1::0;;5447:3:34::1;::::0;;::::1;::::0;-1:-1:-1;5407:102:34::1;::::0;-1:-1:-1;5407:102:34::1;;;2081:1:24;;;4825:688:34::0;;;;:::o;2893:125:4:-;2956:7;2982:12;;;:6;:12;;;;;:29;;:27;:29::i;4739:226::-;4831:12;;;;:6;:12;;;;;:22;;;4823:45;;4855:12;:10;:12::i;4823:45::-;4815:106;;;;-1:-1:-1;;;4815:106:4;;;;;;;:::i;824:60:24:-;-1:-1:-1;;;;;;;;;;;824:60:24;:::o;559:62:32:-;-1:-1:-1;;;;;;;;;;;559:62:32;:::o;1409:498:3:-;1820:4;1864:17;1895:7;1409:498;:::o;1465:72:4:-;1024:12:3;;;;;;;;:31;;;1040:15;:13;:15::i;:::-;1024:47;;;-1:-1:-1;1060:11:3;;;;1059:12;1024:47;1016:106;;;;-1:-1:-1;;;1016:106:3;;;;;;;:::i;:::-;1129:19;1152:12;;;;;;1151:13;1170:80;;;;1198:12;:19;;-1:-1:-1;;;;1198:19:3;;;;;1225:18;1213:4;1225:18;;;1268:14;1264:55;;;-1:-1:-1;1307:5:3;1292:20;;-1:-1:-1;;1292:20:3;;;1465:72:4:o;1059:93:15:-;1024:12:3;;;;;;;;:31;;;1040:15;:13;:15::i;:::-;1024:47;;;-1:-1:-1;1060:11:3;;;;1059:12;1024:47;1016:106;;;;-1:-1:-1;;;1016:106:3;;;;;;;:::i;:::-;1129:19;1152:12;;;;;;1151:13;1170:80;;;;1198:12;:19;;-1:-1:-1;;;;1198:19:3;;;;;1225:18;1213:4;1225:18;;;1170:80;1129:7:15::1;:15:::0;;-1:-1:-1;;1129:15:15::1;::::0;;1264:55:3;;;;-1:-1:-1;1307:5:3;1292:20;;-1:-1:-1;;1292:20:3;;;1059:93:15:o;1010:515:16:-;1024:12:3;;;;;;;;:31;;;1040:15;:13;:15::i;:::-;1024:47;;;-1:-1:-1;1060:11:3;;;;1059:12;1024:47;1016:106;;;;-1:-1:-1;;;1016:106:3;;;;;;;:::i;:::-;1129:19;1152:12;;;;;;1151:13;1170:80;;;;1198:12;:19;;-1:-1:-1;;;;1198:19:3;;;;;1225:18;1213:4;1225:18;;;1170:80;1499:11:16::1;:18:::0;;-1:-1:-1;;1499:18:16::1;1513:4;1499:18;::::0;;1264:55:3;;;;-1:-1:-1;1307:5:3;1292:20;;-1:-1:-1;;1292:20:3;;;1010:515:16:o;6413:124:4:-;6496:12;;;;:6;:12;;;;;;:22;;:34;6413:124::o;10059:160:34:-;10153:15;10183:31;:29;:31::i;6543:184:4:-;6616:12;;;;:6;:12;;;;;:33;;6641:7;6616:24;:33::i;:::-;6612:109;;;6697:12;:10;:12::i;:::-;6670:40;;-1:-1:-1;;;;;6670:40:4;;;;;;;6682:4;;6670:40;;;;;6543:184;;:::o;6733:188::-;6807:12;;;;:6;:12;;;;;:36;;6835:7;6807:27;:36::i;:::-;6803:112;;;6891:12;:10;:12::i;:::-;6864:40;;-1:-1:-1;;;;;6864:40:4;;;;;;;6876:4;;6864:40;;;;;6733:188;;:::o;828:139:25:-;898:11;936:25;954:6;936:17;:25::i;2403:151::-;2471:7;-1:-1:-1;;;;;2493:17:25;;;2519:28;2511:37;2493:56;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;7934:460:34:-;8118:18;8235:9;8252:7;8267:12;8287:15;8310:20;8338:1;8139:206;;;;;;;;;;;;;:::i;:::-;;;;-1:-1:-1;;8139:206:34;;;;;;;;;;;;;;-1:-1:-1;;;;;8139:206:34;-1:-1:-1;;;8139:206:34;;;8358:6;;8139:206;;-1:-1:-1;8351:38:34;;8358:23;;-1:-1:-1;;;;;8358:6:34;:21;:23::i;:::-;8383:5;8689:788;8760:12;9044;9062:17;9158:7;-1:-1:-1;;;;;9158:12:34;9171:5;9158:19;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;9140:37:34;;-1:-1:-1;9140:37:34;-1:-1:-1;9187:8:34;;:27;;;;;9213:1;9199:4;:11;:15;9187:27;9183:273;;;9318:16;9315:1;;9297:38;9354:16;9315:1;9344:27;9287:92;9396:7;9391:65;;9413:36;;-1:-1:-1;;;9413:36:34;;;;;;;:::i;9391:65::-;9468:4;8689:788;-1:-1:-1;;;;8689:788:34:o;9481:144::-;9609:4;9597:17;9591:24;;9574:47::o;1950:117:15:-;1668:7;;;;1660:40;;;;-1:-1:-1;;;1660:40:15;;;;;;;:::i;:::-;2008:7:::1;:15:::0;;-1:-1:-1;;2008:15:15::1;::::0;;2038:22:::1;2047:12;:10;:12::i;:::-;2038:22;;;;;;:::i;:::-;;;;;;;;1950:117::o:0;1406:175:25:-;1486:7;-1:-1:-1;;;;;1508:17:25;;;1534:40;1526:49;;1245:157;1316:7;-1:-1:-1;;;;;1338:17:25;;;1364:31;1356:40;;693:131;757:13;799:19;811:6;799:11;:19::i;1753:151::-;1821:7;-1:-1:-1;;;;;1843:17:25;;;1821:7;1861:37;;7540:390:34;7663:18;7864:6;7872:9;7883:6;7799:91;;;;;;;;;;:::i;:::-;;;;-1:-1:-1;;7799:91:34;;;;;;;;;;;;;;-1:-1:-1;;;;;7799:91:34;-1:-1:-1;;;7799:91:34;;;;-1:-1:-1;7896:29:34;7911:5;7799:91;7896:6;:29::i;:::-;;7540:390;;;;;:::o;834:176:6:-;892:7;923:5;;;946:6;;;;938:46;;;;-1:-1:-1;;;938:46:6;;;;;;;:::i;1776:115:15:-;1477:7;;;;1476:8;1468:37;;;;-1:-1:-1;;;1468:37:15;;;;;;;:::i;:::-;1835:7:::1;:14:::0;;-1:-1:-1;;1835:14:15::1;1845:4;1835:14;::::0;;1864:20:::1;1871:12;:10;:12::i;6052:147:14:-:0;6126:7;6168:22;6172:3;6184:5;6168:3;:22::i;5368:156::-;5448:4;5471:46;5481:3;-1:-1:-1;;;;;5501:14:14;;5471:9;:46::i;5605:115::-;5668:7;5694:19;5702:3;5694:7;:19::i;852:556:0:-;914:19;968:2;949:8;:21;;;;:55;;;974:30;993:10;974:18;:30::i;:::-;945:457;;;-1:-1:-1;1310:14:0;-1:-1:-1;;1306:22:0;1293:36;1290:2;1286:44;1261:83;;;-1:-1:-1;1381:10:0;1374:17;;4831:141:14;4901:4;4924:41;4929:3;-1:-1:-1;;;;;4949:14:14;;4924:4;:41::i;5140:147::-;5213:4;5236:44;5244:3;-1:-1:-1;;;;;5264:14:14;;5236:7;:44::i;1908:163:25:-;1982:7;-1:-1:-1;;;;;2004:17:25;;;2030:34;2022:43;;4390:201:14;4484:18;;4457:7;;4484:26;-1:-1:-1;4476:73:14;;;;-1:-1:-1;;;4476:73:14;;;;;;;:::i;:::-;4566:3;:11;;4578:5;4566:18;;;;;;;;;;;;;;;;4559:25;;4390:201;;;;:::o;3743:127::-;3816:4;3839:19;;;:12;;;;;:19;;;;;;:24;;;3743:127::o;3951:107::-;4033:18;;3951:107::o;1578:404::-;1641:4;1662:21;1672:3;1677:5;1662:9;:21::i;:::-;1657:319;;-1:-1:-1;1699:23:14;;;;;;;;:11;:23;;;;;;;;;;;;;1879:18;;1857:19;;;:12;;;:19;;;;;;:40;;;;1911:11;;1657:319;-1:-1:-1;1960:5:14;1953:12;;2150:1512;2216:4;2353:19;;;:12;;;:19;;;;;;2387:15;;2383:1273;;2816:18;;-1:-1:-1;;2768:14:14;;;;2816:22;;;;-1:-1:-1;;2816:18:14;;:22;;3098;;;;;;;;;;;;;;3078:42;;3241:9;3212:3;:11;;3224:13;3212:26;;;;;;;;;;;;;;;;;;;:38;;;;3316:23;;;3358:1;3316:12;;;:23;;;;;;3342:17;;;3316:43;;3465:17;;3316:3;;3465:17;;;;;;;;;;;;;;;;;;;;;;3557:3;:12;;:19;3570:5;3557:19;;;;;;;;;;;3550:26;;;3598:4;3591:11;;;;;;;;2383:1273;3640:5;3633:12;;;;;5:130:-1;72:20;;97:33;72:20;97:33;:::i;301:352::-;;;431:3;424:4;416:6;412:17;408:27;398:2;;-1:-1;;439:12;398:2;-1:-1;469:20;;509:18;498:30;;495:2;;;-1:-1;;531:12;495:2;575:4;567:6;563:17;551:29;;626:3;575:4;;610:6;606:17;567:6;592:32;;589:41;586:2;;;643:1;;633:12;586:2;391:262;;;;;:::o;1790:707::-;;1907:3;1900:4;1892:6;1888:17;1884:27;1874:2;;-1:-1;;1915:12;1874:2;1962:6;1949:20;1984:80;1999:64;2056:6;1999:64;:::i;:::-;1984:80;:::i;:::-;2092:21;;;1975:89;-1:-1;2136:4;2149:14;;;;2124:17;;;2238;;;2229:27;;;;2226:36;-1:-1;2223:2;;;2275:1;;2265:12;2223:2;2300:1;2285:206;2310:6;2307:1;2304:13;2285:206;;;3029:20;;2378:50;;2442:14;;;;2470;;;;2332:1;2325:9;2285:206;;;2289:14;;;;;1867:630;;;;:::o;3240:241::-;;3344:2;3332:9;3323:7;3319:23;3315:32;3312:2;;;-1:-1;;3350:12;3312:2;85:6;72:20;97:33;124:5;97:33;:::i;3488:263::-;;3603:2;3591:9;3582:7;3578:23;3574:32;3571:2;;;-1:-1;;3609:12;3571:2;226:6;220:13;238:33;265:5;238:33;:::i;3758:491::-;;;;3896:2;3884:9;3875:7;3871:23;3867:32;3864:2;;;-1:-1;;3902:12;3864:2;85:6;72:20;97:33;124:5;97:33;:::i;:::-;3954:63;-1:-1;4054:2;4093:22;;72:20;97:33;72:20;97:33;:::i;:::-;3858:391;;4062:63;;-1:-1;;;4162:2;4201:22;;;;3029:20;;3858:391::o;4256:414::-;;;4401:2;4389:9;4380:7;4376:23;4372:32;4369:2;;;-1:-1;;4407:12;4369:2;85:6;72:20;97:33;124:5;97:33;:::i;:::-;4459:63;-1:-1;4559:2;4622:22;;2868:20;2893:57;2868:20;2893:57;:::i;:::-;4567:87;;;;4363:307;;;;;:::o;4677:366::-;;;4798:2;4786:9;4777:7;4773:23;4769:32;4766:2;;;-1:-1;;4804:12;4766:2;85:6;72:20;97:33;124:5;97:33;:::i;:::-;4856:63;4956:2;4995:22;;;;3029:20;;-1:-1;;;4760:283::o;5050:491::-;;;;5188:2;5176:9;5167:7;5163:23;5159:32;5156:2;;;-1:-1;;5194:12;5156:2;85:6;72:20;97:33;124:5;97:33;:::i;:::-;5246:63;-1:-1;5346:2;5385:22;;3029:20;;-1:-1;5454:2;5493:22;;72:20;97:33;72:20;97:33;:::i;:::-;5462:63;;;;5150:391;;;;;:::o;5548:1025::-;;;;;;;;5772:3;5760:9;5751:7;5747:23;5743:33;5740:2;;;-1:-1;;5779:12;5740:2;85:6;72:20;97:33;124:5;97:33;:::i;:::-;5831:63;-1:-1;5931:2;5970:22;;3029:20;;-1:-1;6039:2;6078:22;;72:20;97:33;72:20;97:33;:::i;:::-;6047:63;-1:-1;6147:2;6186:22;;72:20;97:33;72:20;97:33;:::i;:::-;6155:63;-1:-1;6255:3;6295:22;;3029:20;;-1:-1;6392:3;6377:19;;6364:33;6417:18;6406:30;;6403:2;;;-1:-1;;6439:12;6403:2;6477:80;6549:7;6540:6;6529:9;6525:22;6477:80;:::i;:::-;5734:839;;;;-1:-1;5734:839;;-1:-1;5734:839;;;;6459:98;;-1:-1;;;5734:839::o;6580:879::-;;;;;;6777:3;6765:9;6756:7;6752:23;6748:33;6745:2;;;-1:-1;;6784:12;6745:2;85:6;72:20;97:33;124:5;97:33;:::i;:::-;6836:63;-1:-1;6936:2;6975:22;;3029:20;;-1:-1;7044:2;7083:22;;72:20;97:33;72:20;97:33;:::i;:::-;7052:63;-1:-1;7152:2;7191:22;;3029:20;;-1:-1;7288:3;7273:19;;7260:33;7313:18;7302:30;;7299:2;;;-1:-1;;7335:12;7299:2;7365:78;7435:7;7426:6;7415:9;7411:22;7365:78;:::i;:::-;7355:88;;;6739:720;;;;;;;;:::o;7466:678::-;;;;;7657:2;7645:9;7636:7;7632:23;7628:32;7625:2;;;-1:-1;;7663:12;7625:2;7721:17;7708:31;7759:18;;7751:6;7748:30;7745:2;;;-1:-1;;7781:12;7745:2;7819:80;7891:7;7882:6;7871:9;7867:22;7819:80;:::i;:::-;7801:98;;-1:-1;7801:98;-1:-1;7964:2;7949:18;;7936:32;;-1:-1;7977:30;;;7974:2;;;-1:-1;;8010:12;7974:2;;8048:80;8120:7;8111:6;8100:9;8096:22;8048:80;:::i;:::-;7619:525;;;;-1:-1;8030:98;-1:-1;;;;7619:525::o;8151:1151::-;;;;;;8398:3;8386:9;8377:7;8373:23;8369:33;8366:2;;;-1:-1;;8405:12;8366:2;8463:17;8450:31;8501:18;;8493:6;8490:30;8487:2;;;-1:-1;;8523:12;8487:2;8614:6;8603:9;8599:22;;;796:3;789:4;781:6;777:17;773:27;763:2;;-1:-1;;804:12;763:2;851:6;838:20;873:80;888:64;945:6;888:64;:::i;873:80::-;959:16;995:6;988:5;981:21;1025:4;;1042:3;1038:14;1031:21;;1025:4;1017:6;1013:17;1147:3;1025:4;;1131:6;1127:17;1017:6;1118:27;;1115:36;1112:2;;;-1:-1;;1154:12;1112:2;-1:-1;1180:10;;1174:206;1199:6;1196:1;1193:13;1174:206;;;1279:37;1312:3;1300:10;1279:37;:::i;:::-;1267:50;;1221:1;1214:9;;;;;1331:14;;;;1359;;1174:206;;;-1:-1;8543:88;;-1:-1;8681:18;;8668:32;;-1:-1;;;8709:30;;;8706:2;;;-1:-1;;8742:12;8706:2;8772:78;8842:7;8833:6;8822:9;8818:22;8772:78;:::i;:::-;8762:88;;8887:2;8930:9;8926:22;3029:20;8895:63;;9013:53;9058:7;8995:2;9038:9;9034:22;9013:53;:::i;:::-;9003:63;;9131:3;9120:9;9116:19;9103:33;9089:47;;8501:18;9148:6;9145:30;9142:2;;;-1:-1;;9178:12;9142:2;;9208:78;9278:7;9269:6;9258:9;9254:22;9208:78;:::i;9309:257::-;;9421:2;9409:9;9400:7;9396:23;9392:32;9389:2;;;-1:-1;;9427:12;9389:2;2586:6;2580:13;34504:5;32582:13;32575:21;34482:5;34479:32;34469:2;;-1:-1;;34515:12;9573:241;;9677:2;9665:9;9656:7;9652:23;9648:32;9645:2;;;-1:-1;;9683:12;9645:2;-1:-1;2707:20;;9639:175;-1:-1;9639:175::o;9821:366::-;;;9942:2;9930:9;9921:7;9917:23;9913:32;9910:2;;;-1:-1;;9948:12;9910:2;2720:6;2707:20;10000:63;;10100:2;10143:9;10139:22;72:20;97:33;124:5;97:33;:::i;10194:366::-;;;10315:2;10303:9;10294:7;10290:23;10286:32;10283:2;;;-1:-1;;10321:12;10283:2;-1:-1;;2707:20;;;10473:2;10512:22;;;3029:20;;-1:-1;10277:283::o;10567:263::-;;10682:2;10670:9;10661:7;10657:23;10653:32;10650:2;;;-1:-1;;10688:12;10650:2;-1:-1;3177:13;;10644:186;-1:-1;10644:186::o;19353:271::-;;12408:5;31493:12;12519:52;12564:6;12559:3;12552:4;12545:5;12541:16;12519:52;:::i;:::-;12583:16;;;;;19487:137;-1:-1;;19487:137::o;19631:222::-;-1:-1;;;;;32871:54;;;;11239:37;;19758:2;19743:18;;19729:124::o;20105:460::-;-1:-1;;;;;32871:54;;;11098:58;;32871:54;;;;20468:2;20453:18;;11239:37;20551:2;20536:18;;12199:37;;;;20296:2;20281:18;;20267:298::o;21023:940::-;-1:-1;;;;;32871:54;;;11239:37;;32871:54;;21511:2;21496:18;;;11239:37;;;;21594:2;21579:18;;12199:37;;;21677:2;21662:18;;12199:37;;;21346:3;21714;21699:19;;21692:49;;;31493:12;;21331:19;;;32025;;;-1:-1;;31347:14;;;;32065;;;;21511:2;-1:-1;11727:260;11752:6;11749:1;11746:13;11727:260;;;11813:13;;12199:37;;31880:14;;;;10991;;;;11774:1;11767:9;11727:260;;;11731:14;;;21747:116;;;;;33087:4;33080:5;33076:16;21948:3;21937:9;21933:19;12869:56;21317:646;;;;;;;;;:::o;21970:333::-;-1:-1;;;;;32871:54;;;;11239:37;;22289:2;22274:18;;12199:37;22125:2;22110:18;;22096:207::o;22310:210::-;32582:13;;32575:21;12082:34;;22431:2;22416:18;;22402:118::o;22527:222::-;12199:37;;;22654:2;22639:18;;22625:124::o;23033:310::-;;23180:2;23201:17;23194:47;13082:5;31493:12;32037:6;23180:2;23169:9;23165:18;32025:19;13176:52;13221:6;32065:14;23169:9;32065:14;23180:2;13202:5;13198:16;13176:52;:::i;:::-;34278:7;34262:14;-1:-1;;34258:28;13240:39;;;;32065:14;13240:39;;23151:192;-1:-1;;23151:192::o;23350:416::-;23550:2;23564:47;;;13516:2;23535:18;;;32025:19;13552:34;32065:14;;;13532:55;-1:-1;;;13607:12;;;13600:26;13645:12;;;23521:245::o;23773:416::-;23973:2;23987:47;;;13896:2;23958:18;;;32025:19;13932:34;32065:14;;;13912:55;-1:-1;;;13987:12;;;13980:39;14038:12;;;23944:245::o;24196:416::-;24396:2;24410:47;;;14289:2;24381:18;;;32025:19;-1:-1;;;32065:14;;;14305:43;14367:12;;;24367:245::o;24619:416::-;24819:2;24833:47;;;14618:2;24804:18;;;32025:19;14654:34;32065:14;;;14634:55;-1:-1;;;14709:12;;;14702:36;14757:12;;;24790:245::o;25042:416::-;25242:2;25256:47;;;15008:2;25227:18;;;32025:19;15044:29;32065:14;;;15024:50;15093:12;;;25213:245::o;25465:416::-;25665:2;25679:47;;;15344:2;25650:18;;;32025:19;15380:34;32065:14;;;15360:55;-1:-1;;;15435:12;;;15428:39;15486:12;;;25636:245::o;25888:416::-;26088:2;26102:47;;;15737:2;26073:18;;;32025:19;15773:28;32065:14;;;15753:49;15821:12;;;26059:245::o;26311:416::-;26511:2;26525:47;;;16072:2;26496:18;;;32025:19;16108:34;32065:14;;;16088:55;-1:-1;;;16163:12;;;16156:40;-1:-1;16215:12;;26482:245::o;26734:416::-;26934:2;26948:47;;;16466:2;26919:18;;;32025:19;-1:-1;;;32065:14;;;16482:39;16540:12;;;26905:245::o;27157:416::-;27357:2;27371:47;;;27342:18;;;32025:19;16827:34;32065:14;;;16807:55;16881:12;;;27328:245::o;27580:416::-;27780:2;27794:47;;;17132:2;27765:18;;;32025:19;-1:-1;;;32065:14;;;17148:44;17211:12;;;27751:245::o;28003:416::-;28203:2;28217:47;;;17462:2;28188:18;;;32025:19;17498:34;32065:14;;;17478:55;-1:-1;;;17553:12;;;17546:26;17591:12;;;28174:245::o;28426:416::-;28626:2;28640:47;;;17842:2;28611:18;;;32025:19;17878:34;32065:14;;;17858:55;-1:-1;;;17933:12;;;17926:38;17983:12;;;28597:245::o;28849:416::-;29049:2;29063:47;;;18234:2;29034:18;;;32025:19;18270:25;32065:14;;;18250:46;18315:12;;;29020:245::o;29272:416::-;29472:2;29486:47;;;18566:2;29457:18;;;32025:19;18602:34;32065:14;;;18582:55;-1:-1;;;18657:12;;;18650:35;18704:12;;;29443:245::o;29695:416::-;29895:2;29909:47;;;18955:2;29880:18;;;32025:19;18991:34;32065:14;;;18971:55;-1:-1;;;19046:12;;;19039:39;19097:12;;;29866:245::o;30347:256::-;30409:2;30403:9;30435:17;;;30510:18;30495:34;;30531:22;;;30492:62;30489:2;;;30567:1;;30557:12;30489:2;30409;30576:22;30387:216;;-1:-1;30387:216::o;30610:304::-;;30769:18;30761:6;30758:30;30755:2;;;-1:-1;;30791:12;30755:2;-1:-1;30836:4;30824:17;;;30889:15;;30692:222::o;33918:268::-;33983:1;33990:101;34004:6;34001:1;33998:13;33990:101;;;34071:11;;;34065:18;34052:11;;;34045:39;34026:2;34019:10;33990:101;;;34106:6;34103:1;34100:13;34097:2;;;33983:1;34162:6;34157:3;34153:16;34146:27;34097:2;;33967:219;;;:::o;34299:117::-;-1:-1;;;;;32871:54;;34358:35;;34348:2;;34407:1;;34397:12

Swarm Source

ipfs://89d425cc3f11864e9755ea9a5b456a5a7330c9e704a89cc1038a1c1b0c6e981d

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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

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