Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article examines ERC-7565, which proposes an NFT-based collateralized lending mechanism focused on access to liquidity and efficient asset management.

This article translates, summarizes, and expands on the proposal below, as discussed in the original article published on April 9, 2024.

I have also written about various other EIPs.

Overview

This ERC (Ethereum Request for Comments) proposal describes a mechanism for borrowing funds against assets pledged as collateral.

Here, an asset owner is someone who borrows funds using an NFT representing locked deposits or assets as collateral. These NFTs represent the right to claim the underlying assets and the associated returns after a predefined maturity date.

Motivation

The proposal addresses the challenge of maintaining access to liquidity while assets are locked in decentralized finance (DeFi). Many DeFi mechanisms offer benefits such as interest or voting rights in exchange for locking assets. However, retaining access to liquidity while those assets remain locked is difficult.

The proposal uses ERC-721, the NFT standard, and ERC-4907, an extension for representing rental or temporary usage rights through NFTs, as a way of deriving value from locked assets.

For more on ERC-721, see the following article.

https://chaldene.net/erc721

For more on ERC-4907, see the following article.

[ERC-4907] Understanding Time-Limited NFT User Roles

The process works as follows.

1. Locking assets and issuing NFTs

In DeFi services, particularly automated market makers (AMMs), liquidity providers contribute assets to pools and receive NFTs representing their positions in implementations that use NFTs. These NFTs represent rights to the assets and their associated benefits. At the same time, the assets are locked in the pool, which creates liquidity constraints for providers.

2. Using NFTs as collateral

Under existing approaches, providers may have to withdraw their assets to meet urgent liquidity needs, reducing liquidity in the pool.

The proposed mechanism allows NFTs representing assets locked in liquidity pools to be used as collateral. Liquidity providers can then obtain temporary access to funds without withdrawing their assets, preserving liquidity in the pool.

An automated market maker (AMM) in decentralized finance (DeFi) automates the role of traditional financial market makers using blockchain technology and smart contracts. An AMM determines asset prices algorithmically and provides liquidity for trading.

Basic structure of an AMM

Liquidity pools

At the heart of an AMM are collections of tokens held in smart contracts called liquidity pools. These pools hold different types of tokens, such as ETH and DAI, in proportions determined by the pool's design and trading activity.

Liquidity providers

Users become liquidity providers by depositing tokens into a pool for a particular token pair. This increases the pool's liquidity and makes it easier for other users to exchange the two tokens.

Pricing algorithm

Rather than matching buy and sell orders directly, an AMM automatically determines prices using a mathematical algorithm implemented in a smart contract, such as x*y=k. The algorithm calculates exchange rates based on the relative amounts of the tokens.

Benefits and challenges of AMMs

Benefits
  • Continuous trading
    • Buyers and sellers do not have to be matched as they would on a traditional order-book exchange, so trades can be executed whenever sufficient liquidity is available.
  • Open participation for liquidity providers
    • Users can participate in liquidity pools and earn a portion of trading fees.
  • Decentralization
    • Smart contract code manages operations without requiring a centralized operator or intermediary.
Challenges
  • Impermanent loss
    • Changes in relative token prices can cause liquidity providers to lose value compared with simply holding the assets.
  • Smart contract risk
    • Bugs or vulnerabilities in the code can create security problems.

AMMs play an important role in DeFi by providing liquidity, enabling new financial mechanisms, and broadening participation. They also involve risks that users should understand before participating.

3. Perpetual contract NFTs

The proposal also introduces the concept of a perpetual contract NFT. Drawing on perpetual futures contracts in cryptocurrency derivatives markets, these NFTs represent rights associated with a perpetual contract and its collateral.

This creates a new form of NFT intended to increase the usefulness of locked assets, providing liquidity across different DeFi applications while retaining the benefits of locking those assets.

By allowing NFTs representing locked assets to be pledged as collateral, the proposal aims to provide a general liquidity mechanism that can benefit a wide range of users across DeFi services where asset locking is common, including lending and trading. The intended result is greater liquidity and usability throughout the DeFi ecosystem.

Perpetual

The word perpetual means continuing indefinitely. In finance, it can refer to contracts or products that have no specified expiration or maturity date.

Perpetual contracts

Perpetual contracts resemble traditional futures contracts, but unlike conventional futures, they have no fixed expiration or settlement date. Traders can theoretically maintain a position indefinitely without having to close it or roll it over into another contract. Perpetual contracts on major cryptocurrencies such as Bitcoin and Ether are popular in cryptocurrency markets.

Main features and mechanisms

  • No expiration date

    • As the name suggests, a perpetual contract continues indefinitely, and traders can choose when to close their positions.
  • Funding rates

    • Perpetual contracts use a mechanism called the funding rate to support market liquidity and help keep the contract price aligned with the spot price.
    • When the funding rate is positive, traders holding long positions pay traders holding short positions, and vice versa.
  • Leverage: Perpetual contracts allow leveraged trading, in which traders can take larger positions with less capital. This also increases the risks involved.

Benefits of using perpetual contracts
  • Flexibility

    • Traders can close positions at any time, making it easier to pursue strategies based on longer-term market views or short-term price movements.
  • Accessibility

    • Access to derivatives markets becomes easier, allowing even participants with relatively little capital to take positions in larger markets.

Risks

  • High risk

    • Highly leveraged trading can generate substantial gains, but it also carries the risk of substantial losses.
  • Price fluctuations

    • Changes in funding rates or sudden market price movements may affect the cost of maintaining a position.

Perpetual contracts are an advanced trading instrument in cryptocurrency markets and can provide a way to gain exposure to market opportunities. It is important to understand their mechanics and risks thoroughly before using them.

The following article provides further detail.

https://mirror.xyz/0xcE77b9fCd390847627c84359fC1Bc02fC78f0e58/4xXjI1IWvLIOeLbdKLb5vlOiwFZdte4nQVvS0Fog7L4

Specification

Contract interface

ts
    interface IPerpetualContractNFT {

        // Emitted when an NFT is collateralized for obtaining a loan
        event Collateralized(uint256 indexed tokenId, address indexed owner, uint256 loanAmount, uint256 interestRate, uint256 loanDuration);

        // Emitted when a loan secured by an NFT is fully repaid, releasing the NFT from collateral
        event LoanRepaid(uint256 indexed tokenId, address indexed owner);

        // Emitted when a loan defaults, resulting in the transfer of the NFT to the lender
        event Defaulted(uint256 indexed tokenId, address indexed lender);

        // Enables an NFT owner to collateralize their NFT in exchange for a loan
        // @param tokenId The NFT to be used as collateral
        // @param loanAmount The amount of funds to be borrowed
        // @param interestRate The interest rate for the loan
        // @param loanDuration The duration of the loan
        function collateralize(uint256 tokenId, uint256 loanAmount, uint256 interestRate, uint64 loanDuration) external;

        // Enables a borrower to repay their loan and regain ownership of the collateralized NFT
        // @param tokenId The NFT that was used as collateral
        // @param repayAmount The amount of funds to be repaid
        function repayLoan(uint256 tokenId, uint256 repayAmount) external;

        // Allows querying the loan terms for a given NFT
        // @param tokenId The NFT used as collateral
        // @return loanAmount The amount of funds borrowed
        // @return interestRate The interest rate for the loan
        // @return loanDuration The duration of the loan
        // @return loanDueDate The due date for the loan repayment
        function getLoanTerms(uint256 tokenId) external view returns (uint256 loanAmount, uint256 interestRate, uint256 loanDuration, uint256 loanDueDate);

        // Allows querying the current owner of the NFT
        // @param tokenId The NFT in question
        // @return The address of the current owner
        function currentOwner(uint256 tokenId) external view returns (address);

        // View the total amount required to repay the loan for a given NFT
        // @param tokenId The NFT used as collateral
        // @return The total amount required to repay the loan, including interest
        function viewRepayAmount(uint256 tokenId) external view returns (uint256);
    }

Collateralized event

Records that an NFT has been pledged as collateral for a loan. It captures important details, including the loan amount, interest rate, and loan duration.

The event is emitted when the collateralize function succeeds.

LoanRepaid event

Records that a loan has been repaid and the corresponding NFT has been released from collateral.

The event is emitted when the repayLoan function succeeds.

Defaulted event

Records that a loan has defaulted and the NFT has been transferred to the lender. It describes the process through which the lender is protected when a borrower defaults and the NFT is transferred to the lender.

The event is emitted when the loan enters a default state.

collateralize function

Allows an NFT owner to obtain a loan using their NFT as collateral.

The function should be implemented with external visibility so that it can be called externally.

repayLoan function

Allows an NFT owner to repay their loan and recover the NFT pledged as collateral.

This function should also use external visibility, making it accessible through external calls.

getLoanTerms function

Allows callers to retrieve the loan terms associated with a specific NFT, such as the loan amount, interest rate, and repayment period.

The function can be implemented as external view, providing read-only access. The view modifier indicates that the function reads data without modifying state.

currentOwner function

Allows callers to query the current owner of a specific NFT.

This function can also be implemented as external view, providing read-only access.

viewRepayAmount function

Allows callers to retrieve the current repayment amount associated with a specific NFT, including the principal and interest.

It can also be implemented as external view for read-only access.

These functions cover the basic operations of an NFT-backed lending system and allow the lending process to be managed automatically and transparently through smart contracts.

Each function serves a specific purpose, covering the provision of NFTs as collateral, borrowing, repayment, and checking loan terms.

Additional considerations

The proposal describes a new standard designed to address particular challenges in decentralized finance (DeFi), with an emphasis on the liquidity and management of assets locked as collateral.

In conventional DeFi mechanisms, asset holders must lock assets to participate in activities such as lending, staking, and yield farming. This restricts their access to liquidity.

The aim of the new standard is to introduce a more flexible approach that allows asset holders to retain some access to liquidity while their assets remain locked, making DeFi products more useful and attractive.

Design motivation

Liquidity and asset management challenges

The design stems from the need to address the loss of access to liquidity when assets are locked as collateral in DeFi.

Design decisions

Dual-role system

Clearly distinguishing between the NFT owner (the asset holder) and the DeFi platform or contract using the NFT as collateral simplifies the management of rights and responsibilities, improves clarity, and reduces potential conflicts.

Improved liquidity

By enabling asset owners to obtain loans using NFTs representing locked assets as collateral, the mechanism provides access to liquidity without requiring them to withdraw assets from pools or staking programs.

Automated loan and collateral management

Integrating automated functionality for managing the terms associated with collateralized NFTs is a deliberate design choice intended to minimize transaction costs and complexity.

DeFi composability

By focusing on the integration of asset-locking and collateralization services, the standard aims to encourage adoption across DeFi platforms and services and make it easier for them to interoperate within the DeFi ecosystem.

Comparison with ERC-4907

ERC-4907 also introduces a dual-role model for NFTs, distinguishing between an owner and a user. The proposed standard, however, specifically focuses on the use of NFTs as collateral in financial transactions, rather than the rental-oriented approach of ERC-4907.

Improving conventional collateralization methods

Compared with traditional DeFi collateralization methods that require assets to be fully locked up, the standard proposes a more flexible model that allows ongoing access to liquidity.

The design addresses asset management and liquidity challenges in DeFi. By allowing asset holders to retain partial access to liquidity while their assets remain locked, it aims to improve the usefulness and appeal of DeFi.

Compatibility

The proposal is fully compatible with ERC-721 and can be integrated with ERC-4907 to support NFT rentals.

Implementation

ts
// SPDX-License-Identifier: CC0-1.0 
pragma solidity ^0.8.0;

//import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./IPerpetualContractNFT.sol";
import "./ERC4907/ERC4907.sol";

contract PerpetualContractNFT is ERC4907, IPerpetualContractNFT {
    struct LoanInfo {
        address borrower;   // Address that borrowed against the NFT
        uint256 loanAmount; // Amount of funds borrowed
        uint256 interestRate; // Interest rate for the loan
        uint64 loanDuration; // Duration of the loan
        uint256 loanStartTime; // Timestamp when the loan starts
    }

    mapping(uint256 => LoanInfo) internal _loans;

    //Constructor to initialize the Perpetual Contract NFT contract with the given name and symbo
    constructor(string memory name_, string memory symbol_)
        ERC4907(name_, symbol_)
    {}

    function collateralize(uint256 tokenId, uint256 loanAmount, uint256 interestRate, uint64 loanDuration) public override {
        require(ownerOf(tokenId) == msg.sender || isApprovedForAll(ownerOf(tokenId), msg.sender) || getApproved(tokenId) == msg.sender, "Not owner nor approved");

        LoanInfo storage info = _loans[tokenId];
        info.borrower = msg.sender;
        // The loan amount should reflect the asset's value as represented by the NFT, considering an appropriate loan-to-value (LTV) ratio.
        info.loanAmount = loanAmount;
        info.interestRate = interestRate;
        info.loanDuration = loanDuration;
        info.loanStartTime = block.timestamp;

        setUser(tokenId, address(this), loanDuration);
        emit Collateralized(tokenId, msg.sender, loanAmount, interestRate, loanDuration);

        // Further logic can be implemented here to manage the lending of assets
    }

    function repayLoan(uint256 tokenId, uint256 repayAmount) public override {
        require(_loans[tokenId].borrower == msg.sender, "Not the borrower.");

        // Calculate the total amount due for repayment
        uint256 totalDue = viewRepayAmount(tokenId);

        // Check if the repayAmount is sufficient to cover at least a part of the total due amount
        require(repayAmount <= totalDue, "Repay amount exceeds total due.");

        // Calculate the remaining loan amount after repayment
        _loans[tokenId].loanAmount = totalDue - repayAmount;

        // Resets the user of the NFT to the default state if the entire loan amount is fully repaid
        if(_loans[tokenId].loanAmount == 0) {
            setUser(tokenId, address(0), 0);
        }

        emit LoanRepaid(tokenId, msg.sender);
    }


    function getLoanTerms(uint256 tokenId) public view override returns (uint256, uint256, uint256, uint256) {
        LoanInfo storage info = _loans[tokenId];
        return (info.loanAmount, info.interestRate, info.loanDuration, info.loanStartTime);
    }

    function currentOwner(uint256 tokenId) public view override returns (address) {
        return ownerOf(tokenId);
    }

    function viewRepayAmount(uint256 tokenId) public view returns (uint256) {
        if (_loans[tokenId].loanAmount == 0) {
            // If the loan amount is zero, there is nothing to repay
            return 0;
        }

        // The interest is calculated on an hourly basis, prorated based on the actual duration for which the loan was held.
        // If the borrower repays before the loan duration ends, they are charged interest only for the time the loan was held.
        // For example, if the annual interest rate is 5% and the borrower repays in half the loan term, they pay only 2.5% interest.
        uint256 elapsed = block.timestamp > (_loans[tokenId].loanStartTime + _loans[tokenId].loanDuration) 
                        ? _loans[tokenId].loanDuration  / 1 hours
                        : (block.timestamp - _loans[tokenId].loanStartTime) / 1 hours;

        // Round up
        // Example: 15/4 = 3.75
        // round((15 + 4 - 1)/4) = 4, round((15/4) = 3)
        uint256 interest = ((_loans[tokenId].loanAmount * _loans[tokenId].interestRate / 100) * elapsed + (_loans[tokenId].loanDuration / 1 hours) - 1) / 
                    (_loans[tokenId].loanDuration / 1 hours);

        // Calculate the total amount due
        uint256 totalDue = _loans[tokenId].loanAmount + interest;

        return totalDue;
    }

    // Additional functions and logic to handle loan defaults, transfers, and other aspects of the NFT lifecycle
}

LoanInfo

javascript
struct LoanInfo {
    address borrower;   // Address that borrowed against the NFT
    uint256 loanAmount; // Amount of funds borrowed
    uint256 interestRate; // Interest rate for the loan
    uint64 loanDuration; // Duration of the loan
    uint256 loanStartTime; // Timestamp when the loan starts
}

Overview

A struct that stores the details of a loan associated with an NFT.

Details

The struct is used to manage information about a loan obtained by pledging an NFT as collateral. It contains key information such as the borrower's address, the amount borrowed, the interest rate, the loan duration, and the loan start time.

Parameters

  • borrower
    • The address of the borrower who received the loan.
  • loanAmount
    • The amount of funds borrowed.
  • interestRate
    • The interest rate of the loan.
  • loanDuration
    • The loan duration in seconds.
  • loanStartTime
    • The timestamp at which the loan started.

_loans

javascript
mapping(uint256 => LoanInfo) internal _loans;

Overview

The _loans mapping manages loan information.

Details

This mapping associates an individual loan record with each NFT. The key is a unique identifier for the NFT, such as its token ID, and the value is the detailed loan information stored in the LoanInfo struct.

Parameters

  • uint256
    • The NFT's unique identifier (token ID).
  • LoanInfo
    • A struct storing loan information for a specific NFT.

collateralize

javascript
function collateralize(uint256 tokenId, uint256 loanAmount, uint256 interestRate, uint64 loanDuration) public override {
    require(ownerOf(tokenId) == msg.sender || isApprovedForAll(ownerOf(tokenId), msg.sender) || getApproved(tokenId) == msg.sender, "Not owner nor approved");
    LoanInfo storage info = _loans[tokenId];
    info.borrower = msg.sender;
    info.loanAmount = loanAmount;
    info.interestRate = interestRate;
    info.loanDuration = loanDuration;
    info.loanStartTime = block.timestamp;
    setUser(tokenId, address(this), loanDuration);
    emit Collateralized(tokenId, msg.sender, loanAmount, interestRate, loanDuration);
}

Overview

Obtains a loan using an NFT as collateral.

Details

An NFT owner uses this function to obtain a loan against their NFT. The owner specifies the loan amount, interest rate, and duration to initiate a loan agreement. The NFT pledged as collateral is temporarily transferred to the contract.

Arguments

  • tokenId
    • The token ID of the NFT being pledged as collateral.
  • loanAmount
    • The amount of funds to borrow.
  • interestRate
    • The interest rate of the loan.
  • loanDuration
    • The loan duration in seconds.

repayLoan

javascript
function repayLoan(uint256 tokenId, uint256 repayAmount) public override {
    require(_loans[tokenId].borrower == msg.sender, "Not the borrower.");
    uint256 totalDue = viewRepayAmount(tokenId);
    require(repayAmount <= totalDue, "Repay amount exceeds total due.");
    _loans[tokenId].loanAmount = totalDue - repayAmount;
    if(_loans[tokenId].loanAmount == 0) {
        setUser(tokenId, address(0), 0);
    }
    emit LoanRepaid(tokenId, msg.sender);
}

Overview

Repays a loan and recovers the NFT pledged as collateral.

Details

This function allows the borrower to make a repayment on the loan. Once the loan is repaid in full, the NFT pledged as collateral is returned to the borrower.

Arguments

  • tokenId
    • The token ID of the NFT associated with the loan being repaid.
  • repayAmount
    • The amount to repay.

getLoanTerms

javascript
function getLoanTerms(uint256 tokenId) public view override returns (uint256, uint256, uint256, uint256) {
    LoanInfo storage info = _loans[tokenId];
    return (info.loanAmount, info.interestRate, info.loanDuration, info.loanStartTime);
}

Overview

Retrieves the terms of a specific loan agreement.

Details

This function returns the detailed loan terms associated with the specified NFT: the loan amount, interest rate, loan duration, and loan start time.

Arguments

  • tokenId
    • The token ID of the NFT whose loan terms are being queried.

Return values

  • The loan amount, interest rate, loan duration, and loan start time.

currentOwner

javascript
function currentOwner(uint256 tokenId) public view override returns (address) {
    return ownerOf(tokenId);
}

Overview

Queries the current owner of a specific NFT.

Details

This function returns the address of the current owner of the NFT identified by the specified token ID.

Arguments

  • tokenId
    • The token ID of the NFT whose current owner is being queried.

Return value

  • The address of the current owner of the specified NFT.

viewRepayAmount

javascript
function viewRepayAmount(uint256 tokenId) public view returns (uint256) {
    if (_loans[tokenId].loanAmount == 0) {
        return 0;
    }
    uint256 elapsed = block.timestamp > (_loans[tokenId].loanStartTime + _loans[tokenId].loanDuration) 
                    ? _loans[tokenId].loanDuration  / 1 hours
                    : (block.timestamp - _loans[tokenId].loanStartTime) / 1 hours;
    uint256 interest = ((_loans[tokenId].loanAmount * _loans[tokenId].interestRate / 100) * elapsed + (_loans[tokenId].loanDuration / 1 hours) - 1) / 
                (_loans[tokenId].loanDuration / 1 hours);
    uint256 totalDue = _loans[tokenId].loanAmount + interest;
    return totalDue;
}

Overview

Queries the current repayment amount for the loan associated with a specific NFT.

Details

This function calculates and returns the total amount required for repayment, including the principal and interest. Interest is calculated on an hourly basis according to how long the loan has actually been outstanding.

Arguments

  • tokenId
    • The token ID of the NFT associated with the loan whose repayment amount is being queried.

Return value

  • The total amount required to repay the specified loan.

Citation

Hyoungsung Kim (@HyoungsungKim) hyougnsung@keti.re.kr, Yong-Suk Park yspark@keti.re.kr, Hyun-Sik Kim hskim@keti.re.kr, "ERC-7565: Perpetual Contract NFTs as Collateral [DRAFT]," Ethereum Improvement Proposals, no. 7565, November 2023. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-7565.

Final thoughts

This article covered ERC-7565, which proposes an NFT-based collateralized lending mechanism focused on access to liquidity and efficient asset management.

If you have questions, feel free to send me a direct message on Twitter.

Twitter @cardene777

I also publish content on other platforms.

https://chaldene.net/