ETH Price: $3,412.25 (-0.27%)

Contract

0xCfA2427c5CFE89BE278C9a6fC4445b497CD61d02
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
0x60806040200715162024-06-11 22:17:35168 days ago1718144255IN
 Create: BackerRewards
0 ETH0.0471135914.22333148

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
BackerRewards

Compiler Version
v0.6.12+commit.27d51765

Optimization Enabled:
Yes with 100 runs

Other Settings:
istanbul EvmVersion, MIT license
File 1 of 46 : BackerRewards.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import {Math} from "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import {Babylonian} from "@uniswap/lib/contracts/libraries/Babylonian.sol";

import {SafeERC20Transfer} from "../library/SafeERC20Transfer.sol";
import {GoldfinchConfig} from "../protocol/core/GoldfinchConfig.sol";
import {ConfigHelper} from "../protocol/core/ConfigHelper.sol";
import {BaseUpgradeablePausable} from "../protocol/core/BaseUpgradeablePausable.sol";
import {IPoolTokens} from "../interfaces/IPoolTokens.sol";
import {ITranchedPool} from "../interfaces/ITranchedPool.sol";
import {IBackerRewards} from "../interfaces/IBackerRewards.sol";
import {IEvents} from "../interfaces/IEvents.sol";
import {IERC20withDec} from "../interfaces/IERC20withDec.sol";

// Basically, Every time a interest payment comes back
// we keep a running total of dollars (totalInterestReceived) until it reaches the maxInterestDollarsEligible limit
// Every dollar of interest received from 0->maxInterestDollarsEligible
// has a allocated amount of rewards based on a sqrt function.

// When a interest payment comes in for a given Pool or the pool balance increases
// we recalculate the pool's accRewardsPerPrincipalDollar

// equation ref `_calculateNewGrossGFIRewardsForInterestAmount()`:
// (sqrtNewTotalInterest - sqrtOrigTotalInterest) / sqrtMaxInterestDollarsEligible * (totalRewards / totalGFISupply)

// When a PoolToken is minted, we set the mint price to the pool's current accRewardsPerPrincipalDollar
// Every time a PoolToken withdraws rewards, we determine the allocated rewards,
// increase that PoolToken's rewardsClaimed, and transfer the owner the gfi

contract BackerRewards is IBackerRewards, BaseUpgradeablePausable, IEvents {
  GoldfinchConfig public config;
  using ConfigHelper for GoldfinchConfig;
  using SafeERC20Transfer for IERC20withDec;

  uint256 internal constant GFI_MANTISSA = 10 ** 18;
  uint256 internal constant FIDU_MANTISSA = 10 ** 18;
  uint256 internal constant USDC_MANTISSA = 10 ** 6;
  uint256 internal constant NUM_TRANCHES_PER_SLICE = 2;

  /// @inheritdoc IBackerRewards
  uint256 public override totalRewards;

  /// @inheritdoc IBackerRewards
  uint256 public override maxInterestDollarsEligible;

  /// @inheritdoc IBackerRewards
  uint256 public override totalInterestReceived;

  /// @inheritdoc IBackerRewards
  uint256 public override totalRewardPercentOfTotalGFI;

  mapping(uint256 => BackerRewardsTokenInfo) public tokens;
  mapping(address => BackerRewardsInfo) public pools;
  mapping(ITranchedPool => StakingRewardsPoolInfo) public poolStakingRewards;

  /// @notice Staking rewards info for each pool token
  mapping(uint256 => StakingRewardsTokenInfo) public tokenStakingRewards;

  // solhint-disable-next-line func-name-mixedcase
  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);
    config = _config;
  }

  /// @inheritdoc IBackerRewards
  function allocateRewards(uint256 _interestPaymentAmount) external override onlyPool nonReentrant {
    // note: do not use a require statment because that will TranchedPool kill execution
    if (_interestPaymentAmount > 0) {
      _allocateRewards(_interestPaymentAmount);
    }
  }

  /**
   * @notice Set the total gfi rewards and the % of total GFI
   * @param _totalRewards The amount of GFI rewards available, expects 10^18 value
   */
  function setTotalRewards(uint256 _totalRewards) public onlyAdmin {
    totalRewards = _totalRewards;
    uint256 totalGFISupply = config.getGFI().totalSupply();
    totalRewardPercentOfTotalGFI = _totalRewards.mul(GFI_MANTISSA).div(totalGFISupply).mul(100);
    emit BackerRewardsSetTotalRewards(_msgSender(), _totalRewards, totalRewardPercentOfTotalGFI);
  }

  /**
   * @notice Set the total interest received to date.
   * This should only be called once on contract deploy.
   * @param _totalInterestReceived The amount of interest the protocol has received to date, expects 10^6 value
   */
  function setTotalInterestReceived(uint256 _totalInterestReceived) public onlyAdmin {
    totalInterestReceived = _totalInterestReceived;
    emit BackerRewardsSetTotalInterestReceived(_msgSender(), _totalInterestReceived);
  }

  /**
   * @notice Set the max dollars across the entire protocol that are eligible for GFI rewards
   * @param _maxInterestDollarsEligible The amount of interest dollars eligible for GFI rewards, expects 10^18 value
   */
  function setMaxInterestDollarsEligible(uint256 _maxInterestDollarsEligible) public onlyAdmin {
    maxInterestDollarsEligible = _maxInterestDollarsEligible;
    emit BackerRewardsSetMaxInterestDollarsEligible(_msgSender(), _maxInterestDollarsEligible);
  }

  /// @inheritdoc IBackerRewards
  function setPoolTokenAccRewardsPerPrincipalDollarAtMint(
    address poolAddress,
    uint256 tokenId
  ) external override {
    require(_msgSender() == config.poolTokensAddress(), "Invalid sender!");
    require(config.getPoolTokens().validPool(poolAddress), "Invalid pool!");
    if (tokens[tokenId].accRewardsPerPrincipalDollarAtMint != 0) {
      return;
    }
    IPoolTokens poolTokens = config.getPoolTokens();
    IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
    require(poolAddress == tokenInfo.pool, "PoolAddress must equal PoolToken pool address");

    tokens[tokenId].accRewardsPerPrincipalDollarAtMint = pools[tokenInfo.pool]
      .accRewardsPerPrincipalDollar;
  }

  /// @inheritdoc IBackerRewards
  function onTranchedPoolDrawdown(uint256 _sliceIndex) external override onlyPool nonReentrant {
    // No-op so the call doesn't revert
  }

  /**
   * @inheritdoc IBackerRewards
   * @dev The sum of newRewardsClaimed across the split tokens MUST be equal to (or be very slightly smaller
   * than, in the case of rounding due to integer division) the original token's rewardsClaimed. Furthermore,
   * they must be split proportional to the original and new token's principalAmounts. This impl validates
   * neither of those things because only the pool tokens contract can call it, and it trusts that the PoolTokens
   * contract doesn't call maliciously.
   */
  function setBackerAndStakingRewardsTokenInfoOnSplit(
    BackerRewardsTokenInfo memory originalBackerRewardsTokenInfo,
    StakingRewardsTokenInfo memory originalStakingRewardsTokenInfo,
    uint256 newTokenId,
    uint256 newRewardsClaimed
  ) external override onlyPoolTokens {
    tokens[newTokenId] = BackerRewardsTokenInfo({
      rewardsClaimed: newRewardsClaimed,
      accRewardsPerPrincipalDollarAtMint: originalBackerRewardsTokenInfo
        .accRewardsPerPrincipalDollarAtMint
    });
    tokenStakingRewards[newTokenId] = originalStakingRewardsTokenInfo;
  }

  /// @inheritdoc IBackerRewards
  function clearTokenInfo(uint256 tokenId) external override onlyPoolTokens {
    delete tokens[tokenId];
    delete tokenStakingRewards[tokenId];
  }

  /// @inheritdoc IBackerRewards
  function getTokenInfo(
    uint256 poolTokenId
  ) external view override returns (BackerRewardsTokenInfo memory) {
    return tokens[poolTokenId];
  }

  /// @inheritdoc IBackerRewards
  function getStakingRewardsTokenInfo(
    uint256 poolTokenId
  ) external view override returns (StakingRewardsTokenInfo memory) {
    return tokenStakingRewards[poolTokenId];
  }

  /// @inheritdoc IBackerRewards
  function getBackerStakingRewardsPoolInfo(
    ITranchedPool pool
  ) external view override returns (StakingRewardsPoolInfo memory) {
    return poolStakingRewards[pool];
  }

  /**
   * @notice Calculate the gross available gfi rewards for a PoolToken
   * @param tokenId Pool token id
   * @return The amount of GFI claimable
   */
  function poolTokenClaimableRewards(uint256 tokenId) public view override returns (uint256) {
    IPoolTokens poolTokens = config.getPoolTokens();
    IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);

    if (_isSeniorTrancheToken(tokenInfo)) {
      return 0;
    }

    // Note: If a TranchedPool is oversubscribed, reward allocations scale down proportionately.

    uint256 diffOfAccRewardsPerPrincipalDollar = pools[tokenInfo.pool]
      .accRewardsPerPrincipalDollar
      .sub(tokens[tokenId].accRewardsPerPrincipalDollarAtMint);
    uint256 rewardsClaimed = tokens[tokenId].rewardsClaimed.mul(GFI_MANTISSA);

    /*
      equation for token claimable rewards:
        token.principalAmount
        * (pool.accRewardsPerPrincipalDollar - token.accRewardsPerPrincipalDollarAtMint)
        - token.rewardsClaimed
    */

    return
      _usdcToAtomic(tokenInfo.principalAmount)
        .mul(diffOfAccRewardsPerPrincipalDollar)
        .sub(rewardsClaimed)
        .div(GFI_MANTISSA);
  }

  /**
   * @notice Calculates the amount of staking rewards already claimed for a PoolToken.
   * This function is provided for the sake of external (e.g. frontend client) consumption;
   * it is not necessary as an input to the mutative calculations in this contract.
   * @param tokenId Pool token id
   * @return The amount of GFI claimed
   */
  function stakingRewardsClaimed(uint256 tokenId) external view returns (uint256) {
    IPoolTokens poolTokens = config.getPoolTokens();
    IPoolTokens.TokenInfo memory poolTokenInfo = poolTokens.getTokenInfo(tokenId);

    if (_isSeniorTrancheToken(poolTokenInfo)) {
      return 0;
    }

    ITranchedPool pool = ITranchedPool(poolTokenInfo.pool);
    uint256 sliceIndex = _juniorTrancheIdToSliceIndex(poolTokenInfo.tranche);

    if (
      !_poolRewardsHaveBeenInitialized(pool) || !_sliceRewardsHaveBeenInitialized(pool, sliceIndex)
    ) {
      return 0;
    }

    StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool];
    StakingRewardsSliceInfo memory sliceInfo = poolInfo.slicesInfo[sliceIndex];
    StakingRewardsTokenInfo memory tokenInfo = tokenStakingRewards[tokenId];

    uint256 sliceAccumulator = sliceInfo.accumulatedRewardsPerTokenAtDrawdown;
    uint256 tokenAccumulator = _getTokenAccumulatorAtLastWithdraw(tokenInfo, sliceInfo);
    uint256 rewardsPerFidu = tokenAccumulator.sub(sliceAccumulator);
    uint256 principalAsFidu = _fiduToUsdc(
      poolTokenInfo.principalAmount,
      sliceInfo.fiduSharePriceAtDrawdown
    );
    uint256 rewards = principalAsFidu.mul(rewardsPerFidu).div(FIDU_MANTISSA);
    return rewards;
  }

  /**
   * @notice PoolToken request to withdraw multiple PoolTokens allocated rewards
   * @param tokenIds Array of pool token id
   */
  function withdrawMultiple(uint256[] calldata tokenIds) public {
    require(tokenIds.length > 0, "TokensIds length must not be 0");

    for (uint256 i = 0; i < tokenIds.length; i++) {
      withdraw(tokenIds[i]);
    }
  }

  /// @inheritdoc IBackerRewards
  function withdraw(uint256 tokenId) public override whenNotPaused nonReentrant returns (uint256) {
    IPoolTokens poolTokens = config.getPoolTokens();
    IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);

    address poolAddr = tokenInfo.pool;
    require(config.getPoolTokens().validPool(poolAddr), "Invalid pool!");
    require(msg.sender == poolTokens.ownerOf(tokenId), "Must be owner of PoolToken");

    BaseUpgradeablePausable pool = BaseUpgradeablePausable(poolAddr);
    require(!pool.paused(), "Pool withdraw paused");

    require(!_isSeniorTrancheToken(tokenInfo), "Ineligible senior tranche token");

    uint256 claimableBackerRewards = poolTokenClaimableRewards(tokenId);
    uint256 claimableStakingRewards = stakingRewardsEarnedSinceLastWithdraw(tokenId);
    uint256 totalClaimableRewards = claimableBackerRewards.add(claimableStakingRewards);
    uint256 poolTokenRewardsClaimed = tokens[tokenId].rewardsClaimed;

    // Only account for claimed backer rewards, the staking rewards should not impact the
    // distribution of backer rewards
    tokens[tokenId].rewardsClaimed = poolTokenRewardsClaimed.add(claimableBackerRewards);

    if (claimableStakingRewards != 0) {
      _checkpointTokenStakingRewards(tokenId);
    }

    config.getGFI().safeERC20Transfer(poolTokens.ownerOf(tokenId), totalClaimableRewards);
    emit BackerRewardsClaimed(
      _msgSender(),
      tokenId,
      claimableBackerRewards,
      claimableStakingRewards
    );

    return totalClaimableRewards;
  }

  /**
   * @notice Returns the amount of staking rewards earned by a given token since the last
   * time its staking rewards were withdrawn.
   * @param tokenId token id to get rewards
   * @return amount of rewards
   */
  function stakingRewardsEarnedSinceLastWithdraw(uint256 tokenId) public view returns (uint256) {
    IPoolTokens.TokenInfo memory poolTokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
    if (_isSeniorTrancheToken(poolTokenInfo)) {
      return 0;
    }

    ITranchedPool pool = ITranchedPool(poolTokenInfo.pool);
    uint256 sliceIndex = _juniorTrancheIdToSliceIndex(poolTokenInfo.tranche);

    if (
      !_poolRewardsHaveBeenInitialized(pool) || !_sliceRewardsHaveBeenInitialized(pool, sliceIndex)
    ) {
      return 0;
    }

    StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool];
    StakingRewardsSliceInfo memory sliceInfo = poolInfo.slicesInfo[sliceIndex];
    StakingRewardsTokenInfo memory tokenInfo = tokenStakingRewards[tokenId];

    uint256 sliceAccumulator = _getSliceAccumulatorAtLastCheckpoint(sliceInfo, poolInfo);
    uint256 tokenAccumulator = _getTokenAccumulatorAtLastWithdraw(tokenInfo, sliceInfo);
    uint256 rewardsPerFidu = sliceAccumulator.sub(tokenAccumulator);
    uint256 principalAsFidu = _fiduToUsdc(
      poolTokenInfo.principalAmount,
      sliceInfo.fiduSharePriceAtDrawdown
    );
    uint256 rewards = principalAsFidu.mul(rewardsPerFidu).div(FIDU_MANTISSA);
    return rewards;
  }

  /* Internal functions  */
  function _allocateRewards(uint256 _interestPaymentAmount) internal {
    uint256 _totalInterestReceived = totalInterestReceived;
    if (_usdcToAtomic(_totalInterestReceived) >= maxInterestDollarsEligible) {
      return;
    }

    address _poolAddress = _msgSender();

    // Gross GFI Rewards earned for incoming interest dollars
    uint256 newGrossRewards = _calculateNewGrossGFIRewardsForInterestAmount(_interestPaymentAmount);

    ITranchedPool pool = ITranchedPool(_poolAddress);
    BackerRewardsInfo storage _poolInfo = pools[_poolAddress];

    uint256 totalJuniorDepositsAtomic = _usdcToAtomic(pool.totalJuniorDeposits());
    // If total junior deposits are 0, or less than 1, allocate no rewards. The latter condition
    // is necessary to prevent a perverse, "infinite mint" scenario in which we'd allocate
    // an even greater amount of rewards than `newGrossRewards`, due to dividing by less than 1.
    // This scenario and its mitigation are analogous to that of
    // `StakingRewards.additionalRewardsPerTokenSinceLastUpdate()`.

    if (totalJuniorDepositsAtomic < GFI_MANTISSA) {
      emit SafetyCheckTriggered();
      return;
    }

    // example: (6708203932437400000000 * 10^18) / (100000*10^18)
    _poolInfo.accRewardsPerPrincipalDollar = _poolInfo.accRewardsPerPrincipalDollar.add(
      newGrossRewards.mul(GFI_MANTISSA).div(totalJuniorDepositsAtomic)
    );

    totalInterestReceived = _totalInterestReceived.add(_interestPaymentAmount);
  }

  /**
   * @notice Updates the staking rewards accounting for for a given tokenId
   * @param tokenId token id to checkpoint
   */
  function _checkpointTokenStakingRewards(uint256 tokenId) internal {
    IPoolTokens poolTokens = config.getPoolTokens();
    IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
    require(!_isSeniorTrancheToken(tokenInfo), "Ineligible senior tranche token");

    ITranchedPool pool = ITranchedPool(tokenInfo.pool);
    StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool];
    uint256 sliceIndex = _juniorTrancheIdToSliceIndex(tokenInfo.tranche);
    StakingRewardsSliceInfo memory sliceInfo = poolInfo.slicesInfo[sliceIndex];

    uint256 newAccumulatedRewardsPerTokenAtLastWithdraw = _getSliceAccumulatorAtLastCheckpoint(
      sliceInfo,
      poolInfo
    );

    // If for any reason the new accumulator is less than our last one, abort for safety.
    if (
      newAccumulatedRewardsPerTokenAtLastWithdraw <
      tokenStakingRewards[tokenId].accumulatedRewardsPerTokenAtLastWithdraw
    ) {
      emit SafetyCheckTriggered();
      return;
    }

    tokenStakingRewards[tokenId]
      .accumulatedRewardsPerTokenAtLastWithdraw = newAccumulatedRewardsPerTokenAtLastWithdraw;
  }

  /**
   * @notice Calculate the rewards earned for a given interest payment
   * @param _interestPaymentAmount interest payment amount times 1e6
   */
  function _calculateNewGrossGFIRewardsForInterestAmount(
    uint256 _interestPaymentAmount
  ) internal view returns (uint256) {
    uint256 totalGFISupply = config.getGFI().totalSupply();

    // incoming interest payment, times * 1e18 divided by 1e6
    uint256 interestPaymentAmount = _usdcToAtomic(_interestPaymentAmount);

    // all-time interest payments prior to the incoming amount, times 1e18
    uint256 _previousTotalInterestReceived = _usdcToAtomic(totalInterestReceived);
    uint256 sqrtOrigTotalInterest = Babylonian.sqrt(_previousTotalInterestReceived);

    // sum of new interest payment + previous total interest payments, times 1e18
    uint256 newTotalInterest = _usdcToAtomic(
      _atomicToUsdc(_previousTotalInterestReceived).add(_atomicToUsdc(interestPaymentAmount))
    );

    // interest payment passed the maxInterestDollarsEligible cap, should only partially be rewarded
    if (newTotalInterest > maxInterestDollarsEligible) {
      newTotalInterest = maxInterestDollarsEligible;
    }

    /*
      equation:
        (sqrtNewTotalInterest-sqrtOrigTotalInterest)
        * totalRewardPercentOfTotalGFI
        / sqrtMaxInterestDollarsEligible
        / 100
        * totalGFISupply
        / 10^18

      example scenario:
      - new payment = 5000*10^18
      - original interest received = 0*10^18
      - total reward percent = 3 * 10^18
      - max interest dollars = 1 * 10^27 ($1 billion)
      - totalGfiSupply = 100_000_000 * 10^18

      example math:
        (70710678118 - 0)
        * 3000000000000000000
        / 31622776601683
        / 100
        * 100000000000000000000000000
        / 10^18
        = 6708203932437400000000 (6,708.2039 GFI)
    */
    uint256 sqrtDiff = Babylonian.sqrt(newTotalInterest).sub(sqrtOrigTotalInterest);
    uint256 sqrtMaxInterestDollarsEligible = Babylonian.sqrt(maxInterestDollarsEligible);

    require(sqrtMaxInterestDollarsEligible > 0, "maxInterestDollarsEligible must not be zero");

    uint256 newGrossRewards = sqrtDiff
      .mul(totalRewardPercentOfTotalGFI)
      .div(sqrtMaxInterestDollarsEligible)
      .div(100)
      .mul(totalGFISupply)
      .div(GFI_MANTISSA);

    // Extra safety check to make sure the logic is capped at a ceiling of potential rewards
    // Calculating the gfi/$ for first dollar of interest to the protocol, and multiplying by new interest amount
    uint256 absoluteMaxGfiCheckPerDollar = Babylonian
      .sqrt((uint256)(1).mul(GFI_MANTISSA))
      .mul(totalRewardPercentOfTotalGFI)
      .div(sqrtMaxInterestDollarsEligible)
      .div(100)
      .mul(totalGFISupply)
      .div(GFI_MANTISSA);
    require(
      newGrossRewards < absoluteMaxGfiCheckPerDollar.mul(newTotalInterest),
      "newGrossRewards cannot be greater then the max gfi per dollar"
    );

    return newGrossRewards;
  }

  /**
   * @return Whether the provided `tokenInfo` is a token corresponding to a senior tranche.
   */
  function _isSeniorTrancheToken(
    IPoolTokens.TokenInfo memory tokenInfo
  ) internal pure returns (bool) {
    return tokenInfo.tranche.mod(NUM_TRANCHES_PER_SLICE) == 1;
  }

  /// @notice Returns an amount with the base of usdc (1e6) as an 1e18 number
  function _usdcToAtomic(uint256 amount) internal pure returns (uint256) {
    return amount.mul(GFI_MANTISSA).div(USDC_MANTISSA);
  }

  /// @notice Returns an amount with the base 1e18 as a usdc amount (1e6)
  function _atomicToUsdc(uint256 amount) internal pure returns (uint256) {
    return amount.div(GFI_MANTISSA.div(USDC_MANTISSA));
  }

  /// @notice Returns the equivalent amount of USDC given an amount of fidu and a share price
  /// @param amount amount of FIDU
  /// @param sharePrice share price of FIDU
  /// @return equivalent amount of USDC
  function _fiduToUsdc(uint256 amount, uint256 sharePrice) internal pure returns (uint256) {
    return _usdcToAtomic(amount).mul(FIDU_MANTISSA).div(sharePrice);
  }

  /// @notice Returns the slice index for the given junior tranche id
  /// @param trancheId tranche id
  /// @return slice index that the given tranche id belongs to
  function _juniorTrancheIdToSliceIndex(uint256 trancheId) internal pure returns (uint256) {
    return trancheId.sub(1).div(2);
  }

  /// @notice Returns true if a TranchedPool's rewards parameters have been initialized, otherwise false
  /// @param pool pool to check rewards info
  function _poolRewardsHaveBeenInitialized(ITranchedPool pool) internal view returns (bool) {
    StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool];
    return _poolStakingRewardsInfoHaveBeenInitialized(poolInfo);
  }

  /// @notice Returns true if a given pool's staking rewards parameters have been initialized
  function _poolStakingRewardsInfoHaveBeenInitialized(
    StakingRewardsPoolInfo memory poolInfo
  ) internal pure returns (bool) {
    return poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint != 0;
  }

  /// @notice Returns true if a TranchedPool's slice's rewards parameters have been initialized, otherwise false
  function _sliceRewardsHaveBeenInitialized(
    ITranchedPool pool,
    uint256 sliceIndex
  ) internal view returns (bool) {
    StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool];
    return
      poolInfo.slicesInfo.length > sliceIndex &&
      poolInfo.slicesInfo[sliceIndex].unrealizedAccumulatedRewardsPerTokenAtLastCheckpoint != 0;
  }

  /// @notice Return a slice's rewards accumulator if it has been intialized,
  ///           otherwise return the TranchedPool's accumulator
  function _getSliceAccumulatorAtLastCheckpoint(
    StakingRewardsSliceInfo memory sliceInfo,
    StakingRewardsPoolInfo memory poolInfo
  ) internal pure returns (uint256) {
    require(
      poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint != 0,
      "unsafe: pool accumulator hasn't been initialized"
    );
    bool sliceHasNotReceivedAPayment = sliceInfo.accumulatedRewardsPerTokenAtLastCheckpoint == 0;
    return
      sliceHasNotReceivedAPayment
        ? poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint
        : sliceInfo.accumulatedRewardsPerTokenAtLastCheckpoint;
  }

  /// @notice Return a tokenss rewards accumulator if its been initialized, otherwise return the slice's accumulator
  function _getTokenAccumulatorAtLastWithdraw(
    StakingRewardsTokenInfo memory tokenInfo,
    StakingRewardsSliceInfo memory sliceInfo
  ) internal pure returns (uint256) {
    require(
      sliceInfo.accumulatedRewardsPerTokenAtDrawdown != 0,
      "unsafe: slice accumulator hasn't been initialized"
    );
    bool hasNotWithdrawn = tokenInfo.accumulatedRewardsPerTokenAtLastWithdraw == 0;
    if (hasNotWithdrawn) {
      return sliceInfo.accumulatedRewardsPerTokenAtDrawdown;
    } else {
      require(
        tokenInfo.accumulatedRewardsPerTokenAtLastWithdraw >=
          sliceInfo.accumulatedRewardsPerTokenAtDrawdown,
        "Unexpected token accumulator"
      );
      return tokenInfo.accumulatedRewardsPerTokenAtLastWithdraw;
    }
  }

  /* ======== MODIFIERS  ======== */

  modifier onlyPoolTokens() {
    require(msg.sender == address(config.getPoolTokens()), "Not PoolTokens");
    _;
  }

  modifier onlyPool() {
    require(config.getPoolTokens().validPool(_msgSender()), "Invalid pool!");
    _;
  }

  /* ======== EVENTS ======== */
  event BackerRewardsClaimed(
    address indexed owner,
    uint256 indexed tokenId,
    uint256 amountOfTranchedPoolRewards,
    uint256 amountOfSeniorPoolRewards
  );
  event BackerRewardsSetTotalRewards(
    address indexed owner,
    uint256 totalRewards,
    uint256 totalRewardPercentOfTotalGFI
  );
  event BackerRewardsSetTotalInterestReceived(address indexed owner, uint256 totalInterestReceived);
  event BackerRewardsSetMaxInterestDollarsEligible(
    address indexed owner,
    uint256 maxInterestDollarsEligible
  );
}

File 2 of 46 : 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 46 : 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 46 : 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 46 : 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 46 : 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 46 : 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 8 of 46 : 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 9 of 46 : 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 10 of 46 : 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 11 of 46 : 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 12 of 46 : 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 13 of 46 : Babylonian.sol
// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.4.0;

// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
    // credit for this implementation goes to
    // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
    function sqrt(uint256 x) internal pure returns (uint256) {
        if (x == 0) return 0;
        // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
        // however that code costs significantly more gas
        uint256 xx = x;
        uint256 r = 1;
        if (xx >= 0x100000000000000000000000000000000) {
            xx >>= 128;
            r <<= 64;
        }
        if (xx >= 0x10000000000000000) {
            xx >>= 64;
            r <<= 32;
        }
        if (xx >= 0x100000000) {
            xx >>= 32;
            r <<= 16;
        }
        if (xx >= 0x10000) {
            xx >>= 16;
            r <<= 8;
        }
        if (xx >= 0x100) {
            xx >>= 8;
            r <<= 4;
        }
        if (xx >= 0x10) {
            xx >>= 4;
            r <<= 2;
        }
        if (xx >= 0x8) {
            r <<= 1;
        }
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1; // Seven iterations should be enough
        uint256 r1 = x / r;
        return (r < r1 ? r : r1);
    }
}

File 14 of 46 : IBackerRewards.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;

pragma experimental ABIEncoderV2;

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

interface IBackerRewards {
  struct BackerRewardsTokenInfo {
    uint256 rewardsClaimed; // gfi claimed
    uint256 accRewardsPerPrincipalDollarAtMint; // Pool's accRewardsPerPrincipalDollar at PoolToken mint()
  }

  struct BackerRewardsInfo {
    uint256 accRewardsPerPrincipalDollar; // accumulator gfi per interest dollar
  }

  /// @notice Staking rewards parameters relevant to a TranchedPool
  struct StakingRewardsPoolInfo {
    // @notice the value `StakingRewards.accumulatedRewardsPerToken()` at the last checkpoint
    uint256 accumulatedRewardsPerTokenAtLastCheckpoint;
    // @notice last time the rewards info was updated
    //
    // we need this in order to know how much to pro rate rewards after the term is over.
    uint256 lastUpdateTime;
    // @notice staking rewards parameters for each slice of the tranched pool
    StakingRewardsSliceInfo[] slicesInfo;
  }

  /// @notice Staking rewards paramters relevant to a TranchedPool slice
  struct StakingRewardsSliceInfo {
    // @notice fidu share price when the slice is first drawn down
    //
    // we need to save this to calculate what an equivalent position in
    // the senior pool would be at the time the slice is downdown
    uint256 fiduSharePriceAtDrawdown;
    // @notice the amount of principal deployed at the last checkpoint
    //
    // we use this to calculate the amount of principal that should
    // acctually accrue rewards during between the last checkpoint and
    // and subsequent updates
    uint256 principalDeployedAtLastCheckpoint;
    // @notice the value of StakingRewards.accumulatedRewardsPerToken() at time of drawdown
    //
    // we need to keep track of this to use this as a base value to accumulate rewards
    // for tokens. If the token has never claimed staking rewards, we use this value
    // and the current staking rewards accumulator
    uint256 accumulatedRewardsPerTokenAtDrawdown;
    // @notice amount of rewards per token accumulated over the lifetime of the slice that a backer
    //          can claim
    uint256 accumulatedRewardsPerTokenAtLastCheckpoint;
    // @notice the amount of rewards per token accumulated over the lifetime of the slice
    //
    // this value is "unrealized" because backers will be unable to claim against this value.
    // we keep this value so that we can always accumulate rewards for the amount of capital
    // deployed at any point in time, but not allow backers to withdraw them until a payment
    // is made. For example: we want to accumulate rewards when a backer does a drawdown. but
    // a backer shouldn't be allowed to claim rewards until a payment is made.
    //
    // this value is scaled depending on the current proportion of capital currently deployed
    // in the slice. For example, if the staking rewards contract accrued 10 rewards per token
    // between the current checkpoint and a new update, and only 20% of the capital was deployed
    // during that period, we would accumulate 2 (10 * 20%) rewards.
    uint256 unrealizedAccumulatedRewardsPerTokenAtLastCheckpoint;
  }

  /// @notice Staking rewards parameters relevant to a PoolToken
  struct StakingRewardsTokenInfo {
    // @notice the amount of rewards accumulated the last time a token's rewards were withdrawn
    uint256 accumulatedRewardsPerTokenAtLastWithdraw;
  }

  /// @notice total amount of GFI rewards available, times 1e18
  function totalRewards() external view returns (uint256);

  /// @notice interest $ eligible for gfi rewards, times 1e18
  function maxInterestDollarsEligible() external view returns (uint256);

  /// @notice counter of total interest repayments, times 1e6
  function totalInterestReceived() external view returns (uint256);

  /// @notice totalRewards/totalGFISupply * 100, times 1e18
  function totalRewardPercentOfTotalGFI() external view returns (uint256);

  /// @notice Get backer rewards metadata for a pool token
  function getTokenInfo(uint256 poolTokenId) external view returns (BackerRewardsTokenInfo memory);

  /// @notice Get backer staking rewards metadata for a pool token
  function getStakingRewardsTokenInfo(
    uint256 poolTokenId
  ) external view returns (StakingRewardsTokenInfo memory);

  /// @notice Get backer staking rewards for a pool
  function getBackerStakingRewardsPoolInfo(
    ITranchedPool pool
  ) external view returns (StakingRewardsPoolInfo memory);

  /// @notice Calculates the accRewardsPerPrincipalDollar for a given pool,
  ///   when a interest payment is received by the protocol
  /// @param _interestPaymentAmount Atomic usdc amount of the interest payment
  function allocateRewards(uint256 _interestPaymentAmount) external;

  /// @notice callback for TranchedPools when they drawdown
  /// @param sliceIndex index of the tranched pool slice
  /// @dev initializes rewards info for the calling TranchedPool if it's the first
  ///  drawdown for the given slice
  function onTranchedPoolDrawdown(uint256 sliceIndex) external;

  /// @notice When a pool token is minted for multiple drawdowns,
  ///   set accRewardsPerPrincipalDollarAtMint to the current accRewardsPerPrincipalDollar price
  /// @param poolAddress Address of the pool associated with the pool token
  /// @param tokenId Pool token id
  function setPoolTokenAccRewardsPerPrincipalDollarAtMint(
    address poolAddress,
    uint256 tokenId
  ) external;

  /// @notice PoolToken request to withdraw all allocated rewards
  /// @param tokenId Pool token id
  /// @return amount of rewards withdrawn
  function withdraw(uint256 tokenId) external returns (uint256);

  /**
   * @notice Set BackerRewards and BackerStakingRewards metadata for tokens created by a pool token split.
   * @param originalBackerRewardsTokenInfo backer rewards info for the pool token that was split
   * @param originalStakingRewardsTokenInfo backer staking rewards info for the pool token that was split
   * @param newTokenId id of one of the tokens in the split
   * @param newRewardsClaimed rewardsClaimed value for the new token.
   */
  function setBackerAndStakingRewardsTokenInfoOnSplit(
    BackerRewardsTokenInfo memory originalBackerRewardsTokenInfo,
    StakingRewardsTokenInfo memory originalStakingRewardsTokenInfo,
    uint256 newTokenId,
    uint256 newRewardsClaimed
  ) external;

  /**
   * @notice Calculate the gross available gfi rewards for a PoolToken
   * @param tokenId Pool token id
   * @return The amount of GFI claimable
   */
  function poolTokenClaimableRewards(uint256 tokenId) external view returns (uint256);

  /// @notice Clear all BackerRewards and StakingRewards associated data for `tokenId`
  function clearTokenInfo(uint256 tokenId) external;
}

File 15 of 46 : 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 16 of 46 : ICallableLoan.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import {ILoan} from "./ILoan.sol";
import {ISchedule} from "./ISchedule.sol";
import {IGoldfinchConfig} from "./IGoldfinchConfig.sol";

/// A LoanPhase represents a period of time during which certain callable loan actions are prohibited.
/// @param Prefunding Starts when a loan is created and ends at fundableAt.
/// In Prefunding, all actions are prohibited or ineffectual.
/// @param Funding Starts at the fundableAt timestamp and ends at the first borrower drawdown.
/// In Funding, lenders can deposit principal to mint a pool token and they can withdraw their deposited principal.
/// @param DrawdownPeriod Starts when the first borrower drawdown occurs and
/// ends after ConfigHelper.DrawdownPeriodInSeconds elapses.
/// In DrawdownPeriod, the borrower can drawdown principal as many times as they want.
/// Lenders cannot withdraw their principal, deposit new principal, or submit call requests.
/// @param InProgress Starts after ConfigHelper.DrawdownPeriodInSeconds elapses and never ends.
/// In InProgress, all post-funding & drawdown actions are allowed (not withdraw, deposit, or drawdown).
/// When a loan is fully paid back, we do not update the loan state, but most of these actions will
/// be prohibited or ineffectual.
/// There is no "Closed" or "Finished" state because after accounting variables reflect a balance of 0 - the loan
/// will still behave the same.
enum LoanPhase {
  Prefunding,
  Funding,
  DrawdownPeriod,
  InProgress
}

/// @dev A CallableLoan is a loan which allows the lender to call the borrower's principal.
///     The lender can call the borrower's principal at any time, and the borrower must pay back the principal
///     by the end of the call request period.
/// @dev The ICallableLoanErrors interface contains all errors due to Solidity version compatibility with custom errors.
interface ICallableLoan is ILoan {
  /*================================================================================
  Structs
  ================================================================================*/
  /// @param principalDeposited The amount of principal deposited towards this call request period.
  /// @param principalPaid The amount of principal which has already been paid back towards this call request period.
  ///                      There are 3 ways principal paid can enter a CallRequestPeriod.
  ///                      1. Converted from principalReserved after a call request period becomes due.
  ///                      2. Moved from uncalled tranche as the result of a call request.
  ///                      3. Paid directly when a CallRequestPeriod is past due and has a remaining balance.
  /// @param principalReserved The amount of principal reserved for this call request period.
  ///                          Payments to a not-yet-due CallRequestPeriod are applied to principalReserved.
  /// @param interestPaid The amount of interest paid towards this call request period.
  struct CallRequestPeriod {
    uint256 principalDeposited;
    uint256 principalPaid;
    uint256 principalReserved;
    uint256 interestPaid;
  }

  /// @param principalDeposited The amount of uncalled, deposited principal.
  /// @param principalPaid The amount of principal which has already been paid back.
  ///                      There are two ways uncalled principal can be paid.
  ///                      1. Remainder after drawdowns.
  ///                      2. Conversion from principalReserved after a call request period becomes due.
  ///                         All call requested principal outstanding must already be paid
  ///                         (or have principal reserved) before uncalled principal can be paid.
  ///                      3. Paid directly after term end time.
  /// @param principalReserved The amount of principal reserved for uncalled tranche.
  ///                          principalReserved is greedily moved to call request periods (as much as can fill)
  ///                          when a call request is submitted.
  /// @param interestPaid The amount of interest paid towards uncalled capital.
  struct UncalledCapitalInfo {
    uint256 principalDeposited;
    uint256 principalPaid;
    uint256 principalReserved;
    uint256 interestPaid;
  }

  /*================================================================================
  Functions
  ================================================================================*/
  /// @notice Initialize the pool. Can only be called once, and should be called in the same transaction as
  ///   contract creation to avoid initialization front-running
  /// @param _config address of GoldfinchConfig
  /// @param _borrower address of borrower, a non-transferrable role for performing privileged actions like
  ///   drawdown
  /// @param _numLockupPeriods the number of periods at the tail end of a principal period during which call requests
  ///   are not allowed
  /// @param _interestApr interest rate for the loan
  /// @param _lateFeeApr late fee interest rate for the loan, which kicks in `LatenessGracePeriodInDays` days after a
  ///   payment becomes late
  /// @param _fundableAt earliest time at which the first slice can be funded
  function initialize(
    IGoldfinchConfig _config,
    address _borrower,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _numLockupPeriods,
    ISchedule _schedule,
    uint256 _lateFeeApr,
    uint256 _fundableAt,
    uint256[] calldata _allowedUIDTypes
  ) external;

  /// @notice Submits a call request for the specified pool token and amount
  ///         Mints a new, called pool token of the called amount.
  ///         Splits off any uncalled amount as a new uncalled pool token.
  /// @param amountToCall The amount of the pool token that should be called.
  /// @param poolTokenId The id of the pool token that should be called.
  /// @return callRequestedTokenId  Token id of the call requested token.
  /// @return remainingTokenId Token id of the remaining token.
  function submitCall(
    uint256 amountToCall,
    uint256 poolTokenId
  ) external returns (uint256, uint256);

  function schedule() external view returns (ISchedule);

  function nextDueTimeAt(uint256 timestamp) external view returns (uint256);

  function nextPrincipalDueTime() external view returns (uint256);

  function numLockupPeriods() external view returns (uint256);

  function inLockupPeriod() external view returns (bool);

  function getUncalledCapitalInfo() external view returns (UncalledCapitalInfo memory);

  function getCallRequestPeriod(
    uint256 callRequestPeriodIndex
  ) external view returns (CallRequestPeriod memory);

  function uncalledCapitalTrancheIndex() external view returns (uint256);

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

  /// @notice Returns the current phase of the loan.
  ///         See documentation on LoanPhase enum.
  function loanPhase() external view returns (LoanPhase);

  /// @notice Returns the current balance of the loan which will be used for
  ///         interest calculations.
  ///         Settles any principal reserved if a call request period has
  ///         ended since the last checkpoint
  ///         Excludes principal reserved for future call request periods
  function interestBearingBalance() external view returns (uint256);

  /// @notice Returns a naive estimate of the interest owed at the timestamp.
  ///         Omits any late fees, and assumes no future payments.
  function estimateOwedInterestAt(uint256 timestamp) external view returns (uint256);

  /// @notice Returns a naive estimate of the interest owed at the timestamp.
  ///         Omits any late fees, and assumes no future payments.
  function estimateOwedInterestAt(
    uint256 balance,
    uint256 timestamp
  ) external view returns (uint256);

  /*================================================================================
  Events
  ================================================================================*/
  event CallRequestSubmitted(
    uint256 indexed originalTokenId,
    uint256 indexed callRequestedTokenId,
    uint256 indexed remainingTokenId,
    uint256 callAmount
  );
  event DepositsLocked(address indexed loan);
}

File 17 of 46 : ICreditLine.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

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

import {ICreditLine} from "./ICreditLine.sol";
import {ISchedule} from "./ISchedule.sol";

interface ICreditLine {
  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);

  function borrower() external view returns (address);

  function currentLimit() external view returns (uint256);

  function limit() external view returns (uint256);

  function maxLimit() external view returns (uint256);

  function interestApr() external view returns (uint256);

  function lateFeeApr() external view returns (uint256);

  function isLate() external view returns (bool);

  function withinPrincipalGracePeriod() external view returns (bool);

  /// @notice Cumulative interest accrued up to now
  function totalInterestAccrued() external view returns (uint256);

  /// @notice Cumulative interest accrued up to `timestamp`
  function totalInterestAccruedAt(uint256 timestamp) external view returns (uint256);

  /// @notice Cumulative interest paid back up to now
  function totalInterestPaid() external view returns (uint256);

  /// @notice Cumulative interest owed up to now
  function totalInterestOwed() external view returns (uint256);

  /// @notice Cumulative interest owed up to `timestamp`
  function totalInterestOwedAt(uint256 timestamp) external view returns (uint256);

  /// @notice Interest that would be owed at `timestamp`
  function interestOwedAt(uint256 timestamp) external view returns (uint256);

  /// @notice Interest accrued in the current payment period up to now. Converted to
  ///   owed interest once we cross into the next payment period. Is 0 if the
  ///   current time is after loan maturity (all interest accrued immediately becomes
  ///   interest owed).
  function interestAccrued() external view returns (uint256);

  /// @notice Interest accrued in the current payment period for `timestamp`. Coverted to
  ///   owed interest once we cross into the payment period after `timestamp`. Is 0
  ///   if `timestamp` is after loan maturity (all interest accrued immediately becomes
  ///   interest owed).
  function interestAccruedAt(uint256 timestamp) external view returns (uint256);

  /// @notice Principal owed up to `timestamp`
  function principalOwedAt(uint256 timestamp) external view returns (uint256);

  /// @notice Returns the total amount of principal thats been paid
  function totalPrincipalPaid() external view returns (uint256);

  /// @notice Cumulative principal owed at timestamp
  function totalPrincipalOwedAt(uint256 timestamp) external view returns (uint256);

  /// @notice Cumulative principal owed at current timestamp
  function totalPrincipalOwed() external view returns (uint256);

  function setLimit(uint256 newAmount) external;

  function setMaxLimit(uint256 newAmount) external;

  /// @notice Time of first drawdown
  function termStartTime() external view returns (uint256);

  /// @notice Process a bulk payment, allocating the payment amount based on the payment waterfall
  function pay(uint paymentAmount) external returns (ILoan.PaymentAllocation memory);

  /**
   * Process a payment according to the waterfall described in `Accountant.allocatePayment`
   * @param principalPayment principal payment amount
   * @param interestPayment interest payment amount
   * @return payment allocation
   */
  function pay(
    uint256 principalPayment,
    uint256 interestPayment
  ) external returns (ILoan.PaymentAllocation memory);

  /// @notice Drawdown on the line
  /// @param amount amount to drawdown. Cannot exceed the line's limit
  function drawdown(uint256 amount) external;
}

File 18 of 46 : 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 19 of 46 : 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 20 of 46 : IEvents.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

/// @notice Common events that can be emmitted by multiple contracts
interface IEvents {
  /// @notice Emitted when a safety check fails
  event SafetyCheckTriggered();
}

File 21 of 46 : 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 22 of 46 : 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 23 of 46 : IGoldfinchConfig.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

interface IGoldfinchConfig {
  /**
   * @dev Adds a user to go-list
   * @param _member address to add to go-list
   */
  function addToGoList(address _member) external;

  /**
   * @dev removes a user from go-list
   * @param _member address to remove from go-list
   */
  function removeFromGoList(address _member) external;

  /**
   * @dev adds many users to go-list at once
   * @param _members addresses to ad to go-list
   */
  function bulkAddToGoList(address[] calldata _members) external;

  /**
   * @dev removes many users from go-list at once
   * @param _members addresses to remove from go-list
   */
  function bulkRemoveFromGoList(address[] calldata _members) external;

  function getNumber(uint256 index) external view returns (uint256);

  /*
    Using custom getters in case we want to change underlying implementation later,
    or add checks or validations later on.
  */
  function getAddress(uint256 index) external view returns (address);

  function setAddress(uint256 index, address newAddress) external;

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

File 24 of 46 : IGoldfinchFactory.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import {ISchedule} from "./ISchedule.sol";
import {ICallableLoan} from "./ICallableLoan.sol";

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

  function createCallableLoan(
    address _borrower,
    uint256 _limit,
    uint256 _interestApr,
    uint256 _numLockupPeriods,
    ISchedule _schedule,
    uint256 _lateFeeApr,
    uint256 _fundableAt,
    uint256[] calldata _allowedUIDTypes
  ) external returns (ICallableLoan);
}

File 25 of 46 : IImplementationRepository.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

/// @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.
interface IImplementationRepository {
  /// @notice returns data that will be delegatedCalled when the given implementation
  ///           is upgraded to
  function upgradeDataFor(address key) external returns (bytes memory);

  /// @notice Returns the id of the lineage a given implementation belongs to
  function lineageIdOf(address key) external returns (uint256);

  /// @notice Returns the id of the most recently created lineage
  function currentLineageId() external view returns (uint256);

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

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

  /// @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 returns (uint256);

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

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

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

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

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

  /// @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 returns (address);

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

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

  /// @notice return current implementaton of the current lineage
  function currentImplementation() external view returns (address);

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

File 26 of 46 : ILoan.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import {ISchedule} from "./ISchedule.sol";
import {ICreditLine} from "./ICreditLine.sol";

enum LoanType {
  TranchedPool,
  CallableLoan
}

interface ILoan {
  /// @notice getLoanType was added to support the new callable loan type.
  ///         It is not supported in older versions of ILoan (e.g. legacy TranchedPools)
  function getLoanType() external view returns (LoanType);

  /// @notice Pool's credit line, responsible for managing the loan's accounting variables
  function creditLine() external view returns (ICreditLine);

  /// @notice Time when the pool was initialized. Zero if uninitialized
  function createdAt() external view returns (uint256);

  /// @notice Pay down interest + principal. Excess payments are refunded to the caller
  /// @param amount USDC amount to pay
  /// @return PaymentAllocation info on how the payment was allocated
  /// @dev {this} must be approved by msg.sender to transfer {amount} of USDC
  function pay(uint256 amount) external returns (PaymentAllocation memory);

  /// @notice Compute interest and principal owed on the current balance at a future timestamp
  /// @param timestamp time to calculate up to
  /// @return interestOwed amount of obligated interest owed at `timestamp`
  /// @return interestAccrued amount of accrued interest (not yet owed) that can be paid at `timestamp`
  /// @return principalOwed amount of principal owed at `timestamp`
  function getAmountsOwed(
    uint256 timestamp
  ) external view returns (uint256 interestOwed, uint256 interestAccrued, uint256 principalOwed);

  function getAllowedUIDTypes() external view returns (uint256[] memory);

  /// @notice Drawdown the loan. The credit line's balance should increase by the amount drawn down.
  ///   Junior capital must be locked before this function can be called. If senior capital isn't locked
  ///   then this function will lock it for you (convenience to avoid calling lockPool() separately).
  ///   This function should revert if the amount requested exceeds the the current slice's currentLimit
  ///   This function should revert if the caller is not the borrower.
  /// @param amount USDC to drawdown. This amount is transferred to the caller
  function drawdown(uint256 amount) external;

  /// @notice Update `fundableAt` to a new timestamp. Only the borrower can call this.
  function setFundableAt(uint256 newFundableAt) external;

  /// @notice Supply capital to this pool. Caller can't deposit to the junior tranche if the junior pool is locked.
  ///   Caller can't deposit to a senior tranche if the pool is locked. Caller can't deposit if they are missing the
  ///   required UID NFT.
  /// @param tranche id of tranche to supply capital to. Id must correspond to a tranche in the current slice.
  /// @param amount amount of capital to supply
  /// @return tokenId NFT representing your position in this pool
  function deposit(uint256 tranche, uint256 amount) external returns (uint256 tokenId);

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

  /// @notice Query the max amount available to withdraw for tokenId's position
  /// @param tokenId position to query max amount withdrawable for
  /// @return interestRedeemable total interest withdrawable on the position
  /// @return principalRedeemable total principal redeemable on the position
  function availableToWithdraw(
    uint256 tokenId
  ) external view returns (uint256 interestRedeemable, uint256 principalRedeemable);

  /// @notice Withdraw an already deposited amount if the funds are available. Caller must be the owner or
  ///   approved by the owner on tokenId. Amount withdrawn is sent to the caller.
  /// @param tokenId the NFT representing the position
  /// @param amount amount to withdraw (must be <= interest+principal available to withdraw)
  /// @return interestWithdrawn interest withdrawn
  /// @return principalWithdrawn principal withdrawn
  function withdraw(
    uint256 tokenId,
    uint256 amount
  ) external returns (uint256 interestWithdrawn, uint256 principalWithdrawn);

  /// @notice Similar to withdraw but withdraw the max interest and principal available for `tokenId`
  function withdrawMax(
    uint256 tokenId
  ) external returns (uint256 interestWithdrawn, uint256 principalWithdrawn);

  /// @notice Withdraw from multiple tokens
  /// @param tokenIds NFT positions to withdraw. Caller must be an owner or approved on all tokens in the array
  /// @param amounts amounts to withdraw from positions such that amounts[i] is withdrawn from position tokenIds[i]
  function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external;

  /// @notice Result of applying a payment to a v2 pool
  /// @param owedInterestPayment payment portion of interest owed
  /// @param accruedInterestPayment payment portion of accrued (but not yet owed) interest
  /// @param principalPayment payment portion on principal owed
  /// @param additionalBalancePayment payment portion on any balance that is currently owed
  /// @param paymentRemaining payment amount leftover
  struct PaymentAllocation {
    uint256 owedInterestPayment;
    uint256 accruedInterestPayment;
    uint256 principalPayment;
    uint256 additionalBalancePayment;
    uint256 paymentRemaining;
  }
  /// @notice Event emitted on payment
  /// @param payer address that made the payment
  /// @param pool pool to which the payment was made
  /// @param interest amount of payment allocated to interest (obligated + additional)
  /// @param principal amount of payment allocated to principal owed and remaining balance
  /// @param remaining any excess payment amount that wasn't allocated to a debt owed
  /// @param reserve of payment that went to the protocol reserve
  event PaymentApplied(
    address indexed payer,
    address indexed pool,
    uint256 interest,
    uint256 principal,
    uint256 remaining,
    uint256 reserve
  );
  event DepositMade(
    address indexed owner,
    uint256 indexed tranche,
    uint256 indexed tokenId,
    uint256 amount
  );

  /// @notice While owner is the label of the first argument, it is actually the sender of the transaction.
  event WithdrawalMade(
    address indexed owner,
    uint256 indexed tranche,
    uint256 indexed tokenId,
    uint256 interestWithdrawn,
    uint256 principalWithdrawn
  );
  event ReserveFundsCollected(address indexed from, uint256 amount);
  event DrawdownMade(address indexed borrower, uint256 amount);
  event DrawdownsPaused(address indexed pool);
  event DrawdownsUnpaused(address indexed pool);
  event EmergencyShutdown(address indexed pool);
}

File 27 of 46 : IPoolTokens.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import "./openzeppelin/IERC721.sol";

interface IPoolTokens is IERC721 {
  struct TokenInfo {
    address pool;
    uint256 tranche;
    uint256 principalAmount;
    uint256 principalRedeemed;
    uint256 interestRedeemed;
  }

  struct MintParams {
    uint256 principalAmount;
    uint256 tranche;
  }

  struct PoolInfo {
    uint256 totalMinted;
    uint256 totalPrincipalRedeemed;
    bool created;
  }

  /**
   * @notice Called by pool to create a debt position in a particular tranche and amount
   * @param params Struct containing the tranche and the amount
   * @param to The address that should own the position
   * @return tokenId The token ID (auto-incrementing integer across all pools)
   */
  function mint(MintParams calldata params, address to) external returns (uint256);

  /**
   * @notice Redeem principal and interest on a pool token. Called by valid pools as part of their redemption
   *  flow
   * @param tokenId pool token id
   * @param principalRedeemed principal to redeem. This cannot exceed the token's principal amount, and
   *  the redemption cannot cause the pool's total principal redeemed to exceed the pool's total minted
   *  principal
   * @param interestRedeemed interest to redeem.
   */
  function redeem(uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed) external;

  /**
   * @notice Withdraw a pool token's principal up to the token's principalAmount. Called by valid pools
   *  as part of their withdraw flow before the pool is locked (i.e. before the principal is committed)
   * @param tokenId pool token id
   * @param principalAmount principal to withdraw
   */
  function withdrawPrincipal(uint256 tokenId, uint256 principalAmount) external;

  /**
   * @notice Burns a specific ERC721 token and removes deletes the token metadata for PoolTokens, BackerReards,
   *  and BackerStakingRewards
   * @param tokenId uint256 id of the ERC721 token to be burned.
   */
  function burn(uint256 tokenId) external;

  /**
   * @notice Called by the GoldfinchFactory to register the pool as a valid pool. Only valid pools can mint/redeem
   * tokens
   * @param newPool The address of the newly created pool
   */
  function onPoolCreated(address newPool) external;

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

  function getPoolInfo(address pool) external view returns (PoolInfo memory);

  /// @notice Query if `pool` is a valid pool. A pool is valid if it was created by the Goldfinch Factory
  function validPool(address pool) external view returns (bool);

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

  /**
   * @notice Splits a pool token into two smaller positions. The original token is burned and all
   * its associated data is deleted.
   * @param tokenId id of the token to split.
   * @param newPrincipal1 principal amount for the first token in the split. The principal amount for the
   *  second token in the split is implicitly the original token's principal amount less newPrincipal1
   * @return tokenId1 id of the first token in the split
   * @return tokenId2 id of the second token in the split
   */
  function splitToken(
    uint256 tokenId,
    uint256 newPrincipal1
  ) external returns (uint256 tokenId1, uint256 tokenId2);

  /**
   * @notice Mint event emitted for a new TranchedPool deposit or when an existing pool token is
   *  split
   * @param owner address to which the token was minted
   * @param pool tranched pool that the deposit was in
   * @param tokenId ERC721 tokenId
   * @param amount the deposit amount
   * @param tranche id of the tranche of the deposit
   */
  event TokenMinted(
    address indexed owner,
    address indexed pool,
    uint256 indexed tokenId,
    uint256 amount,
    uint256 tranche
  );

  /**
   * @notice Redeem event emitted when interest and/or principal is redeemed in the token's pool
   * @param owner owner of the pool token
   * @param pool tranched pool that the token belongs to
   * @param principalRedeemed amount of principal redeemed from the pool
   * @param interestRedeemed amount of interest redeemed from the pool
   * @param tranche id of the tranche the token belongs to
   */
  event TokenRedeemed(
    address indexed owner,
    address indexed pool,
    uint256 indexed tokenId,
    uint256 principalRedeemed,
    uint256 interestRedeemed,
    uint256 tranche
  );

  /**
   * @notice Burn event emitted when the token owner/operator manually burns the token or burns
   *  it implicitly by splitting it
   * @param owner owner of the pool token
   * @param pool tranched pool that the token belongs to
   */
  event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);

  /**
   * @notice Split event emitted when the token owner/operator splits the token
   * @param pool tranched pool to which the orginal and split tokens belong
   * @param tokenId id of the original token that was split
   * @param newTokenId1 id of the first split token
   * @param newPrincipal1 principalAmount of the first split token
   * @param newTokenId2 id of the second split token
   * @param newPrincipal2 principalAmount of the second split token
   */
  event TokenSplit(
    address indexed owner,
    address indexed pool,
    uint256 indexed tokenId,
    uint256 newTokenId1,
    uint256 newPrincipal1,
    uint256 newTokenId2,
    uint256 newPrincipal2
  );

  /**
   * @notice Principal Withdrawn event emitted when a token's principal is withdrawn from the pool
   *  BEFORE the pool's drawdown period
   * @param pool tranched pool of the token
   * @param principalWithdrawn amount of principal withdrawn from the pool
   */
  event TokenPrincipalWithdrawn(
    address indexed owner,
    address indexed pool,
    uint256 indexed tokenId,
    uint256 principalWithdrawn,
    uint256 tranche
  );
}

File 28 of 46 : ISchedule.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

interface ISchedule {
  function periodsPerPrincipalPeriod() external view returns (uint256);

  function periodsInTerm() external view returns (uint256);

  function periodsPerInterestPeriod() external view returns (uint256);

  function gracePrincipalPeriods() external view returns (uint256);

  /**
   * @notice Returns the period that timestamp resides in
   */
  function periodAt(uint256 startTime, uint256 timestamp) external view returns (uint256);

  /**
   * @notice Returns the principal period that timestamp resides in
   */
  function principalPeriodAt(uint256 startTime, uint256 timestamp) external view returns (uint256);

  /**
   * @notice Returns the interest period that timestamp resides in
   */
  function interestPeriodAt(uint256 startTime, uint256 timestamp) external view returns (uint256);

  /**
   * @notice Returns true if the given timestamp resides in a principal grace period
   */
  function withinPrincipalGracePeriodAt(
    uint256 startTime,
    uint256 timestamp
  ) external view returns (bool);

  /**
   * Returns the next timestamp where either principal or interest will come due following `timestamp`
   */
  function nextDueTimeAt(uint256 startTime, uint256 timestamp) external view returns (uint256);

  /**
   * @notice Returns the previous timestamp where either principal or timestamp came due
   */
  function previousDueTimeAt(uint256 startTime, uint256 timestamp) external view returns (uint256);

  /**
   * @notice Returns the previous timestamp where new interest came due
   */
  function previousInterestDueTimeAt(
    uint256 startTime,
    uint256 timestamp
  ) external view returns (uint256);

  /**
   * @notice Returns the previous timestamp where new principal came due
   */
  function previousPrincipalDueTimeAt(
    uint256 startTime,
    uint256 timestamp
  ) external view returns (uint256);

  /**
   * @notice Returns the total number of principal periods
   */
  function totalPrincipalPeriods() external view returns (uint256);

  /**
   * @notice Returns the total number of interest periods
   */
  function totalInterestPeriods() external view returns (uint256);

  /**
   * @notice Returns the timestamp that the term will end
   */
  function termEndTime(uint256 startTime) external view returns (uint256);

  /**
   * @notice Returns the timestamp that the term began
   */
  function termStartTime(uint256 startTime) external view returns (uint256);

  /**
   * @notice Returns the next time principal will come due, or the termEndTime if there are no more due times
   */
  function nextPrincipalDueTimeAt(
    uint256 startTime,
    uint256 timestamp
  ) external view returns (uint256);

  /**
   * @notice Returns the next time interest will come due, or the termEndTime if there are no more due times
   */
  function nextInterestDueTimeAt(
    uint256 startTime,
    uint256 timestamp
  ) external view returns (uint256);

  /**
   * @notice Returns the end time of the given period.
   */
  function periodEndTime(uint256 startTime, uint256 period) external view returns (uint256);
}

File 29 of 46 : 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. Callable
   * by Zapper only.
   */
  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. Callable by Zapper only
   */
  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 30 of 46 : 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 withdrawal 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 caller 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 31 of 46 : 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);

  /**
   * @notice Determines how much money to invest in the senior tranche based on what is committed to the junior
   * tranche, what is committed to the senior tranche, and a leverage ratio to the junior tranche. Because
   * it takes into account what is already committed to the senior tranche, the value returned by this
   * function can be used "idempotently" to achieve the investment target amount without exceeding that target.
   * @param seniorPool The senior pool to invest from
   * @param pool The tranched pool to invest into (as the senior)
   * @return amount of money to invest into the tranched pool's senior tranche, from the senior pool
   */
  function invest(
    ISeniorPool seniorPool,
    ITranchedPool pool
  ) public view virtual returns (uint256 amount);

  /**
   * @notice A companion of `invest()`: determines how much would be returned by `invest()`, as the
   * value to invest into the senior tranche, if the junior tranche were locked and the senior tranche
   * were not locked.
   * @param seniorPool The senior pool to invest from
   * @param pool The tranched pool to invest into (as the senior)
   * @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool
   */
  function estimateInvestment(
    ISeniorPool seniorPool,
    ITranchedPool pool
  ) public view virtual returns (uint256);
}

File 32 of 46 : 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 {
  /// @notice Get the staking rewards position
  /// @param tokenId id of the position token
  /// @return position the position
  function getPosition(uint256 tokenId) external view returns (StakedPosition memory position);

  /// @notice Unstake an amount of `stakingToken()` (FIDU, FiduUSDCCurveLP, etc) associated with
  ///   a given position and transfer to msg.sender. Any remaining staked amount will continue to
  ///   accrue rewards.
  /// @dev This function checkpoints rewards
  /// @param tokenId A staking position token ID
  /// @param amount Amount of `stakingToken()` to be unstaked from the position
  function unstake(uint256 tokenId, uint256 amount) external;

  /// @notice Add `amount` to an existing FIDU position (`tokenId`)
  /// @param tokenId A staking position token ID
  /// @param amount Amount of `stakingToken()` to be added to tokenId's position
  function addToStake(uint256 tokenId, uint256 amount) external;

  /// @notice Returns the staked balance of a given position token.
  /// @dev The value returned is the bare amount, not the effective amount. The bare amount represents
  ///   the number of tokens the user has staked for a given position. The effective amount is the bare
  ///   amount multiplied by the token's underlying asset type multiplier. This multiplier is a crypto-
  ///   economic parameter determined by governance.
  /// @param tokenId A staking position token ID
  /// @return Amount of staked tokens denominated in `stakingToken().decimals()`
  function stakedBalanceOf(uint256 tokenId) external view returns (uint256);

  /// @notice Deposit to FIDU and USDC into the Curve LP, and stake your Curve LP tokens in the same transaction.
  /// @param fiduAmount The amount of FIDU to deposit
  /// @param usdcAmount The amount of USDC to deposit
  function depositToCurveAndStakeFrom(
    address nftRecipient,
    uint256 fiduAmount,
    uint256 usdcAmount
  ) external;

  /// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward
  ///   multiplier will be reset to 1x.
  /// @dev This will also checkpoint their rewards up to the current time.
  function kick(uint256 tokenId) external;

  /// @notice Accumulated rewards per token at the last checkpoint
  function accumulatedRewardsPerToken() external view returns (uint256);

  /// @notice The block timestamp when rewards were last checkpointed
  function lastUpdateTime() external view returns (uint256);

  /// @notice Claim rewards for a given staked position
  /// @param tokenId A staking position token ID
  /// @return amount of rewards claimed
  function getReward(uint256 tokenId) external returns (uint256);

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

  event RewardAdded(uint256 reward);
  event RewardRemoved(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 33 of 46 : ITranchedPool.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import {ISchedule} from "./ISchedule.sol";
import {ILoan} from "./ILoan.sol";
import {ICreditLine} from "./ICreditLine.sol";

interface ITranchedPool is ILoan {
  struct TrancheInfo {
    uint256 id;
    uint256 principalDeposited;
    uint256 principalSharePrice;
    uint256 interestSharePrice;
    uint256 lockedUntil;
  }
  struct PoolSlice {
    TrancheInfo seniorTranche;
    TrancheInfo juniorTranche;
    uint256 totalInterestAccrued;
    uint256 principalDeployed;
  }
  enum Tranches {
    Reserved,
    Senior,
    Junior
  }

  /// @notice Initialize the pool. Can only be called once, and should be called in the same transaction as
  ///   contract creation to avoid initialization front-running
  /// @param _config address of GoldfinchConfig
  /// @param _borrower address of borrower, a non-transferrable role for performing privileged actions like
  ///   drawdown
  /// @param _juniorFeePercent percent (whole number) of senior interest that gets re-allocated to the junior tranche.
  ///   valid range is [0, 100]
  /// @param _limit the max USDC amount that can be drawn down across all pool slices
  /// @param _interestApr interest rate for the loan
  /// @param _lateFeeApr late fee interest rate for the loan, which kicks in `LatenessGracePeriodInDays` days after a
  ///   payment becomes late
  /// @param _fundableAt earliest time at which the first slice can be funded
  /// @param _reservePercent percent (whole number) of interest that goes to the reserves. Valid range is [0,100], with
  ///   the exception of -1, which is a sentinel value that will use the default global value in GoldfinchConfig.

  function initialize(
    address _config,
    address _borrower,
    uint256 _juniorFeePercent,
    uint256 _limit,
    uint256 _interestApr,
    ISchedule _schedule,
    uint256 _lateFeeApr,
    uint256 _fundableAt,
    uint256[] calldata _allowedUIDTypes,
    uint256 _reservePercent
  ) external;

  /// @notice Pay down the credit line, separating the principal and interest payments. You must pay back all interest
  ///   before paying back principal. Excess payments are refunded to the caller
  /// @param principalPayment USDC amount to pay down principal
  /// @param interestPayment USDC amount to pay down interest
  /// @return PaymentAllocation info on how the payment was allocated
  /// @dev {this} must be approved by msg.sender to transfer {principalPayment} + {interestPayment} of USDC
  function pay(
    uint256 principalPayment,
    uint256 interestPayment
  ) external returns (PaymentAllocation memory);

  /// @notice TrancheInfo for tranche with id `trancheId`. The senior tranche of slice i has id 2*(i-1)+1. The
  ///   junior tranche of slice i has id 2*i. Slice indices start at 1.
  /// @param trancheId id of tranche. Valid ids are in the range [1, 2*numSlices]
  function getTranche(uint256 trancheId) external view returns (ITranchedPool.TrancheInfo memory);

  /// @notice Get a slice by index
  /// @param index of slice. Valid indices are on the interval [0, numSlices - 1]
  function poolSlices(uint256 index) external view returns (ITranchedPool.PoolSlice memory);

  /// @notice Lock the junior capital in the junior tranche of the current slice. The capital is locked for
  ///   `DrawdownPeriodInSeconds` seconds and gives the senior pool time to decide how much to invest (ensure
  ///   leverage ratio cannot change for the period). During this period the borrower has the option to lock
  ///   the senior capital by calling `lockPool()`. Backers may withdraw their junior capital if the the senior
  ///   tranche has not been locked and the drawdown period has ended. Only the borrower can call this function.
  function lockJuniorCapital() external;

  /// @notice Lock the senior capital in the senior tranche of the current slice and reset the lock period of
  ///   the junior capital to match the senior capital lock period. During this period the borrower has the
  ///   option to draw down the pool. Beyond the drawdown period any unused capital is available to withdraw by
  ///   all depositors.
  function lockPool() external;

  /// @notice Initialize the next slice for the pool. Enables backers and the senior pool to provide additional
  ///   capital to the borrower.
  /// @param _fundableAt time at which the new slice (now the current slice) becomes fundable
  function initializeNextSlice(uint256 _fundableAt) external;

  /// @notice Query the total capital supplied to the pool's junior tranches
  function totalJuniorDeposits() external view returns (uint256);

  function assess() external;

  /// @notice Get the current number of slices for this pool
  /// @return numSlices total current slice count
  function numSlices() external view returns (uint256);

  // Note: This has to exactly match the event in the TranchingLogic library for events to be emitted
  // correctly
  event SharePriceUpdated(
    address indexed pool,
    uint256 indexed tranche,
    uint256 principalSharePrice,
    int256 principalDelta,
    uint256 interestSharePrice,
    int256 interestDelta
  );
  event CreditLineMigrated(ICreditLine indexed oldCreditLine, ICreditLine indexed newCreditLine);
  event TrancheLocked(address indexed pool, uint256 trancheId, uint256 lockedUntil);
  event SliceCreated(address indexed pool, uint256 sliceId);
}

File 34 of 46 : IWithdrawalRequestToken.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

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

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 35 of 46 : IERC165.sol
// SPDX-License-Identifier: MIT

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 36 of 46 : IERC721.sol
// SPDX-License-Identifier: MIT

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 37 of 46 : 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 38 of 46 : 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 39 of 46 : SafeERC20Transfer.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

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

/**
 * @title Safe ERC20 Transfer
 * @notice Reverts when transfer is not successful
 * @author Goldfinch
 */
library SafeERC20Transfer {
  function safeERC20Transfer(
    IERC20 erc20,
    address to,
    uint256 amount,
    string memory message
  ) internal {
    /// @dev ZERO address
    require(to != address(0), "ZERO");
    bool success = erc20.transfer(to, amount);
    require(success, message);
  }

  function safeERC20Transfer(IERC20 erc20, address to, uint256 amount) internal {
    safeERC20Transfer(erc20, to, amount, "");
  }

  function safeERC20TransferFrom(
    IERC20 erc20,
    address from,
    address to,
    uint256 amount,
    string memory message
  ) internal {
    require(to != address(0), "ZERO");
    bool success = erc20.transferFrom(from, to, amount);
    require(success, message);
  }

  function safeERC20TransferFrom(IERC20 erc20, address from, address to, uint256 amount) internal {
    safeERC20TransferFrom(erc20, from, to, amount, "");
  }

  function safeERC20Approve(
    IERC20 erc20,
    address spender,
    uint256 allowance,
    string memory message
  ) internal {
    bool success = erc20.approve(spender, allowance);
    require(success, message);
  }

  function safeERC20Approve(IERC20 erc20, address spender, uint256 allowance) internal {
    safeERC20Approve(erc20, spender, allowance, "");
  }
}

File 40 of 46 : SafeMath.sol
pragma solidity >=0.6.12;

// NOTE: this file exists only to remove the extremely long error messages in safe math.

import {SafeMath as OzSafeMath} from "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";

/**
 * @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);
    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 OzSafeMath.sub(a, b, "");
  }

  /**
   * @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) {
    return OzSafeMath.sub(a, b, errorMessage);
  }

  /// @notice Do a - b. If that would result in overflow then return 0
  function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
    return b > a ? 0 : a - b;
  }

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

    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 OzSafeMath.div(a, b, "");
  }

  /**
   * @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) {
    return OzSafeMath.div(a, b, errorMessage);
  }

  /**
   * @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 OzSafeMath.mod(a, b, "");
  }

  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
    return OzSafeMath.mod(a, b, errorMessage);
  }
}

File 41 of 46 : BaseUpgradeablePausable.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import {AccessControlUpgradeSafe} from "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import {ReentrancyGuardUpgradeSafe} from "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import {Initializable} from "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import {SafeMath} from "../../library/SafeMath.sol";
import {PauserPausable} from "./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 42 of 46 : 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 getCallableLoanImplementationRepository(
    GoldfinchConfig config
  ) internal view returns (ImplementationRepository) {
    return
      ImplementationRepository(
        config.getAddress(uint256(ConfigOptions.Addresses.CallableLoanImplementationRepository))
      );
  }

  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 43 of 46 : 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,
    MonthlyScheduleRepo,
    CallableLoanImplementationRepository
  }
}

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

pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;

import {BaseUpgradeablePausable} from "./BaseUpgradeablePausable.sol";
import {IGoldfinchConfig} from "../../interfaces/IGoldfinchConfig.sol";
import {ConfigOptions} from "./ConfigOptions.sol";

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

contract GoldfinchConfig is BaseUpgradeablePausable, IGoldfinchConfig {
  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);
  }

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

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

  /// @inheritdoc IGoldfinchConfig
  function setNumber(uint256 index, uint256 newNumber) public override 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 setMonthlyScheduleRepo(address newAddress) public onlyAdmin {
    uint256 key = uint256(ConfigOptions.Addresses.MonthlyScheduleRepo);
    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;
  }

  /// @inheritdoc IGoldfinchConfig
  function addToGoList(address _member) public override onlyGoListerRole {
    goList[_member] = true;
    emit GoListed(_member);
  }

  /// @inheritdoc IGoldfinchConfig
  function removeFromGoList(address _member) public override onlyGoListerRole {
    goList[_member] = false;
    emit NoListed(_member);
  }

  /// @inheritdoc IGoldfinchConfig
  function bulkAddToGoList(address[] calldata _members) external override onlyGoListerRole {
    for (uint256 i = 0; i < _members.length; i++) {
      addToGoList(_members[i]);
    }
  }

  /// @inheritdoc IGoldfinchConfig
  function bulkRemoveFromGoList(address[] calldata _members) external override onlyGoListerRole {
    for (uint256 i = 0; i < _members.length; i++) {
      removeFromGoList(_members[i]);
    }
  }

  /// @inheritdoc IGoldfinchConfig
  function getAddress(uint256 index) public view override returns (address) {
    return addresses[index];
  }

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

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

File 45 of 46 : 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 46 of 46 : 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";
import {IImplementationRepository} from "../../../interfaces/IImplementationRepository.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, IImplementationRepository {
  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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override whenNotPaused returns (address) {
    return _nextImplementationOf[implementation];
  }

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

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

  /// @notice return current implementaton of the current lineage
  function currentImplementation() external view override 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": {},
  "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":"owner","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountOfTranchedPoolRewards","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountOfSeniorPoolRewards","type":"uint256"}],"name":"BackerRewardsClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"maxInterestDollarsEligible","type":"uint256"}],"name":"BackerRewardsSetMaxInterestDollarsEligible","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalInterestReceived","type":"uint256"}],"name":"BackerRewardsSetTotalInterestReceived","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalRewards","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalRewardPercentOfTotalGFI","type":"uint256"}],"name":"BackerRewardsSetTotalRewards","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[],"name":"SafetyCheckTriggered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"OWNER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"__BaseUpgradeablePausable__init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"__PauserPausable__init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"contract GoldfinchConfig","name":"_config","type":"address"}],"name":"__initialize__","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_interestPaymentAmount","type":"uint256"}],"name":"allocateRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"clearTokenInfo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"config","outputs":[{"internalType":"contract GoldfinchConfig","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ITranchedPool","name":"pool","type":"address"}],"name":"getBackerStakingRewardsPoolInfo","outputs":[{"components":[{"internalType":"uint256","name":"accumulatedRewardsPerTokenAtLastCheckpoint","type":"uint256"},{"internalType":"uint256","name":"lastUpdateTime","type":"uint256"},{"components":[{"internalType":"uint256","name":"fiduSharePriceAtDrawdown","type":"uint256"},{"internalType":"uint256","name":"principalDeployedAtLastCheckpoint","type":"uint256"},{"internalType":"uint256","name":"accumulatedRewardsPerTokenAtDrawdown","type":"uint256"},{"internalType":"uint256","name":"accumulatedRewardsPerTokenAtLastCheckpoint","type":"uint256"},{"internalType":"uint256","name":"unrealizedAccumulatedRewardsPerTokenAtLastCheckpoint","type":"uint256"}],"internalType":"struct IBackerRewards.StakingRewardsSliceInfo[]","name":"slicesInfo","type":"tuple[]"}],"internalType":"struct IBackerRewards.StakingRewardsPoolInfo","name":"","type":"tuple"}],"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":"uint256","name":"poolTokenId","type":"uint256"}],"name":"getStakingRewardsTokenInfo","outputs":[{"components":[{"internalType":"uint256","name":"accumulatedRewardsPerTokenAtLastWithdraw","type":"uint256"}],"internalType":"struct IBackerRewards.StakingRewardsTokenInfo","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"poolTokenId","type":"uint256"}],"name":"getTokenInfo","outputs":[{"components":[{"internalType":"uint256","name":"rewardsClaimed","type":"uint256"},{"internalType":"uint256","name":"accRewardsPerPrincipalDollarAtMint","type":"uint256"}],"internalType":"struct IBackerRewards.BackerRewardsTokenInfo","name":"","type":"tuple"}],"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":[],"name":"isAdmin","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxInterestDollarsEligible","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_sliceIndex","type":"uint256"}],"name":"onTranchedPoolDrawdown","outputs":[],"stateMutability":"nonpayable","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":"contract ITranchedPool","name":"","type":"address"}],"name":"poolStakingRewards","outputs":[{"internalType":"uint256","name":"accumulatedRewardsPerTokenAtLastCheckpoint","type":"uint256"},{"internalType":"uint256","name":"lastUpdateTime","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"poolTokenClaimableRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"pools","outputs":[{"internalType":"uint256","name":"accRewardsPerPrincipalDollar","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"rewardsClaimed","type":"uint256"},{"internalType":"uint256","name":"accRewardsPerPrincipalDollarAtMint","type":"uint256"}],"internalType":"struct IBackerRewards.BackerRewardsTokenInfo","name":"originalBackerRewardsTokenInfo","type":"tuple"},{"components":[{"internalType":"uint256","name":"accumulatedRewardsPerTokenAtLastWithdraw","type":"uint256"}],"internalType":"struct IBackerRewards.StakingRewardsTokenInfo","name":"originalStakingRewardsTokenInfo","type":"tuple"},{"internalType":"uint256","name":"newTokenId","type":"uint256"},{"internalType":"uint256","name":"newRewardsClaimed","type":"uint256"}],"name":"setBackerAndStakingRewardsTokenInfoOnSplit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxInterestDollarsEligible","type":"uint256"}],"name":"setMaxInterestDollarsEligible","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"poolAddress","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"setPoolTokenAccRewardsPerPrincipalDollarAtMint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_totalInterestReceived","type":"uint256"}],"name":"setTotalInterestReceived","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_totalRewards","type":"uint256"}],"name":"setTotalRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"stakingRewardsClaimed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"stakingRewardsEarnedSinceLastWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"tokenStakingRewards","outputs":[{"internalType":"uint256","name":"accumulatedRewardsPerTokenAtLastWithdraw","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"tokens","outputs":[{"internalType":"uint256","name":"rewardsClaimed","type":"uint256"},{"internalType":"uint256","name":"accRewardsPerPrincipalDollarAtMint","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalInterestReceived","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalRewardPercentOfTotalGFI","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"withdrawMultiple","outputs":[],"stateMutability":"nonpayable","type":"function"}]

608060405234801561001057600080fd5b50613af3806100206000396000f3fe608060405234801561001057600080fd5b506004361061025e5760003560e01c806371d5a25311610146578063b6db75a0116100c3578063d547741f11610087578063d547741f146104f0578063dfc1f3a814610503578063e149ee8014610523578063e58378bb14610536578063e5b791061461053e578063e63ab1e9146105515761025e565b8063b6db75a01461049a578063b6f8fd40146104a2578063ca15c873146104b5578063ccf5a971146104c8578063d3d64722146104d05761025e565b80639010d07c1161010a5780639010d07c1461044657806391d1485414610459578063927356751461046c578063a217fddf1461047f578063a4063dbc146104875761025e565b806371d5a253146103ee57806379502c55146104015780638456cb591461041657806387f5769e1461041e5780638c7a63ae146104265761025e565b80632f2ff15d116101df5780634f64b2be116101a35780634f64b2be14610385578063526d81f6146103985780635c975abb146103a05780635e3f5d64146103b55780635f464bb2146103c85780636efbe643146103db5761025e565b80632f2ff15d1461032357806334cbd4581461033657806336568abe14610357578063369dfa841461036a5780633f4ba83a1461037d5761025e565b8063248a9ca311610226578063248a9ca3146102c45780632808e69e146102d75780632879e4de146102ea57806328fc33c7146102fd5780632e1a7d4d146103105761025e565b8063097616a3146102635780630c9dbe94146102785780630de74932146102965780630e15561a146102a9578063242a7286146102b1575b600080fd5b610276610271366004613058565b610559565b005b610280610692565b60405161028d9190613300565b60405180910390f35b6102806102a4366004613182565b610699565b610280610928565b6102766102bf366004613182565b61092f565b6102806102d2366004613182565b6109a4565b6102806102e5366004613182565b6109b9565b6102766102f8366004613182565b610c3e565b61027661030b366004613182565b610ca8565b61028061031e366004613182565b610da7565b61027661033136600461319a565b611220565b610349610344366004613058565b611264565b60405161028d929190613a33565b61027661036536600461319a565b61127e565b610280610378366004613182565b6112c0565b610276611410565b610349610393366004613182565b611450565b61027661146a565b6103a86114f5565b60405161028d91906132f5565b6102766103c33660046131df565b6114fe565b6102806103d6366004613182565b611587565b6102766103e93660046130c8565b61159a565b6102766103fc366004613182565b6117b9565b610409611825565b60405161028d91906132c8565b610276611835565b610280611873565b610439610434366004613182565b61187a565b60405161028d9190613985565b6104096104543660046131be565b6118ad565b6103a861046736600461319a565b6118ce565b61027661047a366004613182565b6118e6565b610280611a0b565b610280610495366004613058565b611a10565b6103a8611a23565b6102766104b0366004613090565b611a44565b6102806104c3366004613182565b611b2a565b610280611b41565b6104e36104de366004613058565b611b48565b60405161028d919061399c565b6102766104fe36600461319a565b611c2c565b610516610511366004613182565b611c66565b60405161028d9190613a29565b610276610531366004613182565b611c91565b610280611d67565b61027661054c3660046130f3565b611d79565b610280611dc5565b600054610100900460ff16806105725750610572611dd7565b80610580575060005460ff16155b6105a55760405162461bcd60e51b815260040161059c9061372e565b60405180910390fd5b600054610100900460ff161580156105d0576000805460ff1961ff0019909116610100171660011790555b6001600160a01b0382166105f65760405162461bcd60e51b815260040161059c90613694565b6105fe611ddd565b610606611e5e565b61060e611eea565b610626600080516020613a7e8339815191528361125a565b61063e600080516020613a9e8339815191528361125a565b610664600080516020613a9e833981519152600080516020613a7e833981519152611f79565b61067c600080516020613a7e83398151915280611f79565b801561068e576000805461ff00191690555b5050565b6101c75481565b60006106a3612fa3565b6101c3546106b9906001600160a01b0316611f8e565b6001600160a01b0316638c7a63ae846040518263ffffffff1660e01b81526004016106e49190613300565b60a06040518083038186803b1580156106fc57600080fd5b505afa158015610710573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107349190613254565b905061073f81611f99565b1561074e576000915050610923565b8051602082015160009061076190611fb5565b905061076c82611fc7565b158061077f575061077d82826120b9565b155b156107905760009350505050610923565b610798612fdb565b6101ca6000846001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b8282101561086657838290600052602060002090600502016040518060a00160405290816000820154815260200160018201548152602001600282015481526020016003820154815260200160048201548152505081526020019060010190610802565b50505050815250509050610878612ffc565b8160400151838151811061088857fe5b6020026020010151905061089a61302b565b5060008781526101cb602090815260408083208151928301909152548152906108c383856121d3565b905060006108d18385612211565b905060006108df838361227b565b905060006108f58a604001518760000151612297565b90506000610915670de0b6b3a764000061090f84866122b2565b906122d9565b9b5050505050505050505050505b919050565b6101c45481565b610937611a23565b6109535760405162461bcd60e51b815260040161059c90613857565b6101c58190556109616122f5565b6001600160a01b03167fbd23f227ee01d5b74d28337b4aa192bdb10824b0f2ad21e725a2f08af91ec81b826040516109999190613300565b60405180910390a250565b60009081526065602052604090206002015490565b6101c35460009081906109d4906001600160a01b0316611f8e565b90506109de612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae90610a0a908790600401613300565b60a06040518083038186803b158015610a2257600080fd5b505afa158015610a36573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a5a9190613254565b9050610a6581611f99565b15610a7557600092505050610923565b80516020820151600090610a8890611fb5565b9050610a9382611fc7565b1580610aa65750610aa482826120b9565b155b15610ab8576000945050505050610923565b610ac0612fdb565b6101ca6000846001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b82821015610b8e57838290600052602060002090600502016040518060a00160405290816000820154815260200160018201548152602001600282015481526020016003820154815260200160048201548152505081526020019060010190610b2a565b50505050815250509050610ba0612ffc565b81604001518381518110610bb057fe5b60200260200101519050610bc261302b565b5060008881526101cb60209081526040808320815192830182525482528301519091610bee8385612211565b90506000610bfc828461227b565b90506000610c128a604001518760000151612297565b90506000610c2c670de0b6b3a764000061090f84866122b2565b9e9d5050505050505050505050505050565b610c46611a23565b610c625760405162461bcd60e51b815260040161059c90613857565b6101c6819055610c706122f5565b6001600160a01b03167feabaa681e9990f0da888d0feb7ec727809a7e832013b120a9a248ba6b16d5f44826040516109999190613300565b6101c354610cbe906001600160a01b0316611f8e565b6001600160a01b031663b5ada6d8610cd46122f5565b6040518263ffffffff1660e01b8152600401610cf091906132c8565b60206040518083038186803b158015610d0857600080fd5b505afa158015610d1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d409190613162565b610d5c5760405162461bcd60e51b815260040161059c90613521565b60c95460ff16610d7e5760405162461bcd60e51b815260040161059c90613820565b60c9805460ff191690558015610d9757610d97816122f9565b5060c9805460ff19166001179055565b60975460009060ff1615610dcd5760405162461bcd60e51b815260040161059c90613633565b60c95460ff16610def5760405162461bcd60e51b815260040161059c90613820565b60c9805460ff191690556101c354600090610e12906001600160a01b0316611f8e565b9050610e1c612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae90610e48908790600401613300565b60a06040518083038186803b158015610e6057600080fd5b505afa158015610e74573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e989190613254565b80516101c35491925090610eb4906001600160a01b0316611f8e565b6001600160a01b031663b5ada6d8826040518263ffffffff1660e01b8152600401610edf91906132c8565b60206040518083038186803b158015610ef757600080fd5b505afa158015610f0b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f2f9190613162565b610f4b5760405162461bcd60e51b815260040161059c90613521565b6040516331a9108f60e11b81526001600160a01b03841690636352211e90610f77908890600401613300565b60206040518083038186803b158015610f8f57600080fd5b505afa158015610fa3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fc79190613074565b6001600160a01b0316336001600160a01b031614610ff75760405162461bcd60e51b815260040161059c906136c9565b6000819050806001600160a01b0316635c975abb6040518163ffffffff1660e01b815260040160206040518083038186803b15801561103557600080fd5b505afa158015611049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061106d9190613162565b1561108a5760405162461bcd60e51b815260040161059c90613700565b61109383611f99565b156110b05760405162461bcd60e51b815260040161059c906138f1565b60006110bb876112c0565b905060006110c888610699565b905060006110d68383612441565b60008a81526101c860205260409020549091506110f38185612441565b60008b81526101c860205260409020558215611112576111128a612453565b6040516331a9108f60e11b81526111ba906001600160a01b038a1690636352211e90611142908e90600401613300565b60206040518083038186803b15801561115a57600080fd5b505afa15801561116e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111929190613074565b6101c35484906111aa906001600160a01b03166126a3565b6001600160a01b031691906126ae565b896111c36122f5565b6001600160a01b03167ff282434f7158cb3a5501455a72b1946fe84ef5f1e84350beae1f3bf45ffc583e86866040516111fd929190613a33565b60405180910390a350965050505050505060c9805460ff19166001179055919050565b60008281526065602052604090206002015461123e906104676122f5565b61125a5760405162461bcd60e51b815260040161059c906133eb565b61068e82826126c9565b6101ca602052600090815260409020805460019091015482565b6112866122f5565b6001600160a01b0316816001600160a01b0316146112b65760405162461bcd60e51b815260040161059c906138a2565b61068e8282612732565b6101c35460009081906112db906001600160a01b0316611f8e565b90506112e5612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae90611311908790600401613300565b60a06040518083038186803b15801561132957600080fd5b505afa15801561133d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113619190613254565b905061136c81611f99565b1561137c57600092505050610923565b60008481526101c8602090815260408083206001015484516001600160a01b031684526101c99092528220546113b19161227b565b60008681526101c86020526040812054919250906113d790670de0b6b3a76400006122b2565b9050611406670de0b6b3a764000061090f83611400866113fa896040015161279b565b906122b2565b9061227b565b9695505050505050565b61142a600080516020613a9e8339815191526104676122f5565b6114465760405162461bcd60e51b815260040161059c9061377c565b61144e6127b6565b565b6101c8602052600090815260409020805460019091015482565b600054610100900460ff16806114835750611483611dd7565b80611491575060005460ff16155b6114ad5760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff161580156114d8576000805460ff1961ff0019909116610100171660011790555b6114e0611e5e565b80156114f2576000805461ff00191690555b50565b60975460ff1690565b6101c354611514906001600160a01b0316611f8e565b6001600160a01b0316336001600160a01b0316146115445760405162461bcd60e51b815260040161059c906137c1565b60408051808201825291825260209485015185830190815260009384526101c8865281842092518355516001909201919091556101cb9093529190912090519055565b6101cb6020526000908152604090205481565b6101c3546115b0906001600160a01b0316612822565b6001600160a01b03166115c16122f5565b6001600160a01b0316146115e75760405162461bcd60e51b815260040161059c90613798565b6101c3546115fd906001600160a01b0316611f8e565b6001600160a01b031663b5ada6d8836040518263ffffffff1660e01b815260040161162891906132c8565b60206040518083038186803b15801561164057600080fd5b505afa158015611654573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116789190613162565b6116945760405162461bcd60e51b815260040161059c90613521565b60008181526101c86020526040902060010154156116b15761068e565b6101c3546000906116ca906001600160a01b0316611f8e565b90506116d4612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae90611700908690600401613300565b60a06040518083038186803b15801561171857600080fd5b505afa15801561172c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117509190613254565b905080600001516001600160a01b0316846001600160a01b0316146117875760405162461bcd60e51b815260040161059c9061339e565b516001600160a01b031660009081526101c960209081526040808320548584526101c890925290912060010155505050565b6101c3546117cf906001600160a01b0316611f8e565b6001600160a01b0316336001600160a01b0316146117ff5760405162461bcd60e51b815260040161059c906137c1565b60009081526101c8602090815260408083208381556001018390556101cb909152812055565b6101c3546001600160a01b031681565b61184f600080516020613a9e8339815191526104676122f5565b61186b5760405162461bcd60e51b815260040161059c9061377c565b61144e6128a2565b6101c65481565b61188261303e565b5060009081526101c86020908152604091829020825180840190935280548352600101549082015290565b60008281526065602052604081206118c590836128fb565b90505b92915050565b60008281526065602052604081206118c59083612907565b6118ee611a23565b61190a5760405162461bcd60e51b815260040161059c90613857565b6101c48190556101c354600090611929906001600160a01b03166126a3565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561196157600080fd5b505afa158015611975573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061199991906132b0565b90506119b660646113fa8361090f86670de0b6b3a76400006122b2565b6101c7556119c26122f5565b6001600160a01b03167fa75d65370da375e8498bef76d6c105c80386c2d14e939f1c680da7f9a411c609836101c7546040516119ff929190613a33565b60405180910390a25050565b600081565b6101c96020526000908152604090205481565b6000611a3f600080516020613a7e8339815191526104676122f5565b905090565b600054610100900460ff1680611a5d5750611a5d611dd7565b80611a6b575060005460ff16155b611a875760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff16158015611ab2576000805460ff1961ff0019909116610100171660011790555b6001600160a01b03831615801590611ad257506001600160a01b03821615155b611aee5760405162461bcd60e51b815260040161059c90613468565b611af783610559565b6101c380546001600160a01b0319166001600160a01b0384161790558015611b25576000805461ff00191690555b505050565b60008181526065602052604081206118c89061291c565b6101c55481565b611b50612fdb565b6101ca6000836001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b82821015611c1e57838290600052602060002090600502016040518060a00160405290816000820154815260200160018201548152602001600282015481526020016003820154815260200160048201548152505081526020019060010190611bba565b505050915250909392505050565b600082815260656020526040902060020154611c4a906104676122f5565b6112b65760405162461bcd60e51b815260040161059c906135e3565b611c6e61302b565b5060009081526101cb602090815260409182902082519182019092529054815290565b6101c354611ca7906001600160a01b0316611f8e565b6001600160a01b031663b5ada6d8611cbd6122f5565b6040518263ffffffff1660e01b8152600401611cd991906132c8565b60206040518083038186803b158015611cf157600080fd5b505afa158015611d05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d299190613162565b611d455760405162461bcd60e51b815260040161059c90613521565b60c95460ff16610d975760405162461bcd60e51b815260040161059c90613820565b600080516020613a7e83398151915281565b80611d965760405162461bcd60e51b815260040161059c9061365d565b60005b81811015611b2557611dbc838383818110611db057fe5b90506020020135610da7565b50600101611d99565b600080516020613a9e83398151915281565b303b1590565b600054610100900460ff1680611df65750611df6611dd7565b80611e04575060005460ff16155b611e205760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff161580156114e0576000805460ff1961ff00199091166101001716600117905580156114f2576000805461ff001916905550565b600054610100900460ff1680611e775750611e77611dd7565b80611e85575060005460ff16155b611ea15760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff16158015611ecc576000805460ff1961ff0019909116610100171660011790555b6097805460ff1916905580156114f2576000805461ff001916905550565b600054610100900460ff1680611f035750611f03611dd7565b80611f11575060005460ff16155b611f2d5760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff16158015611f58576000805460ff1961ff0019909116610100171660011790555b60c9805460ff1916600117905580156114f2576000805461ff001916905550565b60009182526065602052604090912060020155565b60006118c882612822565b6020810151600090611fac906002612927565b60011492915050565b60006118c8600261090f84600161227b565b6000611fd1612fdb565b6101ca6000846001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b8282101561209f57838290600052602060002090600502016040518060a0016040529081600082015481526020016001820154815260200160028201548152602001600382015481526020016004820154815250508152602001906001019061203b565b505050508152505090506120b281612943565b9392505050565b60006120c3612fdb565b6101ca6000856001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b8282101561219157838290600052602060002090600502016040518060a0016040529081600082015481526020016001820154815260200160028201548152602001600382015481526020016004820154815250508152602001906001019061212d565b50505050815250509050828160400151511180156121cb5750806040015183815181106121ba57fe5b602002602001015160800151600014155b949350505050565b80516000906121f45760405162461bcd60e51b815260040161059c90613548565b606083015115806122095783606001516121cb565b505051919050565b60008160400151600014156122385760405162461bcd60e51b815260040161059c906134b2565b825115801561224d57505060408101516118c8565b6040830151845110156122725760405162461bcd60e51b815260040161059c906137e9565b505081516118c8565b60006118c5838360405180602001604052806000815250612949565b60006118c58261090f670de0b6b3a76400006113fa8761279b565b6000826122c1575060006118c8565b828202828482816122ce57fe5b04146118c557600080fd5b60006118c5838360405180602001604052806000815250612975565b3390565b6101c6546101c55461230a8261279b565b1061231557506114f2565b600061231f6122f5565b9050600061232c846129ac565b6001600160a01b03831660008181526101c960209081526040808320815163dd0ec24160e01b81529151959650879590946123c193909263dd0ec2419260048083019392829003018186803b15801561238457600080fd5b505afa158015612398573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123bc91906132b0565b61279b565b9050670de0b6b3a7640000811015612407576040517f75a25907c86842cd8f301fe24ccf300b65e4b0f91b7fe55286a7d0ec33a2490e90600090a15050505050506114f2565b6124286124208261090f87670de0b6b3a76400006122b2565b835490612441565b82556124348688612441565b6101c65550505050505050565b6000828201838110156118c557600080fd5b6101c35460009061246c906001600160a01b0316611f8e565b9050612476612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae906124a2908690600401613300565b60a06040518083038186803b1580156124ba57600080fd5b505afa1580156124ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124f29190613254565b90506124fd81611f99565b1561251a5760405162461bcd60e51b815260040161059c906138f1565b8051612524612fdb565b6101ca6000836001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b828210156125f257838290600052602060002090600502016040518060a0016040529081600082015481526020016001820154815260200160028201548152602001600382015481526020016004820154815250508152602001906001019061258e565b50505050815250509050600061260b8460200151611fb5565b9050612615612ffc565b8260400151828151811061262557fe5b60200260200101519050600061263b82856121d3565b60008981526101cb602052604090205490915081101561268a576040517f75a25907c86842cd8f301fe24ccf300b65e4b0f91b7fe55286a7d0ec33a2490e90600090a1505050505050506114f2565b60008881526101cb602052604090205550505050505050565b60006118c882612b88565b611b2583838360405180602001604052806000815250612ba0565b60008281526065602052604090206126e19082612c72565b1561068e576126ee6122f5565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600082815260656020526040902061274a9082612c87565b1561068e576127576122f5565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b60006118c8620f424061090f84670de0b6b3a76400006122b2565b60975460ff166127d85760405162461bcd60e51b815260040161059c9061343a565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa61280b6122f5565b60405161281891906132c8565b60405180910390a1565b60006001600160a01b03821663b93f9b0a600c5b6040518263ffffffff1660e01b81526004016128529190613300565b60206040518083038186803b15801561286a57600080fd5b505afa15801561287e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118c89190613074565b60975460ff16156128c55760405162461bcd60e51b815260040161059c90613633565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861280b6122f5565b60006118c58383612c9c565b60006118c5836001600160a01b038416612ce1565b60006118c882612cf9565b60006118c5838360405180602001604052806000815250612cfd565b51151590565b6000818484111561296d5760405162461bcd60e51b815260040161059c9190613309565b505050900390565b600081836129965760405162461bcd60e51b815260040161059c9190613309565b5060008385816129a257fe5b0495945050505050565b6101c35460009081906129c7906001600160a01b03166126a3565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156129ff57600080fd5b505afa158015612a13573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a3791906132b0565b90506000612a448461279b565b90506000612a546101c65461279b565b90506000612a6182612d31565b90506000612a836123bc612a7486612e72565b612a7d86612e72565b90612441565b90506101c554811115612a9657506101c5545b6000612aa58361140084612d31565b90506000612ab56101c554612d31565b905060008111612ad75760405162461bcd60e51b815260040161059c90613598565b6000612b08670de0b6b3a764000061090f8a6113fa606461090f8861090f6101c7548c6122b290919063ffffffff16565b90506000612b50670de0b6b3a764000061090f8b6113fa606461090f8961090f6101c7546113fa612b4b670de0b6b3a764000060016122b290919063ffffffff16565b612d31565b9050612b5c81866122b2565b8210612b7a5760405162461bcd60e51b815260040161059c90613928565b509998505050505050505050565b60006001600160a01b03821663b93f9b0a6012612836565b6001600160a01b038316612bc65760405162461bcd60e51b815260040161059c90613503565b60405163a9059cbb60e01b81526000906001600160a01b0386169063a9059cbb90612bf790879087906004016132dc565b602060405180830381600087803b158015612c1157600080fd5b505af1158015612c25573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c499190613162565b90508181612c6a5760405162461bcd60e51b815260040161059c9190613309565b505050505050565b60006118c5836001600160a01b038416612e93565b60006118c5836001600160a01b038416612edd565b81546000908210612cbf5760405162461bcd60e51b815260040161059c9061335c565b826000018281548110612cce57fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b5490565b60008183612d1e5760405162461bcd60e51b815260040161059c9190613309565b50828481612d2857fe5b06949350505050565b600081612d4057506000610923565b816001600160801b8210612d595760809190911c9060401b5b600160401b8210612d6f5760409190911c9060201b5b6401000000008210612d865760209190911c9060101b5b620100008210612d9b5760109190911c9060081b5b6101008210612daf5760089190911c9060041b5b60108210612dc25760049190911c9060021b5b60088210612dce5760011b5b6001818581612dd957fe5b048201901c90506001818581612deb57fe5b048201901c90506001818581612dfd57fe5b048201901c90506001818581612e0f57fe5b048201901c90506001818581612e2157fe5b048201901c90506001818581612e3357fe5b048201901c90506001818581612e4557fe5b048201901c90506000818581612e5757fe5b049050808210612e675780612e69565b815b95945050505050565b60006118c8612e8c670de0b6b3a7640000620f42406122d9565b83906122d9565b6000612e9f8383612ce1565b612ed5575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556118c8565b5060006118c8565b60008181526001830160205260408120548015612f995783546000198083019190810190600090879083908110612f1057fe5b9060005260206000200154905080876000018481548110612f2d57fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080612f5d57fe5b600190038181906000526020600020016000905590558660010160008781526020019081526020016000206000905560019450505050506118c8565b60009150506118c8565b6040518060a0016040528060006001600160a01b03168152602001600081526020016000815260200160008152602001600081525090565b60405180606001604052806000815260200160008152602001606081525090565b6040518060a0016040528060008152602001600081526020016000815260200160008152602001600081525090565b6040518060200160405280600081525090565b604051806040016040528060008152602001600081525090565b600060208284031215613069578081fd5b81356118c581613a68565b600060208284031215613085578081fd5b81516118c581613a68565b600080604083850312156130a2578081fd5b82356130ad81613a68565b915060208301356130bd81613a68565b809150509250929050565b600080604083850312156130da578182fd5b82356130e581613a68565b946020939093013593505050565b60008060208385031215613105578182fd5b823567ffffffffffffffff8082111561311c578384fd5b818501915085601f83011261312f578384fd5b81358181111561313d578485fd5b8660208083028501011115613150578485fd5b60209290920196919550909350505050565b600060208284031215613173578081fd5b815180151581146118c5578182fd5b600060208284031215613193578081fd5b5035919050565b600080604083850312156131ac578182fd5b8235915060208301356130bd81613a68565b600080604083850312156131d0578182fd5b50508035926020909101359150565b60008060008084860360a08112156131f5578283fd5b6040811215613202578283fd5b61320c6040613a41565b8635815260208088013581830152909550603f198201121561322c578283fd5b506132376020613a41565b604086013581529396939550505060608301359260800135919050565b600060a08284031215613265578081fd5b61326f60a0613a41565b825161327a81613a68565b80825250602083015160208201526040830151604082015260608301516060820152608083015160808201528091505092915050565b6000602082840312156132c1578081fd5b5051919050565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b901515815260200190565b90815260200190565b6000602080835283518082850152825b8181101561333557858101830151858201604001528201613319565b818111156133465783604083870101525b50601f01601f1916929092016040019392505050565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b6020808252602d908201527f506f6f6c41646472657373206d75737420657175616c20506f6f6c546f6b656e60408201526c20706f6f6c206164647265737360981b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b60208082526014908201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604082015260600190565b6020808252602a908201527f4f776e657220616e6420636f6e666967206164647265737365732063616e6e6f6040820152697420626520656d70747960b01b606082015260800190565b60208082526031908201527f756e736166653a20736c69636520616363756d756c61746f72206861736e2774604082015270081899595b881a5b9a5d1a585b1a5e9959607a1b606082015260800190565b6020808252600490820152635a45524f60e01b604082015260600190565b6020808252600d908201526c496e76616c696420706f6f6c2160981b604082015260600190565b60208082526030908201527f756e736166653a20706f6f6c20616363756d756c61746f72206861736e27742060408201526f1899595b881a5b9a5d1a585b1a5e995960821b606082015260800190565b6020808252602b908201527f6d6178496e746572657374446f6c6c617273456c696769626c65206d7573742060408201526a6e6f74206265207a65726f60a81b606082015260800190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b6020808252601e908201527f546f6b656e73496473206c656e677468206d757374206e6f7420626520300000604082015260600190565b6020808252818101527f4f776e65722063616e6e6f7420626520746865207a65726f2061646472657373604082015260600190565b6020808252601a908201527f4d757374206265206f776e6572206f6620506f6f6c546f6b656e000000000000604082015260600190565b602080825260149082015273141bdbdb081dda5d1a191c985dc81c185d5cd95960621b604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252600290820152614e4160f01b604082015260600190565b6020808252600f908201526e496e76616c69642073656e6465722160881b604082015260600190565b6020808252600e908201526d4e6f7420506f6f6c546f6b656e7360901b604082015260600190565b6020808252601c908201527f556e657870656374656420746f6b656e20616363756d756c61746f7200000000604082015260600190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b6020808252602b908201527f4d75737420686176652061646d696e20726f6c6520746f20706572666f726d2060408201526a3a3434b99030b1ba34b7b760a91b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b6020808252601f908201527f496e656c696769626c652073656e696f72207472616e63686520746f6b656e00604082015260600190565b6020808252603d908201527f6e657747726f7373526577617264732063616e6e6f742062652067726561746560408201527f72207468656e20746865206d6178206766692070657220646f6c6c6172000000606082015260800190565b815181526020918201519181019190915260400190565b60006020808352608080840185518386015282860151604081818801528088015191506060808189015283835180865260a09550858a0191508785019450885b81811015613a1957855180518452898101518a850152858101518685015284810151858501528801518884015294880194918601916001016139dc565b50909a9950505050505050505050565b9051815260200190565b918252602082015260400190565b60405181810167ffffffffffffffff81118282101715613a6057600080fd5b604052919050565b6001600160a01b03811681146114f257600080fdfeb19546dff01e856fb3f010c267a7b1c60363cf8a4664e21cc89c26224620214e65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862aa2646970667358221220e19bce8039d94cdc7ce7c928c88c515aec9276c24e3fd9a8e881131cdd58b20764736f6c634300060c0033

Deployed Bytecode

0x608060405234801561001057600080fd5b506004361061025e5760003560e01c806371d5a25311610146578063b6db75a0116100c3578063d547741f11610087578063d547741f146104f0578063dfc1f3a814610503578063e149ee8014610523578063e58378bb14610536578063e5b791061461053e578063e63ab1e9146105515761025e565b8063b6db75a01461049a578063b6f8fd40146104a2578063ca15c873146104b5578063ccf5a971146104c8578063d3d64722146104d05761025e565b80639010d07c1161010a5780639010d07c1461044657806391d1485414610459578063927356751461046c578063a217fddf1461047f578063a4063dbc146104875761025e565b806371d5a253146103ee57806379502c55146104015780638456cb591461041657806387f5769e1461041e5780638c7a63ae146104265761025e565b80632f2ff15d116101df5780634f64b2be116101a35780634f64b2be14610385578063526d81f6146103985780635c975abb146103a05780635e3f5d64146103b55780635f464bb2146103c85780636efbe643146103db5761025e565b80632f2ff15d1461032357806334cbd4581461033657806336568abe14610357578063369dfa841461036a5780633f4ba83a1461037d5761025e565b8063248a9ca311610226578063248a9ca3146102c45780632808e69e146102d75780632879e4de146102ea57806328fc33c7146102fd5780632e1a7d4d146103105761025e565b8063097616a3146102635780630c9dbe94146102785780630de74932146102965780630e15561a146102a9578063242a7286146102b1575b600080fd5b610276610271366004613058565b610559565b005b610280610692565b60405161028d9190613300565b60405180910390f35b6102806102a4366004613182565b610699565b610280610928565b6102766102bf366004613182565b61092f565b6102806102d2366004613182565b6109a4565b6102806102e5366004613182565b6109b9565b6102766102f8366004613182565b610c3e565b61027661030b366004613182565b610ca8565b61028061031e366004613182565b610da7565b61027661033136600461319a565b611220565b610349610344366004613058565b611264565b60405161028d929190613a33565b61027661036536600461319a565b61127e565b610280610378366004613182565b6112c0565b610276611410565b610349610393366004613182565b611450565b61027661146a565b6103a86114f5565b60405161028d91906132f5565b6102766103c33660046131df565b6114fe565b6102806103d6366004613182565b611587565b6102766103e93660046130c8565b61159a565b6102766103fc366004613182565b6117b9565b610409611825565b60405161028d91906132c8565b610276611835565b610280611873565b610439610434366004613182565b61187a565b60405161028d9190613985565b6104096104543660046131be565b6118ad565b6103a861046736600461319a565b6118ce565b61027661047a366004613182565b6118e6565b610280611a0b565b610280610495366004613058565b611a10565b6103a8611a23565b6102766104b0366004613090565b611a44565b6102806104c3366004613182565b611b2a565b610280611b41565b6104e36104de366004613058565b611b48565b60405161028d919061399c565b6102766104fe36600461319a565b611c2c565b610516610511366004613182565b611c66565b60405161028d9190613a29565b610276610531366004613182565b611c91565b610280611d67565b61027661054c3660046130f3565b611d79565b610280611dc5565b600054610100900460ff16806105725750610572611dd7565b80610580575060005460ff16155b6105a55760405162461bcd60e51b815260040161059c9061372e565b60405180910390fd5b600054610100900460ff161580156105d0576000805460ff1961ff0019909116610100171660011790555b6001600160a01b0382166105f65760405162461bcd60e51b815260040161059c90613694565b6105fe611ddd565b610606611e5e565b61060e611eea565b610626600080516020613a7e8339815191528361125a565b61063e600080516020613a9e8339815191528361125a565b610664600080516020613a9e833981519152600080516020613a7e833981519152611f79565b61067c600080516020613a7e83398151915280611f79565b801561068e576000805461ff00191690555b5050565b6101c75481565b60006106a3612fa3565b6101c3546106b9906001600160a01b0316611f8e565b6001600160a01b0316638c7a63ae846040518263ffffffff1660e01b81526004016106e49190613300565b60a06040518083038186803b1580156106fc57600080fd5b505afa158015610710573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107349190613254565b905061073f81611f99565b1561074e576000915050610923565b8051602082015160009061076190611fb5565b905061076c82611fc7565b158061077f575061077d82826120b9565b155b156107905760009350505050610923565b610798612fdb565b6101ca6000846001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b8282101561086657838290600052602060002090600502016040518060a00160405290816000820154815260200160018201548152602001600282015481526020016003820154815260200160048201548152505081526020019060010190610802565b50505050815250509050610878612ffc565b8160400151838151811061088857fe5b6020026020010151905061089a61302b565b5060008781526101cb602090815260408083208151928301909152548152906108c383856121d3565b905060006108d18385612211565b905060006108df838361227b565b905060006108f58a604001518760000151612297565b90506000610915670de0b6b3a764000061090f84866122b2565b906122d9565b9b5050505050505050505050505b919050565b6101c45481565b610937611a23565b6109535760405162461bcd60e51b815260040161059c90613857565b6101c58190556109616122f5565b6001600160a01b03167fbd23f227ee01d5b74d28337b4aa192bdb10824b0f2ad21e725a2f08af91ec81b826040516109999190613300565b60405180910390a250565b60009081526065602052604090206002015490565b6101c35460009081906109d4906001600160a01b0316611f8e565b90506109de612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae90610a0a908790600401613300565b60a06040518083038186803b158015610a2257600080fd5b505afa158015610a36573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a5a9190613254565b9050610a6581611f99565b15610a7557600092505050610923565b80516020820151600090610a8890611fb5565b9050610a9382611fc7565b1580610aa65750610aa482826120b9565b155b15610ab8576000945050505050610923565b610ac0612fdb565b6101ca6000846001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b82821015610b8e57838290600052602060002090600502016040518060a00160405290816000820154815260200160018201548152602001600282015481526020016003820154815260200160048201548152505081526020019060010190610b2a565b50505050815250509050610ba0612ffc565b81604001518381518110610bb057fe5b60200260200101519050610bc261302b565b5060008881526101cb60209081526040808320815192830182525482528301519091610bee8385612211565b90506000610bfc828461227b565b90506000610c128a604001518760000151612297565b90506000610c2c670de0b6b3a764000061090f84866122b2565b9e9d5050505050505050505050505050565b610c46611a23565b610c625760405162461bcd60e51b815260040161059c90613857565b6101c6819055610c706122f5565b6001600160a01b03167feabaa681e9990f0da888d0feb7ec727809a7e832013b120a9a248ba6b16d5f44826040516109999190613300565b6101c354610cbe906001600160a01b0316611f8e565b6001600160a01b031663b5ada6d8610cd46122f5565b6040518263ffffffff1660e01b8152600401610cf091906132c8565b60206040518083038186803b158015610d0857600080fd5b505afa158015610d1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d409190613162565b610d5c5760405162461bcd60e51b815260040161059c90613521565b60c95460ff16610d7e5760405162461bcd60e51b815260040161059c90613820565b60c9805460ff191690558015610d9757610d97816122f9565b5060c9805460ff19166001179055565b60975460009060ff1615610dcd5760405162461bcd60e51b815260040161059c90613633565b60c95460ff16610def5760405162461bcd60e51b815260040161059c90613820565b60c9805460ff191690556101c354600090610e12906001600160a01b0316611f8e565b9050610e1c612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae90610e48908790600401613300565b60a06040518083038186803b158015610e6057600080fd5b505afa158015610e74573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e989190613254565b80516101c35491925090610eb4906001600160a01b0316611f8e565b6001600160a01b031663b5ada6d8826040518263ffffffff1660e01b8152600401610edf91906132c8565b60206040518083038186803b158015610ef757600080fd5b505afa158015610f0b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f2f9190613162565b610f4b5760405162461bcd60e51b815260040161059c90613521565b6040516331a9108f60e11b81526001600160a01b03841690636352211e90610f77908890600401613300565b60206040518083038186803b158015610f8f57600080fd5b505afa158015610fa3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fc79190613074565b6001600160a01b0316336001600160a01b031614610ff75760405162461bcd60e51b815260040161059c906136c9565b6000819050806001600160a01b0316635c975abb6040518163ffffffff1660e01b815260040160206040518083038186803b15801561103557600080fd5b505afa158015611049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061106d9190613162565b1561108a5760405162461bcd60e51b815260040161059c90613700565b61109383611f99565b156110b05760405162461bcd60e51b815260040161059c906138f1565b60006110bb876112c0565b905060006110c888610699565b905060006110d68383612441565b60008a81526101c860205260409020549091506110f38185612441565b60008b81526101c860205260409020558215611112576111128a612453565b6040516331a9108f60e11b81526111ba906001600160a01b038a1690636352211e90611142908e90600401613300565b60206040518083038186803b15801561115a57600080fd5b505afa15801561116e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111929190613074565b6101c35484906111aa906001600160a01b03166126a3565b6001600160a01b031691906126ae565b896111c36122f5565b6001600160a01b03167ff282434f7158cb3a5501455a72b1946fe84ef5f1e84350beae1f3bf45ffc583e86866040516111fd929190613a33565b60405180910390a350965050505050505060c9805460ff19166001179055919050565b60008281526065602052604090206002015461123e906104676122f5565b61125a5760405162461bcd60e51b815260040161059c906133eb565b61068e82826126c9565b6101ca602052600090815260409020805460019091015482565b6112866122f5565b6001600160a01b0316816001600160a01b0316146112b65760405162461bcd60e51b815260040161059c906138a2565b61068e8282612732565b6101c35460009081906112db906001600160a01b0316611f8e565b90506112e5612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae90611311908790600401613300565b60a06040518083038186803b15801561132957600080fd5b505afa15801561133d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113619190613254565b905061136c81611f99565b1561137c57600092505050610923565b60008481526101c8602090815260408083206001015484516001600160a01b031684526101c99092528220546113b19161227b565b60008681526101c86020526040812054919250906113d790670de0b6b3a76400006122b2565b9050611406670de0b6b3a764000061090f83611400866113fa896040015161279b565b906122b2565b9061227b565b9695505050505050565b61142a600080516020613a9e8339815191526104676122f5565b6114465760405162461bcd60e51b815260040161059c9061377c565b61144e6127b6565b565b6101c8602052600090815260409020805460019091015482565b600054610100900460ff16806114835750611483611dd7565b80611491575060005460ff16155b6114ad5760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff161580156114d8576000805460ff1961ff0019909116610100171660011790555b6114e0611e5e565b80156114f2576000805461ff00191690555b50565b60975460ff1690565b6101c354611514906001600160a01b0316611f8e565b6001600160a01b0316336001600160a01b0316146115445760405162461bcd60e51b815260040161059c906137c1565b60408051808201825291825260209485015185830190815260009384526101c8865281842092518355516001909201919091556101cb9093529190912090519055565b6101cb6020526000908152604090205481565b6101c3546115b0906001600160a01b0316612822565b6001600160a01b03166115c16122f5565b6001600160a01b0316146115e75760405162461bcd60e51b815260040161059c90613798565b6101c3546115fd906001600160a01b0316611f8e565b6001600160a01b031663b5ada6d8836040518263ffffffff1660e01b815260040161162891906132c8565b60206040518083038186803b15801561164057600080fd5b505afa158015611654573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116789190613162565b6116945760405162461bcd60e51b815260040161059c90613521565b60008181526101c86020526040902060010154156116b15761068e565b6101c3546000906116ca906001600160a01b0316611f8e565b90506116d4612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae90611700908690600401613300565b60a06040518083038186803b15801561171857600080fd5b505afa15801561172c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117509190613254565b905080600001516001600160a01b0316846001600160a01b0316146117875760405162461bcd60e51b815260040161059c9061339e565b516001600160a01b031660009081526101c960209081526040808320548584526101c890925290912060010155505050565b6101c3546117cf906001600160a01b0316611f8e565b6001600160a01b0316336001600160a01b0316146117ff5760405162461bcd60e51b815260040161059c906137c1565b60009081526101c8602090815260408083208381556001018390556101cb909152812055565b6101c3546001600160a01b031681565b61184f600080516020613a9e8339815191526104676122f5565b61186b5760405162461bcd60e51b815260040161059c9061377c565b61144e6128a2565b6101c65481565b61188261303e565b5060009081526101c86020908152604091829020825180840190935280548352600101549082015290565b60008281526065602052604081206118c590836128fb565b90505b92915050565b60008281526065602052604081206118c59083612907565b6118ee611a23565b61190a5760405162461bcd60e51b815260040161059c90613857565b6101c48190556101c354600090611929906001600160a01b03166126a3565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561196157600080fd5b505afa158015611975573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061199991906132b0565b90506119b660646113fa8361090f86670de0b6b3a76400006122b2565b6101c7556119c26122f5565b6001600160a01b03167fa75d65370da375e8498bef76d6c105c80386c2d14e939f1c680da7f9a411c609836101c7546040516119ff929190613a33565b60405180910390a25050565b600081565b6101c96020526000908152604090205481565b6000611a3f600080516020613a7e8339815191526104676122f5565b905090565b600054610100900460ff1680611a5d5750611a5d611dd7565b80611a6b575060005460ff16155b611a875760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff16158015611ab2576000805460ff1961ff0019909116610100171660011790555b6001600160a01b03831615801590611ad257506001600160a01b03821615155b611aee5760405162461bcd60e51b815260040161059c90613468565b611af783610559565b6101c380546001600160a01b0319166001600160a01b0384161790558015611b25576000805461ff00191690555b505050565b60008181526065602052604081206118c89061291c565b6101c55481565b611b50612fdb565b6101ca6000836001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b82821015611c1e57838290600052602060002090600502016040518060a00160405290816000820154815260200160018201548152602001600282015481526020016003820154815260200160048201548152505081526020019060010190611bba565b505050915250909392505050565b600082815260656020526040902060020154611c4a906104676122f5565b6112b65760405162461bcd60e51b815260040161059c906135e3565b611c6e61302b565b5060009081526101cb602090815260409182902082519182019092529054815290565b6101c354611ca7906001600160a01b0316611f8e565b6001600160a01b031663b5ada6d8611cbd6122f5565b6040518263ffffffff1660e01b8152600401611cd991906132c8565b60206040518083038186803b158015611cf157600080fd5b505afa158015611d05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d299190613162565b611d455760405162461bcd60e51b815260040161059c90613521565b60c95460ff16610d975760405162461bcd60e51b815260040161059c90613820565b600080516020613a7e83398151915281565b80611d965760405162461bcd60e51b815260040161059c9061365d565b60005b81811015611b2557611dbc838383818110611db057fe5b90506020020135610da7565b50600101611d99565b600080516020613a9e83398151915281565b303b1590565b600054610100900460ff1680611df65750611df6611dd7565b80611e04575060005460ff16155b611e205760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff161580156114e0576000805460ff1961ff00199091166101001716600117905580156114f2576000805461ff001916905550565b600054610100900460ff1680611e775750611e77611dd7565b80611e85575060005460ff16155b611ea15760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff16158015611ecc576000805460ff1961ff0019909116610100171660011790555b6097805460ff1916905580156114f2576000805461ff001916905550565b600054610100900460ff1680611f035750611f03611dd7565b80611f11575060005460ff16155b611f2d5760405162461bcd60e51b815260040161059c9061372e565b600054610100900460ff16158015611f58576000805460ff1961ff0019909116610100171660011790555b60c9805460ff1916600117905580156114f2576000805461ff001916905550565b60009182526065602052604090912060020155565b60006118c882612822565b6020810151600090611fac906002612927565b60011492915050565b60006118c8600261090f84600161227b565b6000611fd1612fdb565b6101ca6000846001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b8282101561209f57838290600052602060002090600502016040518060a0016040529081600082015481526020016001820154815260200160028201548152602001600382015481526020016004820154815250508152602001906001019061203b565b505050508152505090506120b281612943565b9392505050565b60006120c3612fdb565b6101ca6000856001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b8282101561219157838290600052602060002090600502016040518060a0016040529081600082015481526020016001820154815260200160028201548152602001600382015481526020016004820154815250508152602001906001019061212d565b50505050815250509050828160400151511180156121cb5750806040015183815181106121ba57fe5b602002602001015160800151600014155b949350505050565b80516000906121f45760405162461bcd60e51b815260040161059c90613548565b606083015115806122095783606001516121cb565b505051919050565b60008160400151600014156122385760405162461bcd60e51b815260040161059c906134b2565b825115801561224d57505060408101516118c8565b6040830151845110156122725760405162461bcd60e51b815260040161059c906137e9565b505081516118c8565b60006118c5838360405180602001604052806000815250612949565b60006118c58261090f670de0b6b3a76400006113fa8761279b565b6000826122c1575060006118c8565b828202828482816122ce57fe5b04146118c557600080fd5b60006118c5838360405180602001604052806000815250612975565b3390565b6101c6546101c55461230a8261279b565b1061231557506114f2565b600061231f6122f5565b9050600061232c846129ac565b6001600160a01b03831660008181526101c960209081526040808320815163dd0ec24160e01b81529151959650879590946123c193909263dd0ec2419260048083019392829003018186803b15801561238457600080fd5b505afa158015612398573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123bc91906132b0565b61279b565b9050670de0b6b3a7640000811015612407576040517f75a25907c86842cd8f301fe24ccf300b65e4b0f91b7fe55286a7d0ec33a2490e90600090a15050505050506114f2565b6124286124208261090f87670de0b6b3a76400006122b2565b835490612441565b82556124348688612441565b6101c65550505050505050565b6000828201838110156118c557600080fd5b6101c35460009061246c906001600160a01b0316611f8e565b9050612476612fa3565b60405163463d31d760e11b81526001600160a01b03831690638c7a63ae906124a2908690600401613300565b60a06040518083038186803b1580156124ba57600080fd5b505afa1580156124ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124f29190613254565b90506124fd81611f99565b1561251a5760405162461bcd60e51b815260040161059c906138f1565b8051612524612fdb565b6101ca6000836001600160a01b03166001600160a01b03168152602001908152602001600020604051806060016040529081600082015481526020016001820154815260200160028201805480602002602001604051908101604052809291908181526020016000905b828210156125f257838290600052602060002090600502016040518060a0016040529081600082015481526020016001820154815260200160028201548152602001600382015481526020016004820154815250508152602001906001019061258e565b50505050815250509050600061260b8460200151611fb5565b9050612615612ffc565b8260400151828151811061262557fe5b60200260200101519050600061263b82856121d3565b60008981526101cb602052604090205490915081101561268a576040517f75a25907c86842cd8f301fe24ccf300b65e4b0f91b7fe55286a7d0ec33a2490e90600090a1505050505050506114f2565b60008881526101cb602052604090205550505050505050565b60006118c882612b88565b611b2583838360405180602001604052806000815250612ba0565b60008281526065602052604090206126e19082612c72565b1561068e576126ee6122f5565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600082815260656020526040902061274a9082612c87565b1561068e576127576122f5565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b60006118c8620f424061090f84670de0b6b3a76400006122b2565b60975460ff166127d85760405162461bcd60e51b815260040161059c9061343a565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa61280b6122f5565b60405161281891906132c8565b60405180910390a1565b60006001600160a01b03821663b93f9b0a600c5b6040518263ffffffff1660e01b81526004016128529190613300565b60206040518083038186803b15801561286a57600080fd5b505afa15801561287e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118c89190613074565b60975460ff16156128c55760405162461bcd60e51b815260040161059c90613633565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861280b6122f5565b60006118c58383612c9c565b60006118c5836001600160a01b038416612ce1565b60006118c882612cf9565b60006118c5838360405180602001604052806000815250612cfd565b51151590565b6000818484111561296d5760405162461bcd60e51b815260040161059c9190613309565b505050900390565b600081836129965760405162461bcd60e51b815260040161059c9190613309565b5060008385816129a257fe5b0495945050505050565b6101c35460009081906129c7906001600160a01b03166126a3565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156129ff57600080fd5b505afa158015612a13573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a3791906132b0565b90506000612a448461279b565b90506000612a546101c65461279b565b90506000612a6182612d31565b90506000612a836123bc612a7486612e72565b612a7d86612e72565b90612441565b90506101c554811115612a9657506101c5545b6000612aa58361140084612d31565b90506000612ab56101c554612d31565b905060008111612ad75760405162461bcd60e51b815260040161059c90613598565b6000612b08670de0b6b3a764000061090f8a6113fa606461090f8861090f6101c7548c6122b290919063ffffffff16565b90506000612b50670de0b6b3a764000061090f8b6113fa606461090f8961090f6101c7546113fa612b4b670de0b6b3a764000060016122b290919063ffffffff16565b612d31565b9050612b5c81866122b2565b8210612b7a5760405162461bcd60e51b815260040161059c90613928565b509998505050505050505050565b60006001600160a01b03821663b93f9b0a6012612836565b6001600160a01b038316612bc65760405162461bcd60e51b815260040161059c90613503565b60405163a9059cbb60e01b81526000906001600160a01b0386169063a9059cbb90612bf790879087906004016132dc565b602060405180830381600087803b158015612c1157600080fd5b505af1158015612c25573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c499190613162565b90508181612c6a5760405162461bcd60e51b815260040161059c9190613309565b505050505050565b60006118c5836001600160a01b038416612e93565b60006118c5836001600160a01b038416612edd565b81546000908210612cbf5760405162461bcd60e51b815260040161059c9061335c565b826000018281548110612cce57fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b5490565b60008183612d1e5760405162461bcd60e51b815260040161059c9190613309565b50828481612d2857fe5b06949350505050565b600081612d4057506000610923565b816001600160801b8210612d595760809190911c9060401b5b600160401b8210612d6f5760409190911c9060201b5b6401000000008210612d865760209190911c9060101b5b620100008210612d9b5760109190911c9060081b5b6101008210612daf5760089190911c9060041b5b60108210612dc25760049190911c9060021b5b60088210612dce5760011b5b6001818581612dd957fe5b048201901c90506001818581612deb57fe5b048201901c90506001818581612dfd57fe5b048201901c90506001818581612e0f57fe5b048201901c90506001818581612e2157fe5b048201901c90506001818581612e3357fe5b048201901c90506001818581612e4557fe5b048201901c90506000818581612e5757fe5b049050808210612e675780612e69565b815b95945050505050565b60006118c8612e8c670de0b6b3a7640000620f42406122d9565b83906122d9565b6000612e9f8383612ce1565b612ed5575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556118c8565b5060006118c8565b60008181526001830160205260408120548015612f995783546000198083019190810190600090879083908110612f1057fe5b9060005260206000200154905080876000018481548110612f2d57fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080612f5d57fe5b600190038181906000526020600020016000905590558660010160008781526020019081526020016000206000905560019450505050506118c8565b60009150506118c8565b6040518060a0016040528060006001600160a01b03168152602001600081526020016000815260200160008152602001600081525090565b60405180606001604052806000815260200160008152602001606081525090565b6040518060a0016040528060008152602001600081526020016000815260200160008152602001600081525090565b6040518060200160405280600081525090565b604051806040016040528060008152602001600081525090565b600060208284031215613069578081fd5b81356118c581613a68565b600060208284031215613085578081fd5b81516118c581613a68565b600080604083850312156130a2578081fd5b82356130ad81613a68565b915060208301356130bd81613a68565b809150509250929050565b600080604083850312156130da578182fd5b82356130e581613a68565b946020939093013593505050565b60008060208385031215613105578182fd5b823567ffffffffffffffff8082111561311c578384fd5b818501915085601f83011261312f578384fd5b81358181111561313d578485fd5b8660208083028501011115613150578485fd5b60209290920196919550909350505050565b600060208284031215613173578081fd5b815180151581146118c5578182fd5b600060208284031215613193578081fd5b5035919050565b600080604083850312156131ac578182fd5b8235915060208301356130bd81613a68565b600080604083850312156131d0578182fd5b50508035926020909101359150565b60008060008084860360a08112156131f5578283fd5b6040811215613202578283fd5b61320c6040613a41565b8635815260208088013581830152909550603f198201121561322c578283fd5b506132376020613a41565b604086013581529396939550505060608301359260800135919050565b600060a08284031215613265578081fd5b61326f60a0613a41565b825161327a81613a68565b80825250602083015160208201526040830151604082015260608301516060820152608083015160808201528091505092915050565b6000602082840312156132c1578081fd5b5051919050565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b901515815260200190565b90815260200190565b6000602080835283518082850152825b8181101561333557858101830151858201604001528201613319565b818111156133465783604083870101525b50601f01601f1916929092016040019392505050565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b6020808252602d908201527f506f6f6c41646472657373206d75737420657175616c20506f6f6c546f6b656e60408201526c20706f6f6c206164647265737360981b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b60208082526014908201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604082015260600190565b6020808252602a908201527f4f776e657220616e6420636f6e666967206164647265737365732063616e6e6f6040820152697420626520656d70747960b01b606082015260800190565b60208082526031908201527f756e736166653a20736c69636520616363756d756c61746f72206861736e2774604082015270081899595b881a5b9a5d1a585b1a5e9959607a1b606082015260800190565b6020808252600490820152635a45524f60e01b604082015260600190565b6020808252600d908201526c496e76616c696420706f6f6c2160981b604082015260600190565b60208082526030908201527f756e736166653a20706f6f6c20616363756d756c61746f72206861736e27742060408201526f1899595b881a5b9a5d1a585b1a5e995960821b606082015260800190565b6020808252602b908201527f6d6178496e746572657374446f6c6c617273456c696769626c65206d7573742060408201526a6e6f74206265207a65726f60a81b606082015260800190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b6020808252601e908201527f546f6b656e73496473206c656e677468206d757374206e6f7420626520300000604082015260600190565b6020808252818101527f4f776e65722063616e6e6f7420626520746865207a65726f2061646472657373604082015260600190565b6020808252601a908201527f4d757374206265206f776e6572206f6620506f6f6c546f6b656e000000000000604082015260600190565b602080825260149082015273141bdbdb081dda5d1a191c985dc81c185d5cd95960621b604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252600290820152614e4160f01b604082015260600190565b6020808252600f908201526e496e76616c69642073656e6465722160881b604082015260600190565b6020808252600e908201526d4e6f7420506f6f6c546f6b656e7360901b604082015260600190565b6020808252601c908201527f556e657870656374656420746f6b656e20616363756d756c61746f7200000000604082015260600190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b6020808252602b908201527f4d75737420686176652061646d696e20726f6c6520746f20706572666f726d2060408201526a3a3434b99030b1ba34b7b760a91b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b6020808252601f908201527f496e656c696769626c652073656e696f72207472616e63686520746f6b656e00604082015260600190565b6020808252603d908201527f6e657747726f7373526577617264732063616e6e6f742062652067726561746560408201527f72207468656e20746865206d6178206766692070657220646f6c6c6172000000606082015260800190565b815181526020918201519181019190915260400190565b60006020808352608080840185518386015282860151604081818801528088015191506060808189015283835180865260a09550858a0191508785019450885b81811015613a1957855180518452898101518a850152858101518685015284810151858501528801518884015294880194918601916001016139dc565b50909a9950505050505050505050565b9051815260200190565b918252602082015260400190565b60405181810167ffffffffffffffff81118282101715613a6057600080fd5b604052919050565b6001600160a01b03811681146114f257600080fdfeb19546dff01e856fb3f010c267a7b1c60363cf8a4664e21cc89c26224620214e65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862aa2646970667358221220e19bce8039d94cdc7ce7c928c88c515aec9276c24e3fd9a8e881131cdd58b20764736f6c634300060c0033

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.