ETH Price: $3,245.23 (-0.42%)
Gas: 1 Gwei

Contract

0x361212F99a653B20AB6F8beDe07Cff8DeB5a5F28
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
0x60806040160792232022-11-30 0:28:23606 days ago1669768103IN
 Create: SeniorPool
0 ETH0.0465845910.50171488

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
SeniorPool

Compiler Version
v0.6.12+commit.27d51765

Optimization Enabled:
Yes with 100 runs

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

pragma solidity 0.6.12;

pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol";
import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import {Math} from "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import {IERC20} from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";

import {ISeniorPool} from "../../interfaces/ISeniorPool.sol";
import {IFidu} from "../../interfaces/IFidu.sol";
import {ISeniorPoolEpochWithdrawals} from "../../interfaces/ISeniorPoolEpochWithdrawals.sol";
import {IWithdrawalRequestToken} from "../../interfaces/IWithdrawalRequestToken.sol";
import {ISeniorPoolStrategy} from "../../interfaces/ISeniorPoolStrategy.sol";
import {ITranchedPool} from "../../interfaces/ITranchedPool.sol";
import {ICUSDCContract} from "../../interfaces/ICUSDCContract.sol";
import {IERC20withDec} from "../../interfaces/IERC20withDec.sol";
import {IPoolTokens} from "../../interfaces/IPoolTokens.sol";
import {Accountant} from "./Accountant.sol";
import {BaseUpgradeablePausable} from "./BaseUpgradeablePausable.sol";
import {ConfigHelper} from "./ConfigHelper.sol";
import {GoldfinchConfig} from "./GoldfinchConfig.sol";

/**
 * @title Goldfinch's SeniorPool contract
 * @notice Main entry point for senior LPs (a.k.a. capital providers)
 *  Automatically invests across borrower pools using an adjustable strategy.
 * @author Goldfinch
 */
contract SeniorPool is BaseUpgradeablePausable, ISeniorPool {
  using SignedSafeMath for int256;
  using Math for uint256;
  using SafeCast for uint256;
  using SafeCast for int256;
  using ConfigHelper for GoldfinchConfig;
  using SafeERC20 for IFidu;
  using SafeERC20 for IERC20withDec;

  uint256 internal constant USDC_MANTISSA = 1e6;
  uint256 internal constant FIDU_MANTISSA = 1e18;
  bytes32 public constant ZAPPER_ROLE = keccak256("ZAPPER_ROLE");

  /*================================================================================
    Storage
    ================================================================================*/

  GoldfinchConfig public config;

  /// @dev DEPRECATED!
  uint256 internal compoundBalance;

  /// @dev DEPRECATED, DO NOT USE.
  mapping(ITranchedPool => uint256) internal writedowns;

  /// @dev Writedowns by PoolToken id. This is used to ensure writedowns are incremental.
  ///   Example: At t1, a pool is late and should be written down by 10%. At t2, the pool
  ///   is even later, and should be written down by 25%. This variable helps ensure that
  ///   if writedowns occur at both t1 and t2, t2's writedown is only by the delta of 15%,
  ///   rather than double-counting the writedown percent from t1.
  mapping(uint256 => uint256) public writedownsByPoolToken;

  uint256 internal _checkpointedEpochId;
  mapping(uint256 => Epoch) internal _epochs;
  mapping(uint256 => WithdrawalRequest) internal _withdrawalRequests;
  /// @dev Tracks usdc available for investments, zaps, withdrawal allocations etc. Due to the time
  /// based nature of epochs, if the last epoch has ended but isn't checkpointed yet then this var
  /// doesn't reflect the true usdc available at the current timestamp. To query for the up to date
  /// usdc available without having to execute a tx, use the usdcAvailable() view fn
  uint256 internal _usdcAvailable;
  uint256 internal _epochDuration;

  /*================================================================================
    Initialization Functions
    ================================================================================*/

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

    __BaseUpgradeablePausable__init(owner);
    _setRoleAdmin(ZAPPER_ROLE, OWNER_ROLE);

    config = _config;
    sharePrice = FIDU_MANTISSA;
    totalLoansOutstanding = 0;
    totalWritedowns = 0;
  }

  /*================================================================================
  Admin Functions
  ================================================================================*/

  /**
   * @inheritdoc ISeniorPoolEpochWithdrawals
   * @dev Triggers a checkpoint
   */
  function setEpochDuration(uint256 newEpochDuration) external override onlyAdmin {
    require(newEpochDuration > 0, "Zero duration");
    Epoch storage headEpoch = _applyEpochCheckpoints();
    // When we're updating the epoch duration we need to update the head epoch endsAt
    // time to be the new epoch duration
    if (headEpoch.endsAt > block.timestamp) {
      /*
      This codepath happens when we successfully finalize the previous epoch. This results
      in a timestamp in the future. In this case we need to account for no-op epochs that
      would be created by setting the duration to a value less than the previous epoch.
      */

      uint256 previousEpochEndsAt = headEpoch.endsAt.sub(_epochDuration);
      _epochDuration = newEpochDuration;
      headEpoch.endsAt = _mostRecentEndsAtAfter(previousEpochEndsAt).add(newEpochDuration);
      assert(headEpoch.endsAt > block.timestamp);
    } else {
      headEpoch.endsAt = _mostRecentEndsAtAfter(headEpoch.endsAt).add(newEpochDuration);
    }
    _epochDuration = newEpochDuration;
    emit EpochDurationChanged(newEpochDuration);
  }

  /**
   * @notice Initialize the epoch withdrawal system. This includes writing the
   *          initial epoch and snapshotting usdcAvailable at the current usdc balance of
   *          the senior pool.
   */
  function initializeEpochs() external onlyAdmin {
    require(_epochs[0].endsAt == 0);
    _epochDuration = 2 weeks;
    _usdcAvailable = config.getUSDC().balanceOf(address(this));
    _epochs[0].endsAt = block.timestamp;
    _applyInitializeNextEpochFrom(_epochs[0]);
  }

  /*================================================================================
    LP functions
    ================================================================================*/

  // External Functions
  //--------------------------------------------------------------------------------

  /**
   * @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the
   *  equivalent value of FIDU tokens
   * @param amount The amount of USDC to deposit
   */
  function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) {
    require(config.getGo().goSeniorPool(msg.sender), "NA");
    require(amount > 0, "Must deposit more than zero");
    _applyEpochCheckpoints();
    _usdcAvailable = _usdcAvailable.add(amount);
    // Check if the amount of new shares to be added is within limits
    depositShares = getNumShares(amount);
    emit DepositMade(msg.sender, amount, depositShares);
    require(config.getUSDC().transferFrom(msg.sender, address(this), amount), "Failed to transfer for deposit");

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

  /**
   * @notice Identical to deposit, except it allows for a passed up signature to permit
   *  the Senior Pool to move funds on behalf of the user, all within one transaction.
   * @param amount The amount of USDC to deposit
   * @param v secp256k1 signature component
   * @param r secp256k1 signature component
   * @param s secp256k1 signature component
   */
  function depositWithPermit(
    uint256 amount,
    uint256 deadline,
    uint8 v,
    bytes32 r,
    bytes32 s
  ) external override returns (uint256 depositShares) {
    IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
    return deposit(amount);
  }

  /**
   * @inheritdoc ISeniorPoolEpochWithdrawals
   * @dev Reverts if a withdrawal with the given tokenId does not exist
   * @dev Reverts if the caller is not the owner of the given token
   * @dev Triggers a checkpoint
   */
  function addToWithdrawalRequest(uint256 fiduAmount, uint256 tokenId) external override whenNotPaused nonReentrant {
    require(config.getGo().goSeniorPool(msg.sender), "NA");
    IWithdrawalRequestToken requestTokens = config.getWithdrawalRequestToken();
    require(msg.sender == requestTokens.ownerOf(tokenId), "NA");

    (Epoch storage thisEpoch, WithdrawalRequest storage request) = _applyEpochAndRequestCheckpoints(tokenId);

    request.fiduRequested = request.fiduRequested.add(fiduAmount);
    thisEpoch.fiduRequested = thisEpoch.fiduRequested.add(fiduAmount);

    emit WithdrawalAddedTo({
      epochId: _checkpointedEpochId,
      tokenId: tokenId,
      operator: msg.sender,
      fiduRequested: fiduAmount
    });

    config.getFidu().safeTransferFrom(msg.sender, address(this), fiduAmount);
  }

  /**
   * @inheritdoc ISeniorPoolEpochWithdrawals
   * @dev triggers a checkpoint
   */
  function requestWithdrawal(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256) {
    IWithdrawalRequestToken requestTokens = config.getWithdrawalRequestToken();
    require(config.getGo().goSeniorPool(msg.sender), "NA");
    require(requestTokens.balanceOf(msg.sender) == 0, "Existing request");
    Epoch storage thisEpoch = _applyEpochCheckpoints();

    uint256 tokenId = requestTokens.mint(msg.sender);

    WithdrawalRequest storage request = _withdrawalRequests[tokenId];

    request.epochCursor = _checkpointedEpochId;
    request.fiduRequested = fiduAmount;

    thisEpoch.fiduRequested = thisEpoch.fiduRequested.add(fiduAmount);
    config.getFidu().safeTransferFrom(msg.sender, address(this), fiduAmount);

    emit WithdrawalRequested(_checkpointedEpochId, tokenId, msg.sender, fiduAmount);
    return tokenId;
  }

  /**
   * @inheritdoc ISeniorPoolEpochWithdrawals
   * @dev triggers a checkpoint
   */
  function cancelWithdrawalRequest(uint256 tokenId) external override whenNotPaused nonReentrant returns (uint256) {
    require(config.getGo().goSeniorPool(msg.sender), "NA");
    require(msg.sender == config.getWithdrawalRequestToken().ownerOf(tokenId), "NA");

    (Epoch storage thisEpoch, WithdrawalRequest storage request) = _applyEpochAndRequestCheckpoints(tokenId);
    require(request.fiduRequested != 0, "Cant cancel");

    uint256 reserveBps = config.getSeniorPoolWithdrawalCancelationFeeInBps();
    require(reserveBps <= 10_000, "Invalid Bps");
    uint256 reserveFidu = request.fiduRequested.mul(reserveBps).div(10_000);
    uint256 userFidu = request.fiduRequested.sub(reserveFidu);

    thisEpoch.fiduRequested = thisEpoch.fiduRequested.sub(request.fiduRequested);
    request.fiduRequested = 0;

    // only delete the withdraw request if there is no more possible value to be added
    if (request.usdcWithdrawable == 0) {
      _burnWithdrawRequest(tokenId);
    }
    config.getFidu().safeTransfer(msg.sender, userFidu);

    address reserve = config.protocolAdminAddress();
    config.getFidu().safeTransfer(reserve, reserveFidu);

    emit ReserveSharesCollected(msg.sender, reserve, reserveFidu);
    emit WithdrawalCanceled(_checkpointedEpochId, tokenId, msg.sender, userFidu, reserveFidu);
    return userFidu;
  }

  /**
   * @inheritdoc ISeniorPoolEpochWithdrawals
   * @dev triggers a checkpoint
   */
  function claimWithdrawalRequest(uint256 tokenId) external override whenNotPaused nonReentrant returns (uint256) {
    require(config.getGo().goSeniorPool(msg.sender), "NA");
    require(msg.sender == config.getWithdrawalRequestToken().ownerOf(tokenId), "NA");
    (, WithdrawalRequest storage request) = _applyEpochAndRequestCheckpoints(tokenId);

    uint256 totalUsdcAmount = request.usdcWithdrawable;
    request.usdcWithdrawable = 0;
    uint256 reserveAmount = totalUsdcAmount.div(config.getWithdrawFeeDenominator());
    uint256 userAmount = totalUsdcAmount.sub(reserveAmount);

    // if there is no outstanding FIDU, burn the token
    if (request.fiduRequested == 0) {
      _burnWithdrawRequest(tokenId);
    }

    _sendToReserve(reserveAmount, msg.sender);
    config.getUSDC().safeTransfer(msg.sender, userAmount);

    emit WithdrawalMade(msg.sender, userAmount, reserveAmount);

    return userAmount;
  }

  // view functions
  //--------------------------------------------------------------------------------

  /// @inheritdoc ISeniorPoolEpochWithdrawals
  function epochDuration() external view override returns (uint256) {
    return _epochDuration;
  }

  /// @inheritdoc ISeniorPoolEpochWithdrawals
  function withdrawalRequest(uint256 tokenId) external view override returns (WithdrawalRequest memory) {
    // This call will revert if the tokenId does not exist
    config.getWithdrawalRequestToken().ownerOf(tokenId);
    WithdrawalRequest storage wr = _withdrawalRequests[tokenId];
    return _previewWithdrawRequestCheckpoint(wr);
  }

  // internal view functions
  //--------------------------------------------------------------------------------

  /**
   * @notice Preview the effects of attempting to checkpoint a given epoch. If
   *         the epoch doesn't need to be checkpointed then the same epoch will be return
   *          along with a bool indicated it didn't need to be checkpointed.
   * @param epoch epoch to checkpoint
   * @return maybeCheckpointedEpoch the checkpointed epoch if the epoch was
   *                                  able to be checkpointed, otherwise the same epoch
   * @return epochStatus If the epoch can't be finalized, returns `Unapplied`.
   *                      If the Epoch is after the end time of the epoch the epoch will be extended.
   *                      An extended epoch will have its endTime set to the next endtime but won't
   *                      have any usdc allocated to it. If the epoch can be finalized and its after
   *                      the end time, it will have usdc allocated to it.
   */
  function _previewEpochCheckpoint(Epoch memory epoch) internal view returns (Epoch memory, EpochCheckpointStatus) {
    if (block.timestamp < epoch.endsAt) {
      return (epoch, EpochCheckpointStatus.Unapplied);
    }

    // After this point block.timestamp >= epoch.endsAt

    uint256 usdcNeededToFullyLiquidate = _getUSDCAmountFromShares(epoch.fiduRequested);
    epoch.endsAt = _mostRecentEndsAtAfter(epoch.endsAt);
    /*
    If usdc available is zero for an epoch, or the epoch's usdc equivalent
    of its fidu requested is zero, then the epoch is extended instead of finalized.
    Why? Because if usdc available is zero then we can't liquidate any fidu,
    and if the fidu requested is zero (in usdc terms) then there's no need to
    allocate usdc. 
    */
    if (_usdcAvailable == 0 || usdcNeededToFullyLiquidate == 0) {
      // When we extend the epoch, we need to add an additional epoch to the end so that
      // the next time a checkpoint happens it won't immediately finalize the epoch
      epoch.endsAt = epoch.endsAt.add(_epochDuration);
      return (epoch, EpochCheckpointStatus.Extended);
    }

    // finalize epoch
    uint256 usdcAllocated = _usdcAvailable.min(usdcNeededToFullyLiquidate);
    uint256 fiduLiquidated = getNumShares(usdcAllocated);
    epoch.fiduLiquidated = fiduLiquidated;
    epoch.usdcAllocated = usdcAllocated;
    return (epoch, EpochCheckpointStatus.Finalized);
  }

  /// @notice Returns the most recent, uncheckpointed epoch
  function _headEpoch() internal view returns (Epoch storage) {
    return _epochs[_checkpointedEpochId];
  }

  /// @notice Returns the state of a withdraw request after checkpointing
  function _previewWithdrawRequestCheckpoint(WithdrawalRequest memory wr)
    internal
    view
    returns (WithdrawalRequest memory)
  {
    Epoch memory epoch;
    // Iterate through each epoch, calculating the amount of USDC that would be
    // allocated to the withdraw request by using the proportion of FIDU the
    // withdraw request had in that epoch and subtracting the allocation from
    // the withdraw request.
    for (uint256 i = wr.epochCursor; i <= _checkpointedEpochId && wr.fiduRequested > 0; ++i) {
      epoch = _epochs[i];

      // The withdraw request could have FIDU in the most recent, non-finalized-
      // epoch, and so we need to apply the checkpoint to get an accurate count
      if (i == _checkpointedEpochId) {
        (epoch, ) = _previewEpochCheckpoint(epoch);
      }
      uint256 proRataUsdc = epoch.usdcAllocated.mul(wr.fiduRequested).div(epoch.fiduRequested);
      uint256 fiduLiquidated = epoch.fiduLiquidated.mul(wr.fiduRequested).div(epoch.fiduRequested);
      wr.fiduRequested = wr.fiduRequested.sub(fiduLiquidated);
      wr.usdcWithdrawable = wr.usdcWithdrawable.add(proRataUsdc);

      if (epoch.fiduLiquidated != 0) {
        /*
        If the user's outstanding fiduAmount, when claimed, would result in them
        receiving no usdc amount because of loss of precision in conversion we
        just zero out the request so when they claim they don't need to
        unnecessarily iterate through many epochs where they receive nothing.

        The sum of the withdraw request that are "dust" (would result in 0 usdc)
        may result in a non zero usdc allocation at the epoch level. USDC will
        be allocated to these "dusty" requests, but the very small amount of
        usdc will not be claimable by anyone.
        */
        uint256 epochSharePrice = epoch.usdcAllocated.mul(FIDU_MANTISSA).mul(1e12).div(epoch.fiduLiquidated);
        bool noUsdcValueRemainingInRequest = _getUSDCAmountFromShares(wr.fiduRequested, epochSharePrice) == 0;
        if (noUsdcValueRemainingInRequest) {
          wr.fiduRequested = 0;
        }
      }
    }
    wr.epochCursor = _checkpointedEpochId;

    return wr;
  }

  /**
   * @notice Returns the most recent time an epoch would end assuming the current epoch duration
   *          and the starting point of `endsAt`.
   * @param endsAt basis for calculating the most recent endsAt time
   * @return mostRecentEndsAt The most recent endsAt
   */
  function _mostRecentEndsAtAfter(uint256 endsAt) internal view returns (uint256) {
    // if multiple epochs have passed since checkpointing, update the endtime
    // and emit many events so that we don't need to write a bunch of useless epochs
    uint256 nopEpochsElapsed = block.timestamp.sub(endsAt).div(_epochDuration);
    // update the last epoch timestamp to the timestamp of the most recently ended epoch
    return endsAt.add(nopEpochsElapsed.mul(_epochDuration));
  }

  // internal functions
  //--------------------------------------------------------------------------------

  function _sendToReserve(uint256 amount, address userForEvent) internal {
    emit ReserveFundsCollected(userForEvent, amount);
    config.getUSDC().safeTransfer(config.reserveAddress(), amount);
  }

  /**
   * @notice Initialize the next epoch using a given epoch by carrying forward its oustanding fidu
   */
  function _applyInitializeNextEpochFrom(Epoch storage previousEpoch) internal returns (Epoch storage) {
    _epochs[++_checkpointedEpochId] = _initializeNextEpochFrom(previousEpoch);
    return _epochs[_checkpointedEpochId];
  }

  function _initializeNextEpochFrom(Epoch memory previousEpoch) internal view returns (Epoch memory) {
    Epoch memory nextEpoch;
    nextEpoch.endsAt = previousEpoch.endsAt.add(_epochDuration);
    uint256 fiduToCarryOverFromLastEpoch = previousEpoch.fiduRequested.sub(previousEpoch.fiduLiquidated);
    nextEpoch.fiduRequested = fiduToCarryOverFromLastEpoch;
    return nextEpoch;
  }

  /// @notice Increment _checkpointedEpochId cursor up to the current epoch
  function _applyEpochCheckpoints() private returns (Epoch storage) {
    return _applyEpochCheckpoint(_headEpoch());
  }

  function _applyWithdrawalRequestCheckpoint(uint256 tokenId) internal returns (WithdrawalRequest storage) {
    WithdrawalRequest storage wr = _withdrawalRequests[tokenId];
    Epoch storage epoch;

    for (uint256 i = wr.epochCursor; i < _checkpointedEpochId && wr.fiduRequested > 0; i++) {
      epoch = _epochs[i];
      uint256 proRataUsdc = epoch.usdcAllocated.mul(wr.fiduRequested).div(epoch.fiduRequested);
      uint256 fiduLiquidated = epoch.fiduLiquidated.mul(wr.fiduRequested).div(epoch.fiduRequested);
      wr.fiduRequested = wr.fiduRequested.sub(fiduLiquidated);
      wr.usdcWithdrawable = wr.usdcWithdrawable.add(proRataUsdc);

      /*
      If the user's outstanding fiduAmount, when claimed, would result in them
      receiving no usdc amount because of loss of precision in conversion we
      just zero out the request so when they claim they don't need to
      unnecessarily iterate through many epochs where they receive nothing.

      At the epoch level, the sum of the withdraw request that are "dust" (would
      result in 0 usdc) may result in a non zero usdc allocation at the epoch
      level. USDC will be allocated to these "dusty" requests, but the very
      small amount of usdc will not be claimable by anyone.
      */
      uint256 epochSharePrice = epoch.usdcAllocated.mul(FIDU_MANTISSA).mul(1e12).div(epoch.fiduLiquidated);
      bool noUsdcValueRemainingInRequest = _getUSDCAmountFromShares(wr.fiduRequested, epochSharePrice) == 0;
      if (noUsdcValueRemainingInRequest) {
        wr.fiduRequested = 0;
      }
    }

    // Update a fully liquidated request's cursor. Otherwise new fiduRequested would be applied to liquidated
    // epochs that the request was not part of.
    wr.epochCursor = _checkpointedEpochId;
    return wr;
  }

  function _applyEpochAndRequestCheckpoints(uint256 tokenId)
    internal
    returns (Epoch storage, WithdrawalRequest storage)
  {
    Epoch storage headEpoch = _applyEpochCheckpoints();
    WithdrawalRequest storage wr = _applyWithdrawalRequestCheckpoint(tokenId);
    return (headEpoch, wr);
  }

  /**
   * @notice Checkpoint an epoch, returning the same epoch if it doesn't need
   * to be checkpointed or a newly initialized epoch if the given epoch was
   * successfully checkpointed. In other words, return the most current epoch
   * @dev To decrease storage writes we have introduced optimizations based on two observations
   *      1. If block.timestamp < endsAt, then the epoch is unchanged and we can return
   *       the unmodified epoch (checkpointStatus == Unappled).
   *      2. If the epoch has ended but its fiduRequested is 0 OR the senior pool's usdcAvailable
   *       is 0, then the next epoch will have the SAME fiduRequested, and the only variable we have to update
   *       is endsAt (chekpointStatus == Extended).
   * @param epoch epoch to checkpoint
   * @return currentEpoch current epoch
   */
  function _applyEpochCheckpoint(Epoch storage epoch) internal returns (Epoch storage) {
    (Epoch memory checkpointedEpoch, EpochCheckpointStatus checkpointStatus) = _previewEpochCheckpoint(epoch);
    if (checkpointStatus == EpochCheckpointStatus.Unapplied) {
      return epoch;
    } else if (checkpointStatus == EpochCheckpointStatus.Extended) {
      uint256 oldEndsAt = epoch.endsAt;
      epoch.endsAt = checkpointedEpoch.endsAt;
      emit EpochExtended(_checkpointedEpochId, epoch.endsAt, oldEndsAt);
      return epoch;
    } else {
      // copy checkpointed data
      epoch.fiduLiquidated = checkpointedEpoch.fiduLiquidated;
      epoch.usdcAllocated = checkpointedEpoch.usdcAllocated;
      epoch.endsAt = checkpointedEpoch.endsAt;

      _usdcAvailable = _usdcAvailable.sub(epoch.usdcAllocated);
      uint256 endingEpochId = _checkpointedEpochId;
      Epoch storage newEpoch = _applyInitializeNextEpochFrom(epoch);
      config.getFidu().burnFrom(address(this), epoch.fiduLiquidated);

      emit EpochEnded(endingEpochId, epoch.endsAt, epoch.fiduRequested, epoch.usdcAllocated, epoch.fiduLiquidated);
      return newEpoch;
    }
  }

  function _burnWithdrawRequest(uint256 tokenId) internal {
    delete _withdrawalRequests[tokenId];
    config.getWithdrawalRequestToken().burn(tokenId);
  }

  /*================================================================================
    Zapper Withdraw
    ================================================================================*/
  /**
   * @notice Withdraws USDC from the SeniorPool 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
    onlyZapper
    returns (uint256 amount)
  {
    require(usdcAmount > 0, "Must withdraw more than zero");
    uint256 withdrawShares = getNumShares(usdcAmount);
    return _withdraw(usdcAmount, withdrawShares);
  }

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

  // Zapper Withdraw: Internal functions
  //--------------------------------------------------------------------------------
  function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal returns (uint256 userAmount) {
    _applyEpochCheckpoints();
    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");

    _usdcAvailable = _usdcAvailable.sub(usdcAmount, "IB");
    // Send to reserves
    userAmount = usdcAmount;

    // Send to user
    config.getUSDC().safeTransfer(msg.sender, usdcAmount);

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

    emit WithdrawalMade(msg.sender, userAmount, 0);

    return userAmount;
  }

  /*================================================================================
    Asset Management
    ----------------
    functions related to investing, writing off, and redeeming assets
    ================================================================================*/

  // External functions
  //--------------------------------------------------------------------------------

  /**
   * @notice Invest in an ITranchedPool's senior tranche using the senior pool's strategy
   * @param pool An ITranchedPool whose senior tranche should be considered for investment
   */
  function invest(ITranchedPool pool) external override whenNotPaused nonReentrant returns (uint256) {
    require(_isValidPool(pool), "Pool must be valid");
    _applyEpochCheckpoints();

    ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
    uint256 amount = strategy.invest(this, pool);

    require(amount > 0, "Investment amount must be positive");
    require(amount <= _usdcAvailable, "not enough usdc");

    _usdcAvailable = _usdcAvailable.sub(amount);

    _approvePool(pool, amount);
    uint256 nSlices = pool.numSlices();
    require(nSlices >= 1, "Pool has no slices");
    uint256 sliceIndex = nSlices.sub(1);
    uint256 seniorTrancheId = _sliceIndexToSeniorTrancheId(sliceIndex);
    totalLoansOutstanding = totalLoansOutstanding.add(amount);
    uint256 poolToken = pool.deposit(seniorTrancheId, amount);

    emit InvestmentMadeInSenior(address(pool), amount);

    return poolToken;
  }

  /**
   * @notice Redeem interest and/or principal from an ITranchedPool investment
   * @param tokenId the ID of an IPoolTokens token to be redeemed
   * @dev triggers a checkpoint
   */
  function redeem(uint256 tokenId) external override whenNotPaused nonReentrant {
    _applyEpochCheckpoints();
    IPoolTokens poolTokens = config.getPoolTokens();
    IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);

    ITranchedPool pool = ITranchedPool(tokenInfo.pool);
    (uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId);

    _collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed);
  }

  /**
   * @notice Write down an ITranchedPool investment. This will adjust the senior pool's share price
   *  down if we're considering the investment a loss, or up if the borrower has subsequently
   *  made repayments that restore confidence that the full loan will be repaid.
   * @param tokenId the ID of an IPoolTokens token to be considered for writedown
   * @dev triggers a checkpoint
   */
  function writedown(uint256 tokenId) external override whenNotPaused nonReentrant {
    IPoolTokens poolTokens = config.getPoolTokens();
    require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior pool can be written down");

    IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
    ITranchedPool pool = ITranchedPool(tokenInfo.pool);
    require(_isValidPool(pool), "Pool must be valid");
    _applyEpochCheckpoints();

    // Assess the pool first in case it has unapplied USDC in its credit line
    pool.assess();

    uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);

    (uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);

    uint256 prevWritedownAmount = writedownsByPoolToken[tokenId];

    if (writedownPercent == 0 && prevWritedownAmount == 0) {
      return;
    }

    int256 writedownDelta = prevWritedownAmount.toInt256().sub(writedownAmount.toInt256());
    writedownsByPoolToken[tokenId] = writedownAmount;
    _distributeLosses(writedownDelta);
    if (writedownDelta > 0) {
      // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns.
      totalWritedowns = totalWritedowns.sub(writedownDelta.toUint256());
    } else {
      totalWritedowns = totalWritedowns.add((writedownDelta * -1).toUint256());
    }
    emit PrincipalWrittenDown(address(pool), writedownDelta);
  }

  // View Functions
  //--------------------------------------------------------------------------------

  /// @inheritdoc ISeniorPoolEpochWithdrawals
  function usdcAvailable() public view override returns (uint256) {
    (Epoch memory e, ) = _previewEpochCheckpoint(_headEpoch());
    uint256 usdcThatWillBeAllocatedToLatestEpoch = e.usdcAllocated;
    return _usdcAvailable.sub(usdcThatWillBeAllocatedToLatestEpoch);
  }

  /// @inheritdoc ISeniorPoolEpochWithdrawals
  function currentEpoch() external view override returns (Epoch memory) {
    (Epoch memory e, EpochCheckpointStatus checkpointStatus) = _previewEpochCheckpoint(_headEpoch());
    if (checkpointStatus == EpochCheckpointStatus.Finalized) e = _initializeNextEpochFrom(e);
    return e;
  }

  /**
   * @notice Returns the net assests controlled by and owed to the pool
   */
  function assets() external view override returns (uint256) {
    return usdcAvailable().add(totalLoansOutstanding).sub(totalWritedowns);
  }

  /**
   * @notice Returns the number of shares outstanding, accounting for shares that will be burned
   *          when an epoch checkpoint happens
   */
  function sharesOutstanding() external view override returns (uint256) {
    (Epoch memory e, ) = _previewEpochCheckpoint(_headEpoch());
    uint256 fiduThatWillBeBurnedOnCheckpoint = e.fiduLiquidated;
    return config.getFidu().totalSupply().sub(fiduThatWillBeBurnedOnCheckpoint);
  }

  function getNumShares(uint256 usdcAmount) public view override returns (uint256) {
    return _getNumShares(usdcAmount, sharePrice);
  }

  function estimateInvestment(ITranchedPool pool) external view override returns (uint256) {
    require(_isValidPool(pool), "Pool must be valid");
    ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
    return strategy.estimateInvestment(this, pool);
  }

  /**
   * @notice Calculates the writedown amount for a particular pool position
   * @param tokenId The token reprsenting the position
   * @return The amount in dollars the principal should be written down by
   */
  function calculateWritedown(uint256 tokenId) external view override returns (uint256) {
    IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
    ITranchedPool pool = ITranchedPool(tokenInfo.pool);

    uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);

    (, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);
    return writedownAmount;
  }

  // Internal functions
  //--------------------------------------------------------------------------------

  function _getNumShares(uint256 _usdcAmount, uint256 _sharePrice) internal pure returns (uint256) {
    return _usdcToFidu(_usdcAmount).mul(FIDU_MANTISSA).div(_sharePrice);
  }

  function _calculateWritedown(ITranchedPool pool, uint256 principal)
    internal
    view
    returns (uint256 writedownPercent, uint256 writedownAmount)
  {
    return
      Accountant.calculateWritedownForPrincipal(
        pool.creditLine(),
        principal,
        block.timestamp,
        config.getLatenessGracePeriodInDays(),
        config.getLatenessMaxDays()
      );
  }

  function _distributeLosses(int256 writedownDelta) internal {
    _applyEpochCheckpoints();
    if (writedownDelta > 0) {
      uint256 delta = _usdcToSharePrice(writedownDelta.toUint256());
      sharePrice = sharePrice.add(delta);
    } else {
      // If delta is negative, convert to positive uint, and sub from sharePrice
      uint256 delta = _usdcToSharePrice((writedownDelta * -1).toUint256());
      sharePrice = sharePrice.sub(delta);
    }
  }

  function _collectInterestAndPrincipal(
    address from,
    uint256 interest,
    uint256 principal
  ) internal {
    uint256 increment = _usdcToSharePrice(interest);
    sharePrice = sharePrice.add(increment);

    if (interest > 0) {
      emit InterestCollected(from, interest);
    }
    if (principal > 0) {
      emit PrincipalCollected(from, principal);
      totalLoansOutstanding = totalLoansOutstanding.sub(principal);
    }
    _usdcAvailable = _usdcAvailable.add(interest).add(principal);
  }

  function _isValidPool(ITranchedPool pool) internal view returns (bool) {
    return config.getPoolTokens().validPool(address(pool));
  }

  function _approvePool(ITranchedPool pool, uint256 allowance) internal {
    IERC20withDec usdc = config.getUSDC();
    require(usdc.approve(address(pool), allowance));
  }

  /*================================================================================
    General Internal Functions
    ================================================================================*/

  function _usdcToFidu(uint256 amount) internal pure returns (uint256) {
    return amount.mul(FIDU_MANTISSA).div(USDC_MANTISSA);
  }

  function _fiduToUsdc(uint256 amount) internal pure returns (uint256) {
    return amount.div(FIDU_MANTISSA.div(USDC_MANTISSA));
  }

  function _getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) {
    return _getUSDCAmountFromShares(fiduAmount, sharePrice);
  }

  function _getUSDCAmountFromShares(uint256 _fiduAmount, uint256 _sharePrice) internal pure returns (uint256) {
    return _fiduToUsdc(_fiduAmount.mul(_sharePrice)).div(FIDU_MANTISSA);
  }

  function _usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) {
    return _usdcToFidu(usdcAmount).mul(FIDU_MANTISSA).div(_totalShares());
  }

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

  /// @notice Returns the senion tranche id for the given slice index
  /// @param index slice index
  /// @return senior tranche id of given slice index
  function _sliceIndexToSeniorTrancheId(uint256 index) internal pure returns (uint256) {
    return index.mul(2).add(1);
  }

  modifier onlyZapper() {
    require(hasRole(ZAPPER_ROLE, msg.sender), "Not Zapper");
    _;
  }

  enum EpochCheckpointStatus {
    Unapplied,
    Extended,
    Finalized
  }
}

File 2 of 48 : 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 3 of 48 : 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 4 of 48 : 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 5 of 48 : 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 6 of 48 : 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 7 of 48 : 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 8 of 48 : 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 9 of 48 : SafeERC20.sol
pragma solidity ^0.6.0;

import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";

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

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

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

    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        // solhint-disable-next-line max-line-length
        require((value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

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

    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

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

        // A Solidity high level call has three parts:
        //  1. The target address is checked to verify it contains contract code
        //  2. The call itself is made, and success asserted
        //  3. The return value is decoded, which in turn checks the size of the returned data.
        // solhint-disable-next-line max-line-length
        require(address(token).isContract(), "SafeERC20: call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = address(token).call(data);
        require(success, "SafeERC20: low-level call failed");

        if (returndata.length > 0) { // Return data is optional
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 10 of 48 : 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 11 of 48 : 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 12 of 48 : 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 13 of 48 : 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 48 : IERC20Permit.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

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

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

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

File 15 of 48 : SafeMath.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.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, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        uint256 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b > a) return (false, 0);
        return (true, a - b);
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
        uint256 c = a * b;
        if (c / a != b) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a / b);
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a % b);
    }

    /**
     * @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) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @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) {
        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, reverting 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) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting 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) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * 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);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * 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) {
        require(b > 0, errorMessage);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * 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 16 of 48 : SignedSafeMath.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

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

    /**
     * @dev Returns the multiplication of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot 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 Returns the integer division of two signed 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(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 Returns the subtraction of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot 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 Returns the addition of two signed integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot 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 17 of 48 : Address.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.2 <0.8.0;

/**
 * @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) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

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

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

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain`call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
      return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 18 of 48 : SafeCast.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;


/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such 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.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128) {
        require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
        return int128(value);
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64) {
        require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
        return int64(value);
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32) {
        require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
        return int32(value);
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16) {
        require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
        return int16(value);
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8) {
        require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
        return int8(value);
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        require(value < 2**255, "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 19 of 48 : FixedPoint.sol
// SPDX-License-Identifier: AGPL-3.0-only
// solhint-disable
// Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

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 20 of 48 : IBackerRewards.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;

pragma experimental ABIEncoderV2;

interface IBackerRewards {
  function allocateRewards(uint256 _interestPaymentAmount) external;

  function onTranchedPoolDrawdown(uint256 sliceIndex) external;

  function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external;
}

File 21 of 48 : 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;
pragma experimental ABIEncoderV2;

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 22 of 48 : ICreditLine.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

interface ICreditLine {
  function borrower() external view returns (address);

  function limit() external view returns (uint256);

  function maxLimit() external view returns (uint256);

  function interestApr() external view returns (uint256);

  function paymentPeriodInDays() external view returns (uint256);

  function principalGracePeriodInDays() external view returns (uint256);

  function termInDays() external view returns (uint256);

  function lateFeeApr() external view returns (uint256);

  function isLate() external view returns (bool);

  function withinPrincipalGracePeriod() external view returns (bool);

  // Accounting variables
  function balance() external view returns (uint256);

  function interestOwed() external view returns (uint256);

  function principalOwed() external view returns (uint256);

  function termEndTime() external view returns (uint256);

  function nextDueTime() external view returns (uint256);

  function interestAccruedAsOf() external view returns (uint256);

  function lastFullPaymentTime() external view returns (uint256);
}

File 23 of 48 : ICurveLP.sol
// SPDX-License-Identifier: MIT
// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

interface ICurveLP {
  function coins(uint256) external view returns (address);

  function token() external view returns (address);

  function calc_token_amount(uint256[2] calldata amounts) external view returns (uint256);

  function lp_price() external view returns (uint256);

  function add_liquidity(
    uint256[2] calldata amounts,
    uint256 min_mint_amount,
    bool use_eth,
    address receiver
  ) external returns (uint256);

  function remove_liquidity(uint256 _amount, uint256[2] calldata min_amounts) external returns (uint256);

  function remove_liquidity_one_coin(
    uint256 token_amount,
    uint256 i,
    uint256 min_amount
  ) external returns (uint256);

  function get_dy(
    uint256 i,
    uint256 j,
    uint256 dx
  ) external view returns (uint256);

  function exchange(
    uint256 i,
    uint256 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  function balances(uint256 arg0) external view returns (uint256);
}

File 24 of 48 : IERC20withDec.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import {IERC20} from "@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 25 of 48 : IFidu.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import "./IERC20withDec.sol";

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

  function burnFrom(address to, uint256 amount) external;

  function renounceRole(bytes32 role, address account) external;
}

File 26 of 48 : IGo.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

abstract contract IGo {
  uint256 public constant ID_TYPE_0 = 0;
  uint256 public constant ID_TYPE_1 = 1;
  uint256 public constant ID_TYPE_2 = 2;
  uint256 public constant ID_TYPE_3 = 3;
  uint256 public constant ID_TYPE_4 = 4;
  uint256 public constant ID_TYPE_5 = 5;
  uint256 public constant ID_TYPE_6 = 6;
  uint256 public constant ID_TYPE_7 = 7;
  uint256 public constant ID_TYPE_8 = 8;
  uint256 public constant ID_TYPE_9 = 9;
  uint256 public constant ID_TYPE_10 = 10;

  /// @notice Returns the address of the UniqueIdentity contract.
  function uniqueIdentity() external virtual returns (address);

  function go(address account) public view virtual returns (bool);

  function goOnlyIdTypes(address account, uint256[] calldata onlyIdTypes) public view virtual returns (bool);

  /**
   * @notice Returns whether the provided account is go-listed for use of the SeniorPool on the Goldfinch protocol.
   * @param account The account whose go status to obtain
   * @return true if `account` is go listed
   */
  function goSeniorPool(address account) public view virtual returns (bool);
}

File 27 of 48 : IGoldfinchConfig.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

interface IGoldfinchConfig {
  function getNumber(uint256 index) external returns (uint256);

  function getAddress(uint256 index) external returns (address);

  function setAddress(uint256 index, address newAddress) external returns (address);

  function setNumber(uint256 index, uint256 newNumber) external returns (uint256);
}

File 28 of 48 : IGoldfinchFactory.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

interface IGoldfinchFactory {
  function createCreditLine() external returns (address);

  function createBorrower(address owner) external returns (address);

  function createPool(
    address _borrower,
    uint256 _juniorFeePercent,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _paymentPeriodInDays,
    uint256 _termInDays,
    uint256 _lateFeeApr,
    uint256[] calldata _allowedUIDTypes
  ) external returns (address);

  function createMigratedPool(
    address _borrower,
    uint256 _juniorFeePercent,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _paymentPeriodInDays,
    uint256 _termInDays,
    uint256 _lateFeeApr,
    uint256[] calldata _allowedUIDTypes
  ) external returns (address);
}

File 29 of 48 : IPoolTokens.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import "./openzeppelin/IERC721.sol";

interface IPoolTokens is IERC721 {
  event TokenMinted(
    address indexed owner,
    address indexed pool,
    uint256 indexed tokenId,
    uint256 amount,
    uint256 tranche
  );

  event TokenRedeemed(
    address indexed owner,
    address indexed pool,
    uint256 indexed tokenId,
    uint256 principalRedeemed,
    uint256 interestRedeemed,
    uint256 tranche
  );
  event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);

  struct TokenInfo {
    address pool;
    uint256 tranche;
    uint256 principalAmount;
    uint256 principalRedeemed;
    uint256 interestRedeemed;
  }

  struct MintParams {
    uint256 principalAmount;
    uint256 tranche;
  }

  function mint(MintParams calldata params, address to) external returns (uint256);

  function redeem(
    uint256 tokenId,
    uint256 principalRedeemed,
    uint256 interestRedeemed
  ) external;

  function withdrawPrincipal(uint256 tokenId, uint256 principalAmount) external;

  function burn(uint256 tokenId) external;

  function onPoolCreated(address newPool) external;

  function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory);

  function validPool(address sender) external view returns (bool);

  function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}

File 30 of 48 : ISeniorPool.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import {ITranchedPool} from "./ITranchedPool.sol";
import {ISeniorPoolEpochWithdrawals} from "./ISeniorPoolEpochWithdrawals.sol";

abstract contract ISeniorPool is ISeniorPoolEpochWithdrawals {
  uint256 public sharePrice;
  uint256 public totalLoansOutstanding;
  uint256 public totalWritedowns;

  function deposit(uint256 amount) external virtual returns (uint256 depositShares);

  function depositWithPermit(
    uint256 amount,
    uint256 deadline,
    uint8 v,
    bytes32 r,
    bytes32 s
  ) external virtual returns (uint256 depositShares);

  /// @notice Withdraw `usdcAmount` of USDC, bypassing the epoch withdrawal system
  function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount);

  /**
   * @notice Withdraw `fiduAmount` of FIDU converted to USDC at the current share price,
   * bypassing the epoch withdrawal system.
   */
  function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount);

  function invest(ITranchedPool pool) external virtual returns (uint256);

  function estimateInvestment(ITranchedPool pool) external view virtual returns (uint256);

  function redeem(uint256 tokenId) external virtual;

  function writedown(uint256 tokenId) external virtual;

  function calculateWritedown(uint256 tokenId) external view virtual returns (uint256 writedownAmount);

  function sharesOutstanding() external view virtual returns (uint256);

  function assets() external view virtual returns (uint256);

  function getNumShares(uint256 amount) public view virtual returns (uint256);

  event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);
  event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);
  event InterestCollected(address indexed payer, uint256 amount);
  event PrincipalCollected(address indexed payer, uint256 amount);
  event ReserveFundsCollected(address indexed user, uint256 amount);
  event ReserveSharesCollected(address indexed user, address indexed reserve, uint256 amount);

  event PrincipalWrittenDown(address indexed tranchedPool, int256 amount);
  event InvestmentMadeInSenior(address indexed tranchedPool, uint256 amount);
  event InvestmentMadeInJunior(address indexed tranchedPool, uint256 amount);
}

File 31 of 48 : ISeniorPoolEpochWithdrawals.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;

pragma experimental ABIEncoderV2;

interface ISeniorPoolEpochWithdrawals {
  /**
   * @notice A withdrawal epoch
   * @param endsAt timestamp the epoch ends
   * @param fiduRequested amount of fidu requested in the epoch, including fidu
   *                      carried over from previous epochs
   * @param fiduLiquidated Amount of fidu that was liquidated at the end of this epoch
   * @param usdcAllocated Amount of usdc that was allocated to liquidate fidu.
   *                      Does not consider fees.
   */
  struct Epoch {
    uint256 endsAt;
    uint256 fiduRequested;
    uint256 fiduLiquidated;
    uint256 usdcAllocated;
  }

  /**
   * @notice A user's request for withdrawal
   * @param epochCursor id of next epoch the user can liquidate their request
   * @param fiduRequested amount of fidu left to liquidate since last checkpoint
   * @param usdcWithdrawable amount of usdc available for a user to withdraw
   */
  struct WithdrawalRequest {
    uint256 epochCursor;
    uint256 usdcWithdrawable;
    uint256 fiduRequested;
  }

  /**
   * @notice Returns the amount of unallocated usdc in the senior pool, taking into account
   *         usdc that _will_ be allocated to withdrawals when a checkpoint happens
   */
  function usdcAvailable() external view returns (uint256);

  /// @notice Current duration of withdrawal epochs, in seconds
  function epochDuration() external view returns (uint256);

  /// @notice Update epoch duration
  function setEpochDuration(uint256 newEpochDuration) external;

  /// @notice The current withdrawal epoch
  function currentEpoch() external view returns (Epoch memory);

  /// @notice Get request by tokenId. A request is considered active if epochCursor > 0.
  function withdrawalRequest(uint256 tokenId) external view returns (WithdrawalRequest memory);

  /**
   * @notice Submit a request to withdraw `fiduAmount` of FIDU. Request is rejected
   * if callers already owns a request token. A non-transferrable request token is
   * minted to the caller
   * @return tokenId token minted to caller
   */
  function requestWithdrawal(uint256 fiduAmount) external returns (uint256 tokenId);

  /**
   * @notice Add `fiduAmount` FIDU to a withdrawal request for `tokenId`. Caller
   * must own tokenId
   */
  function addToWithdrawalRequest(uint256 fiduAmount, uint256 tokenId) external;

  /**
   * @notice Cancel request for tokenId. The fiduRequested (minus a fee) is returned
   * to the caller. Caller must own tokenId.
   * @return fiduReceived the fidu amount returned to the caller
   */
  function cancelWithdrawalRequest(uint256 tokenId) external returns (uint256 fiduReceived);

  /**
   * @notice Transfer the usdcWithdrawable of request for tokenId to the caller.
   * Caller must own tokenId
   */
  function claimWithdrawalRequest(uint256 tokenId) external returns (uint256 usdcReceived);

  /// @notice Emitted when the epoch duration is changed
  event EpochDurationChanged(uint256 newDuration);

  /// @notice Emitted when a new withdraw request has been created
  event WithdrawalRequested(
    uint256 indexed epochId,
    uint256 indexed tokenId,
    address indexed operator,
    uint256 fiduRequested
  );

  /// @notice Emitted when a user adds to their existing withdraw request
  /// @param epochId epoch that the withdraw was added to
  /// @param tokenId id of token that represents the position being added to
  /// @param operator address that added to the request
  /// @param fiduRequested amount of additional fidu added to request
  event WithdrawalAddedTo(
    uint256 indexed epochId,
    uint256 indexed tokenId,
    address indexed operator,
    uint256 fiduRequested
  );

  /// @notice Emitted when a withdraw request has been canceled
  event WithdrawalCanceled(
    uint256 indexed epochId,
    uint256 indexed tokenId,
    address indexed operator,
    uint256 fiduCanceled,
    uint256 reserveFidu
  );

  /// @notice Emitted when an epoch has been checkpointed
  /// @param epochId id of epoch that ended
  /// @param endTime timestamp the epoch ended
  /// @param fiduRequested amount of FIDU oustanding when the epoch ended
  /// @param usdcAllocated amount of USDC allocated to liquidate FIDU
  /// @param fiduLiquidated amount of FIDU liquidated using `usdcAllocated`
  event EpochEnded(
    uint256 indexed epochId,
    uint256 endTime,
    uint256 fiduRequested,
    uint256 usdcAllocated,
    uint256 fiduLiquidated
  );

  /// @notice Emitted when an epoch could not be finalized and is extended instead
  /// @param epochId id of epoch that was extended
  /// @param newEndTime new epoch end time
  /// @param oldEndTime previous epoch end time
  event EpochExtended(uint256 indexed epochId, uint256 newEndTime, uint256 oldEndTime);
}

File 32 of 48 : ISeniorPoolStrategy.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import "./ISeniorPool.sol";
import "./ITranchedPool.sol";

abstract contract ISeniorPoolStrategy {
  function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256);

  function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount);

  function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256);
}

File 33 of 48 : IStakingRewards.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;

pragma experimental ABIEncoderV2;

import {IERC721} from "./openzeppelin/IERC721.sol";
import {IERC721Metadata} from "./openzeppelin/IERC721Metadata.sol";
import {IERC721Enumerable} from "./openzeppelin/IERC721Enumerable.sol";

interface IStakingRewards is IERC721, IERC721Metadata, IERC721Enumerable {
  function getPosition(uint256 tokenId) external view returns (StakedPosition memory position);

  function unstake(uint256 tokenId, uint256 amount) external;

  function addToStake(uint256 tokenId, uint256 amount) external;

  function stakedBalanceOf(uint256 tokenId) external view returns (uint256);

  function depositToCurveAndStakeFrom(
    address nftRecipient,
    uint256 fiduAmount,
    uint256 usdcAmount
  ) external;

  function kick(uint256 tokenId) external;

  function accumulatedRewardsPerToken() external view returns (uint256);

  function lastUpdateTime() external view returns (uint256);

  /* ========== EVENTS ========== */

  event RewardAdded(uint256 reward);
  event Staked(
    address indexed user,
    uint256 indexed tokenId,
    uint256 amount,
    StakedPositionType positionType,
    uint256 baseTokenExchangeRate
  );
  event DepositedAndStaked(address indexed user, uint256 depositedAmount, uint256 indexed tokenId, uint256 amount);
  event DepositedToCurve(address indexed user, uint256 fiduAmount, uint256 usdcAmount, uint256 tokensReceived);
  event DepositedToCurveAndStaked(
    address indexed user,
    uint256 fiduAmount,
    uint256 usdcAmount,
    uint256 indexed tokenId,
    uint256 amount
  );
  event AddToStake(address indexed user, uint256 indexed tokenId, uint256 amount, StakedPositionType positionType);
  event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount, StakedPositionType positionType);
  event UnstakedMultiple(address indexed user, uint256[] tokenIds, uint256[] amounts);
  event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);
  event RewardsParametersUpdated(
    address indexed who,
    uint256 targetCapacity,
    uint256 minRate,
    uint256 maxRate,
    uint256 minRateAtPercent,
    uint256 maxRateAtPercent
  );
  event EffectiveMultiplierUpdated(address indexed who, StakedPositionType positionType, uint256 multiplier);
}

/// @notice Indicates which ERC20 is staked
enum StakedPositionType {
  Fidu,
  CurveLP
}

struct Rewards {
  uint256 totalUnvested;
  uint256 totalVested;
  // @dev DEPRECATED (definition kept for storage slot)
  //   For legacy vesting positions, this was used in the case of slashing.
  //   For non-vesting positions, this is unused.
  uint256 totalPreviouslyVested;
  uint256 totalClaimed;
  uint256 startTime;
  // @dev DEPRECATED (definition kept for storage slot)
  //   For legacy vesting positions, this is the endTime of the vesting.
  //   For non-vesting positions, this is 0.
  uint256 endTime;
}

struct StakedPosition {
  // @notice Staked amount denominated in `stakingToken().decimals()`
  uint256 amount;
  // @notice Struct describing rewards owed with vesting
  Rewards rewards;
  // @notice Multiplier applied to staked amount when locking up position
  uint256 leverageMultiplier;
  // @notice Time in seconds after which position can be unstaked
  uint256 lockedUntil;
  // @notice Type of the staked position
  StakedPositionType positionType;
  // @notice Multiplier applied to staked amount to denominate in `baseStakingToken().decimals()`
  // @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1.
  //  If you need this field, use `safeEffectiveMultiplier()`, which correctly handles old staked positions.
  uint256 unsafeEffectiveMultiplier;
  // @notice Exchange rate applied to staked amount to denominate in `baseStakingToken().decimals()`
  // @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1.
  //  If you need this field, use `safeBaseTokenExchangeRate()`, which correctly handles old staked positions.
  uint256 unsafeBaseTokenExchangeRate;
}

File 34 of 48 : ITranchedPool.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import {IV2CreditLine} from "./IV2CreditLine.sol";

abstract contract ITranchedPool {
  IV2CreditLine public creditLine;
  uint256 public createdAt;
  enum Tranches {
    Reserved,
    Senior,
    Junior
  }

  struct TrancheInfo {
    uint256 id;
    uint256 principalDeposited;
    uint256 principalSharePrice;
    uint256 interestSharePrice;
    uint256 lockedUntil;
  }

  struct PoolSlice {
    TrancheInfo seniorTranche;
    TrancheInfo juniorTranche;
    uint256 totalInterestAccrued;
    uint256 principalDeployed;
  }

  function initialize(
    address _config,
    address _borrower,
    uint256 _juniorFeePercent,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _paymentPeriodInDays,
    uint256 _termInDays,
    uint256 _lateFeeApr,
    uint256 _principalGracePeriodInDays,
    uint256 _fundableAt,
    uint256[] calldata _allowedUIDTypes
  ) public virtual;

  function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory);

  function pay(uint256 amount) external virtual;

  function poolSlices(uint256 index) external view virtual returns (PoolSlice memory);

  function lockJuniorCapital() external virtual;

  function lockPool() external virtual;

  function initializeNextSlice(uint256 _fundableAt) external virtual;

  function totalJuniorDeposits() external view virtual returns (uint256);

  function drawdown(uint256 amount) external virtual;

  function setFundableAt(uint256 timestamp) external virtual;

  function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId);

  function assess() external virtual;

  function depositWithPermit(
    uint256 tranche,
    uint256 amount,
    uint256 deadline,
    uint8 v,
    bytes32 r,
    bytes32 s
  ) external virtual returns (uint256 tokenId);

  function availableToWithdraw(uint256 tokenId)
    external
    view
    virtual
    returns (uint256 interestRedeemable, uint256 principalRedeemable);

  function withdraw(uint256 tokenId, uint256 amount)
    external
    virtual
    returns (uint256 interestWithdrawn, uint256 principalWithdrawn);

  function withdrawMax(uint256 tokenId)
    external
    virtual
    returns (uint256 interestWithdrawn, uint256 principalWithdrawn);

  function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual;

  function numSlices() external view virtual returns (uint256);
}

File 35 of 48 : IV2CreditLine.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import "./ICreditLine.sol";

abstract contract IV2CreditLine is ICreditLine {
  function principal() external view virtual returns (uint256);

  function totalInterestAccrued() external view virtual returns (uint256);

  function termStartTime() external view virtual returns (uint256);

  function setLimit(uint256 newAmount) external virtual;

  function setMaxLimit(uint256 newAmount) external virtual;

  function setBalance(uint256 newBalance) external virtual;

  function setPrincipal(uint256 _principal) external virtual;

  function setTotalInterestAccrued(uint256 _interestAccrued) external virtual;

  function drawdown(uint256 amount) external virtual;

  function assess()
    external
    virtual
    returns (
      uint256,
      uint256,
      uint256
    );

  function initialize(
    address _config,
    address owner,
    address _borrower,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _paymentPeriodInDays,
    uint256 _termInDays,
    uint256 _lateFeeApr,
    uint256 _principalGracePeriodInDays
  ) public virtual;

  function setTermEndTime(uint256 newTermEndTime) external virtual;

  function setNextDueTime(uint256 newNextDueTime) external virtual;

  function setInterestOwed(uint256 newInterestOwed) external virtual;

  function setPrincipalOwed(uint256 newPrincipalOwed) external virtual;

  function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual;

  function setWritedownAmount(uint256 newWritedownAmount) external virtual;

  function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual;

  function setLateFeeApr(uint256 newLateFeeApr) external virtual;
}

File 36 of 48 : IWithdrawalRequestToken.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import {IERC721Enumerable} from "./openzeppelin/IERC721Enumerable.sol";

// Use base non-transferrable ERC721 class?
interface IWithdrawalRequestToken is IERC721Enumerable {
  /// @notice Mint a withdrawal request token to `receiver`
  /// @dev succeeds if and only if called by senior pool
  function mint(address receiver) external returns (uint256 tokenId);

  /// @notice Burn token `tokenId`
  /// @dev suceeds if and only if called by senior pool
  function burn(uint256 tokenId) external;
}

File 37 of 48 : IERC165.sol
pragma solidity >=0.6.0;

// This file copied from OZ, but with the version pragma updated to use >=.

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
  /**
   * @dev Returns true if this contract implements the interface defined by
   * `interfaceId`. See the corresponding
   * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
   * to learn more about how these ids are created.
   *
   * This function call must use less than 30 000 gas.
   */
  function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 38 of 48 : IERC721.sol
pragma solidity >=0.6.2;

// This file copied from OZ, but with the version pragma updated to use >= & reference other >= pragma interfaces.
// NOTE: Modified to reference our updated pragma version of IERC165
import "./IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
  event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
  event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
  event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

  /**
   * @dev Returns the number of NFTs in ``owner``'s account.
   */
  function balanceOf(address owner) external view returns (uint256 balance);

  /**
   * @dev Returns the owner of the NFT specified by `tokenId`.
   */
  function ownerOf(uint256 tokenId) external view returns (address owner);

  /**
   * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
   * another (`to`).
   *
   *
   *
   * Requirements:
   * - `from`, `to` cannot be zero.
   * - `tokenId` must be owned by `from`.
   * - If the caller is not `from`, it must be have been allowed to move this
   * NFT by either {approve} or {setApprovalForAll}.
   */
  function safeTransferFrom(
    address from,
    address to,
    uint256 tokenId
  ) external;

  /**
   * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
   * another (`to`).
   *
   * Requirements:
   * - If the caller is not `from`, it must be approved to move this NFT by
   * either {approve} or {setApprovalForAll}.
   */
  function transferFrom(
    address from,
    address to,
    uint256 tokenId
  ) external;

  function approve(address to, uint256 tokenId) external;

  function getApproved(uint256 tokenId) external view returns (address operator);

  function setApprovalForAll(address operator, bool _approved) external;

  function isApprovedForAll(address owner, address operator) external view returns (bool);

  function safeTransferFrom(
    address from,
    address to,
    uint256 tokenId,
    bytes calldata data
  ) external;
}

File 39 of 48 : IERC721Enumerable.sol
pragma solidity >=0.6.2;

// This file copied from OZ, but with the version pragma updated to use >=.

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
  function totalSupply() external view returns (uint256);

  function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);

  function tokenByIndex(uint256 index) external view returns (uint256);
}

File 40 of 48 : IERC721Metadata.sol
pragma solidity >=0.6.2;

// This file copied from OZ, but with the version pragma updated to use >=.

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
  function name() external view returns (string memory);

  function symbol() external view returns (string memory);

  function tokenURI(uint256 tokenId) external view returns (string memory);
}

File 41 of 48 : Accountant.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "./CreditLine.sol";
import "../../interfaces/ICreditLine.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 private constant FP_SCALING_FACTOR = 10**18;
  uint256 private constant INTEREST_DECIMALS = 1e18;
  uint256 private constant SECONDS_PER_DAY = 60 * 60 * 24;
  uint256 private constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365);

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

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

  function calculateInterestAndPrincipalAccruedOverPeriod(
    CreditLine cl,
    uint256 balance,
    uint256 startTime,
    uint256 endTime,
    uint256 lateFeeGracePeriod
  ) public view returns (uint256, uint256) {
    uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod);
    uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime);
    return (interestAccrued, principalAccrued);
  }

  function calculatePrincipalAccrued(
    ICreditLine cl,
    uint256 balance,
    uint256 timestamp
  ) public view returns (uint256) {
    // If we've already accrued principal as of the term end time, then don't accrue more principal
    uint256 termEndTime = cl.termEndTime();
    if (cl.interestAccruedAsOf() >= termEndTime) {
      return 0;
    }
    if (timestamp >= termEndTime) {
      return balance;
    } else {
      return 0;
    }
  }

  function calculateWritedownFor(
    ICreditLine cl,
    uint256 timestamp,
    uint256 gracePeriodInDays,
    uint256 maxDaysLate
  ) public view returns (uint256, uint256) {
    return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate);
  }

  function calculateWritedownForPrincipal(
    ICreditLine cl,
    uint256 principal,
    uint256 timestamp,
    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 date, 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 (timestamp > cl.termEndTime()) {
      uint256 secondsLate = timestamp.sub(cl.termEndTime());
      daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_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(principal).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(ICreditLine 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 interestOwedForOneDay = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365);
    return interestOwedForOneDay.add(cl.principalOwed());
  }

  function calculateInterestAccrued(
    CreditLine cl,
    uint256 balance,
    uint256 timestamp,
    uint256 lateFeeGracePeriodInDays
  ) public view returns (uint256) {
    // We use Math.min here to prevent integer overflow (ie. go negative) when calculating
    // numSecondsElapsed. Typically this shouldn't be possible, because
    // the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing
    // we allow this function to be called with a past timestamp, which raises the possibility
    // of overflow.
    // This use of min should not generate incorrect interest calculations, since
    // this function's purpose is just to normalize balances, and handing in a past timestamp
    // will necessarily return zero interest accrued (because zero elapsed time), which is correct.
    uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf());
    return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays);
  }

  function calculateInterestAccruedOverPeriod(
    CreditLine cl,
    uint256 balance,
    uint256 startTime,
    uint256 endTime,
    uint256 lateFeeGracePeriodInDays
  ) public view returns (uint256 interestOwed) {
    uint256 secondsElapsed = endTime.sub(startTime);
    uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS);
    interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
    if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) {
      uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);
      uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
      interestOwed = interestOwed.add(additionalLateFeeInterest);
    }

    return interestOwed;
  }

  function lateFeeApplicable(
    CreditLine cl,
    uint256 timestamp,
    uint256 gracePeriodInDays
  ) public view returns (bool) {
    uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime());
    return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_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 42 of 48 : BaseUpgradeablePausable.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

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 upgradeability, 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 43 of 48 : ConfigHelper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import {ImplementationRepository} from "./proxy/ImplementationRepository.sol";
import {ConfigOptions} from "./ConfigOptions.sol";
import {GoldfinchConfig} from "./GoldfinchConfig.sol";
import {IFidu} from "../../interfaces/IFidu.sol";
import {IWithdrawalRequestToken} from "../../interfaces/IWithdrawalRequestToken.sol";
import {ISeniorPool} from "../../interfaces/ISeniorPool.sol";
import {ISeniorPoolStrategy} from "../../interfaces/ISeniorPoolStrategy.sol";
import {IERC20withDec} from "../../interfaces/IERC20withDec.sol";
import {ICUSDCContract} from "../../interfaces/ICUSDCContract.sol";
import {IPoolTokens} from "../../interfaces/IPoolTokens.sol";
import {IBackerRewards} from "../../interfaces/IBackerRewards.sol";
import {IGoldfinchFactory} from "../../interfaces/IGoldfinchFactory.sol";
import {IGo} from "../../interfaces/IGo.sol";
import {IStakingRewards} from "../../interfaces/IStakingRewards.sol";
import {ICurveLP} from "../../interfaces/ICurveLP.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 getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) {
    return ISeniorPool(seniorPoolAddress(config));
  }

  function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) {
    return ISeniorPoolStrategy(seniorPoolStrategyAddress(config));
  }

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

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

  function getFiduUSDCCurveLP(GoldfinchConfig config) internal view returns (ICurveLP) {
    return ICurveLP(fiduUSDCCurveLPAddress(config));
  }

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

  function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) {
    return IPoolTokens(poolTokensAddress(config));
  }

  function getBackerRewards(GoldfinchConfig config) internal view returns (IBackerRewards) {
    return IBackerRewards(backerRewardsAddress(config));
  }

  function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) {
    return IGoldfinchFactory(goldfinchFactoryAddress(config));
  }

  function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) {
    return IERC20withDec(gfiAddress(config));
  }

  function getGo(GoldfinchConfig config) internal view returns (IGo) {
    return IGo(goAddress(config));
  }

  function getStakingRewards(GoldfinchConfig config) internal view returns (IStakingRewards) {
    return IStakingRewards(stakingRewardsAddress(config));
  }

  function getTranchedPoolImplementationRepository(GoldfinchConfig config)
    internal
    view
    returns (ImplementationRepository)
  {
    return
      ImplementationRepository(
        config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementationRepository))
      );
  }

  function getWithdrawalRequestToken(GoldfinchConfig config) internal view returns (IWithdrawalRequestToken) {
    return IWithdrawalRequestToken(config.getAddress(uint256(ConfigOptions.Addresses.WithdrawalRequestToken)));
  }

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

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

  /// @dev deprecated because we no longer use GSN
  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 poolTokensAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens));
  }

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

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

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

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

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

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

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

  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 tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation));
  }

  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 borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) {
    return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation));
  }

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

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

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

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

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

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

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

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

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

/**
 * @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,
    /// @dev: TotalFundsLimit used to represent a total cap on senior pool deposits
    /// but is now deprecated
    TotalFundsLimit,
    MaxUnderwriterLimit,
    ReserveDenominator,
    WithdrawFeeDenominator,
    LatenessGracePeriodInDays,
    LatenessMaxDays,
    DrawdownPeriodInSeconds,
    TransferRestrictionPeriodInDays,
    LeverageRatio,
    /// A number in the range [0, 10000] representing basis points of FIDU taken as a fee
    /// when a withdrawal request is canceled.
    SeniorPoolWithdrawalCancelationFeeInBps
  }
  /// @dev TrustedForwarder is deprecated because we no longer use GSN. CreditDesk
  ///   and Pool are deprecated because they are no longer used in the protocol.
  enum Addresses {
    Pool, // deprecated
    CreditLineImplementation,
    GoldfinchFactory,
    CreditDesk, // deprecated
    Fidu,
    USDC,
    TreasuryReserve,
    ProtocolAdmin,
    OneInch,
    TrustedForwarder, // deprecated
    CUSDCContract,
    GoldfinchConfig,
    PoolTokens,
    TranchedPoolImplementation, // deprecated
    SeniorPool,
    SeniorPoolStrategy,
    MigratedTranchedPoolImplementation,
    BorrowerImplementation,
    GFI,
    Go,
    BackerRewards,
    StakingRewards,
    FiduUSDCCurveLP,
    TranchedPoolImplementationRepository,
    WithdrawalRequestToken
  }
}

File 45 of 48 : CreditLine.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "./GoldfinchConfig.sol";
import "./ConfigHelper.sol";
import "./BaseUpgradeablePausable.sol";
import "./Accountant.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICreditLine.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";

/**
 * @title CreditLine
 * @notice A contract that represents the agreement between Backers and
 *  a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed.
 *  A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not
 *  operate in any standalone capacity. It should generally be considered internal to the TranchedPool.
 * @author Goldfinch
 */

// solhint-disable-next-line max-states-count
contract CreditLine is BaseUpgradeablePausable, ICreditLine {
  uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;

  event GoldfinchConfigUpdated(address indexed who, address configAddress);

  // Credit line terms
  address public override borrower;
  uint256 public currentLimit;
  uint256 public override maxLimit;
  uint256 public override interestApr;
  uint256 public override paymentPeriodInDays;
  uint256 public override termInDays;
  uint256 public override principalGracePeriodInDays;
  uint256 public override lateFeeApr;

  // Accounting variables
  uint256 public override balance;
  uint256 public override interestOwed;
  uint256 public override principalOwed;
  uint256 public override termEndTime;
  uint256 public override nextDueTime;
  uint256 public override interestAccruedAsOf;
  uint256 public override lastFullPaymentTime;
  uint256 public totalInterestAccrued;

  GoldfinchConfig public config;
  using ConfigHelper for GoldfinchConfig;

  function initialize(
    address _config,
    address owner,
    address _borrower,
    uint256 _maxLimit,
    uint256 _interestApr,
    uint256 _paymentPeriodInDays,
    uint256 _termInDays,
    uint256 _lateFeeApr,
    uint256 _principalGracePeriodInDays
  ) public initializer {
    require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in");
    __BaseUpgradeablePausable__init(owner);
    config = GoldfinchConfig(_config);
    borrower = _borrower;
    maxLimit = _maxLimit;
    interestApr = _interestApr;
    paymentPeriodInDays = _paymentPeriodInDays;
    termInDays = _termInDays;
    lateFeeApr = _lateFeeApr;
    principalGracePeriodInDays = _principalGracePeriodInDays;
    interestAccruedAsOf = block.timestamp;

    // Unlock owner, which is a TranchedPool, for infinite amount
    bool success = config.getUSDC().approve(owner, uint256(-1));
    require(success, "Failed to approve USDC");
  }

  function limit() external view override returns (uint256) {
    return currentLimit;
  }

  /**
   * @notice Updates the internal accounting to track a drawdown as of current block timestamp.
   * Does not move any money
   * @param amount The amount in USDC that has been drawndown
   */
  function drawdown(uint256 amount) external onlyAdmin {
    uint256 timestamp = currentTime();
    require(termEndTime == 0 || (timestamp < termEndTime), "After termEndTime");
    require(amount.add(balance) <= currentLimit, "Cannot drawdown more than the limit");
    require(amount > 0, "Invalid drawdown amount");

    if (balance == 0) {
      setInterestAccruedAsOf(timestamp);
      setLastFullPaymentTime(timestamp);
      setTotalInterestAccrued(0);
      // Set termEndTime only once to prevent extending
      // the loan's end time on every 0 balance drawdown
      if (termEndTime == 0) {
        setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays)));
      }
    }

    (uint256 _interestOwed, uint256 _principalOwed) = _updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
    balance = balance.add(amount);

    updateCreditLineAccounting(balance, _interestOwed, _principalOwed);
    require(!_isLate(timestamp), "Cannot drawdown when payments are past due");
  }

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

  function setLimit(uint256 newAmount) external onlyAdmin {
    require(newAmount <= maxLimit, "Cannot be more than the max limit");
    currentLimit = newAmount;
  }

  function setMaxLimit(uint256 newAmount) external onlyAdmin {
    maxLimit = newAmount;
  }

  function termStartTime() external view returns (uint256) {
    return _termStartTime();
  }

  function isLate() external view override returns (bool) {
    return _isLate(block.timestamp);
  }

  function withinPrincipalGracePeriod() external view override returns (bool) {
    if (termEndTime == 0) {
      // Loan hasn't started yet
      return true;
    }
    return block.timestamp < _termStartTime().add(principalGracePeriodInDays.mul(SECONDS_PER_DAY));
  }

  function setTermEndTime(uint256 newTermEndTime) public onlyAdmin {
    termEndTime = newTermEndTime;
  }

  function setNextDueTime(uint256 newNextDueTime) public onlyAdmin {
    nextDueTime = newNextDueTime;
  }

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

  function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin {
    totalInterestAccrued = _totalInterestAccrued;
  }

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

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

  function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin {
    interestAccruedAsOf = newInterestAccruedAsOf;
  }

  function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin {
    lastFullPaymentTime = newLastFullPaymentTime;
  }

  /**
   * @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied
   * towards the interest and principal.
   * @return Any amount remaining after applying payments towards the interest and principal
   * @return Amount applied towards interest
   * @return Amount applied towards principal
   */
  function assess()
    public
    onlyAdmin
    returns (
      uint256,
      uint256,
      uint256
    )
  {
    // Do not assess until a full period has elapsed or past due
    require(balance > 0, "Must have balance to assess credit line");

    // Don't assess credit lines early!
    if (currentTime() < nextDueTime && !_isLate(currentTime())) {
      return (0, 0, 0);
    }
    uint256 timeToAssess = calculateNextDueTime();
    setNextDueTime(timeToAssess);

    // We always want to assess for the most recently *past* nextDueTime.
    // So if the recalculation above sets the nextDueTime into the future,
    // then ensure we pass in the one just before this.
    if (timeToAssess > currentTime()) {
      uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
      timeToAssess = timeToAssess.sub(secondsPerPeriod);
    }
    return handlePayment(_getUSDCBalance(address(this)), timeToAssess);
  }

  function calculateNextDueTime() internal view returns (uint256) {
    uint256 newNextDueTime = nextDueTime;
    uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
    uint256 curTimestamp = currentTime();
    // You must have just done your first drawdown
    if (newNextDueTime == 0 && balance > 0) {
      return curTimestamp.add(secondsPerPeriod);
    }

    // Active loan that has entered a new period, so return the *next* newNextDueTime.
    // But never return something after the termEndTime
    if (balance > 0 && curTimestamp >= newNextDueTime) {
      uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod);
      newNextDueTime = newNextDueTime.add(secondsToAdvance);
      return Math.min(newNextDueTime, termEndTime);
    }

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

  function currentTime() internal view virtual returns (uint256) {
    return block.timestamp;
  }

  function _isLate(uint256 timestamp) internal view returns (bool) {
    uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime);
    return balance > 0 && secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY);
  }

  function _termStartTime() internal view returns (uint256) {
    return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays));
  }

  /**
   * @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 paymentAmount The amount, in USDC atomic units, to be applied
   * @param timestamp The timestamp on which accrual calculations should be based. This allows us
   *  to be precise when we assess a Credit Line
   */
  function handlePayment(uint256 paymentAmount, uint256 timestamp)
    internal
    returns (
      uint256,
      uint256,
      uint256
    )
  {
    (uint256 newInterestOwed, uint256 newPrincipalOwed) = _updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
    Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(
      paymentAmount,
      balance,
      newInterestOwed,
      newPrincipalOwed
    );

    uint256 newBalance = balance.sub(pa.principalPayment);
    // Apply any additional payment towards the balance
    newBalance = newBalance.sub(pa.additionalBalancePayment);
    uint256 totalPrincipalPayment = balance.sub(newBalance);
    uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);

    updateCreditLineAccounting(
      newBalance,
      newInterestOwed.sub(pa.interestPayment),
      newPrincipalOwed.sub(pa.principalPayment)
    );

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

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

  function _updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) {
    (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
      this,
      timestamp,
      config.getLatenessGracePeriodInDays()
    );
    if (interestAccrued > 0) {
      // If we've accrued any interest, update interestAccruedAsOf to the time 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.
      setInterestAccruedAsOf(timestamp);
      totalInterestAccrued = totalInterestAccrued.add(interestAccrued);
    }
    return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued));
  }

  function updateCreditLineAccounting(
    uint256 newBalance,
    uint256 newInterestOwed,
    uint256 newPrincipalOwed
  ) internal nonReentrant {
    setBalance(newBalance);
    setInterestOwed(newInterestOwed);
    setPrincipalOwed(newPrincipalOwed);

    // This resets lastFullPaymentTime. These conditions assure that they have
    // indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown)
    uint256 _nextDueTime = nextDueTime;
    if (newInterestOwed == 0 && _nextDueTime != 0) {
      // If interest was fully paid off, then set the last full payment as the previous due time
      uint256 mostRecentLastDueTime;
      if (currentTime() < _nextDueTime) {
        uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
        mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod);
      } else {
        mostRecentLastDueTime = _nextDueTime;
      }
      setLastFullPaymentTime(mostRecentLastDueTime);
    }

    setNextDueTime(calculateNextDueTime());
  }

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

File 46 of 48 : GoldfinchConfig.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IGoldfinchConfig.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.
 *  Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this
 *    is mostly to save gas costs of having each call go through a proxy)
 * @author Goldfinch
 */

contract GoldfinchConfig is BaseUpgradeablePausable {
  bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE");

  mapping(uint256 => address) public addresses;
  mapping(uint256 => uint256) public numbers;
  mapping(address => bool) public goList;

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

  event GoListed(address indexed member);
  event NoListed(address indexed member);

  bool public valuesInitialized;

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

    __BaseUpgradeablePausable__init(owner);

    _setupRole(GO_LISTER_ROLE, owner);

    _setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE);
  }

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

  function setSeniorPoolStrategy(address newStrategy) public onlyAdmin {
    uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy);
    emit AddressUpdated(msg.sender, key, addresses[key], newStrategy);
    addresses[key] = newStrategy;
  }

  function setCreditLineImplementation(address newAddress) public onlyAdmin {
    uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation);
    emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
    addresses[key] = newAddress;
  }

  function setTranchedPoolImplementation(address newAddress) public onlyAdmin {
    uint256 key = uint256(ConfigOptions.Addresses.TranchedPoolImplementation);
    emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
    addresses[key] = newAddress;
  }

  function setBorrowerImplementation(address newAddress) public onlyAdmin {
    uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation);
    emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
    addresses[key] = newAddress;
  }

  function setGoldfinchConfig(address newAddress) public onlyAdmin {
    uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);
    emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
    addresses[key] = newAddress;
  }

  function initializeFromOtherConfig(
    address _initialConfig,
    uint256 numbersLength,
    uint256 addressesLength
  ) public onlyAdmin {
    require(!valuesInitialized, "Already initialized values");
    IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig);
    for (uint256 i = 0; i < numbersLength; i++) {
      setNumber(i, initialConfig.getNumber(i));
    }

    for (uint256 i = 0; i < addressesLength; i++) {
      if (getAddress(i) == address(0)) {
        setAddress(i, initialConfig.getAddress(i));
      }
    }
    valuesInitialized = true;
  }

  /**
   * @dev Adds a user to go-list
   * @param _member address to add to go-list
   */
  function addToGoList(address _member) public onlyGoListerRole {
    goList[_member] = true;
    emit GoListed(_member);
  }

  /**
   * @dev removes a user from go-list
   * @param _member address to remove from go-list
   */
  function removeFromGoList(address _member) public onlyGoListerRole {
    goList[_member] = false;
    emit NoListed(_member);
  }

  /**
   * @dev adds many users to go-list at once
   * @param _members addresses to ad to go-list
   */
  function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole {
    for (uint256 i = 0; i < _members.length; i++) {
      addToGoList(_members[i]);
    }
  }

  /**
   * @dev removes many users from go-list at once
   * @param _members addresses to remove from go-list
   */
  function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole {
    for (uint256 i = 0; i < _members.length; i++) {
      removeFromGoList(_members[i]);
    }
  }

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

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

  modifier onlyGoListerRole() {
    require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action");
    _;
  }
}

File 47 of 48 : PauserPausable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

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() {
    /// @dev NA: not authorized
    require(hasRole(PAUSER_ROLE, _msgSender()), "NA");
    _;
  }
}

File 48 of 48 : ImplementationRepository.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import {BaseUpgradeablePausable} from "../BaseUpgradeablePausable.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";

/// @title User Controlled Upgrades (UCU) Proxy Repository
/// A repository maintaing a collection of "lineages" of implementation contracts
///
/// Lineages are a sequence of implementations each lineage can be thought of as
/// a "major" revision of implementations. Implementations between lineages are
/// considered incompatible.
contract ImplementationRepository is BaseUpgradeablePausable {
  address internal constant INVALID_IMPL = address(0);
  uint256 internal constant INVALID_LINEAGE_ID = 0;

  /// @notice returns data that will be delegatedCalled when the given implementation
  ///           is upgraded to
  mapping(address => bytes) public upgradeDataFor;

  /// @dev mapping from one implementation to the succeeding implementation
  mapping(address => address) internal _nextImplementationOf;

  /// @notice Returns the id of the lineage a given implementation belongs to
  mapping(address => uint256) public lineageIdOf;

  /// @dev internal because we expose this through the `currentImplementation(uint256)` api
  mapping(uint256 => address) internal _currentOfLineage;

  /// @notice Returns the id of the most recently created lineage
  uint256 public currentLineageId;

  // //////// External ////////////////////////////////////////////////////////////

  /// @notice initialize the repository's state
  /// @dev reverts if `_owner` is the null address
  /// @dev reverts if `implementation` is not a contract
  /// @param _owner owner of the repository
  /// @param implementation initial implementation in the repository
  function initialize(address _owner, address implementation) external initializer {
    __BaseUpgradeablePausable__init(_owner);
    _createLineage(implementation);
    require(currentLineageId != INVALID_LINEAGE_ID);
  }

  /// @notice set data that will be delegate called when a proxy upgrades to the given `implementation`
  /// @dev reverts when caller is not an admin
  /// @dev reverts when the contract is paused
  /// @dev reverts if the given implementation isn't registered
  function setUpgradeDataFor(address implementation, bytes calldata data) external onlyAdmin whenNotPaused {
    _setUpgradeDataFor(implementation, data);
  }

  /// @notice Create a new lineage of implementations.
  ///
  /// This creates a new "root" of a new lineage
  /// @dev reverts if `implementation` is not a contract
  /// @param implementation implementation that will be the first implementation in the lineage
  /// @return newly created lineage's id
  function createLineage(address implementation) external onlyAdmin whenNotPaused returns (uint256) {
    return _createLineage(implementation);
  }

  /// @notice add a new implementation and set it as the current implementation
  /// @dev reverts if the sender is not an owner
  /// @dev reverts if the contract is paused
  /// @dev reverts if `implementation` is not a contract
  /// @param implementation implementation to append
  function append(address implementation) external onlyAdmin whenNotPaused {
    _append(implementation, currentLineageId);
  }

  /// @notice Append an implementation to a specified lineage
  /// @dev reverts if the contract is paused
  /// @dev reverts if the sender is not an owner
  /// @dev reverts if `implementation` is not a contract
  /// @param implementation implementation to append
  /// @param lineageId id of lineage to append to
  function append(address implementation, uint256 lineageId) external onlyAdmin whenNotPaused {
    _append(implementation, lineageId);
  }

  /// @notice Remove an implementation from the chain and "stitch" together its neighbors
  /// @dev If you have a chain of `A -> B -> C` and I call `remove(B, C)` it will result in `A -> C`
  /// @dev reverts if `previos` is not the ancestor of `toRemove`
  /// @dev we need to provide the previous implementation here to be able to successfully "stitch"
  ///       the chain back together. Because this is an admin action, we can source what the previous
  ///       version is from events.
  /// @param toRemove Implementation to remove
  /// @param previous Implementation that currently has `toRemove` as its successor
  function remove(address toRemove, address previous) external onlyAdmin whenNotPaused {
    _remove(toRemove, previous);
  }

  // //////// External view ////////////////////////////////////////////////////////////

  /// @notice Returns `true` if an implementation has a next implementation set
  /// @param implementation implementation to check
  /// @return The implementation following the given implementation
  function hasNext(address implementation) external view returns (bool) {
    return _nextImplementationOf[implementation] != INVALID_IMPL;
  }

  /// @notice Returns `true` if an implementation has already been added
  /// @param implementation Implementation to check existence of
  /// @return `true` if the implementation has already been added
  function has(address implementation) external view returns (bool) {
    return _has(implementation);
  }

  /// @notice Get the next implementation for a given implementation or
  ///           `address(0)` if it doesn't exist
  /// @dev reverts when contract is paused
  /// @param implementation implementation to get the upgraded implementation for
  /// @return Next Implementation
  function nextImplementationOf(address implementation) external view whenNotPaused returns (address) {
    return _nextImplementationOf[implementation];
  }

  /// @notice Returns `true` if a given lineageId exists
  function lineageExists(uint256 lineageId) external view returns (bool) {
    return _lineageExists(lineageId);
  }

  /// @notice Return the current implementation of a lineage with the given `lineageId`
  function currentImplementation(uint256 lineageId) external view whenNotPaused returns (address) {
    return _currentImplementation(lineageId);
  }

  /// @notice return current implementaton of the current lineage
  function currentImplementation() external view whenNotPaused returns (address) {
    return _currentImplementation(currentLineageId);
  }

  // //////// Internal ////////////////////////////////////////////////////////////

  function _setUpgradeDataFor(address implementation, bytes memory data) internal {
    require(_has(implementation), "unknown impl");
    upgradeDataFor[implementation] = data;
    emit UpgradeDataSet(implementation, data);
  }

  function _createLineage(address implementation) internal virtual returns (uint256) {
    require(Address.isContract(implementation), "not a contract");
    // NOTE: impractical to overflow
    currentLineageId += 1;

    _currentOfLineage[currentLineageId] = implementation;
    lineageIdOf[implementation] = currentLineageId;

    emit Added(currentLineageId, implementation, address(0));
    return currentLineageId;
  }

  function _currentImplementation(uint256 lineageId) internal view returns (address) {
    return _currentOfLineage[lineageId];
  }

  /// @notice Returns `true` if an implementation has already been added
  /// @param implementation implementation to check for
  /// @return `true` if the implementation has already been added
  function _has(address implementation) internal view virtual returns (bool) {
    return lineageIdOf[implementation] != INVALID_LINEAGE_ID;
  }

  /// @notice Set an implementation to the current implementation
  /// @param implementation implementation to set as current implementation
  /// @param lineageId id of lineage to append to
  function _append(address implementation, uint256 lineageId) internal virtual {
    require(Address.isContract(implementation), "not a contract");
    require(!_has(implementation), "exists");
    require(_lineageExists(lineageId), "invalid lineageId");
    require(_currentOfLineage[lineageId] != INVALID_IMPL, "empty lineage");

    address oldImplementation = _currentOfLineage[lineageId];
    _currentOfLineage[lineageId] = implementation;
    lineageIdOf[implementation] = lineageId;
    _nextImplementationOf[oldImplementation] = implementation;

    emit Added(lineageId, implementation, oldImplementation);
  }

  function _remove(address toRemove, address previous) internal virtual {
    require(toRemove != INVALID_IMPL && previous != INVALID_IMPL, "ZERO");
    require(_nextImplementationOf[previous] == toRemove, "Not prev");

    uint256 lineageId = lineageIdOf[toRemove];

    // need to reset the head pointer to the previous version if we remove the head
    if (toRemove == _currentOfLineage[lineageId]) {
      _currentOfLineage[lineageId] = previous;
    }

    _setUpgradeDataFor(toRemove, ""); // reset upgrade data
    _nextImplementationOf[previous] = _nextImplementationOf[toRemove];
    _nextImplementationOf[toRemove] = INVALID_IMPL;
    lineageIdOf[toRemove] = INVALID_LINEAGE_ID;
    emit Removed(lineageId, toRemove);
  }

  function _lineageExists(uint256 lineageId) internal view returns (bool) {
    return lineageId != INVALID_LINEAGE_ID && lineageId <= currentLineageId;
  }

  // //////// Events //////////////////////////////////////////////////////////////
  event Added(uint256 indexed lineageId, address indexed newImplementation, address indexed oldImplementation);
  event Removed(uint256 indexed lineageId, address indexed implementation);
  event UpgradeDataSet(address indexed implementation, bytes data);
}

Settings
{
  "evmVersion": "istanbul",
  "libraries": {
    "contracts/protocol/core/SeniorPool.sol:SeniorPool": {
      "Accountant": "0xf0F8d382a4e1e2F26891B1a95f9Dcb89406bd4A1"
    }
  },
  "metadata": {
    "bytecodeHash": "ipfs",
    "useLiteralContent": true
  },
  "optimizer": {
    "enabled": true,
    "runs": 100
  },
  "remappings": [],
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"capitalProvider","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"DepositMade","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newDuration","type":"uint256"}],"name":"EpochDurationChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epochId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"endTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fiduRequested","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"usdcAllocated","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fiduLiquidated","type":"uint256"}],"name":"EpochEnded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epochId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newEndTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"oldEndTime","type":"uint256"}],"name":"EpochExtended","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"InterestCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tranchedPool","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"InvestmentMadeInJunior","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tranchedPool","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"InvestmentMadeInSenior","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"PrincipalCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tranchedPool","type":"address"},{"indexed":false,"internalType":"int256","name":"amount","type":"int256"}],"name":"PrincipalWrittenDown","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ReserveFundsCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"reserve","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ReserveSharesCollected","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"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epochId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"uint256","name":"fiduRequested","type":"uint256"}],"name":"WithdrawalAddedTo","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epochId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"uint256","name":"fiduCanceled","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reserveFidu","type":"uint256"}],"name":"WithdrawalCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"capitalProvider","type":"address"},{"indexed":false,"internalType":"uint256","name":"userAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reserveAmount","type":"uint256"}],"name":"WithdrawalMade","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"epochId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"uint256","name":"fiduRequested","type":"uint256"}],"name":"WithdrawalRequested","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":[],"name":"ZAPPER_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":[{"internalType":"uint256","name":"fiduAmount","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"addToWithdrawalRequest","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"assets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"calculateWritedown","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"cancelWithdrawalRequest","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"claimWithdrawalRequest","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"config","outputs":[{"internalType":"contract GoldfinchConfig","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentEpoch","outputs":[{"components":[{"internalType":"uint256","name":"endsAt","type":"uint256"},{"internalType":"uint256","name":"fiduRequested","type":"uint256"},{"internalType":"uint256","name":"fiduLiquidated","type":"uint256"},{"internalType":"uint256","name":"usdcAllocated","type":"uint256"}],"internalType":"struct ISeniorPoolEpochWithdrawals.Epoch","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"depositShares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"depositWithPermit","outputs":[{"internalType":"uint256","name":"depositShares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"epochDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ITranchedPool","name":"pool","type":"address"}],"name":"estimateInvestment","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"usdcAmount","type":"uint256"}],"name":"getNumShares","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","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":"initializeEpochs","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ITranchedPool","name":"pool","type":"address"}],"name":"invest","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isAdmin","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":"uint256","name":"tokenId","type":"uint256"}],"name":"redeem","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":"uint256","name":"fiduAmount","type":"uint256"}],"name":"requestWithdrawal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"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":"uint256","name":"newEpochDuration","type":"uint256"}],"name":"setEpochDuration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sharePrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sharesOutstanding","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalLoansOutstanding","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalWritedowns","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"usdcAvailable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"usdcAmount","type":"uint256"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"fiduAmount","type":"uint256"}],"name":"withdrawInFidu","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"withdrawalRequest","outputs":[{"components":[{"internalType":"uint256","name":"epochCursor","type":"uint256"},{"internalType":"uint256","name":"usdcWithdrawable","type":"uint256"},{"internalType":"uint256","name":"fiduRequested","type":"uint256"}],"internalType":"struct ISeniorPoolEpochWithdrawals.WithdrawalRequest","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"writedown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"writedownsByPoolToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

608060405234801561001057600080fd5b50614f48806100206000396000f3fe608060405234801561001057600080fd5b506004361061027f5760003560e01c806379502c551161015c578063adfa3308116100ce578063d547741f11610087578063d547741f14610505578063da4c5a9714610518578063db006a751461052b578063e58378bb1461053e578063e63ab1e914610546578063ed80c8501461054e5761027f565b8063adfa3308146104a9578063b6b55f25146104bc578063b6db75a0146104cf578063c5923023146104d7578063ca15c873146104df578063cf5f1f62146104f25761027f565b80639010d07c116101205780639010d07c1461044d57806391d1485414610460578063945ed49a146104735780639ee679e814610486578063a217fddf14610499578063a6f4487e146104a15761027f565b806379502c55146104025780637e30cdff146104175780638456cb591461042a578063855cb21b1461043257806387269729146104455761027f565b8063485cc955116101f5578063526d81f6116101b9578063526d81f6146103a257806358031d12146103aa5780635c975abb146103bd57806371a97305146103d2578063722eeec3146103da57806376671808146103ed5761027f565b8063485cc9551461034c5780634a970be71461035f5780634d4e3e0c146103725780634ff0876a1461037a5780635209cb98146103825761027f565b80632f2ff15d116102475780632f2ff15d146102f05780632f8f68df1461030357806330024dfe1461030b57806336568abe1461031e5780633f4ba83a1461033157806345b05d09146103395761027f565b806303f9c79314610284578063097616a3146102ad578063242d68c2146102c2578063248a9ca3146102ca5780632e1a7d4d146102dd575b600080fd5b61029761029236600461431e565b610556565b6040516102a491906145c0565b60405180910390f35b6102c06102bb36600461431e565b61087f565b005b6102976109af565b6102976102d83660046143ae565b610a17565b6102976102eb3660046143ae565b610a2f565b6102c06102fe3660046143c6565b610b01565b610297610b45565b6102c06103193660046143ae565b610bf6565b6102c061032c3660046143c6565b610ce7565b6102c0610d29565b6102976103473660046143ae565b610d69565b6102c061035a366004614356565b61112c565b61029761036d3660046144ba565b611251565b6102976112e6565b6102976112f8565b6103956103903660046143ae565b6112ff565b6040516102a49190614e27565b6102c06113e0565b6102976103b83660046143ae565b61146b565b6103c561153f565b6040516102a491906145b5565b610297611548565b6102976103e83660046143ae565b611565565b6103f5611637565b6040516102a49190614dfc565b61040a61167f565b6040516102a49190614523565b61029761042536600461431e565b61168f565b6102c0611750565b6102976104403660046143ae565b61178e565b6102976117a3565b61040a61045b3660046143ea565b6117aa565b6103c561046e3660046143c6565b6117c2565b6102c06104813660046143ae565b6117da565b6102976104943660046143ae565b611b2d565b610297611e2f565b610297611e34565b6102976104b73660046143ae565b611e3b565b6102976104ca3660046143ae565b6120e1565b6103c56123a3565b6102c06123bf565b6102976104ed3660046143ae565b6124ee565b6102976105003660046143ae565b612505565b6102c06105133660046143c6565b612518565b6102c06105263660046143ea565b612552565b6102c06105393660046143ae565b6127c3565b610297612966565b610297612978565b61029761298a565b60975460009060ff16156105855760405162461bcd60e51b815260040161057c90614945565b60405180910390fd5b60c95460ff166105a75760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556105ba82612991565b6105d65760405162461bcd60e51b815260040161057c9061496f565b6105de612a25565b506101c6546000906105f8906001600160a01b0316612a37565b90506000816001600160a01b031663ff8a4efe30866040518363ffffffff1660e01b815260040161062a9291906145f7565b60206040518083038186803b15801561064257600080fd5b505afa158015610656573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061067a919061447f565b90506000811161069c5760405162461bcd60e51b815260040161057c90614b80565b6101cd548111156106bf5760405162461bcd60e51b815260040161057c90614b57565b6101cd546106cd9082612a42565b6101cd556106db8482612a84565b6000846001600160a01b0316637976323d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561071657600080fd5b505afa15801561072a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061074e919061447f565b905060018110156107715760405162461bcd60e51b815260040161057c90614686565b600061077e826001612a42565b9050600061078b82612b29565b6101c45490915061079c9085612b3b565b6101c455604051631c57762b60e31b81526000906001600160a01b0389169063e2bbb158906107d19085908990600401614e48565b602060405180830381600087803b1580156107eb57600080fd5b505af11580156107ff573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610823919061447f565b9050876001600160a01b03167f86da25fff7a4075a94de2ffed109ca6748c3af22736eaf7efc75e3988f899d6e8660405161085e91906145c0565b60405180910390a29550505050505060c9805460ff19166001179055919050565b600054610100900460ff16806108985750610898612b60565b806108a6575060005460ff16155b6108c25760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff161580156108ed576000805460ff1961ff0019909116610100171660011790555b6001600160a01b0382166109135760405162461bcd60e51b815260040161057c906149d0565b61091b612b66565b610923612be7565b61092b612c73565b610943600080516020614eb383398151915283610b3b565b61095b600080516020614ef383398151915283610b3b565b610981600080516020614ef3833981519152600080516020614eb3833981519152612d02565b610999600080516020614eb383398151915280612d02565b80156109ab576000805461ff00191690555b5050565b60006109b961429d565b6109f86109c4612d17565b6040805160808101825282548152600183015460208201526002830154918101919091526003909101546060820152612d2d565b5060608101516101cd5491925090610a109082612a42565b9250505090565b6000818152606560205260409020600201545b919050565b60975460009060ff1615610a555760405162461bcd60e51b815260040161057c90614945565b60c95460ff16610a775760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff19169055610a99600080516020614ed3833981519152336117c2565b610ab55760405162461bcd60e51b815260040161057c90614a94565b60008211610ad55760405162461bcd60e51b815260040161057c90614b04565b6000610ae08361178e565b9050610aec8382612dd4565b91505060c9805460ff19166001179055919050565b600082815260656020526040902060020154610b1f9061046e612f93565b610b3b5760405162461bcd60e51b815260040161057c906146e9565b6109ab8282612f97565b6000610b4f61429d565b610b5a6109c4612d17565b5060408101516101c65491925090610a10908290610b80906001600160a01b0316613000565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015610bb857600080fd5b505afa158015610bcc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf0919061447f565b90612a42565b610bfe6123a3565b610c1a5760405162461bcd60e51b815260040161057c90614d2b565b60008111610c3a5760405162461bcd60e51b815260040161057c90614add565b6000610c44612a25565b90504281600001541115610c91576101ce548154600091610c659190612a42565b6101ce8490559050610c8083610c7a8361300b565b90612b3b565b8083554210610c8b57fe5b50610ca5565b610ca282610c7a836000015461300b565b81555b6101ce8290556040517fc1057a49fd826ed693f6611f22b406e8f41bf73b45b6e8f757d4b14a58d6e9f190610cdb9084906145c0565b60405180910390a15050565b610cef612f93565b6001600160a01b0316816001600160a01b031614610d1f5760405162461bcd60e51b815260040161057c90614d76565b6109ab828261304a565b610d43600080516020614ef383398151915261046e612f93565b610d5f5760405162461bcd60e51b815260040161057c90614b3b565b610d676130b3565b565b60975460009060ff1615610d8f5760405162461bcd60e51b815260040161057c90614945565b60c95460ff16610db15760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654610dd1906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b8152600401610dfc9190614523565b60206040518083038186803b158015610e1457600080fd5b505afa158015610e28573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e4c919061438e565b610e685760405162461bcd60e51b815260040161057c90614b3b565b6101c654610e7e906001600160a01b031661312a565b6001600160a01b0316636352211e836040518263ffffffff1660e01b8152600401610ea991906145c0565b60206040518083038186803b158015610ec157600080fd5b505afa158015610ed5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef9919061433a565b6001600160a01b0316336001600160a01b031614610f295760405162461bcd60e51b815260040161057c90614b3b565b600080610f35846131aa565b91509150806002015460001415610f5e5760405162461bcd60e51b815260040161057c90614ab8565b6101c654600090610f77906001600160a01b03166131d0565b9050612710811115610f9b5760405162461bcd60e51b815260040161057c90614ccf565b6000610fc0612710610fba84866002015461325090919063ffffffff16565b9061328a565b90506000610fdb828560020154612a4290919063ffffffff16565b9050610ff884600201548660010154612a4290919063ffffffff16565b6001808701919091556000600286015584015461101857611018876132cc565b6101c6546110469033908390611036906001600160a01b0316613000565b6001600160a01b0316919061335f565b6101c65460009061105f906001600160a01b03166133b5565b6101c6549091506110809082908590611036906001600160a01b0316613000565b806001600160a01b0316336001600160a01b03167f2f47cf1f0d4e562a169cd1c3cbfbe9735c1fc3e12354494efb79ec1562e37272856040516110c391906145c0565b60405180910390a3336001600160a01b0316886101ca547ff88bc062cd1e95f16709f69e70c521e62602c9d2a875ad4882e8035d15eb3ad5858760405161110b929190614e48565b60405180910390a45094505050505060c9805460ff19166001179055919050565b600054610100900460ff16806111455750611145612b60565b80611153575060005460ff16155b61116f5760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff1615801561119a576000805460ff1961ff0019909116610100171660011790555b6001600160a01b038316158015906111ba57506001600160a01b03821615155b6111d65760405162461bcd60e51b815260040161057c906147e7565b6111df8361087f565b611205600080516020614ed3833981519152600080516020614eb3833981519152612d02565b6101c680546001600160a01b0319166001600160a01b038416179055670de0b6b3a76400006101c35560006101c48190556101c555801561124c576000805461ff00191690555b505050565b6101c65460009061126a906001600160a01b03166133cd565b6001600160a01b031663d505accf333089898989896040518863ffffffff1660e01b81526004016112a1979695949392919061455b565b600060405180830381600087803b1580156112bb57600080fd5b505af11580156112cf573d6000803e3d6000fd5b505050506112dc866120e1565b9695505050505050565b600080516020614ed383398151915281565b6101ce5490565b6113076142c5565b6101c65461131d906001600160a01b031661312a565b6001600160a01b0316636352211e836040518263ffffffff1660e01b815260040161134891906145c0565b60206040518083038186803b15801561136057600080fd5b505afa158015611374573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611398919061433a565b5060008281526101cc60209081526040918290208251606081018452815481526001820154928101929092526002810154928201929092526113d9906133e5565b9392505050565b600054610100900460ff16806113f957506113f9612b60565b80611407575060005460ff16155b6114235760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff1615801561144e576000805460ff1961ff0019909116610100171660011790555b611456612be7565b8015611468576000805461ff00191690555b50565b60975460009060ff16156114915760405162461bcd60e51b815260040161057c90614945565b60c95460ff166114b35760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556114d5600080516020614ed3833981519152336117c2565b6114f15760405162461bcd60e51b815260040161057c90614a94565b600082116115115760405162461bcd60e51b815260040161057c90614b04565b600061151c8361356a565b9050826115298282612dd4565b9250505060c9805460ff19166001179055919050565b60975460ff1690565b60006115606101c554610bf06101c454610c7a6109af565b905090565b600061156f6142e6565b6101c654611585906001600160a01b0316613579565b6001600160a01b0316638c7a63ae846040518263ffffffff1660e01b81526004016115b091906145c0565b60a06040518083038186803b1580156115c857600080fd5b505afa1580156115dc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611600919061440b565b805160608201516040830151929350909160009161161e9190612a42565b9050600061162c8383613584565b979650505050505050565b61163f61429d565b61164761429d565b60006116546109c4612d17565b9092509050600281600281111561166757fe5b141561167957611676826136bc565b91505b50905090565b6101c6546001600160a01b031681565b600061169a82612991565b6116b65760405162461bcd60e51b815260040161057c9061496f565b6101c6546000906116cf906001600160a01b0316612a37565b604051631f999a2d60e01b81529091506001600160a01b03821690631f999a2d9061170090309087906004016145f7565b60206040518083038186803b15801561171857600080fd5b505afa15801561172c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113d9919061447f565b61176a600080516020614ef383398151915261046e612f93565b6117865760405162461bcd60e51b815260040161057c90614b3b565b610d67613700565b600061179d826101c354613759565b92915050565b6101c35481565b60008281526065602052604081206113d99083613774565b60008281526065602052604081206113d99083613780565b60975460ff16156117fd5760405162461bcd60e51b815260040161057c90614945565b60c95460ff1661181f5760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654600090611842906001600160a01b0316613579565b6040516331a9108f60e11b81529091506001600160a01b03821690636352211e906118719085906004016145c0565b60206040518083038186803b15801561188957600080fd5b505afa15801561189d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118c1919061433a565b6001600160a01b0316306001600160a01b0316146118f15760405162461bcd60e51b815260040161057c90614868565b6118f96142e6565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae906119259086906004016145c0565b60a06040518083038186803b15801561193d57600080fd5b505afa158015611951573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611975919061440b565b805190915061198381612991565b61199f5760405162461bcd60e51b815260040161057c9061496f565b6119a7612a25565b50806001600160a01b031663a6a25e886040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156119e357600080fd5b505af11580156119f7573d6000803e3d6000fd5b5050506060830151604084015160009250611a1191612a42565b9050600080611a208484613584565b60008981526101c96020526040902054919350915082158015611a41575080155b15611a525750505050505050611b1d565b6000611a6f611a6084613795565b611a6984613795565b906137be565b60008a81526101c9602052604090208490559050611a8c81613804565b6000811315611ab457611aab611aa18261386f565b6101c55490612a42565b6101c555611ad3565b611ace611ac4826000190261386f565b6101c55490612b3b565b6101c5555b856001600160a01b03167f176e189790e519c3382df7234bd391cc24005bf9cfaaa9de00103c208e10a27482604051611b0c91906145c0565b60405180910390a250505050505050505b5060c9805460ff19166001179055565b60975460009060ff1615611b535760405162461bcd60e51b815260040161057c90614945565b60c95460ff16611b755760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654600090611b98906001600160a01b031661312a565b6101c654909150611bb1906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b8152600401611bdc9190614523565b60206040518083038186803b158015611bf457600080fd5b505afa158015611c08573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c2c919061438e565b611c485760405162461bcd60e51b815260040161057c90614b3b565b6040516370a0823160e01b81526001600160a01b038216906370a0823190611c74903390600401614523565b60206040518083038186803b158015611c8c57600080fd5b505afa158015611ca0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cc4919061447f565b15611ce15760405162461bcd60e51b815260040161057c906147bd565b6000611ceb612a25565b90506000826001600160a01b0316636a627842336040518263ffffffff1660e01b8152600401611d1b9190614523565b602060405180830381600087803b158015611d3557600080fd5b505af1158015611d49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d6d919061447f565b60008181526101cc602052604090206101ca54815560028101879055600184015491925090611d9c9087612b3b565b60018401556101c654611dd290339030908990611dc1906001600160a01b0316613000565b6001600160a01b0316929190613891565b336001600160a01b0316826101ca547f4bd014c167ac618c18f78afa7c88d8ca69c4e4a9321542b1bf050ed165d78e3b89604051611e1091906145c0565b60405180910390a4509250505060c9805460ff19166001179055919050565b600081565b6101c55481565b60975460009060ff1615611e615760405162461bcd60e51b815260040161057c90614945565b60c95460ff16611e835760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654611ea3906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b8152600401611ece9190614523565b60206040518083038186803b158015611ee657600080fd5b505afa158015611efa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f1e919061438e565b611f3a5760405162461bcd60e51b815260040161057c90614b3b565b6101c654611f50906001600160a01b031661312a565b6001600160a01b0316636352211e836040518263ffffffff1660e01b8152600401611f7b91906145c0565b60206040518083038186803b158015611f9357600080fd5b505afa158015611fa7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fcb919061433a565b6001600160a01b0316336001600160a01b031614611ffb5760405162461bcd60e51b815260040161057c90614b3b565b6000612006836131aa565b6001810180546000918290556101c65492945092509061203990612032906001600160a01b03166138b8565b839061328a565b905060006120478383612a42565b905083600201546000141561205f5761205f866132cc565b61206982336138d0565b6101c6546120879033908390611036906001600160a01b031661393f565b336001600160a01b03167f2d4d49c3e017b8235c908cbaa83a2431a08f3b950712696ece2088964fd399f082846040516120c2929190614e48565b60405180910390a2935050505060c9805460ff19166001179055919050565b60975460009060ff16156121075760405162461bcd60e51b815260040161057c90614945565b60c95460ff166121295760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654612149906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b81526004016121749190614523565b60206040518083038186803b15801561218c57600080fd5b505afa1580156121a0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121c4919061438e565b6121e05760405162461bcd60e51b815260040161057c90614b3b565b600082116122005760405162461bcd60e51b815260040161057c90614dc5565b612208612a25565b506101cd546122179083612b3b565b6101cd556122248261178e565b9050336001600160a01b03167f0b05f0d1cd0819f155b8a61f60baf7767c1ee49d04aeaab701df236140eb93f98383604051612261929190614e48565b60405180910390a26101c65461227f906001600160a01b031661393f565b6001600160a01b03166323b872dd3330856040518463ffffffff1660e01b81526004016122ae93929190614537565b602060405180830381600087803b1580156122c857600080fd5b505af11580156122dc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612300919061438e565b61231c5760405162461bcd60e51b815260040161057c906146b2565b6101c654612332906001600160a01b0316613000565b6001600160a01b031663449a52f833836040518363ffffffff1660e01b815260040161235f92919061459c565b600060405180830381600087803b15801561237957600080fd5b505af115801561238d573d6000803e3d6000fd5b5050505060c9805460ff19166001179055919050565b6000611560600080516020614eb383398151915261046e612f93565b6123c76123a3565b6123e35760405162461bcd60e51b815260040161057c90614d2b565b600080526101cb6020527f7815f96d61162a6533de7fc4199513d6e939c8cbee1627dfd11ec1fe503f0bb3541561241957600080fd5b621275006101ce556101c654612437906001600160a01b031661393f565b6001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016124629190614523565b60206040518083038186803b15801561247a57600080fd5b505afa15801561248e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124b2919061447f565b6101cd55600080526101cb602052427f7815f96d61162a6533de7fc4199513d6e939c8cbee1627dfd11ec1fe503f0bb39081556114689061394a565b600081815260656020526040812061179d906139d6565b6101c96020526000908152604090205481565b6000828152606560205260409020600201546125369061046e612f93565b610d1f5760405162461bcd60e51b815260040161057c906148f5565b60975460ff16156125755760405162461bcd60e51b815260040161057c90614945565b60c95460ff166125975760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c6546125b7906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b81526004016125e29190614523565b60206040518083038186803b1580156125fa57600080fd5b505afa15801561260e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612632919061438e565b61264e5760405162461bcd60e51b815260040161057c90614b3b565b6101c654600090612667906001600160a01b031661312a565b6040516331a9108f60e11b81529091506001600160a01b03821690636352211e906126969085906004016145c0565b60206040518083038186803b1580156126ae57600080fd5b505afa1580156126c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126e6919061433a565b6001600160a01b0316336001600160a01b0316146127165760405162461bcd60e51b815260040161057c90614b3b565b600080612722846131aa565b600281015491935091506127369086612b3b565b6002820155600182015461274a9086612b3b565b60018301556101ca54604051339186917f99e2edbbb2b83be9287a6f12d5ad204eb47b5a9da08ee36e58f714784d753fb690612787908a906145c0565b60405180910390a46101c6546127af90339030908890611dc1906001600160a01b0316613000565b505060c9805460ff19166001179055505050565b60975460ff16156127e65760405162461bcd60e51b815260040161057c90614945565b60c95460ff166128085760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff1916905561281a612a25565b506101c654600090612834906001600160a01b0316613579565b905061283e6142e6565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae9061286a9086906004016145c0565b60a06040518083038186803b15801561288257600080fd5b505afa158015612896573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128ba919061440b565b8051604051632a8a9f1360e21b81529192509060009081906001600160a01b0384169063aa2a7c4c906128f19089906004016145c0565b6040805180830381600087803b15801561290a57600080fd5b505af115801561291e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129429190614497565b915091506129518383836139e1565b505060c9805460ff1916600117905550505050565b600080516020614eb383398151915281565b600080516020614ef383398151915281565b6101c45481565b6101c6546000906129aa906001600160a01b0316613579565b6001600160a01b031663b5ada6d8836040518263ffffffff1660e01b81526004016129d59190614523565b60206040518083038186803b1580156129ed57600080fd5b505afa158015612a01573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061179d919061438e565b6000611560612a32612d17565b613ac7565b600061179d82613ca2565b60006113d983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250613cba565b6101c654600090612a9d906001600160a01b031661393f565b60405163095ea7b360e01b81529091506001600160a01b0382169063095ea7b390612ace908690869060040161459c565b602060405180830381600087803b158015612ae857600080fd5b505af1158015612afc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b20919061438e565b61124c57600080fd5b600061179d6001610c7a846002613250565b6000828201838110156113d95760405162461bcd60e51b815260040161057c90614831565b303b1590565b600054610100900460ff1680612b7f5750612b7f612b60565b80612b8d575060005460ff16155b612ba95760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff16158015611456576000805460ff1961ff0019909116610100171660011790558015611468576000805461ff001916905550565b600054610100900460ff1680612c005750612c00612b60565b80612c0e575060005460ff16155b612c2a5760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff16158015612c55576000805460ff1961ff0019909116610100171660011790555b6097805460ff191690558015611468576000805461ff001916905550565b600054610100900460ff1680612c8c5750612c8c612b60565b80612c9a575060005460ff16155b612cb65760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff16158015612ce1576000805460ff1961ff0019909116610100171660011790555b60c9805460ff191660011790558015611468576000805461ff001916905550565b60009182526065602052604090912060020155565b6101ca5460009081526101cb6020526040902090565b612d3561429d565b8151600090421015612d4c57508190506000612dcf565b6000612d5b846020015161356a565b9050612d6a846000015161300b565b84526101cd541580612d7a575080155b15612d9d576101ce548451612d8e91612b3b565b84525082915060019050612dcf565b6101cd54600090612dae9083613ce6565b90506000612dbb8261178e565b604087015250606085015250829150600290505b915091565b6000612dde612a25565b506101c654600090612df8906001600160a01b0316613000565b90506000816001600160a01b03166370a08231336040518263ffffffff1660e01b8152600401612e289190614523565b60206040518083038186803b158015612e4057600080fd5b505afa158015612e54573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e78919061447f565b905080841115612e9a5760405162461bcd60e51b815260040161057c90614766565b60408051808201909152600281526124a160f11b60208201526101cd54612ec2918790613cba565b6101cd556101c654859350612ee79033908590611036906001600160a01b031661393f565b60405163079cc67960e41b81526001600160a01b038316906379cc679090612f15903390889060040161459c565b600060405180830381600087803b158015612f2f57600080fd5b505af1158015612f43573d6000803e3d6000fd5b50505050336001600160a01b03167f2d4d49c3e017b8235c908cbaa83a2431a08f3b950712696ece2088964fd399f0846000604051612f83929190614e48565b60405180910390a2505092915050565b3390565b6000828152606560205260409020612faf9082613cfc565b156109ab57612fbc612f93565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600061179d82613d11565b6000806130286101ce54610fba8542612a4290919063ffffffff16565b90506113d96130436101ce548361325090919063ffffffff16565b8490612b3b565b60008281526065602052604090206130629082613d29565b156109ab5761306f612f93565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b60975460ff166130d55760405162461bcd60e51b815260040161057c90614738565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa613108612f93565b6040516131159190614523565b60405180910390a1565b600061179d82613d3e565b60006001600160a01b03821663b93f9b0a60185b6040518263ffffffff1660e01b815260040161315a91906145c0565b60206040518083038186803b15801561317257600080fd5b505afa158015613186573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061179d919061433a565b60008060006131b7612a25565b905060006131c485613d56565b91935090915050915091565b60006001600160a01b03821663fc563658600a5b6040518263ffffffff1660e01b815260040161320091906145c0565b60206040518083038186803b15801561321857600080fd5b505afa15801561322c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061179d919061447f565b60008261325f5750600061179d565b8282028284828161326c57fe5b04146113d95760405162461bcd60e51b815260040161057c90614a05565b60006113d983836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250613e74565b60008181526101cc6020526040812081815560018101829055600201556101c6546132ff906001600160a01b031661312a565b6001600160a01b03166342966c68826040518263ffffffff1660e01b815260040161332a91906145c0565b600060405180830381600087803b15801561334457600080fd5b505af1158015613358573d6000803e3d6000fd5b5050505050565b61124c8363a9059cbb60e01b848460405160240161337e92919061459c565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152613eab565b60006001600160a01b03821663b93f9b0a600761313e565b60006001600160a01b03821663b93f9b0a600561313e565b6133ed6142c5565b6133f561429d565b82515b6101ca54811115801561340f575060008460400151115b1561355e576101cb600082815260200190815260200160002060405180608001604052908160008201548152602001600182015481526020016002820154815260200160038201548152505091506101ca548114156134755761347182612d2d565b5091505b600061349a8360200151610fba8760400151866060015161325090919063ffffffff16565b905060006134c18460200151610fba8860400151876040015161325090919063ffffffff16565b60408701519091506134d39082612a42565b604087015260208601516134e79083612b3b565b602087015260408401511561355457600061352e8560400151610fba64e8d4a51000613528670de0b6b3a76400008a6060015161325090919063ffffffff16565b90613250565b90506000613540886040015183613f90565b159050801561355157600060408901525b50505b50506001016133f8565b50506101ca5482525090565b600061179d826101c354613f90565b600061179d82613fb0565b60008073f0f8d382a4e1e2f26891b1a95f9dcb89406bd4a16397aec1ab856001600160a01b03166347195e136040518163ffffffff1660e01b815260040160206040518083038186803b1580156135da57600080fd5b505afa1580156135ee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613612919061433a565b6101c6548690429061362c906001600160a01b0316613fc8565b6101c654613642906001600160a01b0316613fe0565b6040518663ffffffff1660e01b81526004016136629594939291906145c9565b604080518083038186803b15801561367957600080fd5b505af415801561368d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136b19190614497565b915091509250929050565b6136c461429d565b6136cc61429d565b6101ce5483516136db91612b3b565b8152604083015160208401516000916136f49190612a42565b60208301525092915050565b60975460ff16156137235760405162461bcd60e51b815260040161057c90614945565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258613108612f93565b60006113d982610fba670de0b6b3a764000061352887613ff8565b60006113d98383614013565b60006113d9836001600160a01b038416614058565b6000600160ff1b82106137ba5760405162461bcd60e51b815260040161057c90614bc2565b5090565b60008183038183128015906137d35750838113155b806137e857506000831280156137e857508381135b6113d95760405162461bcd60e51b815260040161057c90614c0a565b61380c612a25565b5060008113156138445760006138296138248361386f565b614070565b6101c35490915061383a9082612b3b565b6101c35550611468565b6000613856613824836000190261386f565b6101c3549091506138679082612a42565b6101c3555050565b6000808212156137ba5760405162461bcd60e51b815260040161057c9061499b565b6138b2846323b872dd60e01b85858560405160240161337e93929190614537565b50505050565b60006001600160a01b03821663fc56365860046131e4565b806001600160a01b03167ff3583f178a8d4f8888c3683f8e948faf9b6eb701c4f1fab265a6ecad1a1ddebb8360405161390991906145c0565b60405180910390a26101c6546109ab9061392b906001600160a01b0316614092565b6101c6548490611036906001600160a01b03165b600061179d826133cd565b60408051608081018252825481526001830154602082015260028301549181019190915260038201546060820152600090613984906136bc565b6101ca8054600190810180835560009081526101cb6020908152604080832086518155918601519382019390935584830151600282015560609094015160039094019390935590548252902092915050565b600061179d826140aa565b60006139ec83614070565b6101c3549091506139fd9082612b3b565b6101c3558215613a4957836001600160a01b03167fed3bc1b58411ea8e764b3ef8fa6b654877bc1e796a5a1a2373dfc8f1c0e0ea4884604051613a4091906145c0565b60405180910390a25b8115613aa357836001600160a01b03167f8295ad220549851bab232c2a7ae2e3c53a63d2294602bc85f8d8af108778a37e83604051613a8891906145c0565b60405180910390a26101c454613a9e9083612a42565b6101c4555b613abd82610c7a856101cd54612b3b90919063ffffffff16565b6101cd5550505050565b6000613ad161429d565b60408051608081018252845481526001850154602082015260028501549181019190915260038401546060820152600090613b0b90612d2d565b90925090506000816002811115613b1e57fe5b1415613b2e578392505050610a2a565b6001816002811115613b3c57fe5b1415613b9357835482518086556101ca5460405190917f9933f8b03549f37c2bd3c203d4e7fd82d3572bbf69a109f58225495710dba98491613b8091908590614e48565b60405180910390a2849350505050610a2a565b60408201516002850155606082015160038501819055825185556101cd54613bba91612a42565b6101cd556101ca546000613bcd8661394a565b6101c654909150613be6906001600160a01b0316613000565b6001600160a01b03166379cc67903088600201546040518363ffffffff1660e01b8152600401613c1792919061459c565b600060405180830381600087803b158015613c3157600080fd5b505af1158015613c45573d6000803e3d6000fd5b50505050817fbb4a26fa0ace13ee4da343896c20eaa44a618fb9071fdd8c2e2c960a4583189d8760000154886001015489600301548a60020154604051613c8f9493929190614e56565b60405180910390a29350610a2a92505050565b60006001600160a01b03821663b93f9b0a600f61313e565b60008184841115613cde5760405162461bcd60e51b815260040161057c9190614611565b505050900390565b6000818310613cf557816113d9565b5090919050565b60006113d9836001600160a01b0384166140ae565b60006001600160a01b03821663b93f9b0a600461313e565b60006113d9836001600160a01b0384166140f8565b60006001600160a01b03821663b93f9b0a601361313e565b60008181526101cc60205260408120805482905b6101ca5481108015613d80575060008360020154115b15613e665760008181526101cb60205260408120600181015460028601546003830154929550613db392610fba91613250565b90506000613dda8460010154610fba8760020154876002015461325090919063ffffffff16565b6002860154909150613dec9082612a42565b60028601556001850154613e009083612b3b565b600186015560028401546003850154600091613e3391610fba9064e8d4a510009061352890670de0b6b3a7640000613250565b90506000613e45876002015483613f90565b1590508015613e5657600060028801555b505060019092019150613d6a9050565b50506101ca54815592915050565b60008183613e955760405162461bcd60e51b815260040161057c9190614611565b506000838581613ea157fe5b0495945050505050565b613ebd826001600160a01b03166141be565b613ed95760405162461bcd60e51b815260040161057c90614cf4565b60006060836001600160a01b031683604051613ef59190614507565b6000604051808303816000865af19150503d8060008114613f32576040519150601f19603f3d011682016040523d82523d6000602084013e613f37565b606091505b509150915081613f595760405162461bcd60e51b815260040161057c906148c0565b8051156138b25780806020019051810190613f74919061438e565b6138b25760405162461bcd60e51b815260040161057c90614c4e565b60006113d9670de0b6b3a7640000610fba613fab8686613250565b6141fa565b60006001600160a01b03821663b93f9b0a600c61313e565b60006001600160a01b03821663fc56365860056131e4565b60006001600160a01b03821663fc56365860066131e4565b600061179d620f4240610fba84670de0b6b3a7640000613250565b815460009082106140365760405162461bcd60e51b815260040161057c90614644565b82600001828154811061404557fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b600061179d61407d614214565b610fba670de0b6b3a764000061352886613ff8565b60006001600160a01b03821663b93f9b0a600661313e565b5490565b60006140ba8383614058565b6140f05750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561179d565b50600061179d565b600081815260018301602052604081205480156141b4578354600019808301919081019060009087908390811061412b57fe5b906000526020600020015490508087600001848154811061414857fe5b60009182526020808320909101929092558281526001898101909252604090209084019055865487908061417857fe5b6001900381819060005260206000200160009055905586600101600087815260200190815260200160002060009055600194505050505061179d565b600091505061179d565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4708181148015906141f257508115155b949350505050565b600061179d612032670de0b6b3a7640000620f424061328a565b6101c65460009061422d906001600160a01b0316613000565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561426557600080fd5b505afa158015614279573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611560919061447f565b6040518060800160405280600081526020016000815260200160008152602001600081525090565b60405180606001604052806000815260200160008152602001600081525090565b6040518060a0016040528060006001600160a01b03168152602001600081526020016000815260200160008152602001600081525090565b60006020828403121561432f578081fd5b81356113d981614e9d565b60006020828403121561434b578081fd5b81516113d981614e9d565b60008060408385031215614368578081fd5b823561437381614e9d565b9150602083013561438381614e9d565b809150509250929050565b60006020828403121561439f578081fd5b815180151581146113d9578182fd5b6000602082840312156143bf578081fd5b5035919050565b600080604083850312156143d8578182fd5b82359150602083013561438381614e9d565b600080604083850312156143fc578182fd5b50508035926020909101359150565b600060a0828403121561441c578081fd5b60405160a0810181811067ffffffffffffffff8211171561443b578283fd5b604052825161444981614e9d565b80825250602083015160208201526040830151604082015260608301516060820152608083015160808201528091505092915050565b600060208284031215614490578081fd5b5051919050565b600080604083850312156144a9578182fd5b505080516020909101519092909150565b600080600080600060a086880312156144d1578081fd5b8535945060208601359350604086013560ff811681146144ef578182fd5b94979396509394606081013594506080013592915050565b60008251614519818460208701614e71565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b0397881681529590961660208601526040850193909352606084019190915260ff16608083015260a082015260c081019190915260e00190565b6001600160a01b03929092168252602082015260400190565b901515815260200190565b90815260200190565b6001600160a01b03959095168552602085019390935260408401919091526060830152608082015260a00190565b6001600160a01b0392831681529116602082015260400190565b6000602082528251806020840152614630816040850160208701614e71565b601f01601f19169190910160400192915050565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b602080825260129082015271506f6f6c20686173206e6f20736c6963657360701b604082015260600190565b6020808252601e908201527f4661696c656420746f207472616e7366657220666f72206465706f7369740000604082015260600190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b60208082526014908201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604082015260600190565b60208082526037908201527f416d6f756e74207265717565737465642069732067726561746572207468616e604082015276207768617420746869732061646472657373206f776e7360481b606082015260800190565b60208082526010908201526f115e1a5cdd1a5b99c81c995c5d595cdd60821b604082015260600190565b6020808252602a908201527f4f776e657220616e6420636f6e666967206164647265737365732063616e6e6f6040820152697420626520656d70747960b01b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b60208082526038908201527f4f6e6c7920746f6b656e73206f776e6564206279207468652073656e696f72206040820152773837b7b61031b0b7103132903bb934ba3a32b7103237bbb760411b606082015260800190565b6020808252818101527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564604082015260600190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b602080825260129082015271141bdbdb081b5d5cdd081899481d985b1a5960721b604082015260600190565b6020808252818101527f53616665436173743a2076616c7565206d75737420626520706f736974697665604082015260600190565b6020808252818101527f4f776e65722063616e6e6f7420626520746865207a65726f2061646472657373604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252600a90820152692737ba102d30b83832b960b11b604082015260600190565b6020808252600b908201526a10d85b9d0818d85b98d95b60aa1b604082015260600190565b6020808252600d908201526c2d32b93790323ab930ba34b7b760991b604082015260600190565b6020808252601c908201527f4d757374207769746864726177206d6f7265207468616e207a65726f00000000604082015260600190565b6020808252600290820152614e4160f01b604082015260600190565b6020808252600f908201526e6e6f7420656e6f756768207573646360881b604082015260600190565b60208082526022908201527f496e766573746d656e7420616d6f756e74206d75737420626520706f73697469604082015261766560f01b606082015260800190565b60208082526028908201527f53616665436173743a2076616c756520646f65736e27742066697420696e2061604082015267371034b73a191a9b60c11b606082015260800190565b60208082526024908201527f5369676e6564536166654d6174683a207375627472616374696f6e206f766572604082015263666c6f7760e01b606082015260800190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b6020808252600b908201526a496e76616c69642042707360a81b604082015260600190565b6020808252601f908201527f5361666545524332303a2063616c6c20746f206e6f6e2d636f6e747261637400604082015260600190565b6020808252602b908201527f4d75737420686176652061646d696e20726f6c6520746f20706572666f726d2060408201526a3a3434b99030b1ba34b7b760a91b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b6020808252601b908201527f4d757374206465706f736974206d6f7265207468616e207a65726f0000000000604082015260600190565b8151815260208083015190820152604080830151908201526060918201519181019190915260800190565b81518152602080830151908201526040918201519181019190915260600190565b918252602082015260400190565b93845260208401929092526040830152606082015260800190565b60005b83811015614e8c578181015183820152602001614e74565b838111156138b25750506000910152565b6001600160a01b038116811461146857600080fdfeb19546dff01e856fb3f010c267a7b1c60363cf8a4664e21cc89c26224620214ed624b04b6a86de88625cc0780256b85157c5a615db56d1357e0a97a30fde276765d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862aa26469706673582212202bea0517267f8046e9834c584624310728f56f29c4a582d110ce683607aa110e64736f6c634300060c0033

Deployed Bytecode

0x608060405234801561001057600080fd5b506004361061027f5760003560e01c806379502c551161015c578063adfa3308116100ce578063d547741f11610087578063d547741f14610505578063da4c5a9714610518578063db006a751461052b578063e58378bb1461053e578063e63ab1e914610546578063ed80c8501461054e5761027f565b8063adfa3308146104a9578063b6b55f25146104bc578063b6db75a0146104cf578063c5923023146104d7578063ca15c873146104df578063cf5f1f62146104f25761027f565b80639010d07c116101205780639010d07c1461044d57806391d1485414610460578063945ed49a146104735780639ee679e814610486578063a217fddf14610499578063a6f4487e146104a15761027f565b806379502c55146104025780637e30cdff146104175780638456cb591461042a578063855cb21b1461043257806387269729146104455761027f565b8063485cc955116101f5578063526d81f6116101b9578063526d81f6146103a257806358031d12146103aa5780635c975abb146103bd57806371a97305146103d2578063722eeec3146103da57806376671808146103ed5761027f565b8063485cc9551461034c5780634a970be71461035f5780634d4e3e0c146103725780634ff0876a1461037a5780635209cb98146103825761027f565b80632f2ff15d116102475780632f2ff15d146102f05780632f8f68df1461030357806330024dfe1461030b57806336568abe1461031e5780633f4ba83a1461033157806345b05d09146103395761027f565b806303f9c79314610284578063097616a3146102ad578063242d68c2146102c2578063248a9ca3146102ca5780632e1a7d4d146102dd575b600080fd5b61029761029236600461431e565b610556565b6040516102a491906145c0565b60405180910390f35b6102c06102bb36600461431e565b61087f565b005b6102976109af565b6102976102d83660046143ae565b610a17565b6102976102eb3660046143ae565b610a2f565b6102c06102fe3660046143c6565b610b01565b610297610b45565b6102c06103193660046143ae565b610bf6565b6102c061032c3660046143c6565b610ce7565b6102c0610d29565b6102976103473660046143ae565b610d69565b6102c061035a366004614356565b61112c565b61029761036d3660046144ba565b611251565b6102976112e6565b6102976112f8565b6103956103903660046143ae565b6112ff565b6040516102a49190614e27565b6102c06113e0565b6102976103b83660046143ae565b61146b565b6103c561153f565b6040516102a491906145b5565b610297611548565b6102976103e83660046143ae565b611565565b6103f5611637565b6040516102a49190614dfc565b61040a61167f565b6040516102a49190614523565b61029761042536600461431e565b61168f565b6102c0611750565b6102976104403660046143ae565b61178e565b6102976117a3565b61040a61045b3660046143ea565b6117aa565b6103c561046e3660046143c6565b6117c2565b6102c06104813660046143ae565b6117da565b6102976104943660046143ae565b611b2d565b610297611e2f565b610297611e34565b6102976104b73660046143ae565b611e3b565b6102976104ca3660046143ae565b6120e1565b6103c56123a3565b6102c06123bf565b6102976104ed3660046143ae565b6124ee565b6102976105003660046143ae565b612505565b6102c06105133660046143c6565b612518565b6102c06105263660046143ea565b612552565b6102c06105393660046143ae565b6127c3565b610297612966565b610297612978565b61029761298a565b60975460009060ff16156105855760405162461bcd60e51b815260040161057c90614945565b60405180910390fd5b60c95460ff166105a75760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556105ba82612991565b6105d65760405162461bcd60e51b815260040161057c9061496f565b6105de612a25565b506101c6546000906105f8906001600160a01b0316612a37565b90506000816001600160a01b031663ff8a4efe30866040518363ffffffff1660e01b815260040161062a9291906145f7565b60206040518083038186803b15801561064257600080fd5b505afa158015610656573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061067a919061447f565b90506000811161069c5760405162461bcd60e51b815260040161057c90614b80565b6101cd548111156106bf5760405162461bcd60e51b815260040161057c90614b57565b6101cd546106cd9082612a42565b6101cd556106db8482612a84565b6000846001600160a01b0316637976323d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561071657600080fd5b505afa15801561072a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061074e919061447f565b905060018110156107715760405162461bcd60e51b815260040161057c90614686565b600061077e826001612a42565b9050600061078b82612b29565b6101c45490915061079c9085612b3b565b6101c455604051631c57762b60e31b81526000906001600160a01b0389169063e2bbb158906107d19085908990600401614e48565b602060405180830381600087803b1580156107eb57600080fd5b505af11580156107ff573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610823919061447f565b9050876001600160a01b03167f86da25fff7a4075a94de2ffed109ca6748c3af22736eaf7efc75e3988f899d6e8660405161085e91906145c0565b60405180910390a29550505050505060c9805460ff19166001179055919050565b600054610100900460ff16806108985750610898612b60565b806108a6575060005460ff16155b6108c25760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff161580156108ed576000805460ff1961ff0019909116610100171660011790555b6001600160a01b0382166109135760405162461bcd60e51b815260040161057c906149d0565b61091b612b66565b610923612be7565b61092b612c73565b610943600080516020614eb383398151915283610b3b565b61095b600080516020614ef383398151915283610b3b565b610981600080516020614ef3833981519152600080516020614eb3833981519152612d02565b610999600080516020614eb383398151915280612d02565b80156109ab576000805461ff00191690555b5050565b60006109b961429d565b6109f86109c4612d17565b6040805160808101825282548152600183015460208201526002830154918101919091526003909101546060820152612d2d565b5060608101516101cd5491925090610a109082612a42565b9250505090565b6000818152606560205260409020600201545b919050565b60975460009060ff1615610a555760405162461bcd60e51b815260040161057c90614945565b60c95460ff16610a775760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff19169055610a99600080516020614ed3833981519152336117c2565b610ab55760405162461bcd60e51b815260040161057c90614a94565b60008211610ad55760405162461bcd60e51b815260040161057c90614b04565b6000610ae08361178e565b9050610aec8382612dd4565b91505060c9805460ff19166001179055919050565b600082815260656020526040902060020154610b1f9061046e612f93565b610b3b5760405162461bcd60e51b815260040161057c906146e9565b6109ab8282612f97565b6000610b4f61429d565b610b5a6109c4612d17565b5060408101516101c65491925090610a10908290610b80906001600160a01b0316613000565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015610bb857600080fd5b505afa158015610bcc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf0919061447f565b90612a42565b610bfe6123a3565b610c1a5760405162461bcd60e51b815260040161057c90614d2b565b60008111610c3a5760405162461bcd60e51b815260040161057c90614add565b6000610c44612a25565b90504281600001541115610c91576101ce548154600091610c659190612a42565b6101ce8490559050610c8083610c7a8361300b565b90612b3b565b8083554210610c8b57fe5b50610ca5565b610ca282610c7a836000015461300b565b81555b6101ce8290556040517fc1057a49fd826ed693f6611f22b406e8f41bf73b45b6e8f757d4b14a58d6e9f190610cdb9084906145c0565b60405180910390a15050565b610cef612f93565b6001600160a01b0316816001600160a01b031614610d1f5760405162461bcd60e51b815260040161057c90614d76565b6109ab828261304a565b610d43600080516020614ef383398151915261046e612f93565b610d5f5760405162461bcd60e51b815260040161057c90614b3b565b610d676130b3565b565b60975460009060ff1615610d8f5760405162461bcd60e51b815260040161057c90614945565b60c95460ff16610db15760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654610dd1906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b8152600401610dfc9190614523565b60206040518083038186803b158015610e1457600080fd5b505afa158015610e28573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e4c919061438e565b610e685760405162461bcd60e51b815260040161057c90614b3b565b6101c654610e7e906001600160a01b031661312a565b6001600160a01b0316636352211e836040518263ffffffff1660e01b8152600401610ea991906145c0565b60206040518083038186803b158015610ec157600080fd5b505afa158015610ed5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef9919061433a565b6001600160a01b0316336001600160a01b031614610f295760405162461bcd60e51b815260040161057c90614b3b565b600080610f35846131aa565b91509150806002015460001415610f5e5760405162461bcd60e51b815260040161057c90614ab8565b6101c654600090610f77906001600160a01b03166131d0565b9050612710811115610f9b5760405162461bcd60e51b815260040161057c90614ccf565b6000610fc0612710610fba84866002015461325090919063ffffffff16565b9061328a565b90506000610fdb828560020154612a4290919063ffffffff16565b9050610ff884600201548660010154612a4290919063ffffffff16565b6001808701919091556000600286015584015461101857611018876132cc565b6101c6546110469033908390611036906001600160a01b0316613000565b6001600160a01b0316919061335f565b6101c65460009061105f906001600160a01b03166133b5565b6101c6549091506110809082908590611036906001600160a01b0316613000565b806001600160a01b0316336001600160a01b03167f2f47cf1f0d4e562a169cd1c3cbfbe9735c1fc3e12354494efb79ec1562e37272856040516110c391906145c0565b60405180910390a3336001600160a01b0316886101ca547ff88bc062cd1e95f16709f69e70c521e62602c9d2a875ad4882e8035d15eb3ad5858760405161110b929190614e48565b60405180910390a45094505050505060c9805460ff19166001179055919050565b600054610100900460ff16806111455750611145612b60565b80611153575060005460ff16155b61116f5760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff1615801561119a576000805460ff1961ff0019909116610100171660011790555b6001600160a01b038316158015906111ba57506001600160a01b03821615155b6111d65760405162461bcd60e51b815260040161057c906147e7565b6111df8361087f565b611205600080516020614ed3833981519152600080516020614eb3833981519152612d02565b6101c680546001600160a01b0319166001600160a01b038416179055670de0b6b3a76400006101c35560006101c48190556101c555801561124c576000805461ff00191690555b505050565b6101c65460009061126a906001600160a01b03166133cd565b6001600160a01b031663d505accf333089898989896040518863ffffffff1660e01b81526004016112a1979695949392919061455b565b600060405180830381600087803b1580156112bb57600080fd5b505af11580156112cf573d6000803e3d6000fd5b505050506112dc866120e1565b9695505050505050565b600080516020614ed383398151915281565b6101ce5490565b6113076142c5565b6101c65461131d906001600160a01b031661312a565b6001600160a01b0316636352211e836040518263ffffffff1660e01b815260040161134891906145c0565b60206040518083038186803b15801561136057600080fd5b505afa158015611374573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611398919061433a565b5060008281526101cc60209081526040918290208251606081018452815481526001820154928101929092526002810154928201929092526113d9906133e5565b9392505050565b600054610100900460ff16806113f957506113f9612b60565b80611407575060005460ff16155b6114235760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff1615801561144e576000805460ff1961ff0019909116610100171660011790555b611456612be7565b8015611468576000805461ff00191690555b50565b60975460009060ff16156114915760405162461bcd60e51b815260040161057c90614945565b60c95460ff166114b35760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556114d5600080516020614ed3833981519152336117c2565b6114f15760405162461bcd60e51b815260040161057c90614a94565b600082116115115760405162461bcd60e51b815260040161057c90614b04565b600061151c8361356a565b9050826115298282612dd4565b9250505060c9805460ff19166001179055919050565b60975460ff1690565b60006115606101c554610bf06101c454610c7a6109af565b905090565b600061156f6142e6565b6101c654611585906001600160a01b0316613579565b6001600160a01b0316638c7a63ae846040518263ffffffff1660e01b81526004016115b091906145c0565b60a06040518083038186803b1580156115c857600080fd5b505afa1580156115dc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611600919061440b565b805160608201516040830151929350909160009161161e9190612a42565b9050600061162c8383613584565b979650505050505050565b61163f61429d565b61164761429d565b60006116546109c4612d17565b9092509050600281600281111561166757fe5b141561167957611676826136bc565b91505b50905090565b6101c6546001600160a01b031681565b600061169a82612991565b6116b65760405162461bcd60e51b815260040161057c9061496f565b6101c6546000906116cf906001600160a01b0316612a37565b604051631f999a2d60e01b81529091506001600160a01b03821690631f999a2d9061170090309087906004016145f7565b60206040518083038186803b15801561171857600080fd5b505afa15801561172c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113d9919061447f565b61176a600080516020614ef383398151915261046e612f93565b6117865760405162461bcd60e51b815260040161057c90614b3b565b610d67613700565b600061179d826101c354613759565b92915050565b6101c35481565b60008281526065602052604081206113d99083613774565b60008281526065602052604081206113d99083613780565b60975460ff16156117fd5760405162461bcd60e51b815260040161057c90614945565b60c95460ff1661181f5760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654600090611842906001600160a01b0316613579565b6040516331a9108f60e11b81529091506001600160a01b03821690636352211e906118719085906004016145c0565b60206040518083038186803b15801561188957600080fd5b505afa15801561189d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118c1919061433a565b6001600160a01b0316306001600160a01b0316146118f15760405162461bcd60e51b815260040161057c90614868565b6118f96142e6565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae906119259086906004016145c0565b60a06040518083038186803b15801561193d57600080fd5b505afa158015611951573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611975919061440b565b805190915061198381612991565b61199f5760405162461bcd60e51b815260040161057c9061496f565b6119a7612a25565b50806001600160a01b031663a6a25e886040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156119e357600080fd5b505af11580156119f7573d6000803e3d6000fd5b5050506060830151604084015160009250611a1191612a42565b9050600080611a208484613584565b60008981526101c96020526040902054919350915082158015611a41575080155b15611a525750505050505050611b1d565b6000611a6f611a6084613795565b611a6984613795565b906137be565b60008a81526101c9602052604090208490559050611a8c81613804565b6000811315611ab457611aab611aa18261386f565b6101c55490612a42565b6101c555611ad3565b611ace611ac4826000190261386f565b6101c55490612b3b565b6101c5555b856001600160a01b03167f176e189790e519c3382df7234bd391cc24005bf9cfaaa9de00103c208e10a27482604051611b0c91906145c0565b60405180910390a250505050505050505b5060c9805460ff19166001179055565b60975460009060ff1615611b535760405162461bcd60e51b815260040161057c90614945565b60c95460ff16611b755760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654600090611b98906001600160a01b031661312a565b6101c654909150611bb1906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b8152600401611bdc9190614523565b60206040518083038186803b158015611bf457600080fd5b505afa158015611c08573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c2c919061438e565b611c485760405162461bcd60e51b815260040161057c90614b3b565b6040516370a0823160e01b81526001600160a01b038216906370a0823190611c74903390600401614523565b60206040518083038186803b158015611c8c57600080fd5b505afa158015611ca0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cc4919061447f565b15611ce15760405162461bcd60e51b815260040161057c906147bd565b6000611ceb612a25565b90506000826001600160a01b0316636a627842336040518263ffffffff1660e01b8152600401611d1b9190614523565b602060405180830381600087803b158015611d3557600080fd5b505af1158015611d49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d6d919061447f565b60008181526101cc602052604090206101ca54815560028101879055600184015491925090611d9c9087612b3b565b60018401556101c654611dd290339030908990611dc1906001600160a01b0316613000565b6001600160a01b0316929190613891565b336001600160a01b0316826101ca547f4bd014c167ac618c18f78afa7c88d8ca69c4e4a9321542b1bf050ed165d78e3b89604051611e1091906145c0565b60405180910390a4509250505060c9805460ff19166001179055919050565b600081565b6101c55481565b60975460009060ff1615611e615760405162461bcd60e51b815260040161057c90614945565b60c95460ff16611e835760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654611ea3906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b8152600401611ece9190614523565b60206040518083038186803b158015611ee657600080fd5b505afa158015611efa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f1e919061438e565b611f3a5760405162461bcd60e51b815260040161057c90614b3b565b6101c654611f50906001600160a01b031661312a565b6001600160a01b0316636352211e836040518263ffffffff1660e01b8152600401611f7b91906145c0565b60206040518083038186803b158015611f9357600080fd5b505afa158015611fa7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fcb919061433a565b6001600160a01b0316336001600160a01b031614611ffb5760405162461bcd60e51b815260040161057c90614b3b565b6000612006836131aa565b6001810180546000918290556101c65492945092509061203990612032906001600160a01b03166138b8565b839061328a565b905060006120478383612a42565b905083600201546000141561205f5761205f866132cc565b61206982336138d0565b6101c6546120879033908390611036906001600160a01b031661393f565b336001600160a01b03167f2d4d49c3e017b8235c908cbaa83a2431a08f3b950712696ece2088964fd399f082846040516120c2929190614e48565b60405180910390a2935050505060c9805460ff19166001179055919050565b60975460009060ff16156121075760405162461bcd60e51b815260040161057c90614945565b60c95460ff166121295760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c654612149906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b81526004016121749190614523565b60206040518083038186803b15801561218c57600080fd5b505afa1580156121a0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121c4919061438e565b6121e05760405162461bcd60e51b815260040161057c90614b3b565b600082116122005760405162461bcd60e51b815260040161057c90614dc5565b612208612a25565b506101cd546122179083612b3b565b6101cd556122248261178e565b9050336001600160a01b03167f0b05f0d1cd0819f155b8a61f60baf7767c1ee49d04aeaab701df236140eb93f98383604051612261929190614e48565b60405180910390a26101c65461227f906001600160a01b031661393f565b6001600160a01b03166323b872dd3330856040518463ffffffff1660e01b81526004016122ae93929190614537565b602060405180830381600087803b1580156122c857600080fd5b505af11580156122dc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612300919061438e565b61231c5760405162461bcd60e51b815260040161057c906146b2565b6101c654612332906001600160a01b0316613000565b6001600160a01b031663449a52f833836040518363ffffffff1660e01b815260040161235f92919061459c565b600060405180830381600087803b15801561237957600080fd5b505af115801561238d573d6000803e3d6000fd5b5050505060c9805460ff19166001179055919050565b6000611560600080516020614eb383398151915261046e612f93565b6123c76123a3565b6123e35760405162461bcd60e51b815260040161057c90614d2b565b600080526101cb6020527f7815f96d61162a6533de7fc4199513d6e939c8cbee1627dfd11ec1fe503f0bb3541561241957600080fd5b621275006101ce556101c654612437906001600160a01b031661393f565b6001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016124629190614523565b60206040518083038186803b15801561247a57600080fd5b505afa15801561248e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124b2919061447f565b6101cd55600080526101cb602052427f7815f96d61162a6533de7fc4199513d6e939c8cbee1627dfd11ec1fe503f0bb39081556114689061394a565b600081815260656020526040812061179d906139d6565b6101c96020526000908152604090205481565b6000828152606560205260409020600201546125369061046e612f93565b610d1f5760405162461bcd60e51b815260040161057c906148f5565b60975460ff16156125755760405162461bcd60e51b815260040161057c90614945565b60c95460ff166125975760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff191690556101c6546125b7906001600160a01b031661311f565b6001600160a01b031663a37b92c9336040518263ffffffff1660e01b81526004016125e29190614523565b60206040518083038186803b1580156125fa57600080fd5b505afa15801561260e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612632919061438e565b61264e5760405162461bcd60e51b815260040161057c90614b3b565b6101c654600090612667906001600160a01b031661312a565b6040516331a9108f60e11b81529091506001600160a01b03821690636352211e906126969085906004016145c0565b60206040518083038186803b1580156126ae57600080fd5b505afa1580156126c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126e6919061433a565b6001600160a01b0316336001600160a01b0316146127165760405162461bcd60e51b815260040161057c90614b3b565b600080612722846131aa565b600281015491935091506127369086612b3b565b6002820155600182015461274a9086612b3b565b60018301556101ca54604051339186917f99e2edbbb2b83be9287a6f12d5ad204eb47b5a9da08ee36e58f714784d753fb690612787908a906145c0565b60405180910390a46101c6546127af90339030908890611dc1906001600160a01b0316613000565b505060c9805460ff19166001179055505050565b60975460ff16156127e65760405162461bcd60e51b815260040161057c90614945565b60c95460ff166128085760405162461bcd60e51b815260040161057c90614c98565b60c9805460ff1916905561281a612a25565b506101c654600090612834906001600160a01b0316613579565b905061283e6142e6565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae9061286a9086906004016145c0565b60a06040518083038186803b15801561288257600080fd5b505afa158015612896573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128ba919061440b565b8051604051632a8a9f1360e21b81529192509060009081906001600160a01b0384169063aa2a7c4c906128f19089906004016145c0565b6040805180830381600087803b15801561290a57600080fd5b505af115801561291e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129429190614497565b915091506129518383836139e1565b505060c9805460ff1916600117905550505050565b600080516020614eb383398151915281565b600080516020614ef383398151915281565b6101c45481565b6101c6546000906129aa906001600160a01b0316613579565b6001600160a01b031663b5ada6d8836040518263ffffffff1660e01b81526004016129d59190614523565b60206040518083038186803b1580156129ed57600080fd5b505afa158015612a01573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061179d919061438e565b6000611560612a32612d17565b613ac7565b600061179d82613ca2565b60006113d983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250613cba565b6101c654600090612a9d906001600160a01b031661393f565b60405163095ea7b360e01b81529091506001600160a01b0382169063095ea7b390612ace908690869060040161459c565b602060405180830381600087803b158015612ae857600080fd5b505af1158015612afc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b20919061438e565b61124c57600080fd5b600061179d6001610c7a846002613250565b6000828201838110156113d95760405162461bcd60e51b815260040161057c90614831565b303b1590565b600054610100900460ff1680612b7f5750612b7f612b60565b80612b8d575060005460ff16155b612ba95760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff16158015611456576000805460ff1961ff0019909116610100171660011790558015611468576000805461ff001916905550565b600054610100900460ff1680612c005750612c00612b60565b80612c0e575060005460ff16155b612c2a5760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff16158015612c55576000805460ff1961ff0019909116610100171660011790555b6097805460ff191690558015611468576000805461ff001916905550565b600054610100900460ff1680612c8c5750612c8c612b60565b80612c9a575060005460ff16155b612cb65760405162461bcd60e51b815260040161057c90614a46565b600054610100900460ff16158015612ce1576000805460ff1961ff0019909116610100171660011790555b60c9805460ff191660011790558015611468576000805461ff001916905550565b60009182526065602052604090912060020155565b6101ca5460009081526101cb6020526040902090565b612d3561429d565b8151600090421015612d4c57508190506000612dcf565b6000612d5b846020015161356a565b9050612d6a846000015161300b565b84526101cd541580612d7a575080155b15612d9d576101ce548451612d8e91612b3b565b84525082915060019050612dcf565b6101cd54600090612dae9083613ce6565b90506000612dbb8261178e565b604087015250606085015250829150600290505b915091565b6000612dde612a25565b506101c654600090612df8906001600160a01b0316613000565b90506000816001600160a01b03166370a08231336040518263ffffffff1660e01b8152600401612e289190614523565b60206040518083038186803b158015612e4057600080fd5b505afa158015612e54573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e78919061447f565b905080841115612e9a5760405162461bcd60e51b815260040161057c90614766565b60408051808201909152600281526124a160f11b60208201526101cd54612ec2918790613cba565b6101cd556101c654859350612ee79033908590611036906001600160a01b031661393f565b60405163079cc67960e41b81526001600160a01b038316906379cc679090612f15903390889060040161459c565b600060405180830381600087803b158015612f2f57600080fd5b505af1158015612f43573d6000803e3d6000fd5b50505050336001600160a01b03167f2d4d49c3e017b8235c908cbaa83a2431a08f3b950712696ece2088964fd399f0846000604051612f83929190614e48565b60405180910390a2505092915050565b3390565b6000828152606560205260409020612faf9082613cfc565b156109ab57612fbc612f93565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600061179d82613d11565b6000806130286101ce54610fba8542612a4290919063ffffffff16565b90506113d96130436101ce548361325090919063ffffffff16565b8490612b3b565b60008281526065602052604090206130629082613d29565b156109ab5761306f612f93565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b60975460ff166130d55760405162461bcd60e51b815260040161057c90614738565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa613108612f93565b6040516131159190614523565b60405180910390a1565b600061179d82613d3e565b60006001600160a01b03821663b93f9b0a60185b6040518263ffffffff1660e01b815260040161315a91906145c0565b60206040518083038186803b15801561317257600080fd5b505afa158015613186573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061179d919061433a565b60008060006131b7612a25565b905060006131c485613d56565b91935090915050915091565b60006001600160a01b03821663fc563658600a5b6040518263ffffffff1660e01b815260040161320091906145c0565b60206040518083038186803b15801561321857600080fd5b505afa15801561322c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061179d919061447f565b60008261325f5750600061179d565b8282028284828161326c57fe5b04146113d95760405162461bcd60e51b815260040161057c90614a05565b60006113d983836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250613e74565b60008181526101cc6020526040812081815560018101829055600201556101c6546132ff906001600160a01b031661312a565b6001600160a01b03166342966c68826040518263ffffffff1660e01b815260040161332a91906145c0565b600060405180830381600087803b15801561334457600080fd5b505af1158015613358573d6000803e3d6000fd5b5050505050565b61124c8363a9059cbb60e01b848460405160240161337e92919061459c565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152613eab565b60006001600160a01b03821663b93f9b0a600761313e565b60006001600160a01b03821663b93f9b0a600561313e565b6133ed6142c5565b6133f561429d565b82515b6101ca54811115801561340f575060008460400151115b1561355e576101cb600082815260200190815260200160002060405180608001604052908160008201548152602001600182015481526020016002820154815260200160038201548152505091506101ca548114156134755761347182612d2d565b5091505b600061349a8360200151610fba8760400151866060015161325090919063ffffffff16565b905060006134c18460200151610fba8860400151876040015161325090919063ffffffff16565b60408701519091506134d39082612a42565b604087015260208601516134e79083612b3b565b602087015260408401511561355457600061352e8560400151610fba64e8d4a51000613528670de0b6b3a76400008a6060015161325090919063ffffffff16565b90613250565b90506000613540886040015183613f90565b159050801561355157600060408901525b50505b50506001016133f8565b50506101ca5482525090565b600061179d826101c354613f90565b600061179d82613fb0565b60008073f0f8d382a4e1e2f26891b1a95f9dcb89406bd4a16397aec1ab856001600160a01b03166347195e136040518163ffffffff1660e01b815260040160206040518083038186803b1580156135da57600080fd5b505afa1580156135ee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613612919061433a565b6101c6548690429061362c906001600160a01b0316613fc8565b6101c654613642906001600160a01b0316613fe0565b6040518663ffffffff1660e01b81526004016136629594939291906145c9565b604080518083038186803b15801561367957600080fd5b505af415801561368d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136b19190614497565b915091509250929050565b6136c461429d565b6136cc61429d565b6101ce5483516136db91612b3b565b8152604083015160208401516000916136f49190612a42565b60208301525092915050565b60975460ff16156137235760405162461bcd60e51b815260040161057c90614945565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258613108612f93565b60006113d982610fba670de0b6b3a764000061352887613ff8565b60006113d98383614013565b60006113d9836001600160a01b038416614058565b6000600160ff1b82106137ba5760405162461bcd60e51b815260040161057c90614bc2565b5090565b60008183038183128015906137d35750838113155b806137e857506000831280156137e857508381135b6113d95760405162461bcd60e51b815260040161057c90614c0a565b61380c612a25565b5060008113156138445760006138296138248361386f565b614070565b6101c35490915061383a9082612b3b565b6101c35550611468565b6000613856613824836000190261386f565b6101c3549091506138679082612a42565b6101c3555050565b6000808212156137ba5760405162461bcd60e51b815260040161057c9061499b565b6138b2846323b872dd60e01b85858560405160240161337e93929190614537565b50505050565b60006001600160a01b03821663fc56365860046131e4565b806001600160a01b03167ff3583f178a8d4f8888c3683f8e948faf9b6eb701c4f1fab265a6ecad1a1ddebb8360405161390991906145c0565b60405180910390a26101c6546109ab9061392b906001600160a01b0316614092565b6101c6548490611036906001600160a01b03165b600061179d826133cd565b60408051608081018252825481526001830154602082015260028301549181019190915260038201546060820152600090613984906136bc565b6101ca8054600190810180835560009081526101cb6020908152604080832086518155918601519382019390935584830151600282015560609094015160039094019390935590548252902092915050565b600061179d826140aa565b60006139ec83614070565b6101c3549091506139fd9082612b3b565b6101c3558215613a4957836001600160a01b03167fed3bc1b58411ea8e764b3ef8fa6b654877bc1e796a5a1a2373dfc8f1c0e0ea4884604051613a4091906145c0565b60405180910390a25b8115613aa357836001600160a01b03167f8295ad220549851bab232c2a7ae2e3c53a63d2294602bc85f8d8af108778a37e83604051613a8891906145c0565b60405180910390a26101c454613a9e9083612a42565b6101c4555b613abd82610c7a856101cd54612b3b90919063ffffffff16565b6101cd5550505050565b6000613ad161429d565b60408051608081018252845481526001850154602082015260028501549181019190915260038401546060820152600090613b0b90612d2d565b90925090506000816002811115613b1e57fe5b1415613b2e578392505050610a2a565b6001816002811115613b3c57fe5b1415613b9357835482518086556101ca5460405190917f9933f8b03549f37c2bd3c203d4e7fd82d3572bbf69a109f58225495710dba98491613b8091908590614e48565b60405180910390a2849350505050610a2a565b60408201516002850155606082015160038501819055825185556101cd54613bba91612a42565b6101cd556101ca546000613bcd8661394a565b6101c654909150613be6906001600160a01b0316613000565b6001600160a01b03166379cc67903088600201546040518363ffffffff1660e01b8152600401613c1792919061459c565b600060405180830381600087803b158015613c3157600080fd5b505af1158015613c45573d6000803e3d6000fd5b50505050817fbb4a26fa0ace13ee4da343896c20eaa44a618fb9071fdd8c2e2c960a4583189d8760000154886001015489600301548a60020154604051613c8f9493929190614e56565b60405180910390a29350610a2a92505050565b60006001600160a01b03821663b93f9b0a600f61313e565b60008184841115613cde5760405162461bcd60e51b815260040161057c9190614611565b505050900390565b6000818310613cf557816113d9565b5090919050565b60006113d9836001600160a01b0384166140ae565b60006001600160a01b03821663b93f9b0a600461313e565b60006113d9836001600160a01b0384166140f8565b60006001600160a01b03821663b93f9b0a601361313e565b60008181526101cc60205260408120805482905b6101ca5481108015613d80575060008360020154115b15613e665760008181526101cb60205260408120600181015460028601546003830154929550613db392610fba91613250565b90506000613dda8460010154610fba8760020154876002015461325090919063ffffffff16565b6002860154909150613dec9082612a42565b60028601556001850154613e009083612b3b565b600186015560028401546003850154600091613e3391610fba9064e8d4a510009061352890670de0b6b3a7640000613250565b90506000613e45876002015483613f90565b1590508015613e5657600060028801555b505060019092019150613d6a9050565b50506101ca54815592915050565b60008183613e955760405162461bcd60e51b815260040161057c9190614611565b506000838581613ea157fe5b0495945050505050565b613ebd826001600160a01b03166141be565b613ed95760405162461bcd60e51b815260040161057c90614cf4565b60006060836001600160a01b031683604051613ef59190614507565b6000604051808303816000865af19150503d8060008114613f32576040519150601f19603f3d011682016040523d82523d6000602084013e613f37565b606091505b509150915081613f595760405162461bcd60e51b815260040161057c906148c0565b8051156138b25780806020019051810190613f74919061438e565b6138b25760405162461bcd60e51b815260040161057c90614c4e565b60006113d9670de0b6b3a7640000610fba613fab8686613250565b6141fa565b60006001600160a01b03821663b93f9b0a600c61313e565b60006001600160a01b03821663fc56365860056131e4565b60006001600160a01b03821663fc56365860066131e4565b600061179d620f4240610fba84670de0b6b3a7640000613250565b815460009082106140365760405162461bcd60e51b815260040161057c90614644565b82600001828154811061404557fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b600061179d61407d614214565b610fba670de0b6b3a764000061352886613ff8565b60006001600160a01b03821663b93f9b0a600661313e565b5490565b60006140ba8383614058565b6140f05750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561179d565b50600061179d565b600081815260018301602052604081205480156141b4578354600019808301919081019060009087908390811061412b57fe5b906000526020600020015490508087600001848154811061414857fe5b60009182526020808320909101929092558281526001898101909252604090209084019055865487908061417857fe5b6001900381819060005260206000200160009055905586600101600087815260200190815260200160002060009055600194505050505061179d565b600091505061179d565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4708181148015906141f257508115155b949350505050565b600061179d612032670de0b6b3a7640000620f424061328a565b6101c65460009061422d906001600160a01b0316613000565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561426557600080fd5b505afa158015614279573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611560919061447f565b6040518060800160405280600081526020016000815260200160008152602001600081525090565b60405180606001604052806000815260200160008152602001600081525090565b6040518060a0016040528060006001600160a01b03168152602001600081526020016000815260200160008152602001600081525090565b60006020828403121561432f578081fd5b81356113d981614e9d565b60006020828403121561434b578081fd5b81516113d981614e9d565b60008060408385031215614368578081fd5b823561437381614e9d565b9150602083013561438381614e9d565b809150509250929050565b60006020828403121561439f578081fd5b815180151581146113d9578182fd5b6000602082840312156143bf578081fd5b5035919050565b600080604083850312156143d8578182fd5b82359150602083013561438381614e9d565b600080604083850312156143fc578182fd5b50508035926020909101359150565b600060a0828403121561441c578081fd5b60405160a0810181811067ffffffffffffffff8211171561443b578283fd5b604052825161444981614e9d565b80825250602083015160208201526040830151604082015260608301516060820152608083015160808201528091505092915050565b600060208284031215614490578081fd5b5051919050565b600080604083850312156144a9578182fd5b505080516020909101519092909150565b600080600080600060a086880312156144d1578081fd5b8535945060208601359350604086013560ff811681146144ef578182fd5b94979396509394606081013594506080013592915050565b60008251614519818460208701614e71565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b0397881681529590961660208601526040850193909352606084019190915260ff16608083015260a082015260c081019190915260e00190565b6001600160a01b03929092168252602082015260400190565b901515815260200190565b90815260200190565b6001600160a01b03959095168552602085019390935260408401919091526060830152608082015260a00190565b6001600160a01b0392831681529116602082015260400190565b6000602082528251806020840152614630816040850160208701614e71565b601f01601f19169190910160400192915050565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b602080825260129082015271506f6f6c20686173206e6f20736c6963657360701b604082015260600190565b6020808252601e908201527f4661696c656420746f207472616e7366657220666f72206465706f7369740000604082015260600190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b60208082526014908201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604082015260600190565b60208082526037908201527f416d6f756e74207265717565737465642069732067726561746572207468616e604082015276207768617420746869732061646472657373206f776e7360481b606082015260800190565b60208082526010908201526f115e1a5cdd1a5b99c81c995c5d595cdd60821b604082015260600190565b6020808252602a908201527f4f776e657220616e6420636f6e666967206164647265737365732063616e6e6f6040820152697420626520656d70747960b01b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b60208082526038908201527f4f6e6c7920746f6b656e73206f776e6564206279207468652073656e696f72206040820152773837b7b61031b0b7103132903bb934ba3a32b7103237bbb760411b606082015260800190565b6020808252818101527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564604082015260600190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b602080825260129082015271141bdbdb081b5d5cdd081899481d985b1a5960721b604082015260600190565b6020808252818101527f53616665436173743a2076616c7565206d75737420626520706f736974697665604082015260600190565b6020808252818101527f4f776e65722063616e6e6f7420626520746865207a65726f2061646472657373604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252600a90820152692737ba102d30b83832b960b11b604082015260600190565b6020808252600b908201526a10d85b9d0818d85b98d95b60aa1b604082015260600190565b6020808252600d908201526c2d32b93790323ab930ba34b7b760991b604082015260600190565b6020808252601c908201527f4d757374207769746864726177206d6f7265207468616e207a65726f00000000604082015260600190565b6020808252600290820152614e4160f01b604082015260600190565b6020808252600f908201526e6e6f7420656e6f756768207573646360881b604082015260600190565b60208082526022908201527f496e766573746d656e7420616d6f756e74206d75737420626520706f73697469604082015261766560f01b606082015260800190565b60208082526028908201527f53616665436173743a2076616c756520646f65736e27742066697420696e2061604082015267371034b73a191a9b60c11b606082015260800190565b60208082526024908201527f5369676e6564536166654d6174683a207375627472616374696f6e206f766572604082015263666c6f7760e01b606082015260800190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b6020808252600b908201526a496e76616c69642042707360a81b604082015260600190565b6020808252601f908201527f5361666545524332303a2063616c6c20746f206e6f6e2d636f6e747261637400604082015260600190565b6020808252602b908201527f4d75737420686176652061646d696e20726f6c6520746f20706572666f726d2060408201526a3a3434b99030b1ba34b7b760a91b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b6020808252601b908201527f4d757374206465706f736974206d6f7265207468616e207a65726f0000000000604082015260600190565b8151815260208083015190820152604080830151908201526060918201519181019190915260800190565b81518152602080830151908201526040918201519181019190915260600190565b918252602082015260400190565b93845260208401929092526040830152606082015260800190565b60005b83811015614e8c578181015183820152602001614e74565b838111156138b25750506000910152565b6001600160a01b038116811461146857600080fdfeb19546dff01e856fb3f010c267a7b1c60363cf8a4664e21cc89c26224620214ed624b04b6a86de88625cc0780256b85157c5a615db56d1357e0a97a30fde276765d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862aa26469706673582212202bea0517267f8046e9834c584624310728f56f29c4a582d110ce683607aa110e64736f6c634300060c0033

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.