ETH Price: $2,659.36 (-0.14%)

Contract

0x89bc08BA00f135d608bc335f6B33D7a9ABCC98aF
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Token Holdings

Transaction Hash
Method
Block
From
To
Cancel Nonce208484222024-09-28 10:05:353 hrs ago1727517935IN
0x89bc08BA...9ABCC98aF
0 ETH0.000368348.07224227
Cancel Nonce208260492024-09-25 7:11:353 days ago1727248295IN
0x89bc08BA...9ABCC98aF
0 ETH0.0006679914.63912872
Cancel Nonce208259022024-09-25 6:42:113 days ago1727246531IN
0x89bc08BA...9ABCC98aF
0 ETH0.0005529212.11727345
Cancel Nonce208258832024-09-25 6:38:233 days ago1727246303IN
0x89bc08BA...9ABCC98aF
0 ETH0.0005805612.72302114
Cancel Nonce208258682024-09-25 6:35:233 days ago1727246123IN
0x89bc08BA...9ABCC98aF
0 ETH0.0005716812.52839708
Cancel Nonce208212522024-09-24 15:07:473 days ago1727190467IN
0x89bc08BA...9ABCC98aF
0 ETH0.0014542331.86956066
Cancel Nonce208200882024-09-24 11:14:354 days ago1727176475IN
0x89bc08BA...9ABCC98aF
0 ETH0.0007334116.06861427
Cancel Nonce208189982024-09-24 7:35:594 days ago1727163359IN
0x89bc08BA...9ABCC98aF
0 ETH0.0014164731.04193261
Cancel Nonce208189952024-09-24 7:35:234 days ago1727163323IN
0x89bc08BA...9ABCC98aF
0 ETH0.0014252231.23360368
Cancel Nonce208162942024-09-23 22:33:474 days ago1727130827IN
0x89bc08BA...9ABCC98aF
0 ETH0.0011124424.37908676
Cancel Nonce208069512024-09-22 15:15:355 days ago1727018135IN
0x89bc08BA...9ABCC98aF
0 ETH0.0005011310.98234114
Cancel Nonce207975512024-09-21 7:46:477 days ago1726904807IN
0x89bc08BA...9ABCC98aF
0 ETH0.0006013513.17867676
Cancel Nonce207959042024-09-21 2:14:237 days ago1726884863IN
0x89bc08BA...9ABCC98aF
0 ETH0.000444529.74180567
Cancel Nonce207958982024-09-21 2:13:117 days ago1726884791IN
0x89bc08BA...9ABCC98aF
0 ETH0.0004563110
Cancel Nonce207958942024-09-21 2:12:237 days ago1726884743IN
0x89bc08BA...9ABCC98aF
0 ETH0.0004563110
Cancel Nonce207958892024-09-21 2:11:237 days ago1726884683IN
0x89bc08BA...9ABCC98aF
0 ETH0.0004563110
Cancel Nonce207958852024-09-21 2:10:357 days ago1726884635IN
0x89bc08BA...9ABCC98aF
0 ETH0.0004563110
Cancel Nonce207958812024-09-21 2:09:477 days ago1726884587IN
0x89bc08BA...9ABCC98aF
0 ETH0.0004563110
Cancel Nonce207958792024-09-21 2:09:237 days ago1726884563IN
0x89bc08BA...9ABCC98aF
0 ETH0.0004563110
Cancel Nonce207946612024-09-20 22:03:477 days ago1726869827IN
0x89bc08BA...9ABCC98aF
0 ETH0.0007531116.50454363
Cancel Nonce207946582024-09-20 22:03:117 days ago1726869791IN
0x89bc08BA...9ABCC98aF
0 ETH0.000730616.01114621
Cancel Nonce207939242024-09-20 19:34:597 days ago1726860899IN
0x89bc08BA...9ABCC98aF
0 ETH0.000431759.45936748
Cancel Nonce207903032024-09-20 7:27:118 days ago1726817231IN
0x89bc08BA...9ABCC98aF
0 ETH0.0004563110
Cancel Nonce207878522024-09-19 23:13:358 days ago1726787615IN
0x89bc08BA...9ABCC98aF
0 ETH0.000450629.87538529
Cancel Nonce207878462024-09-19 23:12:238 days ago1726787543IN
0x89bc08BA...9ABCC98aF
0 ETH0.00043079.43884043
View all transactions

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
LoanCore

Compiler Version
v0.8.18+commit.87f61d96

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 37 : LoanCore.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

import "./interfaces/ILoanCore.sol";
import "./interfaces/ICallDelegator.sol";
import "./interfaces/IPromissoryNote.sol";

import "./PromissoryNote.sol";
import "./libraries/InterestCalculator.sol";
import "./vault/OwnableERC721.sol";
import {
    LC_ZeroAddress,
    LC_ReusedNote,
    LC_CannotSettle,
    LC_CannotWithdraw,
    LC_ZeroAmount,
    LC_ArrayLengthMismatch,
    LC_OverMaxSplit,
    LC_CollateralInUse,
    LC_InvalidState,
    LC_NotExpired,
    LC_NonceUsed,
    LC_AffiliateCodeAlreadySet,
    LC_CallerNotLoanCore,
    LC_NoReceipt,
    LC_Shutdown
} from "./errors/Lending.sol";

/**
 * @title LoanCore
 * @author Non-Fungible Technologies, Inc.
 *
 * The LoanCore lending contract is the heart of the Arcade.xyz lending protocol.
 * It stores and maintains loan state, enforces loan lifecycle invariants, takes
 * escrow of assets during an active loans, governs the release of collateral on
 * repayment or default, and tracks signature nonces for loan consent.
 *
 * Also contains logic for approving Asset Vault calls using the
 * ICallDelegator interface.
 */
contract LoanCore is
    ILoanCore,
    InterestCalculator,
    AccessControlEnumerable,
    Pausable,
    ReentrancyGuard,
    ICallDelegator
{
    using Counters for Counters.Counter;
    using SafeERC20 for IERC20;

    // ============================================ STATE ==============================================

    // =================== Constants =====================

    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
    bytes32 public constant ORIGINATOR_ROLE = keccak256("ORIGINATOR");
    bytes32 public constant REPAYER_ROLE = keccak256("REPAYER");
    bytes32 public constant AFFILIATE_MANAGER_ROLE = keccak256("AFFILIATE_MANAGER");
    bytes32 public constant FEE_CLAIMER_ROLE = keccak256("FEE_CLAIMER");
    bytes32 public constant SHUTDOWN_ROLE = keccak256("SHUTDOWN");

    /// @dev Max split any affiliate can earn.
    uint96 private constant MAX_AFFILIATE_SPLIT = 50_00;

    /// @dev Grace period for repaying a loan after loan duration.
    uint256 public constant GRACE_PERIOD = 10 minutes;

    // =============== Contract References ================

    IPromissoryNote public immutable override borrowerNote;
    IPromissoryNote public immutable override lenderNote;

    // =================== Loan State =====================

    /// @dev Counter for serial IDs of all loans created.
    Counters.Counter private loanIdTracker;

    /// @dev Lookup table storing loan data structure.
    mapping(uint256 => LoanLibrary.LoanData) private loans;

    /// @dev Lookup table showing what collateral is currently being escrowed.
    ///      Key is hash of (collateralAddress, collateralId).
    mapping(bytes32 => bool) private collateralInUse;

    /// @dev Lookup table showing for which user, which nonces have been used.
    ///      user => nonce => isUsed
    mapping(address => mapping(uint160 => bool)) public usedNonces;

    // =================== Fee Management =====================

    /// @dev affiliate code => affiliate split
    ///      split contains payout address and a feeShare in bps
    mapping(bytes32 => AffiliateSplit) public affiliateSplits;

    /// @dev token => user => amount fees
    mapping(address => mapping(address => uint256)) public feesWithdrawable;

    /// @dev tokenId => {token, amount}
    ///      can be withdrawn by burning LenderNote of matching tokenId
    mapping(uint256 => NoteReceipt) public noteReceipts;

    // ========================================== CONSTRUCTOR ===========================================

    /**
     * @notice Deploys the loan core contract, by setting up roles and external
     *         contract references.
     *
     * @param _borrowerNote       The address of the PromissoryNote contract representing borrower obligation.
     * @param _lenderNote         The address of the PromissoryNote contract representing lender obligation.
     */
    constructor(IPromissoryNote _borrowerNote, IPromissoryNote _lenderNote) {
        if (address(_borrowerNote) == address(0)) revert LC_ZeroAddress("borrowerNote");
        if (address(_lenderNote) == address(0)) revert LC_ZeroAddress("lenderNote");
        if (address(_borrowerNote) == address(_lenderNote)) revert LC_ReusedNote();

        _setupRole(ADMIN_ROLE, msg.sender);
        _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
        _setRoleAdmin(ORIGINATOR_ROLE, ADMIN_ROLE);
        _setRoleAdmin(REPAYER_ROLE, ADMIN_ROLE);
        _setRoleAdmin(FEE_CLAIMER_ROLE, ADMIN_ROLE);
        _setRoleAdmin(AFFILIATE_MANAGER_ROLE, ADMIN_ROLE);
        _setRoleAdmin(SHUTDOWN_ROLE, ADMIN_ROLE);

        /// @dev Although using references for both promissory notes, these
        ///      must be fresh versions and cannot be re-used across multiple
        ///      loanCore instances, to ensure loanId <> tokenID parity. This is
        ///      enforced via deployment processes.
        borrowerNote = _borrowerNote;
        lenderNote = _lenderNote;

        // Avoid having loanId = 0
        loanIdTracker.increment();
    }

    // ====================================== LIFECYCLE OPERATIONS ======================================

    /**
     * @notice Start a loan, matching a set of terms, with a given
     *         lender and borrower. Collects collateral and distributes
     *         principal, along with collecting an origination fee for the
     *         protocol and/or affiliate. Can only be called by OriginationController.
     *
     * @param lender                The lender for the loan.
     * @param borrower              The borrower for the loan.
     * @param terms                 The terms of the loan.
     * @param _amountFromLender     The amount of principal to be collected from the lender.
     * @param _amountToBorrower     The amount of principal to be distributed to the borrower (net after fees).
     *
     * @return loanId               The ID of the newly created loan.
     */
    function startLoan(
        address lender,
        address borrower,
        LoanLibrary.LoanTerms calldata terms,
        uint256 _amountFromLender,
        uint256 _amountToBorrower,
        LoanLibrary.FeeSnapshot calldata _feeSnapshot
    ) external override whenNotPaused onlyRole(ORIGINATOR_ROLE) nonReentrant returns (uint256 loanId) {
        // Check collateral is not already used in a loan
        bytes32 collateralKey = keccak256(abi.encode(terms.collateralAddress, terms.collateralId));
        if (collateralInUse[collateralKey]) revert LC_CollateralInUse(terms.collateralAddress, terms.collateralId);

        // Check that we will not net lose tokens
        if (_amountToBorrower > _amountFromLender) revert LC_CannotSettle(_amountToBorrower, _amountFromLender);

        // Mark collateral as escrowed
        collateralInUse[collateralKey] = true;

        // Assign fees for withdrawal
        uint256 feesEarned;
        unchecked { feesEarned = _amountFromLender - _amountToBorrower; }
        (uint256 protocolFee, uint256 affiliateFee, address affiliate) =
            _getAffiliateSplit(feesEarned, terms.affiliateCode);

        if (protocolFee > 0) feesWithdrawable[terms.payableCurrency][address(this)] += protocolFee;
        if (affiliateFee > 0) feesWithdrawable[terms.payableCurrency][affiliate] += affiliateFee;

        // Get current loanId and increment for next function call
        loanId = loanIdTracker.current();
        loanIdTracker.increment();

        // Initiate loan state
        loans[loanId] = LoanLibrary.LoanData({
            terms: terms,
            startDate: uint160(block.timestamp),
            state: LoanLibrary.LoanState.Active,
            feeSnapshot: _feeSnapshot
        });

        // Distribute notes and principal
        _mintLoanNotes(loanId, borrower, lender);

        // Collect collateral from borrower
        IERC721(terms.collateralAddress).transferFrom(borrower, address(this), terms.collateralId);

        // Collect principal from lender and send net (minus fees) amount to borrower
        _collectIfNonzero(IERC20(terms.payableCurrency), lender, _amountFromLender);
        _transferIfNonzero(IERC20(terms.payableCurrency), borrower, _amountToBorrower);

        emit LoanStarted(loanId, lender, borrower);
    }

    /**
     * @notice Repay the given loan. Can only be called by RepaymentController,
     *         which verifies repayment conditions. This method will collect
     *         the total interest due from the borrower  and redistribute
     *         principal + interest to the lender, and collateral to the borrower.
     *         All promissory notes will be burned and the loan will be marked as complete.
     *
     * @param loanId                The ID of the loan to repay.
     * @param payer                 The party repaying the loan.
     * @param _amountFromPayer      The amount of tokens to be collected from the repayer.
     * @param _amountToLender       The amount of tokens to be distributed to the lender (net after fees).
     */
    function repay(
        uint256 loanId,
        address payer,
        uint256 _amountFromPayer,
        uint256 _amountToLender
    ) external override onlyRole(REPAYER_ROLE) nonReentrant {
        LoanLibrary.LoanData memory data = _handleRepay(loanId, _amountFromPayer, _amountToLender);

        // Get promissory notes from two parties involved, then burn
        address lender = lenderNote.ownerOf(loanId);
        address borrower = borrowerNote.ownerOf(loanId);
        _burnLoanNotes(loanId);

        // Send collected principal + interest, less fees, to lender
        _collectIfNonzero(IERC20(data.terms.payableCurrency), payer, _amountFromPayer);
        _transferIfNonzero(IERC20(data.terms.payableCurrency), lender, _amountToLender);

        // Redistribute collateral
        IERC721(data.terms.collateralAddress).safeTransferFrom(address(this), borrower, data.terms.collateralId);

        emit LoanRepaid(loanId);
    }

    /**
     * @notice Let the borrower repay the given loan, but do not release principal to the lender:
     *         instead, make it available for withdrawal. Should be used in cases where the borrower wants
     *         to fulfill loan obligations but the lender cannot receive tokens (due to malicious or
     *         accidental behavior, token blacklisting etc).
     *
     * @param loanId                The ID of the loan to repay.
     * @param payer                 The party repaying the loan.
     * @param _amountFromPayer      The amount of tokens to be collected from the repayer.
     * @param _amountToLender       The amount of tokens to be distributed to the lender (net after fees).
     */
    function forceRepay(
        uint256 loanId,
        address payer,
        uint256 _amountFromPayer,
        uint256 _amountToLender
    ) external override onlyRole(REPAYER_ROLE) nonReentrant {
        LoanLibrary.LoanData memory data = _handleRepay(loanId, _amountFromPayer, _amountToLender);

        // Do not send collected principal, but make it available for withdrawal by a holder of the lender note
        noteReceipts[loanId] = NoteReceipt({
            token: data.terms.payableCurrency,
            amount: _amountToLender
        });

        // Get promissory notes from two parties involved, then burn
        // borrower note _only_ - do not burn lender note until receipt
        // is redeemed
        address borrower = borrowerNote.ownerOf(loanId);
        borrowerNote.burn(loanId);

        // Collect from borrower and redistribute collateral
        _collectIfNonzero(IERC20(data.terms.payableCurrency), payer, _amountFromPayer);
        IERC721(data.terms.collateralAddress).safeTransferFrom(address(this), borrower, data.terms.collateralId);

        emit LoanRepaid(loanId);
        emit ForceRepay(loanId);
    }

    /**
     * @notice Claim collateral on a given loan. Can only be called by RepaymentController,
     *         which verifies claim conditions. This method validates that the loan's due
     *         date has passed, and the grace period of 10 mins has also passed. Then it distributes
     *         collateral to the lender. All promissory notes will be burned and the loan
     *         will be marked as complete.
     *
     * @param loanId                              The ID of the loan to claim.
     * @param _amountFromLender                   Any claiming fees to be collected from the lender.
     */
    function claim(uint256 loanId, uint256 _amountFromLender)
        external
        override
        whenNotPaused
        onlyRole(REPAYER_ROLE)
        nonReentrant
    {
        LoanLibrary.LoanData memory data = loans[loanId];
        // Ensure valid initial loan state when claiming loan
        if (data.state != LoanLibrary.LoanState.Active) revert LC_InvalidState(data.state);

        // First check if the call is being made after the due date plus 10 min grace period.
        uint256 dueDate = data.startDate + data.terms.durationSecs + GRACE_PERIOD;
        if (dueDate >= block.timestamp) revert LC_NotExpired(dueDate);

        // State changes and cleanup
        loans[loanId].state = LoanLibrary.LoanState.Defaulted;
        collateralInUse[keccak256(abi.encode(data.terms.collateralAddress, data.terms.collateralId))] = false;

        if (_amountFromLender > 0) {
            // Assign fees for withdrawal
            (uint256 protocolFee, uint256 affiliateFee, address affiliate) =
                _getAffiliateSplit(_amountFromLender, data.terms.affiliateCode);

            mapping(address => uint256) storage _feesWithdrawable = feesWithdrawable[data.terms.payableCurrency];
            if (protocolFee > 0) _feesWithdrawable[address(this)] += protocolFee;
            if (affiliateFee > 0) _feesWithdrawable[affiliate] += affiliateFee;
        }

        // Get promissory notes from two parties involved, then burn
        address lender = lenderNote.ownerOf(loanId);
        _burnLoanNotes(loanId);

        // Collateral redistribution
        IERC721(data.terms.collateralAddress).safeTransferFrom(address(this), lender, data.terms.collateralId);

        // Collect claim fee from lender
        _collectIfNonzero(IERC20(data.terms.payableCurrency), lender, _amountFromLender);

        emit LoanClaimed(loanId);
    }

    /**
     * @notice Burn a lender note, for an already-completed loan, in order to receive
     *         held tokens already paid back by the borrower. Can only be called by the
     *         owner of the note.
     *
     * @param loanId                    The ID of the lender note to redeem.
     * @param _amountFromLender         Any redemption fees to be collected from the lender.
     * @param to                        The address to receive the held tokens.
     */
    function redeemNote(
        uint256 loanId,
        uint256 _amountFromLender,
        address to
    ) external override onlyRole(REPAYER_ROLE) nonReentrant {
        NoteReceipt memory receipt = noteReceipts[loanId];
        (address token, uint256 amount) = (receipt.token, receipt.amount);
        if (token == address(0) || amount == 0) revert LC_NoReceipt(loanId);

        // Deduct the redeem fee from the amount and assign for withdrawal
        amount -= _amountFromLender;

        // Assign fees for withdrawal
        (uint256 protocolFee, uint256 affiliateFee, address affiliate) =
            _getAffiliateSplit(_amountFromLender, loans[loanId].terms.affiliateCode);

        mapping(address => uint256) storage _feesWithdrawable = feesWithdrawable[token];
        if (protocolFee > 0) _feesWithdrawable[address(this)] += protocolFee;
        if (affiliateFee > 0) _feesWithdrawable[affiliate] += affiliateFee;

        // Delete the receipt
        delete noteReceipts[loanId];

        // Burn the note
        address lender = lenderNote.ownerOf(loanId);
        lenderNote.burn(loanId);

        // Transfer the held tokens to the lender-specified address
        _transferIfNonzero(IERC20(token), to, amount);

        emit NoteRedeemed(token, lender, to, loanId, amount);
    }

    /**
     * @notice Roll over a loan, atomically closing one and re-opening a new one with the
     *         same collateral. Instead of full repayment, only net payments from each
     *         party are required. Each rolled-over loan is marked as complete, and the new
     *         loan is given a new unique ID and notes. At the time of calling, any needed
     *         net payments have been collected by the RepaymentController for withdrawal.
     *
     * @param oldLoanId             The ID of the old loan.
     * @param borrower              The borrower for the loan.
     * @param lender                The lender for the old loan.
     * @param terms                 The terms of the new loan.
     * @param _settledAmount        The amount LoanCore needs to withdraw to settle.
     * @param _amountToOldLender    The payment to the old lender (if lenders are changing).
     * @param _amountToLender       The payment to the lender (if same as old lender).
     * @param _amountToBorrower     The payment to the borrower (in the case of leftover principal).
     *
     * @return newLoanId            The ID of the new loan.
     */
    function rollover(
        uint256 oldLoanId,
        address borrower,
        address lender,
        LoanLibrary.LoanTerms calldata terms,
        uint256 _settledAmount,
        uint256 _amountToOldLender,
        uint256 _amountToLender,
        uint256 _amountToBorrower
    ) external override whenNotPaused onlyRole(ORIGINATOR_ROLE) nonReentrant returns (uint256 newLoanId) {
        LoanLibrary.LoanData storage data = loans[oldLoanId];
        // Ensure valid loan state for old loan
        if (data.state != LoanLibrary.LoanState.Active) revert LC_InvalidState(data.state);

        // State change for old loan
        data.state = LoanLibrary.LoanState.Repaid;

        address oldLender = lenderNote.ownerOf(oldLoanId);
        IERC20 payableCurrency = IERC20(data.terms.payableCurrency);

        // Check that contract will not net lose tokens
        if (_amountToOldLender + _amountToLender + _amountToBorrower > _settledAmount)
            revert LC_CannotSettle(_amountToOldLender + _amountToLender + _amountToBorrower, _settledAmount);
        {
            // Assign fees for withdrawal
            uint256 feesEarned;
            unchecked { feesEarned = _settledAmount - _amountToOldLender - _amountToLender - _amountToBorrower; }

            // Make sure split goes to affiliate code from _new_ terms
            (uint256 protocolFee, uint256 affiliateFee, address affiliate) =
                _getAffiliateSplit(feesEarned, terms.affiliateCode);

            // Assign fees for withdrawal
            mapping(address => uint256) storage _feesWithdrawable = feesWithdrawable[address(payableCurrency)];
            if (protocolFee > 0) _feesWithdrawable[address(this)] += protocolFee;
            if (affiliateFee > 0) _feesWithdrawable[affiliate] += affiliateFee;
        }

        // Set up new loan
        newLoanId = loanIdTracker.current();
        loanIdTracker.increment();

        loans[newLoanId] = LoanLibrary.LoanData({
            terms: terms,
            state: LoanLibrary.LoanState.Active,
            startDate: uint160(block.timestamp),
            feeSnapshot: data.feeSnapshot
        });

        // Burn old notes
        _burnLoanNotes(oldLoanId);

        // Mint new notes
        _mintLoanNotes(newLoanId, borrower, lender);

        // Perform net settlement operations
        _collectIfNonzero(payableCurrency, msg.sender, _settledAmount);
        _transferIfNonzero(payableCurrency, oldLender, _amountToOldLender);
        _transferIfNonzero(payableCurrency, lender, _amountToLender);
        _transferIfNonzero(payableCurrency, borrower, _amountToBorrower);

        emit LoanRepaid(oldLoanId);
        emit LoanStarted(newLoanId, lender, borrower);
        emit LoanRolledOver(oldLoanId, newLoanId);
    }

    // ======================================== NONCE MANAGEMENT ========================================

    /**
     * @notice Mark a nonce as used in the context of starting a loan. Reverts if
     *         nonce has already been used. Can only be called by Origination Controller.
     *
     * @param user                  The user for whom to consume a nonce.
     * @param nonce                 The nonce to consume.
     */
    function consumeNonce(address user, uint160 nonce) external override whenNotPaused onlyRole(ORIGINATOR_ROLE) {
        _useNonce(user, nonce);
    }

    /**
     * @notice Mark a nonce as used in order to invalidate signatures with the nonce.
     *         Does not allow specifying the user, and automatically consumes the nonce
     *         of the caller.
     *
     * @param nonce                 The nonce to consume.
     */
    function cancelNonce(uint160 nonce) external override {
        _useNonce(msg.sender, nonce);
    }

    // ========================================= VIEW FUNCTIONS =========================================

    /**
     * @notice Returns the LoanData struct for the specified loan ID.
     *
     * @param loanId                The ID of the given loan.
     *
     * @return loanData             The struct containing loan state and terms.
     */
    function getLoan(uint256 loanId) external view override returns (LoanLibrary.LoanData memory loanData) {
        return loans[loanId];
    }

    /**
     * @notice Returns the note receipt data for a given loan ID. Does
     *         not revert, returns 0 if no receipt.
     *
     * @param loanId                The ID of the given loan.
     *
     * @return token                The address of the token for the note.
     * @return amount               The amount of the note.
     */
    function getNoteReceipt(uint256 loanId) external view override returns (address, uint256) {
        NoteReceipt storage receipt = noteReceipts[loanId];
        return (receipt.token, receipt.amount);
    }

    /**
     * @notice Reports if the caller is allowed to call functions on the given vault.
     *         Determined by if they are the borrower for the loan, defined by ownership
     *         of the relevant BorrowerNote.
     *
     * @dev Implemented as part of the ICallDelegator interface.
     *
     * @param caller                The user that wants to call a function.
     * @param vault                 The vault that the caller wants to call a function on.
     *
     * @return allowed              True if the caller is allowed to call on the vault.
     */
    function canCallOn(address caller, address vault) external view override whenNotPaused returns (bool) {
        // if the collateral is not currently being used in a loan, disallow
        if (!collateralInUse[keccak256(abi.encode(OwnableERC721(vault).ownershipToken(), uint256(uint160(vault))))]) {
            return false;
        }

        uint256 noteCount = borrowerNote.balanceOf(caller);
        for (uint256 i = 0; i < noteCount;) {
            uint256 loanId = borrowerNote.tokenOfOwnerByIndex(caller, i);
            LoanLibrary.LoanTerms storage terms = loans[loanId].terms;

            // if the borrower is currently borrowing against this vault,
            // return true
            if (
                terms.collateralAddress == OwnableERC721(vault).ownershipToken() &&
                terms.collateralId == uint256(uint160(vault))
            ) {
                return true;
            }

            // Can never overflow bc balanceOf is bounded by uint256
            unchecked {
                i++;
            }
        }
        return false;
    }

    /**
     * @notice Reports whether the given nonce has been previously used by a user. Returning
     *         false does not mean that the nonce will not clash with another potential off-chain
     *         signature that is stored somewhere.
     *
     * @param user                  The user to check the nonce for.
     * @param nonce                 The nonce to check.
     *
     * @return used                 Whether the nonce has been used.
     */
    function isNonceUsed(address user, uint160 nonce) external view override returns (bool) {
        return usedNonces[user][nonce];
    }

    // ========================================= FEE MANAGEMENT =========================================

    /**
     * @notice Claim any feesWithdrawable balance pending for the caller, as specified by token.
     *         This may accumulate from either affiliate fee shares or borrower forced repayments.
     *
     * @param token                 The contract address of the token to claim tokens for.
     * @param amount                The amount of tokens to claim.
     * @param to                    The address to send the tokens to.
     */
    function withdraw(address token, uint256 amount, address to) external override nonReentrant {
        if (token == address(0)) revert LC_ZeroAddress("token");
        if (amount == 0) revert LC_ZeroAmount();
        if (to == address(0)) revert LC_ZeroAddress("to");

        // any token balances remaining on this contract are fees owned by the protocol
        mapping(address => uint256) storage _feesWithdrawable = feesWithdrawable[token];

        uint256 available = _feesWithdrawable[msg.sender];
        if (amount > available) revert LC_CannotWithdraw(amount, available);

        unchecked { _feesWithdrawable[msg.sender] -= amount; }

        _transferIfNonzero(IERC20(token), to, amount);

        emit FeesWithdrawn(token, msg.sender, to, amount);
    }

    /**
     * @notice Claim the protocol fees for the given token. Any token used as principal
     *         for a loan will have accumulated fees. Must be called by contract owner.
     *
     * @param token                     The contract address of the token to claim fees for.
     * @param to                        The address to send the fees to.
     */
    function withdrawProtocolFees(address token, address to) external override nonReentrant onlyRole(FEE_CLAIMER_ROLE) {
        if (token == address(0)) revert LC_ZeroAddress("token");
        if (to == address(0)) revert LC_ZeroAddress("to");

        // any token balances remaining on this contract are fees owned by the protocol
        mapping(address => uint256) storage _feesWithdrawable = feesWithdrawable[token];
        uint256 amount = _feesWithdrawable[address(this)];
        _feesWithdrawable[address(this)] = 0;

        _transferIfNonzero(IERC20(token), to, amount);

        emit FeesWithdrawn(token, msg.sender, to, amount);
    }

    // ======================================== ADMIN FUNCTIONS =========================================

    /**
     * @notice Set the affiliate fee splits for the batch of affiliate codes. Codes and splits should
     *         be matched index-wise. Can only be called by protocol admin.
     *
     * @param codes                     The affiliate code to set the split for.
     * @param splits                    The splits to set for the given codes.
     */
    function setAffiliateSplits(
        bytes32[] calldata codes,
        AffiliateSplit[] calldata splits
    ) external override onlyRole(AFFILIATE_MANAGER_ROLE) {
        if (codes.length != splits.length) revert LC_ArrayLengthMismatch();

        for (uint256 i = 0; i < codes.length;) {
            if (splits[i].splitBps > MAX_AFFILIATE_SPLIT)
                revert LC_OverMaxSplit(splits[i].splitBps, MAX_AFFILIATE_SPLIT);

            if (affiliateSplits[codes[i]].affiliate != address(0))
                revert LC_AffiliateCodeAlreadySet(codes[i]);

            affiliateSplits[codes[i]] = splits[i];
            emit AffiliateSet(codes[i], splits[i].affiliate, splits[i].splitBps);

            // codes is calldata, overflow is impossible bc of calldata
            // size limits vis-a-vis gas
            unchecked {
                i++;
            }
        }
    }

    /**
     * @notice Shuts down the contract, callable by a designated role. Irreversible.
     *         When the contract is shutdown, loans can only be repaid.
     *         New loans cannot be started, defaults cannot be claimed,
     *         loans cannot be rolled over, and vault utility cannot be
     *         employed. This is an emergency recovery feature.
     */
    function shutdown() external onlyRole(SHUTDOWN_ROLE) {
        _pause();
    }

    // ============================================= HELPERS ============================================


    /**
     * @dev Perform shared logic across repay operations repay and forceRepay - all "checks" and "effects".
     *      Will validate loan state, perform accounting calculations, update storage and burn loan notes.
     *      Transfers should occur in the calling function.
     *
     * @param loanId                The ID of the loan to repay.
     * @param _amountFromPayer      The amount of tokens to be collected from the repayer.
     * @param _amountToLender       The amount of tokens to be distributed to the lender (net after fees).
     *
     * @return data                 The loan data for the repay operation.
     */
    function _handleRepay(
        uint256 loanId,
        uint256 _amountFromPayer,
        uint256 _amountToLender
    ) internal returns (LoanLibrary.LoanData memory data) {
        data = loans[loanId];
        // Ensure valid initial loan state when repaying loan
        if (data.state != LoanLibrary.LoanState.Active) revert LC_InvalidState(data.state);

        // Check that we will not net lose tokens.
        if (_amountToLender > _amountFromPayer) revert LC_CannotSettle(_amountToLender, _amountFromPayer);

        uint256 feesEarned;
        unchecked { feesEarned = _amountFromPayer - _amountToLender; }

        (uint256 protocolFee, uint256 affiliateFee, address affiliate) =
            _getAffiliateSplit(feesEarned, data.terms.affiliateCode);

        // Assign fees for withdrawal
        mapping(address => uint256) storage _feesWithdrawable = feesWithdrawable[data.terms.payableCurrency];
        if (protocolFee > 0) _feesWithdrawable[address(this)] += protocolFee;
        if (affiliateFee > 0) _feesWithdrawable[affiliate] += affiliateFee;

        // State changes and cleanup
        loans[loanId].state = LoanLibrary.LoanState.Repaid;
        collateralInUse[keccak256(abi.encode(data.terms.collateralAddress, data.terms.collateralId))] = false;
    }

    /**
     * @dev Lookup the submitted affiliateCode for a split value, and return the amount
     *      going to protocol and the amount going to the affiliate, along with destination.
     *
     * @param amount                The amount to split.
     * @param affiliateCode         The affiliate code to lookup.
     *
     * @return protocolFee          The amount going to protocol.
     * @return affiliateFee         The amount going to the affiliate.
     * @return affiliate            The address of the affiliate.
     */
    function _getAffiliateSplit(
        uint256 amount,
        bytes32 affiliateCode
    ) internal view returns (uint256 protocolFee, uint256 affiliateFee, address affiliate) {
        AffiliateSplit memory split = affiliateSplits[affiliateCode];

        if (split.affiliate == address(0)) {
            return (amount, 0, address(0));
        }

        affiliate = split.affiliate;
        affiliateFee = amount * split.splitBps / BASIS_POINTS_DENOMINATOR;
        unchecked { protocolFee = amount - affiliateFee; }
    }

    /**
     * @dev Consume a nonce, by marking it as used for that user. Reverts if the nonce
     *      has already been used.
     *
     * @param user                  The user for whom to consume a nonce.
     * @param nonce                 The nonce to consume.
     */
    function _useNonce(address user, uint160 nonce) internal {
        mapping(uint160 => bool) storage _usedNonces = usedNonces[user];

        if (_usedNonces[nonce]) revert LC_NonceUsed(user, nonce);
        // set nonce to used
        _usedNonces[nonce] = true;

        emit NonceUsed(user, nonce);
    }

    /**
     * @dev Mint a borrower and lender note together - easier to make sure
     *      they are synchronized.
     *
     * @param loanId                The token ID to mint.
     * @param borrower              The address of the recipient of the borrower note.
     * @param lender                The address of the recipient of the lender note.
     */
    function _mintLoanNotes(
        uint256 loanId,
        address borrower,
        address lender
    ) internal {
        borrowerNote.mint(borrower, loanId);
        lenderNote.mint(lender, loanId);
    }

    /**
     * @dev Burn a borrower and lender note together - easier to make sure
     *      they are synchronized.
     *
     * @param loanId                The token ID to burn.
     */
    function _burnLoanNotes(uint256 loanId) internal {
        lenderNote.burn(loanId);
        borrowerNote.burn(loanId);
    }

    /**
     * @dev Perform an ERC20 transfer, if the specified amount is nonzero - else no-op.
     *
     * @param token                 The token to transfer.
     * @param to                    The address receiving the tokens.
     * @param amount                The amount of tokens to transfer.
     */
    function _transferIfNonzero(
        IERC20 token,
        address to,
        uint256 amount
    ) internal {
        if (amount > 0) token.safeTransfer(to, amount);
    }

    /**
     * @dev Perform an ERC20 transferFrom, if the specified amount is nonzero - else no-op.
     *
     * @param token                 The token to transfer.
     * @param from                  The address sending the tokens.
     * @param amount                The amount of tokens to transfer.
     */
    function _collectIfNonzero(
        IERC20 token,
        address from,
        uint256 amount
    ) internal {
        if (amount > 0) token.safeTransferFrom(from, address(this), amount);
    }

    /**
     * @dev Blocks the contract from unpausing once paused.
     */
    function _unpause() internal override whenPaused {
        revert LC_Shutdown();
    }
}

File 2 of 37 : SafeERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

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

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

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

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

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

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

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

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 3 of 37 : IERC721.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

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

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

File 4 of 37 : AccessControlEnumerable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
    using EnumerableSet for EnumerableSet.AddressSet;

    mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @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 override returns (address) {
        return _roleMembers[role].at(index);
    }

    /**
     * @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 override returns (uint256) {
        return _roleMembers[role].length();
    }

    /**
     * @dev Overload {grantRole} to track enumerable memberships
     */
    function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
        super.grantRole(role, account);
        _roleMembers[role].add(account);
    }

    /**
     * @dev Overload {revokeRole} to track enumerable memberships
     */
    function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
        super.revokeRole(role, account);
        _roleMembers[role].remove(account);
    }

    /**
     * @dev Overload {renounceRole} to track enumerable memberships
     */
    function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
        super.renounceRole(role, account);
        _roleMembers[role].remove(account);
    }

    /**
     * @dev Overload {_setupRole} to track enumerable memberships
     */
    function _setupRole(bytes32 role, address account) internal virtual override {
        super._setupRole(role, account);
        _roleMembers[role].add(account);
    }
}

File 5 of 37 : Pausable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../utils/Context.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.
 */
abstract contract Pausable is Context {
    /**
     * @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.
     */
    constructor() {
        _paused = false;
    }

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

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

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

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

File 6 of 37 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @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].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being 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 percentage 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.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @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(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

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

File 7 of 37 : Counters.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

File 8 of 37 : ILoanCore.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

import "../libraries/LoanLibrary.sol";
import "./IPromissoryNote.sol";

interface ILoanCore {

    // ================ Data Types =================

    struct AffiliateSplit {
        address affiliate;
        uint96 splitBps;
    }

    struct NoteReceipt {
        address token;
        uint256 amount;
    }

    // ================ Events =================

    event LoanStarted(uint256 loanId, address lender, address borrower);
    event LoanRepaid(uint256 loanId);
    event ForceRepay(uint256 loanId);
    event LoanRolledOver(uint256 oldLoanId, uint256 newLoanId);
    event LoanClaimed(uint256 loanId);
    event NoteRedeemed(address indexed token, address indexed caller, address indexed to, uint256 tokenId, uint256 amount);
    event NonceUsed(address indexed user, uint160 nonce);

    event FeesWithdrawn(address indexed token, address indexed caller, address indexed to, uint256 amount);
    event AffiliateSet(bytes32 indexed code, address indexed affiliate, uint96 splitBps);

    // ============== Lifecycle Operations ==============

    function startLoan(
        address lender,
        address borrower,
        LoanLibrary.LoanTerms calldata terms,
        uint256 _amountFromLender,
        uint256 _amountToBorrower,
        LoanLibrary.FeeSnapshot calldata feeSnapshot
    ) external returns (uint256 loanId);

    function repay(
        uint256 loanId,
        address payer,
        uint256 _amountFromPayer,
        uint256 _amountToLender
    ) external;

    function forceRepay(
        uint256 loanId,
        address payer,
        uint256 _amountFromPayer,
        uint256 _amountToLender
    ) external;

    function claim(
        uint256 loanId,
        uint256 _amountFromLender
    ) external;

    function redeemNote(
        uint256 loanId,
        uint256 _amountFromLender,
        address to
    ) external;

    function rollover(
        uint256 oldLoanId,
        address borrower,
        address lender,
        LoanLibrary.LoanTerms calldata terms,
        uint256 _settledAmount,
        uint256 _amountToOldLender,
        uint256 _amountToLender,
        uint256 _amountToBorrower
    ) external returns (uint256 newLoanId);

    // ============== Nonce Management ==============

    function consumeNonce(address user, uint160 nonce) external;

    function cancelNonce(uint160 nonce) external;

    // ============== Fee Management ==============

    function withdraw(address token, uint256 amount, address to) external;

    function withdrawProtocolFees(address token, address to) external;

    // ============== Admin Operations ==============

    function setAffiliateSplits(bytes32[] calldata codes, AffiliateSplit[] calldata splits) external;

    // ============== View Functions ==============

    function getLoan(uint256 loanId) external view returns (LoanLibrary.LoanData calldata loanData);

    function getNoteReceipt(uint256 loanId) external view returns (address token, uint256 amount);

    function isNonceUsed(address user, uint160 nonce) external view returns (bool);

    function borrowerNote() external view returns (IPromissoryNote);

    function lenderNote() external view returns (IPromissoryNote);

}

File 9 of 37 : ICallDelegator.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

interface ICallDelegator {
    // ============== View Functions ==============

    function canCallOn(address caller, address vault) external view returns (bool);
}

File 10 of 37 : IPromissoryNote.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";

import "./INFTWithDescriptor.sol";

interface IPromissoryNote is INFTWithDescriptor, IERC721Enumerable {
    // ============== Token Operations ==============

    function mint(address to, uint256 loanId) external returns (uint256);

    function burn(uint256 tokenId) external;

    // ============== Initializer ==============

    function initialize(address loanCore) external;
}

File 11 of 37 : PromissoryNote.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

import "./interfaces/IPromissoryNote.sol";
import "./interfaces/ILoanCore.sol";
import "./interfaces/INFTDescriptor.sol";
import "./nft/ERC721Permit.sol";

import {
    PN_ZeroAddress,
    PN_MintingRole,
    PN_BurningRole,
    PN_DoesNotExist
} from "./errors/Lending.sol";

/**
 * @title PromissoryNote
 * @author Non-Fungible Technologies, Inc.
 *
 * Built off Openzeppelin's ERC721Enumerable. Used for
 * representing rights and obligations in the context of a loan - the
 * right to claim collateral for lenders (instantiated as LenderNote),
 * and the right to recover collateral upon repayment for borrowers
 * (instantiated as BorrowerNote).
 *
 * @dev {ERC721} token, including:
 *
 *  - ability for holders to burn (destroy) their tokens
 *  - a minter role that allows for token minting (creation)
 *  - token ID and URI autogeneration
 *
 * This contract uses {AccessControlEnumerable} to lock permissioned functions using the
 * different roles - head to its documentation for details.
 *
 * The account that deploys the contract will be granted the minter and pauser
 * roles, as well as the admin role, which will let it grant both minter
 * and pauser roles to other accounts.
 */
contract PromissoryNote is
    Context,
    AccessControlEnumerable,
    ERC721Enumerable,
    ERC721Permit,
    IPromissoryNote
{
    using Counters for Counters.Counter;

    // ============================================ STATE ==============================================

    // =================== Constants =====================

    /// @dev After loanCore initialization, admin role is permanently revoked.
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
    bytes32 public constant MINT_BURN_ROLE = keccak256("MINT/BURN");
    bytes32 public constant RESOURCE_MANAGER_ROLE = keccak256("RESOURCE_MANAGER");

    // ================= State Variables ==================

    /// @dev Contract for returning tokenURI resources.
    INFTDescriptor public descriptor;

    // ========================================= CONSTRUCTOR ===========================================

    /**
     * @dev Creates the promissory note contract, granting minter, burner
     *      and pauser roles to the specified owner address (which in practice
     *      will be LoanCore).
     *
     * @param name                  The name of the token (see ERC721).
     * @param symbol                The symbol of the token (see ERC721).
     * @param _descriptor           The resource descriptor contract.
     */
    constructor(
        string memory name,
        string memory symbol,
        address _descriptor
    ) ERC721(name, symbol) ERC721Permit(name) {
        if (_descriptor == address(0)) revert PN_ZeroAddress("descriptor");

        descriptor = INFTDescriptor(_descriptor);

        _setupRole(ADMIN_ROLE, msg.sender);
        _setupRole(RESOURCE_MANAGER_ROLE, msg.sender);

        // Allow admin to set mint/burn role, which they will do
        // during initialize. After initialize, admin role is
        // permanently revoked, so mint/burn role becomes immutable
        // and initialize cannot be called again.
        // Do not set role admin for admin role.
        _setRoleAdmin(MINT_BURN_ROLE, ADMIN_ROLE);
        _setRoleAdmin(RESOURCE_MANAGER_ROLE, RESOURCE_MANAGER_ROLE);
    }

    /**
     * @notice Grants mint/burn access to the specified address, which should be an
     *         instance of LoanCore. Once role is set, it is immutable,
     *         and cannot be set again.
     *
     * @param loanCore              The address of the admin.
     */
    function initialize(address loanCore) external onlyRole(ADMIN_ROLE) {
        // Grant mint/burn role to loanCore
        _setupRole(MINT_BURN_ROLE, loanCore);

        // Revoke admin role from msg.sender. Since there is no ROLE_ADMIN,
        // nobody can ever get ADMIN_ROLE again.
        renounceRole(ADMIN_ROLE, msg.sender);
    }

    // ======================================= TOKEN OPERATIONS =========================================

    /**
     * @notice Create a new token and assign it to a specified owner. The token ID
     *         should match the loan ID, and can only be called by the minter. Also
     *         updates the mapping to lookup loan IDs by note IDs.
     *
     * @dev See {ERC721-_safeMint}.
     *
     * @param to                    The owner of the minted token.
     * @param loanId                The ID of the token to mint, should match a loan.
     *
     * @return tokenId              The newly minted token ID.
     */
    function mint(address to, uint256 loanId) external override returns (uint256) {
        if (!hasRole(MINT_BURN_ROLE, msg.sender)) revert PN_MintingRole(msg.sender);

        _safeMint(to, loanId);

        return loanId;
    }

    /**
     * @notice Burn a token assigned to a specified owner. The token ID should match a loan ID,
     *         and can only be called by a burner - in practice LoanCore, which burns notes when
     *         a loan ends.
     *
     * @dev See {ERC721-_burn}.
     *
     * @param tokenId               The ID of the token to burn, should match a loan.
     */
    function burn(uint256 tokenId) external override {
        if (!hasRole(MINT_BURN_ROLE, msg.sender)) revert PN_BurningRole(msg.sender);
        _burn(tokenId);
    }

    // ===================================== ERC721 UTILITIES ============================================

    /**
     * @notice Getter of specific URI for an ERC721 token ID.
     *
     * @param tokenId               The ID of the token to get the URI for.
     *
     * @return                      The token ID's URI.
     */
    function tokenURI(uint256 tokenId) public view override(INFTWithDescriptor, ERC721) returns (string memory) {
        if (!_exists(tokenId)) revert PN_DoesNotExist(tokenId);

        return descriptor.tokenURI(address(this), tokenId);
    }

    /**
     * @notice Changes the descriptor contract for reporting tokenURI
     *         resources. Can only be called by a resource manager.
     *
     * @param _descriptor           The new descriptor contract.
     */
    function setDescriptor(address _descriptor) external onlyRole(RESOURCE_MANAGER_ROLE) {
        if (_descriptor == address(0)) revert PN_ZeroAddress("descriptor");

        descriptor = INFTDescriptor(_descriptor);

        emit SetDescriptor(msg.sender, _descriptor);
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId)
        public
        view
        virtual
        override(AccessControlEnumerable, ERC721, ERC721Enumerable, IERC165)
        returns (bool)
    {
        return super.supportsInterface(interfaceId);
    }

    /**
     * @dev Hook that is called before any token transfer.
     *      This notifies the promissory note about the ownership transfer.
     *
     * @param from                  The previous owner of the token.
     * @param to                    The owner of the token after transfer.
     * @param tokenId               The token ID.
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual override(ERC721, ERC721Enumerable) {
        super._beforeTokenTransfer(from, to, tokenId);
    }
}

File 12 of 37 : InterestCalculator.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

/**
 * @title InterestCalculator
 * @author Non-Fungible Technologies, Inc.
 *
 * Interface for calculating the interest amount
 * given an interest rate and principal amount. Assumes
 * that the interestRate is already expressed over the desired
 * time period.
 */
abstract contract InterestCalculator {
    // ============================================ STATE ==============================================

    /// @dev The units of precision equal to the minimum interest of 1 basis point.
    uint256 public constant INTEREST_RATE_DENOMINATOR = 1e18;

    uint256 public constant BASIS_POINTS_DENOMINATOR = 1e4;

    // ======================================== CALCULATIONS ===========================================

    /**
     * @notice Calculate the interest due over a full term.
     *
     * @dev Interest and principal must be entered with 18 units of
     *      precision from the basis point unit (e.g. 1e18 == 0.01%)
     *
     * @param principal                             Principal amount in the loan terms.
     * @param proratedInterestRate                  Interest rate in the loan terms, prorated over loan duration.
     *
     * @return interest                             The amount of interest due.
     */
    function getInterestAmount(uint256 principal, uint256 proratedInterestRate) public pure returns (uint256) {
        return principal * proratedInterestRate / (INTEREST_RATE_DENOMINATOR * BASIS_POINTS_DENOMINATOR);
    }
}

File 13 of 37 : OwnableERC721.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.18;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

import { OERC721_CallerNotOwner } from "../errors/Vault.sol";

/**
 * @title OwnableERC721
 * @author Non-Fungible Technologies, Inc.
 *
 * Uses ERC721 ownership for access control to a set of contracts.
 * Ownership of underlying contract determined by ownership of a token ID,
 * where the token ID converts to an on-chain address.
 */
abstract contract OwnableERC721 {
    event SetOwnershipToken(address indexed caller, address indexed ownershipToken);

    // ============================================ STATE ==============================================

    /// @dev The ERC721 token that contract owners should have ownership of.
    address public ownershipToken;

    // ========================================= VIEW FUNCTIONS =========================================

    /**
     * @notice Specifies the owner of the underlying token ID, derived
     *         from the contract address of the contract implementing.
     *
     * @return ownerAddress         The owner of the underlying token derived from
     *                              the calling address.
     */
    function owner() public view virtual returns (address ownerAddress) {
        return IERC721(ownershipToken).ownerOf(uint256(uint160(address(this))));
    }

    // ============================================ HELPERS =============================================

    /**
     * @dev Set the ownership token - the ERC721 that specified who controls
     *      defined addresses.
     *
     * @param _ownershipToken       The address of the ERC721 token that defines ownership.
     */
    function _setNFT(address _ownershipToken) internal {
        ownershipToken = _ownershipToken;

        emit SetOwnershipToken(msg.sender, _ownershipToken);
    }

    /**
     * @dev Similar to Ownable - checks the method is being called by the owner,
     *      where the owner is defined by the token ID in the ownership token which
     *      maps to the calling contract address.
     */
    modifier onlyOwner() {
        if (owner() != msg.sender) revert OERC721_CallerNotOwner(msg.sender);
        _;
    }
}

File 14 of 37 : Lending.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

import "../libraries/LoanLibrary.sol";

/**
 * @title LendingErrors
 * @author Non-Fungible Technologies, Inc.
 *
 * This file contains custom errors for the core lending protocol contracts, with errors
 * prefixed by the contract that throws them (e.g., "OC_" for OriginationController).
 * Errors located in one place to make it possible to holistically look at all
 * protocol failure cases.
 */

// ==================================== ORIGINATION CONTROLLER ======================================
/// @notice All errors prefixed with OC_, to separate from other contracts in the protocol.

/**
 * @notice Zero address passed in where not allowed.
 *
 * @param addressType                  The name of the parameter for which a zero address was provided.
 */
error OC_ZeroAddress(string addressType);

/**
 * @notice Ensure valid loan state for loan lifceycle operations.
 *
 * @param state                         Current state of a loan according to LoanState enum.
 */
error OC_InvalidState(LoanLibrary.LoanState state);

/**
 * @notice Loan duration must be greater than 1hr and less than 3yrs.
 *
 * @param durationSecs                 Total amount of time in seconds.
 */
error OC_LoanDuration(uint256 durationSecs);

/**
 * @notice Interest must be greater than 0.01% and less than 10,000%. (interestRate / 1e18 >= 1)
 *
 * @param interestRate                  InterestRate with 1e18 multiplier.
 */
error OC_InterestRate(uint256 interestRate);

/**
 * @notice One of the predicates for item verification failed.
 *
 * @param borrower                      The address of the borrower.
 * @param lender                        The address of the lender.
 * @param verifier                      The address of the verifier contract.
 * @param collateralAddress             The address of the collateral token.
 * @param collateralId                  The token ID of the collateral.
 * @param data                          The verification data (to be parsed by verifier).
 */
error OC_PredicateFailed(
    address borrower,
    address lender,
    address verifier,
    address collateralAddress,
    uint256 collateralId,
    bytes data
);

/**
 * @notice The predicates array is empty.
 */
error OC_PredicatesArrayEmpty();

/**
 * @notice A caller attempted to approve themselves.
 *
 * @param caller                        The caller of the approve function.
 */
error OC_SelfApprove(address caller);

/**
 * @notice A caller attempted to originate a loan with their own signature.
 *
 * @param caller                        The caller of the approve function, who was also the signer.
 */
error OC_ApprovedOwnLoan(address caller);

/**
 * @notice The signature could not be recovered to the counterparty or approved party.
 *
 * @param target                        The target party of the signature, which should either be the signer,
 *                                      or someone who has approved the signer.
 * @param signer                        The signer determined from ECDSA.recover.
 */
error OC_InvalidSignature(address target, address signer);

/**
 * @notice The verifier contract specified in a predicate has not been whitelisted.
 *
 * @param verifier                      The verifier the caller attempted to use.
 */
error OC_InvalidVerifier(address verifier);

/**
 * @notice The function caller was neither borrower or lender, and was not approved by either.
 *
 * @param caller                        The unapproved function caller.
 */
error OC_CallerNotParticipant(address caller);

/**
 * @notice Signer is attempting to take the wrong side of the loan.
 *
 * @param signer                       The address of the external signer.
 */
error OC_SideMismatch(address signer);

/**
 * @notice Two related parameters for batch operations did not match in length.
 */
error OC_BatchLengthMismatch();

/**
 * @notice Principal must be greater than 9999 Wei.
 *
 * @param principal                     Principal in ether.
 */
error OC_PrincipalTooLow(uint256 principal);

/**
 * @notice Signature must not be expired.
 *
 * @param deadline                      Deadline in seconds.
 */
error OC_SignatureIsExpired(uint256 deadline);

/**
 * @notice New currency does not match for a loan rollover request.
 *
 * @param oldCurrency                   The currency of the active loan.
 * @param newCurrency                   The currency of the new loan.
 */
error OC_RolloverCurrencyMismatch(address oldCurrency, address newCurrency);

/**
 * @notice New currency does not match for a loan rollover request.
 *
 * @param oldCollateralAddress          The address of the active loan's collateral.
 * @param newCollateralAddress          The token ID of the active loan's collateral.
 * @param oldCollateralId               The address of the new loan's collateral.
 * @param newCollateralId               The token ID of the new loan's collateral.
 */
error OC_RolloverCollateralMismatch(
    address oldCollateralAddress,
    uint256 oldCollateralId,
    address newCollateralAddress,
    uint256 newCollateralId
);

/**
 * @notice Provided payable currency address is not approved for lending.
 *
 * @param payableCurrency       ERC20 token address supplied in loan terms.
 */
error OC_InvalidCurrency(address payableCurrency);

/**
 * @notice Provided collateral address is not approved for lending.
 *
 * @param collateralAddress       ERC721 or ERC1155 token address supplied in loan terms.
 */
error OC_InvalidCollateral(address collateralAddress);

/**
 * @notice Provided token array does not hold any token addresses.
 */
error OC_ZeroArrayElements();

/**
 * @notice Provided token array holds more than 50 token addresses.
 */
error OC_ArrayTooManyElements();

// ==================================== ITEMS VERIFIER ======================================
/// @notice All errors prefixed with IV_, to separate from other contracts in the protocol.

/**
 * @notice The predicate payload was decoded successfully, but list of predicates is empty.
 */
error IV_NoPredicates();

/**
 * @notice Provided SignatureItem is missing an address.
 */
error IV_ItemMissingAddress();

/**
 * @notice Provided SignatureItem has an invalid collateral type.
 * @dev    Should never actually fire, since cType is defined by an enum, so will fail on decode.
 *
 * @param asset                        The NFT contract being checked.
 * @param cType                        The collateralTytpe provided.
 */
error IV_InvalidCollateralType(address asset, uint256 cType);

/**
 * @notice Provided signature item with no required amount. For single ERC721s, specify 1.
 *
 * @param asset                         The NFT contract being checked.
 * @param amount                        The amount provided (should be 0).
 */
error IV_NoAmount(address asset, uint256 amount);

/**
 * @notice Provided a wildcard for a non-ERC721.
 *
 * @param asset                         The NFT contract being checked.
 */
error IV_InvalidWildcard(address asset);

/**
 * @notice The provided token ID is out of bounds for the given collection.
 *
 * @param tokenId                       The token ID provided.
 */
error IV_InvalidTokenId(int256 tokenId);

/**
 * @notice The provided project ID does not exist on the target contract. Only
 *         used for ArtBlocks.
 *
 * @param projectId                     The project ID provided.
 * @param nextProjectId                 The contract's reported nextProjectId.
 */
error IV_InvalidProjectId(uint256 projectId, uint256 nextProjectId);

/**
 * @notice The provided collateralId converts to a vault, but
 *         the vault's address does not convert back to the provided collateralId
 *         when casted to a uint256.
 */
error IV_InvalidCollateralId(uint256 collateralId);

// ==================================== REPAYMENT CONTROLLER ======================================
/// @notice All errors prefixed with RC_, to separate from other contracts in the protocol.

/**
 * @notice Zero address passed in where not allowed.
 *
 * @param addressType                  The name of the parameter for which a zero address was provided.
 */
error RC_ZeroAddress(string addressType);

/**
 * @notice Could not dereference loan from loan ID.
 *
 * @param target                     The loanId being checked.
 */
error RC_CannotDereference(uint256 target);

/**
 * @notice Ensure valid loan state for loan lifceycle operations.
 *
 * @param state                         Current state of a loan according to LoanState enum.
 */
error RC_InvalidState(LoanLibrary.LoanState state);

/**
 * @notice Caller is not the owner of lender note.
 *
 * @param lender                     The owner of the lender note.
 * @param caller                     Msg.sender of the function call.
 */
error RC_OnlyLender(address lender, address caller);

// ==================================== Loan Core ======================================
/// @notice All errors prefixed with LC_, to separate from other contracts in the protocol.

/**
 * @notice Zero address passed in where not allowed.
 *
 * @param addressType                  The name of the parameter for which a zero address was provided.
 */
error LC_ZeroAddress(string addressType);

/// @notice Borrower address is same as lender address.
error LC_ReusedNote();

/// @notice Zero amount passed in where not allowed.
error LC_ZeroAmount();

/**
 * @notice Check collateral is not already used in a active loan.
 *
 * @param collateralAddress             Address of the collateral.
 * @param collateralId                  ID of the collateral token.
 */
error LC_CollateralInUse(address collateralAddress, uint256 collateralId);

/**
 * @notice The reported settlements are invalid, and LoanCore would lose tokens
 *         attempting to perform the requested operations.
 *
 *
 * @param payout                        Amount of tokens to be paid out.
 * @param collected                     Amount of tokens to collect - should be fewer than payout.
 */
error LC_CannotSettle(uint256 payout, uint256 collected);

/**
 * @notice User attempted to withdraw a pending balance that was in excess
 *         of what is available.
 *
 * @param amount                        Amount of tokens to be withdrawn.
 * @param available                     Amount of tokens available to withdraw.
 */
error LC_CannotWithdraw(uint256 amount, uint256 available);

/**
 * @notice Two arrays were provided that must be of matching length, but were not.
 *
 */
error LC_ArrayLengthMismatch();

/**
 * @notice A proposed affiliate split was submitted that is over the maximum.
 *
 * @param splitBps                     The proposed affiliate split.
 * @param maxSplitBps                  The maximum allowed affiliate split.
 *
 */
error LC_OverMaxSplit(uint96 splitBps, uint96 maxSplitBps);

/**
 * @notice Ensure valid loan state for loan lifceycle operations.
 *
 * @param state                         Current state of a loan according to LoanState enum.
 */
error LC_InvalidState(LoanLibrary.LoanState state);

/**
 * @notice Loan duration has not expired.
 *
 * @param dueDate                       Timestamp of the end of the loan duration.
 */
error LC_NotExpired(uint256 dueDate);

/**
 * @notice User address and the specified nonce have already been used.
 *
 * @param user                          Address of collateral owner.
 * @param nonce                         Represents the number of transactions sent by address.
 */
error LC_NonceUsed(address user, uint160 nonce);

/**
 * @notice Protocol attempted to set an affiliate code which already exists. Affiliate
 *         codes are immutable.
 *
 * @param affiliateCode                 The affiliate code being set.
 */
error LC_AffiliateCodeAlreadySet(bytes32 affiliateCode);

/**
 * @notice Specified note token ID does not have a redeemable receipt.
 *
 * @param loanId                     The loanId being checked.
 */
error LC_NoReceipt(uint256 loanId);

/**
 * @notice Only Loan Core contract can call this function.
 */
error LC_CallerNotLoanCore();

/**
 * @notice The loan core contract has been irreversibly shut down.
 */
error LC_Shutdown();

// ==================================== Promissory Note ======================================
/// @notice All errors prefixed with PN_, to separate from other contracts in the protocol.

/**
 * @notice Zero address passed in where not allowed.
 *
 * @param addressType                  The name of the parameter for which a zero address was provided.
 */
error PN_ZeroAddress(string addressType);

/**
 * @notice Caller of mint function must have the MINTER_ROLE in AccessControl.
 *
 * @param caller                        Address of the function caller.
 */
error PN_MintingRole(address caller);

/**
 * @notice Caller of burn function must have the BURNER_ROLE in AccessControl.
 *
 * @param caller                        Address of the function caller.
 */
error PN_BurningRole(address caller);

/**
 * @notice Non-existant token id provided as argument.
 *
 * @param tokenId                       The ID of the token to lookup the URI for.
 */
error PN_DoesNotExist(uint256 tokenId);

// ==================================== Fee Controller ======================================
/// @notice All errors prefixed with FC_, to separate from other contracts in the protocol.

/**
 * @notice Caller attempted to set a lending fee which is larger than the global maximum.
 */
error FC_LendingFeeOverMax(bytes32 selector, uint256 fee, uint256 maxFee);

/**
 * @notice Caller attempted to set a vault mint fee which is larger than the global maximum.
 */
error FC_VaultMintFeeOverMax(uint256 fee, uint256 maxFee);

// ==================================== ERC721 Permit ======================================
/// @notice All errors prefixed with ERC721P_, to separate from other contracts in the protocol.

/**
 * @notice Deadline for the permit has expired.
 *
 * @param deadline                      Permit deadline parameter as a timestamp.
 */
error ERC721P_DeadlineExpired(uint256 deadline);

/**
 * @notice Address of the owner to also be the owner of the tokenId.
 *
 * @param owner                        Owner parameter for the function call.
 */
error ERC721P_NotTokenOwner(address owner);

/**
 * @notice Invalid signature.
 *
 * @param signer                        Signer recovered from ECDSA sugnature hash.
 */
error ERC721P_InvalidSignature(address signer);

File 15 of 37 : IERC20.sol
// SPDX-License-Identifier: MIT

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 16 of 37 : Address.sol
// SPDX-License-Identifier: MIT

pragma solidity ^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;
        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");

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

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

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

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal 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

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 17 of 37 : IERC165.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @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 18 of 37 : IAccessControlEnumerable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IAccessControl.sol";

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerable is IAccessControl {
    /**
     * @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) external view returns (address);

    /**
     * @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) external view returns (uint256);
}

File 19 of 37 : AccessControl.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * 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, msg.sender));
 *     ...
 * }
 * ```
 *
 * 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}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role, _msgSender());
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

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

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(uint160(account), 20),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @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 override 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 override onlyRole(getRoleAdmin(role)) {
        _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 override onlyRole(getRoleAdmin(role)) {
        _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 override {
        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.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

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

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

File 20 of 37 : EnumerableSet.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.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.3.0, sets of type `bytes32` (`Bytes32Set`), `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;

            if (lastIndex != toDeleteIndex) {
                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] = valueIndex; // Replace lastvalue's index to valueIndex
            }

            // 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) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        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(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, 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(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

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

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set 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(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        return _values(set._inner);
    }

    // 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(uint160(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(uint160(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(uint160(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(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly {
            result := store
        }

        return result;
    }

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

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly {
            result := store
        }

        return result;
    }
}

File 21 of 37 : IAccessControl.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_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) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

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

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

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

File 22 of 37 : Context.sol
// SPDX-License-Identifier: MIT

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 23 of 37 : Strings.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}

File 24 of 37 : ERC165.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

File 25 of 37 : LoanLibrary.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

/**
 * @title LoanLibrary
 * @author Non-Fungible Technologies, Inc.
 *
 * Contains all data types used across Arcade lending contracts.
 */
library LoanLibrary {
    /**
     * @dev Enum describing the current state of a loan.
     * State change flow:
     * Created -> Active -> Repaid
     *                   -> Defaulted
     */
    enum LoanState {
        // We need a default that is not 'Created' - this is the zero value
        DUMMY_DO_NOT_USE,
        // The loan has been initialized, funds have been delivered to the borrower and the collateral is held.
        Active,
        // The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state.
        Repaid,
        // The loan was delinquent and collateral claimed by the lender. This is a terminal state.
        Defaulted
    }

    /**
     * @dev The raw terms of a loan.
     */
    struct LoanTerms {
        // Interest expressed as a rate, unlike V1 gross value.
        // Input conversion: 0.01% = (1 * 10**18) ,  10.00% = (1000 * 10**18)
        // This represents the rate over the lifetime of the loan, not APR.
        // 0.01% is the minimum interest rate allowed by the protocol.
        uint256 proratedInterestRate;
        /// @dev Full-slot variables
        // The amount of principal in terms of the payableCurrency.
        uint256 principal;
        // The token ID of the address holding the collateral.
        /// @dev Can be an AssetVault, or the NFT contract for unbundled collateral
        address collateralAddress;
        /// @dev Packed variables
        // The number of seconds representing relative due date of the loan.
        /// @dev Max is 94,608,000, fits in 96 bits
        uint96 durationSecs;
        // The token ID of the collateral.
        uint256 collateralId;
        // The payable currency for the loan principal and interest.
        address payableCurrency;
        // Timestamp for when signature for terms expires
        uint96 deadline;
        // Affiliate code used to start the loan.
        bytes32 affiliateCode;
    }

    /**
     * @dev Modification of loan terms, used for signing only.
     *      Instead of a collateralId, a list of predicates
     *      is defined by 'bytes' in items.
     */
    struct LoanTermsWithItems {
        // Interest expressed as a rate, unlike V1 gross value.
        // Input conversion: 0.01% = (1 * 10**18) ,  10.00% = (1000 * 10**18)
        // This represents the rate over the lifetime of the loan, not APR.
        // 0.01% is the minimum interest rate allowed by the protocol.
        uint256 proratedInterestRate;
        /// @dev Full-slot variables
        // The amount of principal in terms of the payableCurrency.
        uint256 principal;
        // The tokenID of the address holding the collateral
        address collateralAddress;
        /// @dev Packed variables
        // The number of seconds representing relative due date of the loan.
        /// @dev Max is 94,608,000, fits in 96 bits
        uint96 durationSecs;
        // An encoded list of predicates, along with their verifiers.
        bytes items;
        // The payable currency for the loan principal and interest.
        address payableCurrency;
        // Timestamp for when signature for terms expires
        uint96 deadline;
        // Affiliate code used to start the loan.
        bytes32 affiliateCode;
    }

    /**
     * @dev Predicate for item-based verifications
     */
    struct Predicate {
        // The encoded predicate, to decoded and parsed by the verifier contract.
        bytes data;
        // The verifier contract.
        address verifier;
    }

    /**
     * @dev Snapshot of lending fees at the time of loan creation.
     */
    struct FeeSnapshot {
        // The fee taken when lender claims defaulted collateral.
        uint16 lenderDefaultFee;
        // The fee taken from the borrower's interest repayment.
        uint16 lenderInterestFee;
        // The fee taken from the borrower's principal repayment.
        uint16 lenderPrincipalFee;
    }

    /**
     * @dev The data of a loan. This is stored once the loan is Active
     */
    struct LoanData {
        /// @dev Packed variables
        // The current state of the loan.
        LoanState state;
        // Start date of the loan, using block.timestamp.
        uint160 startDate;
        /// @dev Full-slot variables
        // The raw terms of the loan.
        LoanTerms terms;
        // Record of lending fees at the time of loan creation.
        FeeSnapshot feeSnapshot;
    }
}

File 26 of 37 : IERC721Enumerable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

File 27 of 37 : INFTWithDescriptor.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

interface INFTWithDescriptor {
    // ============= Events ==============

    event SetDescriptor(address indexed caller, address indexed descriptor);

    // ================ Resource Metadata ================

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

    function setDescriptor(address descriptor) external;
}

File 28 of 37 : ERC721Enumerable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "./IERC721Enumerable.sol";

/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account.
 */
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
    // Mapping from owner to list of owned token IDs
    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;

    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;

    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;

    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
        return _ownedTokens[owner][index];
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
        return _allTokens[index];
    }

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

        if (from == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
}

File 29 of 37 : INFTDescriptor.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

interface INFTDescriptor {
    function tokenURI(address token, uint256 tokenId) external view returns (string memory);
}

File 30 of 37 : ERC721Permit.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

import "../interfaces/IERC721Permit.sol";

import {
    ERC721P_DeadlineExpired,
    ERC721P_NotTokenOwner,
    ERC721P_InvalidSignature
} from "../errors/Lending.sol";

/**
 * @title ERC721Permit
 * @author Non-Fungible Technologies, Inc.
 *
 * @dev Implementation of the ERC721 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/draft-EIP712.sol
 *
 * Adds the {permit} method, which can be used to change an account's ERC721 allowance (see {IERC721-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC721-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * _Available since v3.4._
 */
abstract contract ERC721Permit is ERC721, IERC721Permit, EIP712 {
    using Counters for Counters.Counter;

    // ============================================ STATE ==============================================

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private immutable _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");

    /// @dev Nonce for permit signatures.
    mapping(address => Counters.Counter) private _nonces;

    // ========================================== CONSTRUCTOR ===========================================

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC721 token name.
     *
     * @param name                  The name of the signing domain.
     */
    constructor(string memory name) EIP712(name, "1") {}

    // ===================================== PERMIT FUNCTIONALITY =======================================

    /**
     * @notice Allows the spender to spend the token ID which is owned by owner,
     * given owner's signed approval.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `owner` must be the owner of `tokenId`.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * @param owner                 The owner of the token being permitted.
     * @param spender               The address allowed to spend the token.
     * @param tokenId               The token ID of the given asset.
     * @param deadline              The maximum timestamp the signature is valid for.
     * @param v                     Component of the signature.
     * @param r                     Component of the signature.
     * @param s                     Component of the signature.
     */
    function permit(
        address owner,
        address spender,
        uint256 tokenId,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        if (block.timestamp > deadline) revert ERC721P_DeadlineExpired(deadline);

        address tokenOwner = ownerOf(tokenId);
        if (owner != tokenOwner && !isApprovedForAll(tokenOwner, owner)) revert ERC721P_NotTokenOwner(owner);

        bytes32 structHash = keccak256(
            abi.encode(_PERMIT_TYPEHASH, owner, spender, tokenId, _useNonce(owner), deadline)
        );

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        if (signer != owner) revert ERC721P_InvalidSignature(signer);

        _approve(spender, tokenId);
    }

    /**
     * @notice Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated.
     *
     * Every successful call to permit increases the owner's nonce by one. This
     * prevents a signature from being used multiple times.
     *
     * @param owner                 The given owner to check the nonce for.
     *
     * @return current              The current nonce for the owner.
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

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

    /**
     * @dev Consumes the nonce - returns the current value and increments.
     *
     * @param owner                 The address of the user to consume a nonce for.
     *
     * @return current              The current nonce, before incrementation.
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }
}

File 31 of 37 : ERC721.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: balance query for the zero address");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: owner query for nonexistent token");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overriden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        require(_exists(tokenId), "ERC721: approved query for nonexistent token");

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        require(operator != _msgSender(), "ERC721: approve to caller");

        _operatorApprovals[_msgSender()][operator] = approved;
        emit ApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
        _safeTransfer(from, to, tokenId, _data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `_data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _owners[tokenId] != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, _data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        _balances[owner] -= 1;
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

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

File 32 of 37 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

File 33 of 37 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

File 34 of 37 : draft-EIP712.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ECDSA.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;

    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        bytes32 hashedName = keccak256(bytes(name));
        bytes32 hashedVersion = keccak256(bytes(version));
        bytes32 typeHash = keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );
        _HASHED_NAME = hashedName;
        _HASHED_VERSION = hashedVersion;
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
        _TYPE_HASH = typeHash;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (block.chainid == _CACHED_CHAIN_ID) {
            return _CACHED_DOMAIN_SEPARATOR;
        } else {
            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
        }
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 nameHash,
        bytes32 versionHash
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }
}

File 35 of 37 : ECDSA.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s;
        uint8 v;
        assembly {
            s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
            v := add(shr(255, vs), 27)
        }
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

File 36 of 37 : IERC721Permit.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

interface IERC721Permit is IERC721 {
    // ================ Permit Functionality ================

    function permit(
        address owner,
        address spender,
        uint256 tokenId,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    // ================ View Functions ================

    function nonces(address owner) external view returns (uint256);

    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 37 of 37 : Vault.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.18;

/**
 * @title VaultErrors
 * @author Non-Fungible Technologies, Inc.
 *
 * This file contains all custom errors for vault contracts used by the protocol.
 * All errors prefixed by the contract that throws them (e.g., "AV_" for Asset Vault).
 * Errors located in one place to make it possible to holistically look at all
 * asset vault failure cases.
 */

// ==================================== Asset Vault ======================================
/// @notice All errors prefixed with AV_, to separate from other contracts in the protocol.

/**
 * @notice Vault withdraws must be enabled.
 */
error AV_WithdrawsDisabled();

/**
 * @notice Vault withdraws enabled.
 */
error AV_WithdrawsEnabled();

/**
 * @notice Asset vault already initialized.
 *
 * @param ownershipToken                    Caller of initialize function in asset vault contract.
 */
error AV_AlreadyInitialized(address ownershipToken);

/**
 * @notice CanCallOn authorization returned false.
 *
 * @param caller                             Msg.sender of the function call.
 */
error AV_MissingAuthorization(address caller);

/**
 * @notice Call disallowed.
 *
 * @param to                                The contract address to call.
 * @param data                              The data to call the contract with.
 */
error AV_NonWhitelistedCall(address to, bytes4 data);

/**
 * @notice Approval disallowed.
 *
 * @param token                             The token to approve.
 * @param spender                           The spender to approve.
 */
error AV_NonWhitelistedApproval(address token, address spender);

/**
 * @notice Cannot withdraw more than 25 items from a vault at a time.
 *
 * @param arrayLength                  Total elements provided.
 */
error AV_TooManyItems(uint256 arrayLength);

/**
 * @notice The length of either the tokenIds or tokenTypes array does not match
 *         the length of the tokenAddress array.
 *
 * @param arrayType                    Array type that does not match tokenAddress array length.
 */
error AV_LengthMismatch(string arrayType);

/**
 * @notice Zero address passed in where not allowed.
 *
 * @param addressType                  The name of the parameter for which a zero address was provided.
 */
error AV_ZeroAddress(string addressType);

/**
 * @notice Delegation disallowed.
 *
 * @param token                             The token to delegate.
 */
error AV_NonWhitelistedDelegation(address token);

// ==================================== Ownable ERC721 ======================================
/// @notice All errors prefixed with OERC721_, to separate from other contracts in the protocol.

/**
 * @notice Function caller is not the owner.
 *
 * @param caller                             Msg.sender of the function call.
 */
error OERC721_CallerNotOwner(address caller);

// ==================================== Vault Factory ======================================
/// @notice All errors prefixed with VF_, to separate from other contracts in the protocol.

/**
 * @notice Zero address passed in where not allowed.
 *
 * @param addressType                  The name of the parameter for which a zero address was provided.
 */
error VF_ZeroAddress(string addressType);

/**
 * @notice Global index out of bounds.
 *
 * @param tokenId                            AW-V2 tokenId of the asset vault.
 */
error VF_TokenIdOutOfBounds(uint256 tokenId);

/**
 * @notice Cannot transfer with withdraw enabled.
 *
 * @param tokenId                            AW-V2 tokenId of the asset vault.
 */
error VF_NoTransferWithdrawEnabled(uint256 tokenId);

/**
 * @notice Not enough msg.value sent for the required mint fee.
 *
 * @param value                              The msg.value.
 * @param requiredMintFee                    The required mint fee.
 */
error VF_InsufficientMintFee(uint256 value, uint256 requiredMintFee);

/**
 * @notice Non-existant token id provided as argument.
 *
 * @param tokenId                       The ID of the token to lookup the URI for.
 */
error VF_DoesNotExist(uint256 tokenId);

// ================================== Call Whitelist ======================================
/// @notice All errors prefixed with CW_, to separate from other contracts in the protocol.

/**
 * @notice Cannot whitelist a call which has already been whitelisted.
 *
 * @param callee                             The contract to be added to CallWhitelist mapping.
 * @param selector                           The function selector to be added to CallWhitelist mapping.
 */
error CW_AlreadyWhitelisted(address callee, bytes4 selector);

/**
 * @notice Cannot remove a call from the CallWhitelist that has not yet been added.
 *
 * @param callee                             The contract to be removed from CallWhitelist mapping.
 * @param selector                           The function selector to be removed from CallWhitelist mapping.
 */
error CW_NotWhitelisted(address callee, bytes4 selector);

// ================================== Call Whitelist Delegation ======================================

/**
 * @notice Zero address passed in the constructor.
 */
error CWD_ZeroAddress();

/**
 * @notice The registry address provided is currently set as the registry.
 */
error CWD_RegistryAlreadySet();

Settings
{
  "metadata": {
    "bytecodeHash": "none"
  },
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract IPromissoryNote","name":"_borrowerNote","type":"address"},{"internalType":"contract IPromissoryNote","name":"_lenderNote","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"bytes32","name":"affiliateCode","type":"bytes32"}],"name":"LC_AffiliateCodeAlreadySet","type":"error"},{"inputs":[],"name":"LC_ArrayLengthMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"payout","type":"uint256"},{"internalType":"uint256","name":"collected","type":"uint256"}],"name":"LC_CannotSettle","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"available","type":"uint256"}],"name":"LC_CannotWithdraw","type":"error"},{"inputs":[{"internalType":"address","name":"collateralAddress","type":"address"},{"internalType":"uint256","name":"collateralId","type":"uint256"}],"name":"LC_CollateralInUse","type":"error"},{"inputs":[{"internalType":"enum LoanLibrary.LoanState","name":"state","type":"uint8"}],"name":"LC_InvalidState","type":"error"},{"inputs":[{"internalType":"uint256","name":"loanId","type":"uint256"}],"name":"LC_NoReceipt","type":"error"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint160","name":"nonce","type":"uint160"}],"name":"LC_NonceUsed","type":"error"},{"inputs":[{"internalType":"uint256","name":"dueDate","type":"uint256"}],"name":"LC_NotExpired","type":"error"},{"inputs":[{"internalType":"uint96","name":"splitBps","type":"uint96"},{"internalType":"uint96","name":"maxSplitBps","type":"uint96"}],"name":"LC_OverMaxSplit","type":"error"},{"inputs":[],"name":"LC_ReusedNote","type":"error"},{"inputs":[{"internalType":"string","name":"addressType","type":"string"}],"name":"LC_ZeroAddress","type":"error"},{"inputs":[],"name":"LC_ZeroAmount","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"code","type":"bytes32"},{"indexed":true,"internalType":"address","name":"affiliate","type":"address"},{"indexed":false,"internalType":"uint96","name":"splitBps","type":"uint96"}],"name":"AffiliateSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeesWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"loanId","type":"uint256"}],"name":"ForceRepay","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"loanId","type":"uint256"}],"name":"LoanClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"loanId","type":"uint256"}],"name":"LoanRepaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldLoanId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newLoanId","type":"uint256"}],"name":"LoanRolledOver","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"loanId","type":"uint256"},{"indexed":false,"internalType":"address","name":"lender","type":"address"},{"indexed":false,"internalType":"address","name":"borrower","type":"address"}],"name":"LoanStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint160","name":"nonce","type":"uint160"}],"name":"NonceUsed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"NoteRedeemed","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":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AFFILIATE_MANAGER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BASIS_POINTS_DENOMINATOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FEE_CLAIMER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GRACE_PERIOD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"INTEREST_RATE_DENOMINATOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ORIGINATOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REPAYER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SHUTDOWN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"affiliateSplits","outputs":[{"internalType":"address","name":"affiliate","type":"address"},{"internalType":"uint96","name":"splitBps","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"borrowerNote","outputs":[{"internalType":"contract IPromissoryNote","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"vault","type":"address"}],"name":"canCallOn","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint160","name":"nonce","type":"uint160"}],"name":"cancelNonce","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"loanId","type":"uint256"},{"internalType":"uint256","name":"_amountFromLender","type":"uint256"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint160","name":"nonce","type":"uint160"}],"name":"consumeNonce","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"feesWithdrawable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"loanId","type":"uint256"},{"internalType":"address","name":"payer","type":"address"},{"internalType":"uint256","name":"_amountFromPayer","type":"uint256"},{"internalType":"uint256","name":"_amountToLender","type":"uint256"}],"name":"forceRepay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"principal","type":"uint256"},{"internalType":"uint256","name":"proratedInterestRate","type":"uint256"}],"name":"getInterestAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"loanId","type":"uint256"}],"name":"getLoan","outputs":[{"components":[{"internalType":"enum LoanLibrary.LoanState","name":"state","type":"uint8"},{"internalType":"uint160","name":"startDate","type":"uint160"},{"components":[{"internalType":"uint256","name":"proratedInterestRate","type":"uint256"},{"internalType":"uint256","name":"principal","type":"uint256"},{"internalType":"address","name":"collateralAddress","type":"address"},{"internalType":"uint96","name":"durationSecs","type":"uint96"},{"internalType":"uint256","name":"collateralId","type":"uint256"},{"internalType":"address","name":"payableCurrency","type":"address"},{"internalType":"uint96","name":"deadline","type":"uint96"},{"internalType":"bytes32","name":"affiliateCode","type":"bytes32"}],"internalType":"struct LoanLibrary.LoanTerms","name":"terms","type":"tuple"},{"components":[{"internalType":"uint16","name":"lenderDefaultFee","type":"uint16"},{"internalType":"uint16","name":"lenderInterestFee","type":"uint16"},{"internalType":"uint16","name":"lenderPrincipalFee","type":"uint16"}],"internalType":"struct LoanLibrary.FeeSnapshot","name":"feeSnapshot","type":"tuple"}],"internalType":"struct LoanLibrary.LoanData","name":"loanData","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"loanId","type":"uint256"}],"name":"getNoteReceipt","outputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint160","name":"nonce","type":"uint160"}],"name":"isNonceUsed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lenderNote","outputs":[{"internalType":"contract IPromissoryNote","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"noteReceipts","outputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"loanId","type":"uint256"},{"internalType":"uint256","name":"_amountFromLender","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"redeemNote","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"loanId","type":"uint256"},{"internalType":"address","name":"payer","type":"address"},{"internalType":"uint256","name":"_amountFromPayer","type":"uint256"},{"internalType":"uint256","name":"_amountToLender","type":"uint256"}],"name":"repay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"oldLoanId","type":"uint256"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"address","name":"lender","type":"address"},{"components":[{"internalType":"uint256","name":"proratedInterestRate","type":"uint256"},{"internalType":"uint256","name":"principal","type":"uint256"},{"internalType":"address","name":"collateralAddress","type":"address"},{"internalType":"uint96","name":"durationSecs","type":"uint96"},{"internalType":"uint256","name":"collateralId","type":"uint256"},{"internalType":"address","name":"payableCurrency","type":"address"},{"internalType":"uint96","name":"deadline","type":"uint96"},{"internalType":"bytes32","name":"affiliateCode","type":"bytes32"}],"internalType":"struct LoanLibrary.LoanTerms","name":"terms","type":"tuple"},{"internalType":"uint256","name":"_settledAmount","type":"uint256"},{"internalType":"uint256","name":"_amountToOldLender","type":"uint256"},{"internalType":"uint256","name":"_amountToLender","type":"uint256"},{"internalType":"uint256","name":"_amountToBorrower","type":"uint256"}],"name":"rollover","outputs":[{"internalType":"uint256","name":"newLoanId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"codes","type":"bytes32[]"},{"components":[{"internalType":"address","name":"affiliate","type":"address"},{"internalType":"uint96","name":"splitBps","type":"uint96"}],"internalType":"struct ILoanCore.AffiliateSplit[]","name":"splits","type":"tuple[]"}],"name":"setAffiliateSplits","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"shutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"lender","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"components":[{"internalType":"uint256","name":"proratedInterestRate","type":"uint256"},{"internalType":"uint256","name":"principal","type":"uint256"},{"internalType":"address","name":"collateralAddress","type":"address"},{"internalType":"uint96","name":"durationSecs","type":"uint96"},{"internalType":"uint256","name":"collateralId","type":"uint256"},{"internalType":"address","name":"payableCurrency","type":"address"},{"internalType":"uint96","name":"deadline","type":"uint96"},{"internalType":"bytes32","name":"affiliateCode","type":"bytes32"}],"internalType":"struct LoanLibrary.LoanTerms","name":"terms","type":"tuple"},{"internalType":"uint256","name":"_amountFromLender","type":"uint256"},{"internalType":"uint256","name":"_amountToBorrower","type":"uint256"},{"components":[{"internalType":"uint16","name":"lenderDefaultFee","type":"uint16"},{"internalType":"uint16","name":"lenderInterestFee","type":"uint16"},{"internalType":"uint16","name":"lenderPrincipalFee","type":"uint16"}],"internalType":"struct LoanLibrary.FeeSnapshot","name":"_feeSnapshot","type":"tuple"}],"name":"startLoan","outputs":[{"internalType":"uint256","name":"loanId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint160","name":"","type":"uint160"}],"name":"usedNonces","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"to","type":"address"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"to","type":"address"}],"name":"withdrawProtocolFees","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60c06040523480156200001157600080fd5b50604051620046693803806200466983398101604081905262000034916200046e565b6002805460ff1916905560016003556001600160a01b0382166200008f57604051636e323a4360e01b815260206004820152600c60248201526b626f72726f7765724e6f746560a01b60448201526064015b60405180910390fd5b6001600160a01b038116620000d557604051636e323a4360e01b815260206004820152600a6024820152696c656e6465724e6f746560b01b604482015260640162000086565b806001600160a01b0316826001600160a01b0316036200010857604051630ddea69760e01b815260040160405180910390fd5b62000123600080516020620046498339815191523362000298565b6200013e6000805160206200464983398151915280620002db565b620001797f0e3bd0540e03bb6bc6bbfab3c1f0a7fa58fced33dc3256731217fd01a20479b860008051602062004649833981519152620002db565b620001b47f945556d23be9a7c839faccfc238fc67e56b8e3c9fddab25f8258c8b368d3413d60008051602062004649833981519152620002db565b620001ef7fdc43895cfc822a45cb77eccebfff1143d490fffb619f1141baf172b83c53ecf960008051602062004649833981519152620002db565b6200022a7fc3f1c35a56b30573b2f110479735bf30cf052375c7d5b4436731da1087a01f6860008051602062004649833981519152620002db565b620002657f2b22d873f791abe31d4310d327f02daef6f297a9bbbce4a994bf2bbeadf02d5760008051602062004649833981519152620002db565b6001600160a01b03828116608052811660a05262000290600462000326602090811b620027ff17901c565b5050620004a6565b620002af82826200032f60201b620028081760201c565b6000828152600160209081526040909120620002d6918390620028166200033f821b17901c565b505050565b600082815260208190526040808220600101805490849055905190918391839186917fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9190a4505050565b80546001019055565b6200033b82826200035f565b5050565b600062000356836001600160a01b038416620003ff565b90505b92915050565b6000828152602081815260408083206001600160a01b038516845290915290205460ff166200033b576000828152602081815260408083206001600160a01b03851684529091529020805460ff19166001179055620003bb3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6000818152600183016020526040812054620004485750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915562000359565b50600062000359565b80516001600160a01b03811681146200046957600080fd5b919050565b600080604083850312156200048257600080fd5b6200048d8362000451565b91506200049d6020840162000451565b90509250929050565b60805160a05161411b6200052e600039600081816106f7015281816107be015281816112cb015281816118d70152818161195b0152818161201d01528181612b7c0152612e830152600081816105e60152818161084d01528181610aa601528181610b3a01528181611af401528181611b7a01528181612bf40152612df1015261411b6000f3fe608060405234801561001057600080fd5b506004361061025e5760003560e01c806391d1485411610146578063ca15c873116100c3578063d547741f11610087578063d547741f14610688578063e26847471461069b578063f92179c3146106b0578063f93554ae146106c3578063fc0e74d1146106ea578063ff7aab80146106f257600080fd5b8063ca15c87314610637578063cc3266e81461064a578063cf7b287f14610659578063cfa498a31461066c578063d3582ac71461067557600080fd5b8063bb340b5d1161010a578063bb340b5d146105ce578063bf848f81146105e1578063c1a287e214610608578063c349026314610611578063c836d3411461062457600080fd5b806391d1485414610558578063a125142b1461056b578063a217fddf14610580578063a2b4ec9c14610588578063a443a635146105bb57600080fd5b806351658c5d116101df57806375b238fc116101a357806375b238fc1461048d578063784d8342146104b457806383586156146104c757806384d2b81c146104da57806385b2f183146104ed5780639010d07c1461052d57600080fd5b806351658c5d146103aa57806357b8bd4c146103d15780635c975abb1461043357806369328dec1461043e578063739d6dd21461045157600080fd5b80632f2ff15d116102265780632f2ff15d1461031257806333ed63021461032557806336568abe146103505780633e75dba014610363578063504006ca1461038a57600080fd5b806301ffc9a7146102635780630668445b1461028b57806313ce1064146102b9578063248a9ca3146102ce5780632e4f5b66146102ff575b600080fd5b61027661027136600461379c565b610719565b60405190151581526020015b60405180910390f35b6102766102993660046137eb565b600760209081526000928352604080842090915290825290205460ff1681565b6102cc6102c7366004613824565b610744565b005b6102f16102dc366004613861565b60009081526020819052604090206001015490565b604051908152602001610282565b61027661030d3660046137eb565b6109a3565b6102cc61032036600461387a565b610c82565b6102f16103333660046137eb565b600960209081526000928352604080842090915290825290205481565b6102cc61035e36600461387a565b610ca9565b6102f17fc3f1c35a56b30573b2f110479735bf30cf052375c7d5b4436731da1087a01f6881565b61039d610398366004613861565b610ccb565b60405161028291906138d7565b6102f17f2b22d873f791abe31d4310d327f02daef6f297a9bbbce4a994bf2bbeadf02d5781565b61040c6103df366004613861565b6008602052600090815260409020546001600160a01b03811690600160a01b90046001600160601b031682565b604080516001600160a01b0390931683526001600160601b03909116602083015201610282565b60025460ff16610276565b6102cc61044c3660046139a4565b610de4565b61027661045f3660046137eb565b6001600160a01b03918216600090815260076020908152604080832093909416825291909152205460ff1690565b6102f17fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec4281565b6102cc6104c23660046139e6565b610f7c565b6102f16104d5366004613ac7565b6111ea565b6102f16104e8366004613b41565b6116d7565b61051f6104fb366004613861565b6000908152600a6020526040902080546001909101546001600160a01b0390911691565b604051610282929190613b63565b61054061053b366004613b41565b611708565b6040516001600160a01b039091168152602001610282565b61027661056636600461387a565b611720565b6102f16000805160206140ef83398151915281565b6102f1600081565b61051f610596366004613861565b600a60205260009081526040902080546001909101546001600160a01b039091169082565b6102cc6105c9366004613b7c565b611749565b6102cc6105dc366004613824565b611a3d565b6105407f000000000000000000000000000000000000000000000000000000000000000081565b6102f161025881565b6102cc61061f366004613b41565b611cdd565b6102cc610632366004613baa565b612160565b6102f1610645366004613861565b61216d565b6102f1670de0b6b3a764000081565b6102cc6106673660046137eb565b612184565b6102f161271081565b6102cc6106833660046137eb565b6122d5565b6102cc61069636600461387a565b61231b565b6102f16000805160206140cf83398151915281565b6102f16106be366004613bc7565b612325565b6102f17fdc43895cfc822a45cb77eccebfff1143d490fffb619f1141baf172b83c53ecf981565b6102cc6127cc565b6105407f000000000000000000000000000000000000000000000000000000000000000081565b60006001600160e01b03198216635a05180f60e01b148061073e575061073e8261282b565b92915050565b6000805160206140cf83398151915261075d8133612860565b6002600354036107885760405162461bcd60e51b815260040161077f90613c43565b60405180910390fd5b6002600355600061079a8685856128c4565b6040516331a9108f60e11b8152600481018890529091506000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636352211e90602401602060405180830381865afa158015610805573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108299190613c7a565b6040516331a9108f60e11b8152600481018990529091506000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636352211e90602401602060405180830381865afa158015610894573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b89190613c7a565b90506108c388612b66565b6108d6836040015160a001518888612c5d565b6108e9836040015160a001518387612c78565b8260400151604001516001600160a01b03166342842e0e30838660400151608001516040518463ffffffff1660e01b815260040161092993929190613c97565b600060405180830381600087803b15801561094357600080fd5b505af1158015610957573d6000803e3d6000fd5b505050507f9a7851747cd7ffb3fe0a32caf3da48b31f27cebe131267051640f8b72fc471868860405161098c91815260200190565b60405180910390a150506001600355505050505050565b60006109b160025460ff1690565b156109ce5760405162461bcd60e51b815260040161077f90613cbb565b60066000836001600160a01b0316637b3d9af76040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a10573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a349190613c7a565b846001600160a01b0316604051602001610a4f929190613b63565b60408051601f198184030181529181528151602092830120835290820192909252016000205460ff16610a845750600061073e565b6040516370a0823160e01b81526001600160a01b0384811660048301526000917f0000000000000000000000000000000000000000000000000000000000000000909116906370a0823190602401602060405180830381865afa158015610aef573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b139190613ce5565b905060005b81811015610c7757604051632f745c5960e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690632f745c5990610b719089908690600401613b63565b602060405180830381865afa158015610b8e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bb29190613ce5565b90506000600560008381526020019081526020016000206001019050856001600160a01b0316637b3d9af76040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c0c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c309190613c7a565b60028201546001600160a01b039081169116148015610c5b5750856001600160a01b03168160030154145b15610c6d57600194505050505061073e565b5050600101610b18565b506000949350505050565b610c8c8282612c92565b6000828152600160205260409020610ca49082612816565b505050565b610cb38282612cb8565b6000828152600160205260409020610ca49082612d32565b610cd3613728565b600082815260056020526040908190208151608081019092528054829060ff166003811115610d0457610d0461389f565b6003811115610d1557610d1561389f565b815281546001600160a01b03610100918290048116602080850191909152604080519384018152600186015484526002860154848301526003860154808416858301526001600160601b03600160a01b91829004811660608088019190915260048901546080880152600589015495861660a08801529190940490931660c0850152600686015460e0850152808501939093528251808301845260079095015461ffff808216875262010000820481169287019290925264010000000090041691840191909152015292915050565b600260035403610e065760405162461bcd60e51b815260040161077f90613c43565b60026003556001600160a01b038316610e4a57604051636e323a4360e01b81526020600482015260056024820152643a37b5b2b760d91b604482015260640161077f565b81600003610e6b576040516303ce9ff960e11b815260040160405180910390fd5b6001600160a01b038116610ea757604051636e323a4360e01b8152602060048201526002602482015261746f60f01b604482015260640161077f565b6001600160a01b0383166000908152600960209081526040808320338452918290529091205480841115610ef85760405163263cee5d60e21b8152600481018590526024810182905260440161077f565b33600090815260208390526040902080548590039055610f19858486612c78565b826001600160a01b0316336001600160a01b0316866001600160a01b03167f0fdfbfe3beb0fbd2f67e9471236264610d92e4b37777806fb082eed9d640055687604051610f6891815260200190565b60405180910390a450506001600355505050565b7fc3f1c35a56b30573b2f110479735bf30cf052375c7d5b4436731da1087a01f68610fa78133612860565b838214610fc757604051634095d28160e11b815260040160405180910390fd5b60005b848110156111e257611388848483818110610fe757610fe7613cfe565b9050604002016020016020810190610fff9190613d34565b6001600160601b031611156110655783838281811061102057611020613cfe565b90506040020160200160208101906110389190613d34565b60405163c3592c9f60e01b81526001600160601b039091166004820152611388602482015260440161077f565b600060088188888581811061107c5761107c613cfe565b60209081029290920135835250810191909152604001600020546001600160a01b0316146110d8578585828181106110b6576110b6613cfe565b9050602002013560405162c39a8960e21b815260040161077f91815260200190565b8383828181106110ea576110ea613cfe565b9050604002016008600088888581811061110657611106613cfe565b90506020020135815260200190815260200160002081816111279190613d51565b90505083838281811061113c5761113c613cfe565b6111529260206040909202019081019150613baa565b6001600160a01b031686868381811061116d5761116d613cfe565b905060200201357f230d297d9a5920f13da7c7a0e9245227a6e0e1587a1ec2bed50c8bcea264dcf58686858181106111a7576111a7613cfe565b90506040020160200160208101906111bf9190613d34565b6040516001600160601b03909116815260200160405180910390a3600101610fca565b505050505050565b60006111f860025460ff1690565b156112155760405162461bcd60e51b815260040161077f90613cbb565b6000805160206140ef83398151915261122e8133612860565b6002600354036112505760405162461bcd60e51b815260040161077f90613c43565b600260035560008a81526005602052604090206001815460ff16600381111561127b5761127b61389f565b1461129f578054604051631b2b1be960e11b815261077f9160ff1690600401613d93565b805460ff191660021781556040516331a9108f60e11b8152600481018c90526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636352211e90602401602060405180830381865afa158015611312573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113369190613c7a565b60058301549091506001600160a01b03168886611353898b613db7565b61135d9190613db7565b111561139c578561136e888a613db7565b6113789190613db7565b604051632e2e96a760e21b81526004810191909152602481018a905260440161077f565b600086888a8c030303905060008060006113ba848f60e00135612d47565b6001600160a01b0388166000908152600960205260409020929550909350915083156114055730600090815260208290526040812080548692906113ff908490613db7565b90915550505b8215611439576001600160a01b03821660009081526020829052604081208054859290611433908490613db7565b90915550505b505050505061144760045490565b9450611457600480546001019055565b6040805160808101825260018152426001600160a01b03166020820152908101611486368d90038d018d613de0565b815260408051606081018252600787015461ffff8082168352620100008204811660208481019190915264010000000090920416828401529283015260008881526005909252902081518154829060ff191660018360038111156114ec576114ec61389f565b021790555060208281015182546001600160a01b0391821661010002610100600160a81b031990911617835560408085015180516001860155808401516002860155808201516060808301516001600160601b03908116600160a01b9081029387169390931760038901556080840151600489015560a084015160c08501519091169092029190941617600586015560e00151600685015593015180516007909301805492820151919094015161ffff9081166401000000000265ffff0000000019928216620100000263ffffffff19909416919094161791909117161790556115d58d612b66565b6115e0858d8d612dda565b6115eb81338b612c5d565b6115f681838a612c78565b611601818c89612c78565b61160c818d88612c78565b6040518d81527f9a7851747cd7ffb3fe0a32caf3da48b31f27cebe131267051640f8b72fc471869060200160405180910390a1604080518681526001600160a01b038d811660208301528e168183015290517f80058ebfadf3969c68465e37d0ca6f1647cd2ef5b7a73f5bd388f25be77ed9819181900360600190a1604080518e8152602081018790527ff9ba18ac9881b970234f34498341fa7e0570e645d2bc4505691214fd9720a26d910160405180910390a15050600160035550909998505050505050505050565b60006116ed612710670de0b6b3a7640000613e9f565b6116f78385613e9f565b6117019190613eb6565b9392505050565b60008281526001602052604081206117019083612f03565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b6000805160206140cf8339815191526117628133612860565b6002600354036117845760405162461bcd60e51b815260040161077f90613c43565b60026003556000848152600a6020908152604091829020825180840190935280546001600160a01b0316808452600190910154918301829052908115806117c9575080155b156117ea57604051630fb4759160e21b81526004810188905260240161077f565b6117f48682613ed8565b6000888152600560205260408120600601549192509081908190611819908a90612d47565b6001600160a01b03881660009081526009602052604090209295509093509150831561186457306000908152602082905260408120805486929061185e908490613db7565b90915550505b8215611898576001600160a01b03821660009081526020829052604081208054859290611892908490613db7565b90915550505b60008b8152600a602052604080822080546001600160a01b0319168155600101829055516331a9108f60e11b8152600481018d90526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636352211e90602401602060405180830381865afa15801561191e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119429190613c7a565b604051630852cd8d60e31b8152600481018e90529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906342966c6890602401600060405180830381600087803b1580156119a757600080fd5b505af11580156119bb573d6000803e3d6000fd5b505050506119ca878b88612c78565b896001600160a01b0316816001600160a01b0316886001600160a01b03167fe93bfec96f868f64ab2fd2d8f4eb54431c951a38d408f6defb3b9def3aabe8268f8a604051611a22929190918252602082015260400190565b60405180910390a45050600160035550505050505050505050565b6000805160206140cf833981519152611a568133612860565b600260035403611a785760405162461bcd60e51b815260040161077f90613c43565b60026003556000611a8a8685856128c4565b6040805180820182528282015160a001516001600160a01b039081168252602080830188815260008c8152600a909252848220935184546001600160a01b0319169084161784555160019093019290925591516331a9108f60e11b8152600481018a9052929350917f000000000000000000000000000000000000000000000000000000000000000090911690636352211e90602401602060405180830381865afa158015611b3d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b619190613c7a565b604051630852cd8d60e31b8152600481018990529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906342966c6890602401600060405180830381600087803b158015611bc657600080fd5b505af1158015611bda573d6000803e3d6000fd5b50505050611bf1826040015160a001518787612c5d565b8160400151604001516001600160a01b03166342842e0e30838560400151608001516040518463ffffffff1660e01b8152600401611c3193929190613c97565b600060405180830381600087803b158015611c4b57600080fd5b505af1158015611c5f573d6000803e3d6000fd5b505050507f9a7851747cd7ffb3fe0a32caf3da48b31f27cebe131267051640f8b72fc4718687604051611c9491815260200190565b60405180910390a16040518781527f44cf48278cc21fd830ae2f0d07963cbfcf77500a2fec40cabfec38525fbe35129060200160405180910390a1505060016003555050505050565b60025460ff1615611d005760405162461bcd60e51b815260040161077f90613cbb565b6000805160206140cf833981519152611d198133612860565b600260035403611d3b5760405162461bcd60e51b815260040161077f90613c43565b600260039081556000848152600560205260408082208151608081019092528054929391929091839160ff1690811115611d7757611d7761389f565b6003811115611d8857611d8861389f565b815281546001600160a01b0361010091829004811660208085019190915260408051938401815260018087015485526002870154858401526003870154808516868401526001600160601b03600160a01b91829004811660608089019190915260048a0154608089015260058a015496871660a08901529190950490941660c0860152600687015460e0860152818601949094528051808401825260079096015461ffff80821688526201000082048116938801939093526401000000009004909116908501529091019190915290915081516003811115611e6c57611e6c61389f565b14611e8d578051604051631b2b1be960e11b815261077f9190600401613d93565b60006102588260400151606001516001600160601b03168360200151611eb39190613eeb565b6001600160a01b0316611ec69190613db7565b9050428110611eeb57604051631eb05a5360e21b81526004810182905260240161077f565b6000858152600560209081526040808320805460ff19166003179055848101518082015160809091015191516006938593611f299392909101613b63565b60408051808303601f19018152918152815160209283012083529082019290925201600020805460ff19169115159190911790558315612004576000806000611f7a87866040015160e00151612d47565b60408089015160a001516001600160a01b0316600090815260096020522092955090935091508315611fcb573060009081526020829052604081208054869290611fc5908490613db7565b90915550505b8215611fff576001600160a01b03821660009081526020829052604081208054859290611ff9908490613db7565b90915550505b505050505b6040516331a9108f60e11b8152600481018690526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa15801561206c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120909190613c7a565b905061209b86612b66565b8260400151604001516001600160a01b03166342842e0e30838660400151608001516040518463ffffffff1660e01b81526004016120db93929190613c97565b600060405180830381600087803b1580156120f557600080fd5b505af1158015612109573d6000803e3d6000fd5b50505050612120836040015160a001518287612c5d565b6040518681527fb15e438728b48d46c9a5505713e60ff50c80559f4523c8f99a246a2069a8684a9060200160405180910390a15050600160035550505050565b61216a3382612f0f565b50565b600081815260016020526040812061073e90612fca565b6002600354036121a65760405162461bcd60e51b815260040161077f90613c43565b60026003557fdc43895cfc822a45cb77eccebfff1143d490fffb619f1141baf172b83c53ecf96121d68133612860565b6001600160a01b03831661221557604051636e323a4360e01b81526020600482015260056024820152643a37b5b2b760d91b604482015260640161077f565b6001600160a01b03821661225157604051636e323a4360e01b8152602060048201526002602482015261746f60f01b604482015260640161077f565b6001600160a01b0383166000908152600960209081526040808320308452918290528220805492905590612286858583612c78565b836001600160a01b0316336001600160a01b0316866001600160a01b03167f0fdfbfe3beb0fbd2f67e9471236264610d92e4b37777806fb082eed9d640055684604051610f6891815260200190565b60025460ff16156122f85760405162461bcd60e51b815260040161077f90613cbb565b6000805160206140ef8339815191526123118133612860565b610ca48383612f0f565b610cb38282612fd4565b600061233360025460ff1690565b156123505760405162461bcd60e51b815260040161077f90613cbb565b6000805160206140ef8339815191526123698133612860565b60026003540361238b5760405162461bcd60e51b815260040161077f90613c43565b600260035560006123a26060880160408901613baa565b87608001356040516020016123b8929190613b63565b60408051601f1981840301815291815281516020928301206000818152600690935291205490915060ff1615612418576123f86060880160408901613baa565b8760800135604051632c9f07db60e11b815260040161077f929190613b63565b8585111561244357604051632e2e96a760e21b8152600481018690526024810187905260440161077f565b6000818152600660205260408120805460ff191660011790558587039080806124708460e08d0135612d47565b9194509250905082156124d15782600960008d60a00160208101906124959190613baa565b6001600160a01b0316815260208082019290925260409081016000908120308252909252812080549091906124cb908490613db7565b90915550505b81156125475781600960008d60a00160208101906124ef9190613baa565b6001600160a01b03166001600160a01b031681526020019081526020016000206000836001600160a01b03166001600160a01b0316815260200190815260200160002060008282546125419190613db7565b90915550505b600454965061255a600480546001019055565b6040805160808101825260018152426001600160a01b03166020820152908101612589368e90038e018e613de0565b815260200161259d368b90038b018b613f1d565b9052600088815260056020526040902081518154829060ff191660018360038111156125cb576125cb61389f565b021790555060208281015182546001600160a01b0391821661010002610100600160a81b031990911617835560408085015180516001860155808401516002860155808201516060808301516001600160601b03908116600160a01b9081029387169390931760038901556080840151600489015560a084015160c08501519091169092029190941617600586015560e00151600685015593015180516007909301805492820151919094015161ffff9081166401000000000265ffff0000000019928216620100000263ffffffff19909416919094161791909117161790556126b6878d8f612dda565b6126c660608c0160408d01613baa565b6001600160a01b03166323b872dd8d308e608001356040518463ffffffff1660e01b81526004016126f993929190613c97565b600060405180830381600087803b15801561271357600080fd5b505af1158015612727573d6000803e3d6000fd5b50612747925061274091505060c08d0160a08e01613baa565b8e8c612c5d565b61276161275a60c08d0160a08e01613baa565b8d8b612c78565b7f80058ebfadf3969c68465e37d0ca6f1647cd2ef5b7a73f5bd388f25be77ed981878e8e6040516127ae939291909283526001600160a01b03918216602084015216604082015260600190565b60405180910390a15050600160035550929998505050505050505050565b7f2b22d873f791abe31d4310d327f02daef6f297a9bbbce4a994bf2bbeadf02d576127f78133612860565b61216a612ffa565b80546001019055565b612812828261306f565b5050565b6000611701836001600160a01b0384166130f3565b60006001600160e01b03198216637965db0b60e01b148061073e57506301ffc9a760e01b6001600160e01b031983161461073e565b61286a8282611720565b61281257612882816001600160a01b03166014613142565b61288d836020613142565b60405160200161289e929190613fbb565b60408051601f198184030181529082905262461bcd60e51b825261077f91600401614030565b6128cc613728565b600084815260056020526040908190208151608081019092528054829060ff1660038111156128fd576128fd61389f565b600381111561290e5761290e61389f565b815281546001600160a01b0361010091829004811660208085019190915260408051938401815260018087015485526002870154858401526003870154808516868401526001600160601b03600160a01b91829004811660608089019190915260048a0154608089015260058a015496871660a08901529190950490941660c0860152600687015460e0860152818601949094528051808401825260079096015461ffff808216885262010000820481169388019390935264010000000090049091169085015290910191909152909150815160038111156129f2576129f261389f565b14612a13578051604051631b2b1be960e11b815261077f9190600401613d93565b82821115612a3e57604051632e2e96a760e21b8152600481018390526024810184905260440161077f565b600082840390506000806000612a5c84866040015160e00151612d47565b60408089015160a001516001600160a01b0316600090815260096020522092955090935091508315612aad573060009081526020829052604081208054869290612aa7908490613db7565b90915550505b8215612ae1576001600160a01b03821660009081526020829052604081208054859290612adb908490613db7565b90915550505b6000898152600560209081526040808320805460ff19166002179055888101518082015160809091015191516006938593612b1f9392909101613b63565b60405160208183030381529060405280519060200120815260200190815260200160002060006101000a81548160ff02191690831515021790555050505050509392505050565b604051630852cd8d60e31b8152600481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906342966c6890602401600060405180830381600087803b158015612bc857600080fd5b505af1158015612bdc573d6000803e3d6000fd5b5050604051630852cd8d60e31b8152600481018490527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031692506342966c689150602401600060405180830381600087803b158015612c4257600080fd5b505af1158015612c56573d6000803e3d6000fd5b5050505050565b8015610ca457610ca46001600160a01b0384168330846132de565b8015610ca457610ca46001600160a01b0384168383613336565b600082815260208190526040902060010154612cae8133612860565b610ca4838361306f565b6001600160a01b0381163314612d285760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b606482015260840161077f565b6128128282613355565b6000611701836001600160a01b0384166133ba565b60008181526008602090815260408083208151808301909252546001600160a01b038116808352600160a01b9091046001600160601b0316928201929092528291829190612d9f578560008093509350935050612dd3565b8051602082015190925061271090612dc0906001600160601b031688613e9f565b612dca9190613eb6565b92508286039350505b9250925092565b6040516340c10f1960e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906340c10f1990612e289085908790600401613b63565b6020604051808303816000875af1158015612e47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e6b9190613ce5565b506040516340c10f1960e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906340c10f1990612eba9084908790600401613b63565b6020604051808303816000875af1158015612ed9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612efd9190613ce5565b50505050565b600061170183836134b4565b6001600160a01b03808316600090815260076020908152604080832093851683529083905290205460ff1615612f6b57604051630bf65ee760e11b81526001600160a01b0380851660048301528316602482015260440161077f565b6001600160a01b0382811660008181526020848152604091829020805460ff191660011790559051918252918516917f94307d29ec5ae0d8d8a9c5e8a03194264f6a9a15ab14d2472869784f32c01ce7910160405180910390a2505050565b600061073e825490565b600082815260208190526040902060010154612ff08133612860565b610ca48383613355565b60025460ff161561301d5760405162461bcd60e51b815260040161077f90613cbb565b6002805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586130523390565b6040516001600160a01b03909116815260200160405180910390a1565b6130798282611720565b612812576000828152602081815260408083206001600160a01b03851684529091529020805460ff191660011790556130af3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600081815260018301602052604081205461313a5750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561073e565b50600061073e565b60606000613151836002613e9f565b61315c906002613db7565b67ffffffffffffffff81111561317457613174613dca565b6040519080825280601f01601f19166020018201604052801561319e576020820181803683370190505b509050600360fc1b816000815181106131b9576131b9613cfe565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106131e8576131e8613cfe565b60200101906001600160f81b031916908160001a905350600061320c846002613e9f565b613217906001613db7565b90505b600181111561328f576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061324b5761324b613cfe565b1a60f81b82828151811061326157613261613cfe565b60200101906001600160f81b031916908160001a90535060049490941c9361328881614063565b905061321a565b5083156117015760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e74604482015260640161077f565b612efd846323b872dd60e01b8585856040516024016132ff93929190613c97565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526134de565b610ca48363a9059cbb60e01b84846040516024016132ff929190613b63565b61335f8282611720565b15612812576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b600081815260018301602052604081205480156134a35760006133de600183613ed8565b85549091506000906133f290600190613ed8565b905081811461345757600086600001828154811061341257613412613cfe565b906000526020600020015490508087600001848154811061343557613435613cfe565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806134685761346861407a565b60019003818190600052602060002001600090559055856001016000868152602001908152602001600020600090556001935050505061073e565b600091505061073e565b5092915050565b60008260000182815481106134cb576134cb613cfe565b9060005260206000200154905092915050565b6000613533826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166135b09092919063ffffffff16565b805190915015610ca457808060200190518101906135519190614090565b610ca45760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161077f565b60606135bf84846000856135c7565b949350505050565b6060824710156136285760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161077f565b843b6136765760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161077f565b600080866001600160a01b0316858760405161369291906140b2565b60006040518083038185875af1925050503d80600081146136cf576040519150601f19603f3d011682016040523d82523d6000602084013e6136d4565b606091505b50915091506136e48282866136ef565b979650505050505050565b606083156136fe575081611701565b82511561370e5782518084602001fd5b8160405162461bcd60e51b815260040161077f9190614030565b604080516080808201835260008083526020808401829052845161010081018652828152808201839052808601839052606080820184905293810183905260a0810183905260c0810183905260e0810183905284860152845180840186528281529081018290529384015281019190915290565b6000602082840312156137ae57600080fd5b81356001600160e01b03198116811461170157600080fd5b6001600160a01b038116811461216a57600080fd5b80356137e6816137c6565b919050565b600080604083850312156137fe57600080fd5b8235613809816137c6565b91506020830135613819816137c6565b809150509250929050565b6000806000806080858703121561383a57600080fd5b84359350602085013561384c816137c6565b93969395505050506040820135916060013590565b60006020828403121561387357600080fd5b5035919050565b6000806040838503121561388d57600080fd5b823591506020830135613819816137c6565b634e487b7160e01b600052602160045260246000fd5b600481106138d357634e487b7160e01b600052602160045260246000fd5b9052565b60006101a0820190506138eb8284516138b5565b602083015160018060a01b0380821660208501526040850151915081516040850152602082015160608501528060408301511660808501526001600160601b0360608301511660a0850152608082015160c08501528060a08301511660e08501525060c08101516139686101008501826001600160601b03169052565b5060e001516101208301526060830151805161ffff908116610140850152602082015181166101608501526040820151166101808401526134ad565b6000806000606084860312156139b957600080fd5b83356139c4816137c6565b92506020840135915060408401356139db816137c6565b809150509250925092565b600080600080604085870312156139fc57600080fd5b843567ffffffffffffffff80821115613a1457600080fd5b818701915087601f830112613a2857600080fd5b813581811115613a3757600080fd5b8860208260051b8501011115613a4c57600080fd5b602092830196509450908601359080821115613a6757600080fd5b818701915087601f830112613a7b57600080fd5b813581811115613a8a57600080fd5b8860208260061b8501011115613a9f57600080fd5b95989497505060200194505050565b60006101008284031215613ac157600080fd5b50919050565b6000806000806000806000806101e0898b031215613ae457600080fd5b883597506020890135613af6816137c6565b96506040890135613b06816137c6565b9550613b158a60608b01613aae565b979a96995094976101608101359661018082013596506101a082013595506101c0909101359350915050565b60008060408385031215613b5457600080fd5b50508035926020909101359150565b6001600160a01b03929092168252602082015260400190565b600080600060608486031215613b9157600080fd5b833592506020840135915060408401356139db816137c6565b600060208284031215613bbc57600080fd5b8135611701816137c6565b6000806000806000808688036101e0811215613be257600080fd5b8735613bed816137c6565b96506020880135613bfd816137c6565b9550613c0c8960408a01613aae565b945061014088013593506101608801359250606061017f1982011215613c3157600080fd5b50610180870190509295509295509295565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b600060208284031215613c8c57600080fd5b8151611701816137c6565b6001600160a01b039384168152919092166020820152604081019190915260600190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b600060208284031215613cf757600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b6001600160601b038116811461216a57600080fd5b80356137e681613d14565b600060208284031215613d4657600080fd5b813561170181613d14565b8135613d5c816137c6565b81546001600160a01b03199081166001600160a01b039290921691821783556020840135613d8981613d14565b60a01b1617905550565b6020810161073e82846138b5565b634e487b7160e01b600052601160045260246000fd5b8082018082111561073e5761073e613da1565b634e487b7160e01b600052604160045260246000fd5b6000610100808385031215613df457600080fd5b6040519081019067ffffffffffffffff82118183101715613e2557634e487b7160e01b600052604160045260246000fd5b81604052833581526020840135602082015260408401359150613e47826137c6565b816040820152613e5960608501613d29565b606082015260808401356080820152613e7460a085016137db565b60a0820152613e8560c08501613d29565b60c082015260e084013560e0820152809250505092915050565b808202811582820484141761073e5761073e613da1565b600082613ed357634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561073e5761073e613da1565b6001600160a01b038181168382160190808211156134ad576134ad613da1565b803561ffff811681146137e657600080fd5b600060608284031215613f2f57600080fd5b6040516060810181811067ffffffffffffffff82111715613f6057634e487b7160e01b600052604160045260246000fd5b604052613f6c83613f0b565b8152613f7a60208401613f0b565b6020820152613f8b60408401613f0b565b60408201529392505050565b60005b83811015613fb2578181015183820152602001613f9a565b50506000910152565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351613ff3816017850160208801613f97565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351614024816028840160208801613f97565b01602801949350505050565b602081526000825180602084015261404f816040850160208701613f97565b601f01601f19169190910160400192915050565b60008161407257614072613da1565b506000190190565b634e487b7160e01b600052603160045260246000fd5b6000602082840312156140a257600080fd5b8151801515811461170157600080fd5b600082516140c4818460208701613f97565b919091019291505056fe945556d23be9a7c839faccfc238fc67e56b8e3c9fddab25f8258c8b368d3413d0e3bd0540e03bb6bc6bbfab3c1f0a7fa58fced33dc3256731217fd01a20479b8a164736f6c6343000812000adf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec42000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be00000000000000000000000092ed78b41537c902ad287608d8535bb6780a7618

Deployed Bytecode

0x608060405234801561001057600080fd5b506004361061025e5760003560e01c806391d1485411610146578063ca15c873116100c3578063d547741f11610087578063d547741f14610688578063e26847471461069b578063f92179c3146106b0578063f93554ae146106c3578063fc0e74d1146106ea578063ff7aab80146106f257600080fd5b8063ca15c87314610637578063cc3266e81461064a578063cf7b287f14610659578063cfa498a31461066c578063d3582ac71461067557600080fd5b8063bb340b5d1161010a578063bb340b5d146105ce578063bf848f81146105e1578063c1a287e214610608578063c349026314610611578063c836d3411461062457600080fd5b806391d1485414610558578063a125142b1461056b578063a217fddf14610580578063a2b4ec9c14610588578063a443a635146105bb57600080fd5b806351658c5d116101df57806375b238fc116101a357806375b238fc1461048d578063784d8342146104b457806383586156146104c757806384d2b81c146104da57806385b2f183146104ed5780639010d07c1461052d57600080fd5b806351658c5d146103aa57806357b8bd4c146103d15780635c975abb1461043357806369328dec1461043e578063739d6dd21461045157600080fd5b80632f2ff15d116102265780632f2ff15d1461031257806333ed63021461032557806336568abe146103505780633e75dba014610363578063504006ca1461038a57600080fd5b806301ffc9a7146102635780630668445b1461028b57806313ce1064146102b9578063248a9ca3146102ce5780632e4f5b66146102ff575b600080fd5b61027661027136600461379c565b610719565b60405190151581526020015b60405180910390f35b6102766102993660046137eb565b600760209081526000928352604080842090915290825290205460ff1681565b6102cc6102c7366004613824565b610744565b005b6102f16102dc366004613861565b60009081526020819052604090206001015490565b604051908152602001610282565b61027661030d3660046137eb565b6109a3565b6102cc61032036600461387a565b610c82565b6102f16103333660046137eb565b600960209081526000928352604080842090915290825290205481565b6102cc61035e36600461387a565b610ca9565b6102f17fc3f1c35a56b30573b2f110479735bf30cf052375c7d5b4436731da1087a01f6881565b61039d610398366004613861565b610ccb565b60405161028291906138d7565b6102f17f2b22d873f791abe31d4310d327f02daef6f297a9bbbce4a994bf2bbeadf02d5781565b61040c6103df366004613861565b6008602052600090815260409020546001600160a01b03811690600160a01b90046001600160601b031682565b604080516001600160a01b0390931683526001600160601b03909116602083015201610282565b60025460ff16610276565b6102cc61044c3660046139a4565b610de4565b61027661045f3660046137eb565b6001600160a01b03918216600090815260076020908152604080832093909416825291909152205460ff1690565b6102f17fdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec4281565b6102cc6104c23660046139e6565b610f7c565b6102f16104d5366004613ac7565b6111ea565b6102f16104e8366004613b41565b6116d7565b61051f6104fb366004613861565b6000908152600a6020526040902080546001909101546001600160a01b0390911691565b604051610282929190613b63565b61054061053b366004613b41565b611708565b6040516001600160a01b039091168152602001610282565b61027661056636600461387a565b611720565b6102f16000805160206140ef83398151915281565b6102f1600081565b61051f610596366004613861565b600a60205260009081526040902080546001909101546001600160a01b039091169082565b6102cc6105c9366004613b7c565b611749565b6102cc6105dc366004613824565b611a3d565b6105407f000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be81565b6102f161025881565b6102cc61061f366004613b41565b611cdd565b6102cc610632366004613baa565b612160565b6102f1610645366004613861565b61216d565b6102f1670de0b6b3a764000081565b6102cc6106673660046137eb565b612184565b6102f161271081565b6102cc6106833660046137eb565b6122d5565b6102cc61069636600461387a565b61231b565b6102f16000805160206140cf83398151915281565b6102f16106be366004613bc7565b612325565b6102f17fdc43895cfc822a45cb77eccebfff1143d490fffb619f1141baf172b83c53ecf981565b6102cc6127cc565b6105407f00000000000000000000000092ed78b41537c902ad287608d8535bb6780a761881565b60006001600160e01b03198216635a05180f60e01b148061073e575061073e8261282b565b92915050565b6000805160206140cf83398151915261075d8133612860565b6002600354036107885760405162461bcd60e51b815260040161077f90613c43565b60405180910390fd5b6002600355600061079a8685856128c4565b6040516331a9108f60e11b8152600481018890529091506000906001600160a01b037f00000000000000000000000092ed78b41537c902ad287608d8535bb6780a76181690636352211e90602401602060405180830381865afa158015610805573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108299190613c7a565b6040516331a9108f60e11b8152600481018990529091506000906001600160a01b037f000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be1690636352211e90602401602060405180830381865afa158015610894573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b89190613c7a565b90506108c388612b66565b6108d6836040015160a001518888612c5d565b6108e9836040015160a001518387612c78565b8260400151604001516001600160a01b03166342842e0e30838660400151608001516040518463ffffffff1660e01b815260040161092993929190613c97565b600060405180830381600087803b15801561094357600080fd5b505af1158015610957573d6000803e3d6000fd5b505050507f9a7851747cd7ffb3fe0a32caf3da48b31f27cebe131267051640f8b72fc471868860405161098c91815260200190565b60405180910390a150506001600355505050505050565b60006109b160025460ff1690565b156109ce5760405162461bcd60e51b815260040161077f90613cbb565b60066000836001600160a01b0316637b3d9af76040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a10573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a349190613c7a565b846001600160a01b0316604051602001610a4f929190613b63565b60408051601f198184030181529181528151602092830120835290820192909252016000205460ff16610a845750600061073e565b6040516370a0823160e01b81526001600160a01b0384811660048301526000917f000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be909116906370a0823190602401602060405180830381865afa158015610aef573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b139190613ce5565b905060005b81811015610c7757604051632f745c5960e01b81526000906001600160a01b037f000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be1690632f745c5990610b719089908690600401613b63565b602060405180830381865afa158015610b8e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bb29190613ce5565b90506000600560008381526020019081526020016000206001019050856001600160a01b0316637b3d9af76040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c0c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c309190613c7a565b60028201546001600160a01b039081169116148015610c5b5750856001600160a01b03168160030154145b15610c6d57600194505050505061073e565b5050600101610b18565b506000949350505050565b610c8c8282612c92565b6000828152600160205260409020610ca49082612816565b505050565b610cb38282612cb8565b6000828152600160205260409020610ca49082612d32565b610cd3613728565b600082815260056020526040908190208151608081019092528054829060ff166003811115610d0457610d0461389f565b6003811115610d1557610d1561389f565b815281546001600160a01b03610100918290048116602080850191909152604080519384018152600186015484526002860154848301526003860154808416858301526001600160601b03600160a01b91829004811660608088019190915260048901546080880152600589015495861660a08801529190940490931660c0850152600686015460e0850152808501939093528251808301845260079095015461ffff808216875262010000820481169287019290925264010000000090041691840191909152015292915050565b600260035403610e065760405162461bcd60e51b815260040161077f90613c43565b60026003556001600160a01b038316610e4a57604051636e323a4360e01b81526020600482015260056024820152643a37b5b2b760d91b604482015260640161077f565b81600003610e6b576040516303ce9ff960e11b815260040160405180910390fd5b6001600160a01b038116610ea757604051636e323a4360e01b8152602060048201526002602482015261746f60f01b604482015260640161077f565b6001600160a01b0383166000908152600960209081526040808320338452918290529091205480841115610ef85760405163263cee5d60e21b8152600481018590526024810182905260440161077f565b33600090815260208390526040902080548590039055610f19858486612c78565b826001600160a01b0316336001600160a01b0316866001600160a01b03167f0fdfbfe3beb0fbd2f67e9471236264610d92e4b37777806fb082eed9d640055687604051610f6891815260200190565b60405180910390a450506001600355505050565b7fc3f1c35a56b30573b2f110479735bf30cf052375c7d5b4436731da1087a01f68610fa78133612860565b838214610fc757604051634095d28160e11b815260040160405180910390fd5b60005b848110156111e257611388848483818110610fe757610fe7613cfe565b9050604002016020016020810190610fff9190613d34565b6001600160601b031611156110655783838281811061102057611020613cfe565b90506040020160200160208101906110389190613d34565b60405163c3592c9f60e01b81526001600160601b039091166004820152611388602482015260440161077f565b600060088188888581811061107c5761107c613cfe565b60209081029290920135835250810191909152604001600020546001600160a01b0316146110d8578585828181106110b6576110b6613cfe565b9050602002013560405162c39a8960e21b815260040161077f91815260200190565b8383828181106110ea576110ea613cfe565b9050604002016008600088888581811061110657611106613cfe565b90506020020135815260200190815260200160002081816111279190613d51565b90505083838281811061113c5761113c613cfe565b6111529260206040909202019081019150613baa565b6001600160a01b031686868381811061116d5761116d613cfe565b905060200201357f230d297d9a5920f13da7c7a0e9245227a6e0e1587a1ec2bed50c8bcea264dcf58686858181106111a7576111a7613cfe565b90506040020160200160208101906111bf9190613d34565b6040516001600160601b03909116815260200160405180910390a3600101610fca565b505050505050565b60006111f860025460ff1690565b156112155760405162461bcd60e51b815260040161077f90613cbb565b6000805160206140ef83398151915261122e8133612860565b6002600354036112505760405162461bcd60e51b815260040161077f90613c43565b600260035560008a81526005602052604090206001815460ff16600381111561127b5761127b61389f565b1461129f578054604051631b2b1be960e11b815261077f9160ff1690600401613d93565b805460ff191660021781556040516331a9108f60e11b8152600481018c90526000906001600160a01b037f00000000000000000000000092ed78b41537c902ad287608d8535bb6780a76181690636352211e90602401602060405180830381865afa158015611312573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113369190613c7a565b60058301549091506001600160a01b03168886611353898b613db7565b61135d9190613db7565b111561139c578561136e888a613db7565b6113789190613db7565b604051632e2e96a760e21b81526004810191909152602481018a905260440161077f565b600086888a8c030303905060008060006113ba848f60e00135612d47565b6001600160a01b0388166000908152600960205260409020929550909350915083156114055730600090815260208290526040812080548692906113ff908490613db7565b90915550505b8215611439576001600160a01b03821660009081526020829052604081208054859290611433908490613db7565b90915550505b505050505061144760045490565b9450611457600480546001019055565b6040805160808101825260018152426001600160a01b03166020820152908101611486368d90038d018d613de0565b815260408051606081018252600787015461ffff8082168352620100008204811660208481019190915264010000000090920416828401529283015260008881526005909252902081518154829060ff191660018360038111156114ec576114ec61389f565b021790555060208281015182546001600160a01b0391821661010002610100600160a81b031990911617835560408085015180516001860155808401516002860155808201516060808301516001600160601b03908116600160a01b9081029387169390931760038901556080840151600489015560a084015160c08501519091169092029190941617600586015560e00151600685015593015180516007909301805492820151919094015161ffff9081166401000000000265ffff0000000019928216620100000263ffffffff19909416919094161791909117161790556115d58d612b66565b6115e0858d8d612dda565b6115eb81338b612c5d565b6115f681838a612c78565b611601818c89612c78565b61160c818d88612c78565b6040518d81527f9a7851747cd7ffb3fe0a32caf3da48b31f27cebe131267051640f8b72fc471869060200160405180910390a1604080518681526001600160a01b038d811660208301528e168183015290517f80058ebfadf3969c68465e37d0ca6f1647cd2ef5b7a73f5bd388f25be77ed9819181900360600190a1604080518e8152602081018790527ff9ba18ac9881b970234f34498341fa7e0570e645d2bc4505691214fd9720a26d910160405180910390a15050600160035550909998505050505050505050565b60006116ed612710670de0b6b3a7640000613e9f565b6116f78385613e9f565b6117019190613eb6565b9392505050565b60008281526001602052604081206117019083612f03565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b6000805160206140cf8339815191526117628133612860565b6002600354036117845760405162461bcd60e51b815260040161077f90613c43565b60026003556000848152600a6020908152604091829020825180840190935280546001600160a01b0316808452600190910154918301829052908115806117c9575080155b156117ea57604051630fb4759160e21b81526004810188905260240161077f565b6117f48682613ed8565b6000888152600560205260408120600601549192509081908190611819908a90612d47565b6001600160a01b03881660009081526009602052604090209295509093509150831561186457306000908152602082905260408120805486929061185e908490613db7565b90915550505b8215611898576001600160a01b03821660009081526020829052604081208054859290611892908490613db7565b90915550505b60008b8152600a602052604080822080546001600160a01b0319168155600101829055516331a9108f60e11b8152600481018d90526001600160a01b037f00000000000000000000000092ed78b41537c902ad287608d8535bb6780a76181690636352211e90602401602060405180830381865afa15801561191e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119429190613c7a565b604051630852cd8d60e31b8152600481018e90529091507f00000000000000000000000092ed78b41537c902ad287608d8535bb6780a76186001600160a01b0316906342966c6890602401600060405180830381600087803b1580156119a757600080fd5b505af11580156119bb573d6000803e3d6000fd5b505050506119ca878b88612c78565b896001600160a01b0316816001600160a01b0316886001600160a01b03167fe93bfec96f868f64ab2fd2d8f4eb54431c951a38d408f6defb3b9def3aabe8268f8a604051611a22929190918252602082015260400190565b60405180910390a45050600160035550505050505050505050565b6000805160206140cf833981519152611a568133612860565b600260035403611a785760405162461bcd60e51b815260040161077f90613c43565b60026003556000611a8a8685856128c4565b6040805180820182528282015160a001516001600160a01b039081168252602080830188815260008c8152600a909252848220935184546001600160a01b0319169084161784555160019093019290925591516331a9108f60e11b8152600481018a9052929350917f000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be90911690636352211e90602401602060405180830381865afa158015611b3d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b619190613c7a565b604051630852cd8d60e31b8152600481018990529091507f000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be6001600160a01b0316906342966c6890602401600060405180830381600087803b158015611bc657600080fd5b505af1158015611bda573d6000803e3d6000fd5b50505050611bf1826040015160a001518787612c5d565b8160400151604001516001600160a01b03166342842e0e30838560400151608001516040518463ffffffff1660e01b8152600401611c3193929190613c97565b600060405180830381600087803b158015611c4b57600080fd5b505af1158015611c5f573d6000803e3d6000fd5b505050507f9a7851747cd7ffb3fe0a32caf3da48b31f27cebe131267051640f8b72fc4718687604051611c9491815260200190565b60405180910390a16040518781527f44cf48278cc21fd830ae2f0d07963cbfcf77500a2fec40cabfec38525fbe35129060200160405180910390a1505060016003555050505050565b60025460ff1615611d005760405162461bcd60e51b815260040161077f90613cbb565b6000805160206140cf833981519152611d198133612860565b600260035403611d3b5760405162461bcd60e51b815260040161077f90613c43565b600260039081556000848152600560205260408082208151608081019092528054929391929091839160ff1690811115611d7757611d7761389f565b6003811115611d8857611d8861389f565b815281546001600160a01b0361010091829004811660208085019190915260408051938401815260018087015485526002870154858401526003870154808516868401526001600160601b03600160a01b91829004811660608089019190915260048a0154608089015260058a015496871660a08901529190950490941660c0860152600687015460e0860152818601949094528051808401825260079096015461ffff80821688526201000082048116938801939093526401000000009004909116908501529091019190915290915081516003811115611e6c57611e6c61389f565b14611e8d578051604051631b2b1be960e11b815261077f9190600401613d93565b60006102588260400151606001516001600160601b03168360200151611eb39190613eeb565b6001600160a01b0316611ec69190613db7565b9050428110611eeb57604051631eb05a5360e21b81526004810182905260240161077f565b6000858152600560209081526040808320805460ff19166003179055848101518082015160809091015191516006938593611f299392909101613b63565b60408051808303601f19018152918152815160209283012083529082019290925201600020805460ff19169115159190911790558315612004576000806000611f7a87866040015160e00151612d47565b60408089015160a001516001600160a01b0316600090815260096020522092955090935091508315611fcb573060009081526020829052604081208054869290611fc5908490613db7565b90915550505b8215611fff576001600160a01b03821660009081526020829052604081208054859290611ff9908490613db7565b90915550505b505050505b6040516331a9108f60e11b8152600481018690526000907f00000000000000000000000092ed78b41537c902ad287608d8535bb6780a76186001600160a01b031690636352211e90602401602060405180830381865afa15801561206c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120909190613c7a565b905061209b86612b66565b8260400151604001516001600160a01b03166342842e0e30838660400151608001516040518463ffffffff1660e01b81526004016120db93929190613c97565b600060405180830381600087803b1580156120f557600080fd5b505af1158015612109573d6000803e3d6000fd5b50505050612120836040015160a001518287612c5d565b6040518681527fb15e438728b48d46c9a5505713e60ff50c80559f4523c8f99a246a2069a8684a9060200160405180910390a15050600160035550505050565b61216a3382612f0f565b50565b600081815260016020526040812061073e90612fca565b6002600354036121a65760405162461bcd60e51b815260040161077f90613c43565b60026003557fdc43895cfc822a45cb77eccebfff1143d490fffb619f1141baf172b83c53ecf96121d68133612860565b6001600160a01b03831661221557604051636e323a4360e01b81526020600482015260056024820152643a37b5b2b760d91b604482015260640161077f565b6001600160a01b03821661225157604051636e323a4360e01b8152602060048201526002602482015261746f60f01b604482015260640161077f565b6001600160a01b0383166000908152600960209081526040808320308452918290528220805492905590612286858583612c78565b836001600160a01b0316336001600160a01b0316866001600160a01b03167f0fdfbfe3beb0fbd2f67e9471236264610d92e4b37777806fb082eed9d640055684604051610f6891815260200190565b60025460ff16156122f85760405162461bcd60e51b815260040161077f90613cbb565b6000805160206140ef8339815191526123118133612860565b610ca48383612f0f565b610cb38282612fd4565b600061233360025460ff1690565b156123505760405162461bcd60e51b815260040161077f90613cbb565b6000805160206140ef8339815191526123698133612860565b60026003540361238b5760405162461bcd60e51b815260040161077f90613c43565b600260035560006123a26060880160408901613baa565b87608001356040516020016123b8929190613b63565b60408051601f1981840301815291815281516020928301206000818152600690935291205490915060ff1615612418576123f86060880160408901613baa565b8760800135604051632c9f07db60e11b815260040161077f929190613b63565b8585111561244357604051632e2e96a760e21b8152600481018690526024810187905260440161077f565b6000818152600660205260408120805460ff191660011790558587039080806124708460e08d0135612d47565b9194509250905082156124d15782600960008d60a00160208101906124959190613baa565b6001600160a01b0316815260208082019290925260409081016000908120308252909252812080549091906124cb908490613db7565b90915550505b81156125475781600960008d60a00160208101906124ef9190613baa565b6001600160a01b03166001600160a01b031681526020019081526020016000206000836001600160a01b03166001600160a01b0316815260200190815260200160002060008282546125419190613db7565b90915550505b600454965061255a600480546001019055565b6040805160808101825260018152426001600160a01b03166020820152908101612589368e90038e018e613de0565b815260200161259d368b90038b018b613f1d565b9052600088815260056020526040902081518154829060ff191660018360038111156125cb576125cb61389f565b021790555060208281015182546001600160a01b0391821661010002610100600160a81b031990911617835560408085015180516001860155808401516002860155808201516060808301516001600160601b03908116600160a01b9081029387169390931760038901556080840151600489015560a084015160c08501519091169092029190941617600586015560e00151600685015593015180516007909301805492820151919094015161ffff9081166401000000000265ffff0000000019928216620100000263ffffffff19909416919094161791909117161790556126b6878d8f612dda565b6126c660608c0160408d01613baa565b6001600160a01b03166323b872dd8d308e608001356040518463ffffffff1660e01b81526004016126f993929190613c97565b600060405180830381600087803b15801561271357600080fd5b505af1158015612727573d6000803e3d6000fd5b50612747925061274091505060c08d0160a08e01613baa565b8e8c612c5d565b61276161275a60c08d0160a08e01613baa565b8d8b612c78565b7f80058ebfadf3969c68465e37d0ca6f1647cd2ef5b7a73f5bd388f25be77ed981878e8e6040516127ae939291909283526001600160a01b03918216602084015216604082015260600190565b60405180910390a15050600160035550929998505050505050505050565b7f2b22d873f791abe31d4310d327f02daef6f297a9bbbce4a994bf2bbeadf02d576127f78133612860565b61216a612ffa565b80546001019055565b612812828261306f565b5050565b6000611701836001600160a01b0384166130f3565b60006001600160e01b03198216637965db0b60e01b148061073e57506301ffc9a760e01b6001600160e01b031983161461073e565b61286a8282611720565b61281257612882816001600160a01b03166014613142565b61288d836020613142565b60405160200161289e929190613fbb565b60408051601f198184030181529082905262461bcd60e51b825261077f91600401614030565b6128cc613728565b600084815260056020526040908190208151608081019092528054829060ff1660038111156128fd576128fd61389f565b600381111561290e5761290e61389f565b815281546001600160a01b0361010091829004811660208085019190915260408051938401815260018087015485526002870154858401526003870154808516868401526001600160601b03600160a01b91829004811660608089019190915260048a0154608089015260058a015496871660a08901529190950490941660c0860152600687015460e0860152818601949094528051808401825260079096015461ffff808216885262010000820481169388019390935264010000000090049091169085015290910191909152909150815160038111156129f2576129f261389f565b14612a13578051604051631b2b1be960e11b815261077f9190600401613d93565b82821115612a3e57604051632e2e96a760e21b8152600481018390526024810184905260440161077f565b600082840390506000806000612a5c84866040015160e00151612d47565b60408089015160a001516001600160a01b0316600090815260096020522092955090935091508315612aad573060009081526020829052604081208054869290612aa7908490613db7565b90915550505b8215612ae1576001600160a01b03821660009081526020829052604081208054859290612adb908490613db7565b90915550505b6000898152600560209081526040808320805460ff19166002179055888101518082015160809091015191516006938593612b1f9392909101613b63565b60405160208183030381529060405280519060200120815260200190815260200160002060006101000a81548160ff02191690831515021790555050505050509392505050565b604051630852cd8d60e31b8152600481018290527f00000000000000000000000092ed78b41537c902ad287608d8535bb6780a76186001600160a01b0316906342966c6890602401600060405180830381600087803b158015612bc857600080fd5b505af1158015612bdc573d6000803e3d6000fd5b5050604051630852cd8d60e31b8152600481018490527f000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be6001600160a01b031692506342966c689150602401600060405180830381600087803b158015612c4257600080fd5b505af1158015612c56573d6000803e3d6000fd5b5050505050565b8015610ca457610ca46001600160a01b0384168330846132de565b8015610ca457610ca46001600160a01b0384168383613336565b600082815260208190526040902060010154612cae8133612860565b610ca4838361306f565b6001600160a01b0381163314612d285760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b606482015260840161077f565b6128128282613355565b6000611701836001600160a01b0384166133ba565b60008181526008602090815260408083208151808301909252546001600160a01b038116808352600160a01b9091046001600160601b0316928201929092528291829190612d9f578560008093509350935050612dd3565b8051602082015190925061271090612dc0906001600160601b031688613e9f565b612dca9190613eb6565b92508286039350505b9250925092565b6040516340c10f1960e01b81526001600160a01b037f000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be16906340c10f1990612e289085908790600401613b63565b6020604051808303816000875af1158015612e47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e6b9190613ce5565b506040516340c10f1960e01b81526001600160a01b037f00000000000000000000000092ed78b41537c902ad287608d8535bb6780a761816906340c10f1990612eba9084908790600401613b63565b6020604051808303816000875af1158015612ed9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612efd9190613ce5565b50505050565b600061170183836134b4565b6001600160a01b03808316600090815260076020908152604080832093851683529083905290205460ff1615612f6b57604051630bf65ee760e11b81526001600160a01b0380851660048301528316602482015260440161077f565b6001600160a01b0382811660008181526020848152604091829020805460ff191660011790559051918252918516917f94307d29ec5ae0d8d8a9c5e8a03194264f6a9a15ab14d2472869784f32c01ce7910160405180910390a2505050565b600061073e825490565b600082815260208190526040902060010154612ff08133612860565b610ca48383613355565b60025460ff161561301d5760405162461bcd60e51b815260040161077f90613cbb565b6002805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586130523390565b6040516001600160a01b03909116815260200160405180910390a1565b6130798282611720565b612812576000828152602081815260408083206001600160a01b03851684529091529020805460ff191660011790556130af3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600081815260018301602052604081205461313a5750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561073e565b50600061073e565b60606000613151836002613e9f565b61315c906002613db7565b67ffffffffffffffff81111561317457613174613dca565b6040519080825280601f01601f19166020018201604052801561319e576020820181803683370190505b509050600360fc1b816000815181106131b9576131b9613cfe565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106131e8576131e8613cfe565b60200101906001600160f81b031916908160001a905350600061320c846002613e9f565b613217906001613db7565b90505b600181111561328f576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061324b5761324b613cfe565b1a60f81b82828151811061326157613261613cfe565b60200101906001600160f81b031916908160001a90535060049490941c9361328881614063565b905061321a565b5083156117015760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e74604482015260640161077f565b612efd846323b872dd60e01b8585856040516024016132ff93929190613c97565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526134de565b610ca48363a9059cbb60e01b84846040516024016132ff929190613b63565b61335f8282611720565b15612812576000828152602081815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b600081815260018301602052604081205480156134a35760006133de600183613ed8565b85549091506000906133f290600190613ed8565b905081811461345757600086600001828154811061341257613412613cfe565b906000526020600020015490508087600001848154811061343557613435613cfe565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806134685761346861407a565b60019003818190600052602060002001600090559055856001016000868152602001908152602001600020600090556001935050505061073e565b600091505061073e565b5092915050565b60008260000182815481106134cb576134cb613cfe565b9060005260206000200154905092915050565b6000613533826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166135b09092919063ffffffff16565b805190915015610ca457808060200190518101906135519190614090565b610ca45760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161077f565b60606135bf84846000856135c7565b949350505050565b6060824710156136285760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161077f565b843b6136765760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161077f565b600080866001600160a01b0316858760405161369291906140b2565b60006040518083038185875af1925050503d80600081146136cf576040519150601f19603f3d011682016040523d82523d6000602084013e6136d4565b606091505b50915091506136e48282866136ef565b979650505050505050565b606083156136fe575081611701565b82511561370e5782518084602001fd5b8160405162461bcd60e51b815260040161077f9190614030565b604080516080808201835260008083526020808401829052845161010081018652828152808201839052808601839052606080820184905293810183905260a0810183905260c0810183905260e0810183905284860152845180840186528281529081018290529384015281019190915290565b6000602082840312156137ae57600080fd5b81356001600160e01b03198116811461170157600080fd5b6001600160a01b038116811461216a57600080fd5b80356137e6816137c6565b919050565b600080604083850312156137fe57600080fd5b8235613809816137c6565b91506020830135613819816137c6565b809150509250929050565b6000806000806080858703121561383a57600080fd5b84359350602085013561384c816137c6565b93969395505050506040820135916060013590565b60006020828403121561387357600080fd5b5035919050565b6000806040838503121561388d57600080fd5b823591506020830135613819816137c6565b634e487b7160e01b600052602160045260246000fd5b600481106138d357634e487b7160e01b600052602160045260246000fd5b9052565b60006101a0820190506138eb8284516138b5565b602083015160018060a01b0380821660208501526040850151915081516040850152602082015160608501528060408301511660808501526001600160601b0360608301511660a0850152608082015160c08501528060a08301511660e08501525060c08101516139686101008501826001600160601b03169052565b5060e001516101208301526060830151805161ffff908116610140850152602082015181166101608501526040820151166101808401526134ad565b6000806000606084860312156139b957600080fd5b83356139c4816137c6565b92506020840135915060408401356139db816137c6565b809150509250925092565b600080600080604085870312156139fc57600080fd5b843567ffffffffffffffff80821115613a1457600080fd5b818701915087601f830112613a2857600080fd5b813581811115613a3757600080fd5b8860208260051b8501011115613a4c57600080fd5b602092830196509450908601359080821115613a6757600080fd5b818701915087601f830112613a7b57600080fd5b813581811115613a8a57600080fd5b8860208260061b8501011115613a9f57600080fd5b95989497505060200194505050565b60006101008284031215613ac157600080fd5b50919050565b6000806000806000806000806101e0898b031215613ae457600080fd5b883597506020890135613af6816137c6565b96506040890135613b06816137c6565b9550613b158a60608b01613aae565b979a96995094976101608101359661018082013596506101a082013595506101c0909101359350915050565b60008060408385031215613b5457600080fd5b50508035926020909101359150565b6001600160a01b03929092168252602082015260400190565b600080600060608486031215613b9157600080fd5b833592506020840135915060408401356139db816137c6565b600060208284031215613bbc57600080fd5b8135611701816137c6565b6000806000806000808688036101e0811215613be257600080fd5b8735613bed816137c6565b96506020880135613bfd816137c6565b9550613c0c8960408a01613aae565b945061014088013593506101608801359250606061017f1982011215613c3157600080fd5b50610180870190509295509295509295565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b600060208284031215613c8c57600080fd5b8151611701816137c6565b6001600160a01b039384168152919092166020820152604081019190915260600190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b600060208284031215613cf757600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b6001600160601b038116811461216a57600080fd5b80356137e681613d14565b600060208284031215613d4657600080fd5b813561170181613d14565b8135613d5c816137c6565b81546001600160a01b03199081166001600160a01b039290921691821783556020840135613d8981613d14565b60a01b1617905550565b6020810161073e82846138b5565b634e487b7160e01b600052601160045260246000fd5b8082018082111561073e5761073e613da1565b634e487b7160e01b600052604160045260246000fd5b6000610100808385031215613df457600080fd5b6040519081019067ffffffffffffffff82118183101715613e2557634e487b7160e01b600052604160045260246000fd5b81604052833581526020840135602082015260408401359150613e47826137c6565b816040820152613e5960608501613d29565b606082015260808401356080820152613e7460a085016137db565b60a0820152613e8560c08501613d29565b60c082015260e084013560e0820152809250505092915050565b808202811582820484141761073e5761073e613da1565b600082613ed357634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561073e5761073e613da1565b6001600160a01b038181168382160190808211156134ad576134ad613da1565b803561ffff811681146137e657600080fd5b600060608284031215613f2f57600080fd5b6040516060810181811067ffffffffffffffff82111715613f6057634e487b7160e01b600052604160045260246000fd5b604052613f6c83613f0b565b8152613f7a60208401613f0b565b6020820152613f8b60408401613f0b565b60408201529392505050565b60005b83811015613fb2578181015183820152602001613f9a565b50506000910152565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351613ff3816017850160208801613f97565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351614024816028840160208801613f97565b01602801949350505050565b602081526000825180602084015261404f816040850160208701613f97565b601f01601f19169190910160400192915050565b60008161407257614072613da1565b506000190190565b634e487b7160e01b600052603160045260246000fd5b6000602082840312156140a257600080fd5b8151801515811461170157600080fd5b600082516140c4818460208701613f97565b919091019291505056fe945556d23be9a7c839faccfc238fc67e56b8e3c9fddab25f8258c8b368d3413d0e3bd0540e03bb6bc6bbfab3c1f0a7fa58fced33dc3256731217fd01a20479b8a164736f6c6343000812000a

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be00000000000000000000000092ed78b41537c902ad287608d8535bb6780a7618

-----Decoded View---------------
Arg [0] : _borrowerNote (address): 0xe5B12BEfaf3a91065DA7FDD461dEd2d8F8ECb7BE
Arg [1] : _lenderNote (address): 0x92ED78b41537C902Ad287608d8535bb6780A7618

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 000000000000000000000000e5b12befaf3a91065da7fdd461ded2d8f8ecb7be
Arg [1] : 00000000000000000000000092ed78b41537c902ad287608d8535bb6780a7618


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.