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 ERC5521, a proposal for representing reference relationships between ERC721 NFTs.

This article translates, summarizes, and expands on the proposal below.

As of September 20, 2023, ERC5521 was in Draft.

Overview

The standard extends ERC721 with two reference indicators (referring and referred) and a time-based indicator, createdTimestamp. The relationships between NFTs form a directed acyclic graph (DAG). The standard enables users to query, trace, and analyze these relationships.

For more on ERC721, see the following article.

https://chaldene.net/erc721

Directed acyclic graphs (DAGs)

A directed acyclic graph (DAG) is a graph-theoretic structure with the following properties.

  • Directed
    • Each edge (a connection between vertices) has a specified direction.
    • For example, an edge can lead from vertex AA to vertex BB. A directed graph may also contain edges in both directions, but a DAG cannot contain such a two-edge cycle.
  • Acyclic
    • There is no directed cycle that starts at a vertex and returns to that same vertex.
    • In other words, following directed edges cannot bring you back to the starting vertex.
Example 1: Task dependencies

DAGs are useful for representing task dependencies in project management.

  • Task A
    • Initial project setup.
  • Task B
    • Data collection.
  • Task C
    • Data analysis.
  • Task D
    • Report preparation.

These task dependencies can be represented as a DAG as follows.

  • Task A → Task B
  • Task A → Task C
  • Task B → Task D
  • Task C → Task D

This DAG shows that tasks B and C begin after task A is complete, and task D begins after both B and C are complete. DAGs make the order of task execution clear and enable efficient project management.

14.png

Example 2: Version control systems

Distributed version control systems such as Git also use DAGs. Each commit is represented as a vertex, and dependencies (parent-child relationships) between commits are represented as edges.

  • Commit A
    • Initial project commit.
  • Commit B
    • Changes based on commit A.
  • Commit C
    • Another set of changes based on commit A.
  • Commit D
    • A merge of commits B and C.

This DAG shows the history branching from commit A into commits B and C, then converging again at commit D. DAGs therefore help track and merge multiple histories of changes.

15.png

Example 3: Relationships between rNFTs

The proposed ERC5521 standard also represents relationships between rNFTs using a DAG. Each NFT is a vertex, and reference relationships are represented as edges. For example:

  • NFT A: An original artwork.
  • NFT B: An artwork created with reference to NFT A.
  • NFT C: Another artwork created with reference to NFT A.
  • NFT D: An artwork created with reference to NFTs B and C.

This DAG illustrates how NFTs B and C build on NFT A and how NFT D subsequently combines their contributions. DAGs clarify NFT reference relationships and make complex reference structures easier to manage.

16.png

Benefits of DAGs
  • Clear dependencies
    • Task and version dependencies can be represented visually, making their order and relationships intuitive.
  • Efficient management
    • DAGs provide a foundation for efficient task scheduling and version control.
  • Data consistency
    • The absence of cycles allows dependencies to be managed while preserving an acyclic structure.

As these examples demonstrate, DAGs are particularly useful for managing systems and projects with complex dependencies. ERC5521 also uses these properties to manage and trace relationships between NFTs effectively.

system-arch.png

The diagram above illustrates the relationships between rNFTs as a directed acyclic graph (DAG). Each rNFT has a number and references earlier rNFTs. Referenced rNFTs may also receive a share of revenue. As illustrated, the amount allocated for revenue sharing from rNFT 26 is distributed among the referenced rNFTs as follows.

  • rNFT 11
    • 60%
  • rNFT 21
    • 20%
  • rNFT 25
    • 20%

This revenue distribution is based on a consensus-building process among stakeholders, including external users, the community, rNFT issuers, and regulatory authorities.

Motivation

With existing NFTs, creating a new NFT based on an earlier one or remixing two records can leave no explicit relationship between the new work and the creators of the original works. This can make NFT sales one-off transactions and limit opportunities to increase the value of intellectual property over time. Introducing NFT reference relationships can establish a sustainable economic model and encourage ongoing engagement with NFT creation, use, and promotion. Referable NFTs (rNFTs) make it possible to build a dynamically extensible network. Outgoing and incoming reference relationships form a DAG-based NFT network, enabling users to query, trace, and analyze relationships between NFTs.

Key points

The following points are important.

  • Explicit ownership inheritance
    • Inheriting ownership-related information makes it possible to create works based on existing works.
    • This avoids reinventing the wheel.
  • Incentive compatibility
    • It becomes easier to integrate incentive models for both the creators of referenced NFTs and the creators of new NFTs.
  • Easy integration
    • Integration with existing token standards and third-party protocols is facilitated.
    • For example, rNFTs can also be used in rental scenarios.
    • Standards such as ERC5006 allow multiple users to rent units associated with the same NFT ID at the same time, or one user to rent multiple NFTs during the same period.

For more on ERC5006, see the following article.

[ERC5006] Separating ownership and usage rights for ERC1155 NFTs

  • Scalable interoperability
    • References across different contracts improve interoperability.

Specification

referring (outgoing references)

This indicator shows that a particular NFT references other NFTs. In other words, it identifies the links from an NFT to other NFTs. It makes it possible to track the number of outgoing links. That is, it allows the references that this NFT makes to other NFTs to be counted.

referred (incoming references)

This indicator shows that a particular NFT is referenced by other NFTs. In other words, it identifies the NFTs that link to a given NFT. It makes it possible to track the number of incoming links. That is, it allows the references to this NFT from other NFTs to be counted.

createdTimestamp (creation time)

This indicator identifies when an NFT was created. It provides temporal information, allowing users to compare the creation times of NFTs.

Contracts implementing the standard must provide the specified functionality, as shown below.

javascript

pragma solidity ^0.8.4;

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";

interface IERC_5521 is IERC165 {

    /// Logged when a node in the rNFT gets referred and changed.
    /// @notice Emitted when the `node` (i.e., an rNFT) is changed.
    event UpdateNode(uint256 indexed tokenId, 
                     address indexed owner, 
                     address[] _address_referringList,
                     uint256[][] _tokenIds_referringList,
                     address[] _address_referredList,
                     uint256[][] _tokenIds_referredList
    );

    /// @notice set the referred list of an rNFT associated with different contract addresses and update the referring list of each one in the referred list. Checking the duplication of `addresses` and `tokenIds` is **RECOMMENDED**.
    /// @param `tokenId` of rNFT being set. `addresses` of the contracts in which rNFTs with `tokenIds` being referred accordingly. 
    /// @requirement 
    /// - the size of `addresses` **MUST** be the same as that of `tokenIds`;
    /// - once the size of `tokenIds` is non-zero, the inner size **MUST** also be non-zero;
    /// - the `tokenId` **MUST** be unique within the same contract;
    /// - the `tokenId` **MUST NOT** be the same as `tokenIds[i][j]` if `addresses[i]` is essentially `address(this)`.
    function setNode(uint256 tokenId, address[] memory addresses, uint256[][] memory tokenIds) external;

    /// @notice get the referring list of an rNFT.
    /// @param `tokenId` of the rNFT being focused, `_address` of contract address associated with the focused rNFT.
    /// @return the referring mapping of the rNFT.
    function referringOf(address _address, uint256 tokenId) external view returns(address[] memory, uint256[][] memory);

    /// @notice get the referred list of an rNFT.
    /// @param `tokenId` of the rNFT being focused, `_address` of contract address associated with the focused rNFT.
    /// @return the referred mapping of the rNFT.
    function referredOf(address _address, uint256 tokenId) external view returns(address[] memory, uint256[][] memory);

    /// @notice get the timestamp of an rNFT when is being created.
    /// @param `tokenId` of the rNFT being focused, `_address` of contract address associated with the focused rNFT.
    /// @return the timestamp of the rNFT when is being created with uint256 format.
    function createdTimestampOf(address _address, uint256 tokenId) external view returns(uint256);
    
    /// @notice check supported interfaces, adhereing to ERC165.
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

interface TargetContract is IERC165 {
    /// @notice set the referred list of an rNFT associated with external contract addresses. 
    /// @param `_tokenIds` of rNFTs associated with the contract address `_address` being referred by the rNFT with `tokenId`.
    /// @requirement
    /// - `_address` **MUST NOT** be the same as `address(this)` where `this` is executed by an external contract where `TargetContract` interface is implemented.
    function setNodeReferredExternal(address _address, uint256 tokenId, uint256[] memory _tokenIds) external;

    function referringOf(address _address, uint256 tokenId) external view returns(address[] memory, uint256[][] memory);

    function referredOf(address _address, uint256 tokenId) external view returns(address[] memory, uint256[][] memory);

    function createdTimestampOf(address _address, uint256 tokenId) external view returns(uint256);
    
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
  • UpdateNode
    • An event emitted when setNode is called.
  • safeMint
    • Creates a new rNFT.
  • setNode
    • Sets the reference list for a particular rNFT and updates the list of NFTs it references.
    • Establishes relationships between NFTs.
  • setNodeReferring
    • Sets the reference list for a particular rNFT.
    • Sets outgoing links.
  • setNodeReferred
    • Sets the list of references to the specified rNFT.
    • Sets incoming links.
  • setNodeReferredExternal
    • Sets the list of incoming references supplied by another contract.
    • Establishes external incoming links.
  • referringOf
    • Retrieves the reference list for a particular rNFT.
    • Retrieves outgoing links.
  • referredOf
    • Retrieves the list of references to a particular rNFT.
    • Retrieves incoming links.
  • createdTimestampOf
    • Retrieves the timestamp at which an rNFT was created.

Additional considerations

Does UpdateNode provide enough information?

UpdateNode provides the following information.

  • The rNFT ID.
  • The rNFT owner.
  • Lists of contract addresses and IDs for NFTs that reference or are referenced by a particular rNFT.

This dataset allows participants to manage and navigate the complex relationships within the rNFT ecosystem efficiently. There are several ways to implement this data, including structs and mappings containing arrays; the choice is left to implementers.

Why createdTimestampOf is needed

rNFTs reference one another. A global timestamp for each rNFT makes it possible to establish a time-based sequence of rNFTs.

How are cross-contract references established?

Cross-contract references use setNodeReferredExternal, with interface checks to establish compatibility with existing contracts.

Backwards compatibility

The standard can remain fully compatible with ERC721 by adding an extension set.

Tests

The test code is available below.

https://eips.ethereum.org/assets/eip-5521/ERC_5521.test.js

Reference implementation

Reference implementation code
javascript
pragma solidity ^0.8.4;

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

contract ERC_5521 is ERC721, IERC_5521, TargetContract {

    struct Relationship {
        mapping (address => uint256[]) referring;
        mapping (address => uint256[]) referred;
        address[] referringKeys;
        address[] referredKeys;
        uint256 createdTimestamp; // unix timestamp when the rNFT is being created

        // extensible parameters
        // ...
    }

    mapping (uint256 => Relationship) internal _relationship;
    address contractOwner = address(0);

    constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {
        contractOwner = msg.sender;
    }

    function safeMint(uint256 tokenId, address[] memory addresses, uint256[][] memory _tokenIds) public {
        // require(msg.sender == contractOwner, "ERC_rNFT: Only contract owner can mint");
        _safeMint(msg.sender, tokenId);
        setNode(tokenId, addresses, _tokenIds);
    }

    /// @notice set the referred list of an rNFT associated with different contract addresses and update the referring list of each one in the referred list
    /// @param tokenIds array of rNFTs, recommended to check duplication at the caller's end
    function setNode(uint256 tokenId, address[] memory addresses, uint256[][] memory tokenIds) public virtual override {
        require(
            addresses.length == tokenIds.length,
            "Addresses and TokenID arrays must have the same length"
        );
        for (uint i = 0; i < tokenIds.length; i++) {
            if (tokenIds[i].length == 0) { revert("ERC_5521: the referring list cannot be empty"); }
        }
        setNodeReferring(addresses, tokenId, tokenIds);
        setNodeReferred(addresses, tokenId, tokenIds);
    }

    /// @notice set the referring list of an rNFT associated with different contract addresses 
    /// @param _tokenIds array of rNFTs associated with addresses, recommended to check duplication at the caller's end
    function setNodeReferring(address[] memory addresses, uint256 tokenId, uint256[][] memory _tokenIds) private {
        require(_isApprovedOrOwner(msg.sender, tokenId), "ERC_5521: transfer caller is not owner nor approved");

        Relationship storage relationship = _relationship[tokenId];

        for (uint i = 0; i < addresses.length; i++) {
            if (relationship.referring[addresses[i]].length == 0) { relationship.referringKeys.push(addresses[i]); } // Add the address if it's a new entry
            relationship.referring[addresses[i]] = _tokenIds[i];
        }

        relationship.createdTimestamp = block.timestamp;
        emitEvents(tokenId, msg.sender);
    }

    /// @notice set the referred list of an rNFT associated with different contract addresses 
    /// @param _tokenIds array of rNFTs associated with addresses, recommended to check duplication at the caller's end
    function setNodeReferred(address[] memory addresses, uint256 tokenId, uint256[][] memory _tokenIds) private {
        for (uint i = 0; i < addresses.length; i++) {
            if (addresses[i] == address(this)) {
                for (uint j = 0; j < _tokenIds[i].length; j++) {
                    Relationship storage relationship = _relationship[_tokenIds[i][j]];
                    if (relationship.referred[addresses[i]].length == 0) { relationship.referredKeys.push(addresses[i]); } // Add the address if it's a new entry
                    
                    require(tokenId != _tokenIds[i][j], "ERC_5521: self-reference not allowed");
                    if (relationship.createdTimestamp >= block.timestamp) { revert("ERC_5521: the referred rNFT needs to be a predecessor"); } // Make sure the reference complies with the timing sequence

                    relationship.referred[address(this)].push(tokenId);
                    emitEvents(_tokenIds[i][j], ownerOf(_tokenIds[i][j]));
                }
            } else {
                TargetContract targetContractInstance = TargetContract(addresses[i]);
                bool isSupports = targetContractInstance.supportsInterface(type(TargetContract).interfaceId);
                if (isSupports) {
                    // The target contract supports the interface, safe to call functions of the interface.
                    targetContractInstance.setNodeReferredExternal(address(this), tokenId, _tokenIds[i]);
                }
            }
        }
    }

    /// @notice set the referred list of an rNFT associated with different contract addresses 
    /// @param _tokenIds array of rNFTs associated with addresses, recommended to check duplication at the caller's end
    function setNodeReferredExternal(address _address, uint256 tokenId, uint256[] memory _tokenIds) external {
        for (uint i = 0; i < _tokenIds.length; i++) {
            Relationship storage relationship = _relationship[_tokenIds[i]];
            if (relationship.referred[_address].length == 0) { relationship.referredKeys.push(_address); } // Add the address if it's a new entry

            require(_address != address(this), "ERC_5521: this must be an external contract address");
            if (relationship.createdTimestamp >= block.timestamp) { revert("ERC_5521: the referred rNFT needs to be a predecessor"); } // Make sure the reference complies with the timing sequence

            relationship.referred[_address].push(tokenId);
            emitEvents(_tokenIds[i], ownerOf(_tokenIds[i]));
        }
    }

    /// @notice Get the referring list of an rNFT
    /// @param tokenId The considered rNFT, _address The corresponding contract address
    /// @return The referring mapping of an rNFT
    function referringOf(address _address, uint256 tokenId) external view virtual override(IERC_5521, TargetContract) returns (address[] memory, uint256[][] memory) {
        address[] memory _referringKeys;
        uint256[][] memory _referringValues;

        if (_address == address(this)) {
            require(_exists(tokenId), "ERC_5521: token ID not existed");
            (_referringKeys, _referringValues) = convertMap(tokenId, true);
        } else {
            TargetContract targetContractInstance = TargetContract(_address);
            require(targetContractInstance.supportsInterface(type(TargetContract).interfaceId), "ERC_5521: target contract not supported");
            (_referringKeys, _referringValues) = targetContractInstance.referringOf(_address, tokenId);     
        }      
        return (_referringKeys, _referringValues);
    }

    /// @notice Get the referred list of an rNFT
    /// @param tokenId The considered rNFT, _address The corresponding contract address
    /// @return The referred mapping of an rNFT
    function referredOf(address _address, uint256 tokenId) external view virtual override(IERC_5521, TargetContract) returns (address[] memory, uint256[][] memory) {
        address[] memory _referredKeys;
        uint256[][] memory _referredValues;

        if (_address == address(this)) {
            require(_exists(tokenId), "ERC_5521: token ID not existed");
            (_referredKeys, _referredValues) = convertMap(tokenId, false);
        } else {
            TargetContract targetContractInstance = TargetContract(_address);
            require(targetContractInstance.supportsInterface(type(TargetContract).interfaceId), "ERC_5521: target contract not supported");
            (_referredKeys, _referredValues) = targetContractInstance.referredOf(_address, tokenId);           
        }
        return (_referredKeys, _referredValues);
    }

    /// @notice Get the timestamp of an rNFT when is being created.
    /// @param `tokenId` of the rNFT being focused, `_address` of contract address associated with the focused rNFT.
    /// @return The timestamp of the rNFT when is being created with uint256 format.
    function createdTimestampOf(address _address, uint256 tokenId) external view returns(uint256) {
        uint256 memory createdTimestamp;

        if (_address == address(this)) {
            require(_exists(tokenId), "ERC_5521: token ID not existed");
            Relationship storage relationship = _relationship[tokenId];
            createdTimestamp = relationship.createdTimestamp;
        } else {
            TargetContract targetContractInstance = TargetContract(_address);
            require(targetContractInstance.supportsInterface(type(TargetContract).interfaceId), "ERC_5521: target contract not supported");
            createdTimestamp = targetContractInstance.createdTimestampOf(_address, tokenId);            
        }
        return createdTimestamp;
    }

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

    // @notice Emit an event of UpdateNode
    function emitEvents(uint256 tokenId, address sender) private {
        (address[] memory _referringKeys, uint256[][] memory _referringValues) = convertMap(tokenId, true);
        (address[] memory _referredKeys, uint256[][] memory _referredValues) = convertMap(tokenId, false);
        
        emit UpdateNode(tokenId, sender, _referringKeys, _referringValues, _referredKeys, _referredValues);
    }

    // @notice Convert a specific `local` token mapping to a key array and a value array
    function convertMap(uint256 tokenId, bool isReferring) private view returns (address[] memory, uint256[][] memory) {
        Relationship storage relationship = _relationship[tokenId];

        address[] memory returnKeys;
        uint256[][] memory returnValues;

        if (isReferring) {
            returnKeys = relationship.referringKeys;
            returnValues = new uint256[][](returnKeys.length);
            for (uint i = 0; i < returnKeys.length; i++) {
                returnValues[i] = relationship.referring[returnKeys[i]];
            }            
        } else {
            returnKeys = relationship.referredKeys;
            returnValues = new uint256[][](returnKeys.length);
            for (uint i = 0; i < returnKeys.length; i++) {
                returnValues[i] = relationship.referred[returnKeys[i]];
            }
        }
        return (returnKeys, returnValues);
    }
}

The following implementation approach is recommended.

The Relationship struct

Relationship is a struct for managing relationships between rNFTs (referable NFTs). The struct contains the following fields.

  • referring
    • Reference data for other NFTs.
  • referred
    • Reference data from other NFTs.
  • referringKeys
    • Auxiliary data for efficiently managing referring.
  • referredKeys
    • Auxiliary data for efficiently managing referred.
  • createdTimestamp
    • A timestamp indicating when the rNFT was created, which cannot be externally edited.

Other customizable optional fields include the following.

  • privityOfAgreement
    • Ownership information for the referenced NFTs at the time the rNFT was created.
  • profitSharing
    • Revenue distribution based on reference relationships.

referringOf and referredOf

referringOf and referredOf retrieve the reference relationships of an rNFT. These functions enable references across different smart contracts. This cannot be achieved simply by accessing _relationship directly.

If privacy is not a concern, making _relationship public can simplify the contract. If the visibility of data through the contract interface needs to be controlled, it is preferable to keep the state variable private and provide functions for retrieving that data.

For example, if _relationship contains details about a particular user's transactions or interactions, exposing this data through the interface can reveal behavioral patterns and preferences. This may create privacy risks. On public blockchains, however, private Solidity state is not itself confidential.

convertMap

convertMap is needed to retrieve the complete contents of a mapping within the struct. Even if _relationship is public, accessing the mapping only allows retrieval of individual values for specific keys. Because event emission requires comprehensive access to all stored addresses, convertMap is needed to meet the event requirements.

Security considerations

createdTimestamp (creation time)

This field provides time information based on the block header, but does not provide transaction-specific timing or finer-grained timestamps.

Ownership and references

Ownership changes do not affect token reference relationships. Normally, revenue is distributed according to the parameters established when the NFT was created, regardless of subsequent ownership changes. Referencing an rNFT does not automatically reference the rNFTs that it references. Only direct child-token references are recorded, but it is also possible to construct and record a reference chain from a root token to a particular child token (a root-to-leaf path).

Open minting and relationship risks

The safeMint function is designed to allow unrestricted minting. This resembles an open citation system such as Google Scholar. The design allows users to create NFTs and define relationships between them without centralized control. However, users may create inaccurate or unauthorized references, much like the challenges faced by traditional academic citation systems. Malicious actors may also manipulate relationships or inflate the token supply. These risks are considered deliberate trade-offs between flexibility and reliability, rather than design defects.

On-chain data integrity guarantees only what is recorded on the blockchain; it cannot rule out off-chain errors or manipulation.

Citation

Saber Yu (@OniReimu), Qin Wang qin.wang@data61.csiro.au, Shange Fu shange.fu@monash.edu, Yilin Sai yilin.sai@data61.csiro.au, Shiping Chen shiping.chen@data61.csiro.au, Sherry Xu xiwei.xu@data61.csiro.au, Jiangshan Yu jiangshan.yu@monash.edu, "ERC-5521: Referable NFT [DRAFT]," Ethereum Improvement Proposals, no. 5521, August 2022. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-5521.

Conclusion

This article covered ERC5521, a proposal for representing reference relationships between ERC721 NFTs. I hope you found it useful.

If you have any questions, feel free to contact me via Twitter DM.

Twitter @cardene777

I also publish on other platforms, which you can find below.

https://chaldene.net/