// File: contracts/earn/LoanPoolMetadata.sol



// SPDX-License-Identifier: BUSL-1.1
// See bluejay.finance/license
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/ILoanPool.sol";
import "../interfaces/ILoanPoolFactory.sol";
import "../interfaces/ILoanPoolMetadata.sol";

contract LoanPoolMetadata is ILoanPoolMetadata, Ownable {
  /// @notice Keeps track of valid pool factories
  mapping(address => bool) public validPoolFactory;

  /// @notice Metadata URI of each loan pool address
  mapping(address => bytes) public metadata;

  /// @notice Register the metadata URI of a loan pool
  /// @param _loanPool Address of the loan pool
  /// @param _uri Location of the metadata JSON
  function registerMetadata(address _loanPool, bytes calldata _uri) external {
    address poolDeployer = ILoanPool(_loanPool).deployer();
    if (!validPoolFactory[poolDeployer]) revert InvalidLoanPoolFactory();
    if (!ILoanPoolFactory(poolDeployer).loanPoolDeployed(_loanPool))
      revert ExternalLoanPool();
    if (ILoanPool(_loanPool).borrower() != msg.sender) revert NotBorrower();
    metadata[_loanPool] = _uri;

    emit Update(_loanPool, _uri);
  }

  /// @notice Set the validity of specified LoanPoolFactory address
  /// @param _loanPoolFactory Address of the loan pool factory
  /// @param _valid Validity of the specified loan pool factory
  function setFactoryValidity(
    address _loanPoolFactory,
    bool _valid
  ) external onlyOwner {
    validPoolFactory[_loanPoolFactory] = _valid;
  }
}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: contracts/interfaces/ILoanPool.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

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

import "./ICreditLineBase.sol";

interface ILoanPool {
  /// @notice Amount is zero
  error ZeroAmount();

  /// @notice Funding period has not started
  error FundingPeriodNotStarted();

  /// @notice Funding period has ended
  error FundingPeriodEnded();

  /// @notice Funding period has not ended
  error FundingPeriodNotEnded();

  /// @notice Minimum amount of funds has been raised
  error MinimumFundingReached();

  /// @notice Minimum amount of funds has not been raised
  error MinimumFundingNotReached();

  /// @notice Drawdown period has not ended
  error DrawdownPeriodNotEnded();

  /// @notice Drawdown period has ended
  error DrawdownPeriodEnded();

  /// @notice Loan is not in funding state
  error NotFundingState();

  /// @notice Loan is not in repayment or repaid state
  error NotRepaymentOrRepaidState();

  /// @notice Insufficient balance for withdraw
  error InsufficientBalance();

  /// @notice Tokens cannot be transferred
  error TransferDisabled();

  /// @notice Attempt to transfer token which has claimed repayments
  error EncumberedTokenTransfer();

  /// @notice Attempt to unwithdraw more than what was withdrawn
  error ExcessiveUnwithdraw();

  /// @notice Loan is not in refund state
  error NotRefundState();

  /// @notice Caller is not the borrower
  error NotBorrower();

  /// @notice Funds have been deposited into the loan pool
  /// @param lender Address of the lender
  /// @param recipient Address where loan token is credited to
  /// @param amount Amount of funds deposited
  event Fund(address indexed lender, address indexed recipient, uint256 amount);

  /// @notice Lenders are allowed to withdraw their funds from the loan pool
  event Refunded();

  /// @notice Borrower has drawndown on the loan
  event Drawndown(address indexed borrower, uint256 amount);

  /// @notice Fees are collected from the loan pool
  /// @param borrower Address of borrower
  /// @param recipient Address where fees are credited to
  /// @param amount Amount of fees collected
  event FeesCollected(
    address indexed borrower,
    address indexed recipient,
    uint256 amount
  );

  /// @notice Funds are beind refunded to lender
  /// @param lender Address of the lender
  /// @param recipient Address where refunds are being sent
  /// @param amount Amount of funds refunded
  event Refund(
    address indexed lender,
    address indexed recipient,
    uint256 amount
  );

  /// @notice Borrower repays funds to the loan pool
  /// @param payer Address of the payer
  /// @param amount Amount of funds repaid
  event Repay(address indexed payer, uint256 amount);

  /// @notice Additional payments was refunded to the borrower
  /// @param payer Address of the payer
  /// @param amount Amount of funds refunded
  event RefundAdditionalPayment(address indexed payer, uint256 amount);

  /// @notice Funds are being withdrawn from the loan pool as lender
  /// after funds are repaid by the borrower
  /// @param lender Address of the lender
  /// @param recipient Address where funds are being sent
  /// @param amount Amount of funds withdrawn
  event Withdraw(
    address indexed lender,
    address indexed recipient,
    uint256 amount
  );

  /// @notice Funds are being returned to the loan pool by lender
  /// usually to free up more tokens for transfer
  /// @param sender Address of the sender
  /// @param lender Address where refunds are processed
  /// @param amount Amount of funds withdrawn
  event Unwithdraw(
    address indexed sender,
    address indexed lender,
    uint256 amount
  );

  function initialize(
    ICreditLineBase _creditLine,
    IERC20 _fundingAsset,
    address _borrower,
    address _feeRecipient,
    uint256[12] calldata _uints // collapsing because of stack too deep
  ) external;

  function creditLine() external view returns (ICreditLineBase);

  function fundingAsset() external view returns (IERC20);

  function borrower() external view returns (address);

  function deployer() external view returns (address);

  function feeRecipient() external view returns (address);

  function fundingStart() external view returns (uint256);

  function fundingEnd() external view returns (uint256);

  function minFundingRequired() external view returns (uint256);

  function drawdownPeriod() external view returns (uint256);

  function fees() external view returns (uint256);

  function repayments(address) external view returns (uint256);

  function fund(uint256 amount, address recipient) external;

  function fundDangerous(address recipient) external;

  function refundMinimumNotMet() external;

  function refundInactiveBorrower() external;

  function refund(address recipient) external;

  function drawdown() external;

  function repay(uint256 amount) external;

  function withdraw(uint256 amount, address recipient) external;

  function unwithdraw(uint256 amount, address recipient) external;

  function maxRepaymentAmount(
    address account
  ) external view returns (uint256 repaymentCeiling);

  function balanceAvailable(
    address account
  ) external view returns (uint256 balance);

  function shareOfPool(address account) external view returns (uint256 share);
}

// File: contracts/interfaces/ILoanPoolFactory.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

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

import "./ILoanPool.sol";
import "./ICreditLineBase.sol";

interface ILoanPoolFactory {
  /// @notice Credit line template is not registered with the factory
  error CreditLineTemplateNotRegistered();

  /// @notice New loan pool has been created
  /// @param loanPool Address of the loan pool
  /// @param borrower Address of the borrower
  /// @param fundingAsset Address of the asset used for the loan
  /// @param creditLineTemplate Address of the template which loan terms
  /// @param creditLine Address of the credit line
  /// @param maxLimit Maximum amount of funds that can be raised
  /// @param fees Fees charged for the loan
  event LoanPoolCreated(
    address indexed loanPool,
    address indexed borrower,
    address indexed fundingAsset,
    address creditLineTemplate,
    address creditLine,
    uint256 maxLimit,
    uint256 fees
  );

  /// @notice Fee recipient has been updated
  /// @param feeRecipient Address of fee recipient
  event UpdateFeeRecipient(address indexed feeRecipient);

  /// @notice Fee tier of a particular asset has been updated
  /// @param asset Address of the asset
  /// @param tier Updated fee tier of the asset
  event UpdateAssetFeeTier(address indexed asset, uint256 indexed tier);

  /// @notice Updated fees for a fee tier
  /// @param tier Fee tier
  /// @param fees Fees for the fee tier
  event UpdateFeeTier(uint256 indexed tier, uint256 fees);

  /// @notice Credit line template has been registered or unregistered
  /// @param creditLineTemplate Address of the credit line template
  /// @param isRegistered If the template can be used in creating new loan pools
  event UpdateCreditLineTemplate(
    address indexed creditLineTemplate,
    bool indexed isRegistered
  );

  function createPool(
    address creditLineTemplate,
    address fundingAsset,
    address borrower,
    uint256[11] calldata _uints
  ) external returns (ILoanPool loanPool, ICreditLineBase creditLine);

  function createCustomPool(
    address creditLineTemplate,
    address fundingAsset,
    address borrower,
    uint256[12] calldata _uints
  ) external returns (ILoanPool loanPool, ICreditLineBase creditLine);

  function feeRecipient() external view returns (address);

  function loanPoolTemplate() external view returns (address);

  function isCreditLineTemplate(address template) external view returns (bool);

  function feesForTier(uint256 tier) external view returns (uint256);

  function feesTierForAsset(address asset) external view returns (uint256);

  function loanPoolDeployed(address) external view returns (bool);

  function feesOnAsset(address asset) external view returns (uint256 fee);

  function addCreditLine(address _creditLine) external;

  function removeCreditLine(address _creditLine) external;

  function setFeeTier(uint256 tier, uint256 fee) external;

  function setAssetFeeTier(address asset, uint256 tier) external;

  function setFeeRecipient(address _feeRecipient) external;
}

// File: contracts/interfaces/ILoanPoolMetadata.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "../interfaces/ILoanPool.sol";

interface ILoanPoolMetadata {
  /// @notice Only loan pool borrowers can set the metadata URI
  error NotBorrower();

  /// @notice Loan pool is created with an invalid factory address
  error InvalidLoanPoolFactory();

  /// @notice Loan pool is not deployed by the deployer factory it claims
  error ExternalLoanPool();

  /// @notice Metadata URI has been updated for the specified loan pool
  /// @param loanPool Address of the loan pool
  /// @param uri Location of the metadata JSON
  event Update(address indexed loanPool, bytes indexed uri);

  function metadata(address _loanPool) external view returns (bytes memory);

  function registerMetadata(address _loanPool, bytes calldata _uri) external;

  function setFactoryValidity(address _loanPoolFactory, bool _valid) external;
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)

pragma solidity ^0.8.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: contracts/interfaces/ICreditLineBase.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

interface ICreditLineBase {
  /// @notice State of the loan
  /// @param Funding loan is currently fundraising from lenders
  /// @param Refund funding failed, funds to be returned to lenders, terminal state
  /// @param Repayment loan has been drawndown and borrower is repaying the loan
  /// @param Repaid loan has been fully repaid by borrower, terminal state
  enum State {
    Funding,
    Refund,
    Repayment,
    Repaid
  }

  /// @notice When a function is executed under the wrong loan state
  /// @param expectedState State that the loan should be in for the function to execute
  /// @param currentState State that the loan is currently in
  error IncorrectState(State expectedState, State currentState);

  /// @notice Funding exceeds the max limit
  error MaxLimitExceeded();

  /// @notice Loan state of the credit line has been updated
  /// @param newState State of the loan after the update
  event LoanStateUpdate(State indexed newState);

  /// @notice Repayment has been made towards loan
  /// @param timestamp Timestamp of repayment
  /// @param amount Amount of repayment
  /// @param interestRepaid Payment towards interest
  /// @param principalRepaid Payment towards principal
  /// @param additionalRepayment Excess payments
  event Repayment(
    uint256 timestamp,
    uint256 amount,
    uint256 interestRepaid,
    uint256 principalRepaid,
    uint256 additionalRepayment
  );

  function maxLimit() external view returns (uint256);

  function interestApr() external view returns (uint256);

  function paymentPeriod() external view returns (uint256);

  function gracePeriod() external view returns (uint256);

  function lateFeeApr() external view returns (uint256);

  function earlyRepaymentFee() external view returns (uint256);

  function principalBalance() external view returns (uint256);

  function interestBalance() external view returns (uint256);

  function totalPrincipalRepaid() external view returns (uint256);

  function totalInterestRepaid() external view returns (uint256);

  function totalEarlyFeePaid() external view returns (uint256);

  function additionalRepayment() external view returns (uint256);

  function lateInterestAccrued() external view returns (uint256);

  function interestAccruedAsOf() external view returns (uint256);

  function lastFullPaymentTime() external view returns (uint256);

  function minPaymentPerPeriod() external view returns (uint256);

  function loanStartTime() external view returns (uint256);

  function loanTenureInPeriods() external view returns (uint256);

  function loanState() external view returns (State);

  function initialize(
    uint256 _maxLimit,
    uint256 _interestApr,
    uint256 _paymentPeriod,
    uint256 _gracePeriod,
    uint256 _lateFeeApr,
    uint256 _loanTenureInPeriods,
    uint256 _earlyRepaymentFee
  ) external;

  function fund(uint256 amount) external;

  function drawdown() external returns (uint256 amount);

  function refund() external;

  function repay(
    uint256 amount
  )
    external
    returns (
      uint256 interestPayment,
      uint256 principalPayment,
      uint256 earlyFeePayment,
      uint256 additionalBalancePayment
    );

  function allocatePayment(
    uint256 amount,
    uint256 interestOutstanding,
    uint256 principalOutstanding,
    uint256 paymentExpected
  )
    external
    view
    returns (
      uint256 interestPayment,
      uint256 principalPayment,
      uint256 earlyFeePayment,
      uint256 additionalBalancePayment
    );

  function paymentDue() external view returns (uint256 amount);

  function interestAccruedSinceLastAssessed()
    external
    view
    returns (
      uint256 interestOwed,
      uint256 lateInterestOwed,
      uint256 fullPeriodsElapsed
    );

  function interestAccruedAtTimestamp(
    uint256 timestamp
  )
    external
    view
    returns (
      uint256 interestOwed,
      uint256 lateInterestOwed,
      uint256 fullPeriodsElapsed
    );

  function interestOnBalance(
    uint256 timePeriod
  ) external view returns (uint256 interestOwed);

  function lateInterestOnBalance(
    uint256 timePeriod
  ) external view returns (uint256 interestOwed);

  function totalRepayments() external view returns (uint256 amount);
}