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 ERC8034, a proposal for automatically distributing royalties to creators, collaborators, and owners of referenced NFTs in stages based on a directed acyclic graph (DAG) of NFT references.

The explanation follows the material linked below.

I have also written about various EIPs, BIPs, SLIPs, CAIPs, ENSIPs, RFCs, and ACPs.

Overview

ERC8034 is a standalone royalty distribution standard designed for referable NFTs (rNFTs) introduced by ERC5521.

For more on ERC5521, see the following article.

[ERC5521] Representing Reference Relationships Between ERC721 NFTs

The existing NFT royalty standard, ERC2981, allows only one recipient per NFT and does not account for references between NFTs.

For more on ERC2981, see the following article.

[ERC2981] Does ERC2981 Enforce NFT Royalties? Understanding How It Works

ERC8034 is designed to address these limitations. rNFTs form a network known as a directed acyclic graph (DAG). One NFT can reference another NFT, which can in turn reference yet another. The proposal distributes royalties in stages along these reference relationships. Multiple recipients, such as creators and collaborators, can be assigned to a single NFT, and a portion of the royalty also flows automatically to the owners of referenced NFTs.

The following figure illustrates the DAG formed by rNFTs.

DAG structure of rNFTs

The proposal operates independently of ERC2981. Although it is not tied to a token standard, in practice it targets ERC5521 rNFTs and relies on ERC721 ownership semantics.

For more on ERC721, see the following article.

[ERC721] An Introduction to ERC721

Motivation

Limitations of existing royalty standards

ERC2981 is widely used as a standard for automatically calculating royalties on secondary NFT sales. However, its design treats an NFT as an independent work and has the following limitations.

Because it permits only one recipient, even NFTs jointly created by several creators can specify only one royalty recipient address. Creative work often involves multiple contributors, including illustrators, musicians, and programmers, yet there was no way to distribute royalties directly to all of them.

A more fundamental limitation is the inability to account for relationships between NFTs. With ERC5521 rNFTs, one NFT can reference another, forming a DAG. For example, if an artwork is inspired by an earlier work, that reference can be represented on-chain. However, ERC2981 has no mechanism for propagating royalties along that reference chain.

How the proposal addresses these limitations

ERC8034 addresses these problems through the following mechanisms.

A single NFT can have multiple recipients, each with an individual royalty rate. This allows royalties to reflect contributions, such as 3% for the creator and 2% for a collaborator.

The proposal introduces royalty propagation based on references. Owners of NFTs referenced by the sold NFT automatically receive a portion of the royalties (2% by default). Propagation is controlled by the referenceDepth parameter, stopping at the specified depth rather than following the chain indefinitely.

Royalty configurations are stored on-chain, so anyone can inspect them transparently. Off-chain configuration using EIP712 typed signatures is also supported, allowing flexible operation while reducing gas costs.

For more on EIP712, see the following article.

[EIP712] Hashing and Signing Typed Structured Data

Interface detection through ERC165's supportsInterface also allows marketplaces and wallets to detect support for the standard automatically.

For more on ERC165, see the following article.

[ERC165] Checking Whether a Contract Supports a Specific Interface

The following diagram compares ERC2981 and ERC8034.

Comparison of ERC2981 and ERC8034

Specification

Interface definition

The core functionality of ERC8034 is defined in the IRNFTRoyalty interface. The interface inherits ERC165, enabling detection through supportsInterface.

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

interface IRNFTRoyalty is ERC165 {
    struct RoyaltyInfo {
        address recipient;
        uint256 royaltyAmount;
    }

    struct ReferenceRoyalty {
        RoyaltyInfo[] royaltyInfos;
        uint256 referenceDepth;
    }

    event ReferenceRoyaltiesPaid(
        address indexed rNFTContract,
        uint256 indexed tokenId,
        address indexed buyer,
        address marketplace,
        ReferenceRoyalty royalties
    );

    function getReferenceRoyaltyInfo(
        address rNFTContract,
        uint256 tokenId,
        uint256 salePrice
    ) external view returns (ReferenceRoyalty memory royalties);

    function getReferenceRoyaltyInfo(
        address rNFTContract,
        uint256 tokenId
    ) external view returns (ReferenceRoyalty memory royalties);

    function setReferenceRoyalty(
        address rNFTContract,
        uint256 tokenId,
        address[] memory recipients,
        uint256[] memory royaltyFractions,
        uint256 referenceDepth
    ) external;

    function setReferenceRoyalty(
        address rNFTContract,
        uint256 tokenId,
        address[] memory recipients,
        uint256[] memory royaltyFractions,
        uint256 referenceDepth,
        address signer,
        uint256 deadline,
        bytes calldata signature
    ) external;

    function supportsReferenceRoyalties() external view returns (bool);

    function royaltyNonce(
        address signer,
        address rNFTContract,
        uint256 tokenId
    ) external view returns (uint256);
}

The interface comprises three main groups of functions. These are royalty queries (two overloads of getReferenceRoyaltyInfo), royalty configuration (two overloads of setReferenceRoyalty), and feature detection (supportsReferenceRoyalties). royaltyNonce queries the nonce used to prevent replay of signature-based configuration.

Structs

RoyaltyInfo

javascript
struct RoyaltyInfo {
    address recipient;
    uint256 royaltyAmount;
}

This struct represents a royalty recipient and the corresponding amount as a pair.

Field Type Description
recipient address The address receiving royalties. It may be the creator, a collaborator, or the owner of a referenced NFT.
royaltyAmount uint256 The royalty amount. If salePrice is passed to getReferenceRoyaltyInfo, this is an actual amount in wei; otherwise it is expressed in basis points (100 = 1%).

A key design detail is that the unit of royaltyAmount changes depending on the function overload. When a sale price is supplied, the function returns an amount in wei that the marketplace can use directly for payment. Without a sale price, it returns the configured royalty rate in basis points, making the configuration transparent to inspect.

ReferenceRoyalty

javascript
struct ReferenceRoyalty {
    RoyaltyInfo[] royaltyInfos;
    uint256 referenceDepth;
}

This struct represents the overall royalty allocation for a single NFT.

Field Type Description
royaltyInfos RoyaltyInfo[] An array of royalty recipients, including primary-level recipients (creators and collaborators) and owners of referenced NFTs.
referenceDepth uint256 Maximum depth of royalty propagation through the DAG. Royalties do not propagate to references beyond this depth. The recommended maximum is 3.

The royaltyInfos array includes not only directly configured recipients but also owners of references calculated by traversing the DAG. Reading this single struct therefore provides an overview of who should receive how much when an NFT is sold.

Functions

getReferenceRoyaltyInfo

This function has two overloads. First, the version that takes a sale price.

javascript
function getReferenceRoyaltyInfo(
    address rNFTContract,
    uint256 tokenId,
    uint256 salePrice
) external view returns (ReferenceRoyalty memory royalties);

Marketplaces call this function when processing a secondary NFT sale. It calculates and returns the payment amount for each recipient in wei based on the specified sale price.

For example, with a sale price of 100 ETH (= 100,000,000,000,000,000,000 wei) and a primary royalty of 5% (3% for the creator and 2% for a collaborator), the calculated amounts are 3 ETH for the creator and 2 ETH for the collaborator. If referenced NFTs exist and referenceDepth is at least 1, the result also includes amounts allocated to their owners.

Parameter Type Description
rNFTContract address The address of the rNFT contract. Specify a contract implementing ERC5521.
tokenId uint256 The token ID of the NFT whose royalties are being queried.
salePrice uint256 Sale price of the NFT in wei. Passing 0 returns a royalty amount of 0 for every recipient.
  • Return value

ReferenceRoyalty: A struct containing each recipient's address and payment amount in wei, along with referenceDepth. The marketplace uses this information to transfer a portion of the sale proceeds to each recipient.

Version without a sale price

Next is the version that does not take a sale price.

javascript
function getReferenceRoyaltyInfo(
    address rNFTContract,
    uint256 tokenId
) external view returns (ReferenceRoyalty memory royalties);

This function makes royalty settings transparent to inspect. It returns the configured royalty rates in basis points (100 = 1%) independently of the sale price.

It can be used to display royalty information in a marketplace UI or inspect the royalty settings before a purchase. Use the overload with a sale price to calculate actual payment amounts.

Parameter Type Description
rNFTContract address The address of the rNFT contract.
tokenId uint256 The token ID of the NFT whose royalties are being queried.
  • Return value

ReferenceRoyalty: A struct containing each recipient's address and royalty rate in basis points. An empty array is returned if royalties have not been configured.

setReferenceRoyalty

This function also has two overloads. First, the version for direct on-chain configuration.

javascript
function setReferenceRoyalty(
    address rNFTContract,
    uint256 tokenId,
    address[] memory recipients,
    uint256[] memory royaltyFractions,
    uint256 referenceDepth
) external;

This function configures rNFT royalties directly on-chain. Only addresses holding CONFIGURATOR_ROLE can call it.

Parameter Type Description
rNFTContract address Address of the target rNFT contract. The zero address is not allowed.
tokenId uint256 The token ID for which royalties are configured.
recipients address[] Array of primary-level royalty recipient addresses, with at most 64 entries. No entry may be the zero address.
royaltyFractions uint256[] Array of royalty rates in basis points. Its length must match recipients, and the total is limited to 1,000 bps (10%).
referenceDepth uint256 Maximum depth of royalty propagation through the DAG. A limit of 3 or less is recommended.

For example, to configure 300 bps (3%) for the creator, 200 bps (2%) for a collaborator, and a reference depth of 2, pass two addresses in recipients, [300, 200] in royaltyFractions, and 2 in referenceDepth.

Signature-based version

Next is the version using an EIP712 signature for off-chain approval.

javascript
function setReferenceRoyalty(
    address rNFTContract,
    uint256 tokenId,
    address[] memory recipients,
    uint256[] memory royaltyFractions,
    uint256 referenceDepth,
    address signer,
    uint256 deadline,
    bytes calldata signature
) external;

This function applies a royalty configuration approved off-chain through an EIP712 typed structured data signature. A relayer can submit the transaction, so the signer does not need to pay the gas fee.

Parameter Type Description
rNFTContract address Address of the target rNFT contract.
tokenId uint256 The token ID for which royalties are configured.
recipients address[] Array of primary-level royalty recipient addresses.
royaltyFractions uint256[] Array of royalty rates in basis points.
referenceDepth uint256 Maximum depth of royalty propagation through the DAG.
signer address The signing address. It must hold CONFIGURATOR_ROLE or be the address returned by ownerOf for the target token.
deadline uint256 Signature expiration time (Unix timestamp). The signature is rejected if block.timestamp exceeds this value.
signature bytes EIP712-compliant signature data.

To prevent signature replay attacks, a nonce is maintained for each combination of signer, rNFT contract, and token ID. Successful signature verification increments the nonce, preventing reuse of the same signature.

The following diagram shows the overall sequence of signature-based configuration.

Sequence diagram for EIP712 signature-based configuration

Typed data used for signing
javascript
SetReferenceRoyalty(
    address rNFTContract,
    uint256 tokenId,
    bytes32 recipientsHash,
    bytes32 royaltyFractionsHash,
    uint256 referenceDepth,
    address signer,
    uint256 deadline,
    uint256 nonce
)

recipientsHash and royaltyFractionsHash are calculated with keccak256(abi.encode(recipients)) and keccak256(abi.encode(royaltyFractions)), respectively. Hashing the arrays keeps the signed data at a fixed size while allowing tampering to be detected.

The following values are recommended for the EIP712 domain.

Field Value
name "RNFTRoyalty"
version "2"
chainId ID of the deployment chain
verifyingContract Address of the royalty contract itself

supportsReferenceRoyalties

javascript
function supportsReferenceRoyalties() external view returns (bool);

This simple function indicates whether the contract implements the proposal. It always returns true. However, feature detection is designed to rely on ERC165's supportsInterface.

royaltyNonce

javascript
function royaltyNonce(
    address signer,
    address rNFTContract,
    uint256 tokenId
) external view returns (uint256);

This function queries the current nonce used for signature-based configuration. When generating an off-chain signature, use this function to check the nonce before including it in the data to be signed.

Parameter Type Description
signer address The signer address whose nonce is being queried.
rNFTContract address Address of the target rNFT contract.
tokenId uint256 The target token ID.
  • Return value

uint256: The current nonce, incremented by one each time signature-based setReferenceRoyalty succeeds.

Events

ReferenceRoyaltiesPaid

javascript
event ReferenceRoyaltiesPaid(
    address indexed rNFTContract,
    uint256 indexed tokenId,
    address indexed buyer,
    address marketplace,
    ReferenceRoyalty royalties
);

This event is emitted when royalties are paid. The marketplace records it by calling recordRoyaltyPayment.

Parameter Type indexed Description
rNFTContract address yes Address of the rNFT contract for which royalties are paid.
tokenId uint256 yes Token ID of the sold NFT.
buyer address yes Address of the NFT buyer.
marketplace address no Address of the marketplace that processed the royalty payment (msg.sender).
royalties ReferenceRoyalty no Details of the royalties paid. royaltyAmount is in wei.

This event allows royalty payment history to be tracked on-chain. Indexing the rNFT contract, token ID, and buyer enables efficient searches for royalty payments associated with a particular NFT or buyer.

ERC165 support

A contract implementing the proposal must return true from supportsInterface for type(IRNFTRoyalty).interfaceId. If the contract also inherits other interfaces, such as AccessControl, forwarding parent interface detection through super.supportsInterface(interfaceId) is recommended.

javascript
function supportsInterface(bytes4 interfaceId)
    public
    view
    override(AccessControl, IERC165)
    returns (bool)
{
    return
        interfaceId == type(IRNFTRoyalty).interfaceId ||
        super.supportsInterface(interfaceId);
}

Marketplaces can automatically detect support for rNFT royalties by performing this interface check before processing an NFT sale.

Royalty distribution model

The proposal uses a two-tier distribution model: primary royalties and reference royalties. This two-tier structure is the most significant difference from ERC2981.

Primary royalties

These are royalties paid to recipients configured directly on the NFT, such as creators and collaborators. They are configured through recipients and royaltyFractions in setReferenceRoyalty. For example, 300 bps (3%) can be assigned to the creator and 200 bps (2%) to a collaborator, up to a combined maximum of 1,000 bps (10%).

Reference royalties

These royalties propagate to owners of referenced NFTs in the DAG. At each depth hop, REFERRED_ROYALTY_FRACTION (200 bps = 2% by default) is carved out of the primary royalty and distributed to the referenced NFTs at that depth. When there are multiple references, distribution is proportional to each NFT's configured royalty weight. If all weights are zero, distribution is equal.

Limits and parameters

Parameter Value Description
MAX_ROYALTY_FRACTION 1,000 bps (10%) Maximum combined royalty rate at the primary level.
REFERRED_ROYALTY_FRACTION 200 bps (2%) Royalty portion forwarded to references at each hop.
referenceDepth Maximum 3 (recommended) Maximum depth of royalty propagation through the DAG. Limited to 3 or less to control gas costs.
MAX_RECIPIENTS 64 Maximum number of primary recipients that can be configured for a single NFT.
MAX_CHAIN_STEPS 32 Maximum number of DAG traversal steps, acting as a safeguard against infinite loops.

Worked example

Consider token ID 1 of contract 0xABC being sold for 100 ETH. The NFT has the following configuration.

  • Total primary royalty of 5% (3% for the creator, 2% for a collaborator)
  • referenceDepth = 2
  • Two referenced NFTs at depth 1 (Token A and Token B, with equal weights)

Royalty distribution flow for a 100 ETH sale

Without a sale price (querying basis points), getReferenceRoyaltyInfo(0xABC, 1) returns the following.

Recipient royaltyAmount (bps) Description
Creator 300 3% primary royalty
Collaborator 200 2% primary royalty
Token A owner 100 Half of the 2% reference royalty
Token B owner 100 Half of the 2% reference royalty

With a sale price of 100 ETH, getReferenceRoyaltyInfo(0xABC, 1, 100 ether) returns the following.

Recipient royaltyAmount (ETH) Calculation
Creator 3 ETH 100 ETH × 3%
Collaborator 2 ETH 100 ETH × 2%
Token A owner 1 ETH 100 ETH × 2% ÷ 2
Token B owner 1 ETH 100 ETH × 2% ÷ 2

A total of 7 ETH (7%) is distributed as royalties. In addition to the primary-level 5%, a 2% reference royalty flows to the referenced NFT owners. Token C receives no royalty because propagation stops at referenceDepth = 2.

Rationale

Why fixed-rate royalty queries matter

The overload of getReferenceRoyaltyInfo without a sale price is designed to provide royalty transparency. Marketplaces can use it to display an NFT's royalty settings in the UI or verify royalty rates before purchase. Since it is independent of sale price, the configuration can be queried at any time.

Rationale for multiple recipients

While ERC2981 uses a simple one-to-one model, this proposal adopts a one-to-many model. This reflects the collaborative nature of much real-world creative work. Storing RoyaltyInfo as an array allows royalties to be distributed directly to all project contributors.

Why there is a single depth limit

Managing referenceDepth as a single value balances simple configuration with controlled gas costs. Different settings could be assigned to each depth, but this would make configuration more complex and increase gas costs. The recommended maximum of 3 was chosen as a practical reference-chain depth that can remain within the gas limit.

Benefits of a standalone design

The proposal is designed as a standalone standard that does not depend on ERC2981. It avoids conflicts with contracts that already implement ERC2981 and provides a royalty mechanism specialized for ERC5521 rNFTs. Marketplaces can detect the interface through ERC165 to determine whether it is supported.

Voluntary royalties

Royalty payments are voluntary rather than enforced. This reflects how marketplaces operate today. Improving the transparency of royalty configurations gives marketplaces an incentive to respect royalty allocations voluntarily.

Backward compatibility

Relationship to existing standards

Standard Relationship Details
ERC2981 Independent The proposal does not depend on ERC2981. Both can be implemented together, but their royalty calculation logic is entirely separate.
ERC5521 Prerequisite Royalties propagate using the rNFT DAG (referringOf/referredOf). Reference royalties do not work for contracts that do not implement ERC5521.
ERC721 Indirect dependency ownerOf retrieves the owner address of a referenced NFT. The dependency is indirect because ERC5521 builds on ERC721.
EIP712 Optional Used for signature-based configuration; unnecessary if only direct configuration is used.
ERC165 Required supportsInterface must be implemented for interface detection.

Marketplace integration

A marketplace can support the proposal as follows.

  1. Check support for rNFT royalties with ERC165's supportsInterface(type(IRNFTRoyalty).interfaceId).
  2. If supported, call getReferenceRoyaltyInfo (with a sale price) to calculate royalty amounts.
  3. Transfer the calculated amounts to each recipient.
  4. Call recordRoyaltyPayment to record the royalty payment on-chain.

Optionally, with signature-based setReferenceRoyalty, a marketplace can apply a royalty configuration signed off-chain by the NFT owner on their behalf.

Reference implementation

The full ERC8034 reference implementation follows. It uses OpenZeppelin's AccessControl, EIP712, ECDSA, and ReentrancyGuard.

contracts/RNFTRoyalty.sol
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import "./IRNFTRoyalty.sol";

interface IERC_5521 is IERC165 {
    function setNode(uint256 tokenId, address[] memory addresses, 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 supportsInterface(bytes4 interfaceId) external view returns (bool);
}

contract RNFTRoyalty is IRNFTRoyalty, AccessControl, EIP712, ReentrancyGuard {
    using ECDSA for bytes32;

    bytes32 public constant CONFIGURATOR_ROLE = keccak256("CONFIGURATOR_ROLE");
    uint256 private constant MAX_ROYALTY_FRACTION = 1000;
    uint256 private constant REFERRED_ROYALTY_FRACTION = 200;
    uint256 private constant MAX_CHAIN_STEPS = 32;
    uint256 private constant MAX_RECIPIENTS = 64;

    mapping(address => mapping(uint256 => ReferenceRoyalty)) private _royalties;
    event ReferenceRoyaltyConfigured(
        address indexed rNFTContract,
        uint256 indexed tokenId,
        address indexed setter,
        address[] recipients,
        uint256[] royaltyFractions,
        uint256 referenceDepth,
        bool viaSignature
    );

    bytes32 private constant _SET_TYPEHASH =
        keccak256("SetReferenceRoyalty(address rNFTContract,uint256 tokenId,bytes32 recipientsHash,bytes32 royaltyFractionsHash,uint256 referenceDepth,address signer,uint256 deadline,uint256 nonce)");
    mapping(address => mapping(address => mapping(uint256 => uint256))) private _sigNonces;

    constructor() EIP712("RNFTRoyalty", "2") {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(CONFIGURATOR_ROLE, msg.sender);
    }

    function royaltyNonce(address signer, address rNFTContract, uint256 tokenId)
        external
        view
        returns (uint256)
    {
        return _sigNonces[signer][rNFTContract][tokenId];
    }

    function setReferenceRoyalty(
        address rNFTContract,
        uint256 tokenId,
        address[] calldata recipients,
        uint256[] calldata royaltyFractions,
        uint256 referenceDepth
    ) external onlyRole(CONFIGURATOR_ROLE) {
        _configureRoyalty(rNFTContract, tokenId, recipients, royaltyFractions, referenceDepth);
        emit ReferenceRoyaltyConfigured(
            rNFTContract, tokenId, msg.sender,
            recipients, royaltyFractions, referenceDepth, false
        );
    }

    function setReferenceRoyalty(
        address rNFTContract,
        uint256 tokenId,
        address[] calldata recipients,
        uint256[] calldata royaltyFractions,
        uint256 referenceDepth,
        address signer,
        uint256 deadline,
        bytes calldata signature
    ) external nonReentrant {
        _checkParams(rNFTContract, recipients, royaltyFractions, referenceDepth);

        bytes32 recipientsHash = keccak256(abi.encode(recipients));
        bytes32 fractionsHash  = keccak256(abi.encode(royaltyFractions));
        require(signer != address(0), "Invalid signer");
        uint256 nonce = _sigNonces[signer][rNFTContract][tokenId];

        require(block.timestamp <= deadline, "Signature expired");

        bytes32 structHash = keccak256(
            abi.encode(
                _SET_TYPEHASH,
                rNFTContract, tokenId,
                recipientsHash, fractionsHash,
                referenceDepth, signer, deadline, nonce
            )
        );

        bytes32 digest = _hashTypedDataV4(structHash);
        address recovered = ECDSA.recover(digest, signature);
        require(recovered == signer && signer != address(0), "Invalid signature");

        bool authorized = hasRole(CONFIGURATOR_ROLE, signer);
        if (!authorized) {
            address owner = _safeOwnerOf(IERC721(rNFTContract), tokenId);
            require(signer == owner, "Signer not authorized");
        }

        _sigNonces[signer][rNFTContract][tokenId] = nonce + 1;

        _configureRoyalty(rNFTContract, tokenId, recipients, royaltyFractions, referenceDepth);
        emit ReferenceRoyaltyConfigured(
            rNFTContract, tokenId, signer,
            recipients, royaltyFractions, referenceDepth, true
        );
    }

    function getReferenceRoyaltyInfo(
        address rNFTContract,
        uint256 tokenId,
        uint256 salePrice
    ) external view returns (ReferenceRoyalty memory royalties) {
        royalties = _royalties[rNFTContract][tokenId];
        if (salePrice == 0) {
            uint256 len = royalties.royaltyInfos.length;
            if (len == 0) return royalties;
            RoyaltyInfo[] memory zeroed = new RoyaltyInfo[](len);
            for (uint256 i = 0; i < len; i++) {
                zeroed[i] = RoyaltyInfo(royalties.royaltyInfos[i].recipient, 0);
            }
            royalties.royaltyInfos = zeroed;
            return royalties;
        }
        RoyaltyInfo[] memory chainRoyalties = _calculateChainRoyalties(rNFTContract, tokenId, salePrice);
        royalties.royaltyInfos = chainRoyalties;
        return royalties;
    }

    function getReferenceRoyaltyInfo(
        address rNFTContract,
        uint256 tokenId
    ) external view returns (ReferenceRoyalty memory royalties) {
        royalties = _royalties[rNFTContract][tokenId];
        if (royalties.royaltyInfos.length == 0) return royalties;
        RoyaltyInfo[] memory bpsRoyalties = _calculateChainRoyalties(rNFTContract, tokenId, 0);
        royalties.royaltyInfos = bpsRoyalties;
        return royalties;
    }

    function supportsReferenceRoyalties() external pure returns (bool) {
        return true;
    }

    function supportsInterface(bytes4 interfaceId)
        public
        view
        override(AccessControl, IERC165)
        returns (bool)
    {
        return
            interfaceId == type(IRNFTRoyalty).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    function _checkParams(
        address rNFTContract,
        address[] calldata recipients,
        uint256[] calldata royaltyFractions,
        uint256 referenceDepth
    ) internal pure {
        require(rNFTContract != address(0), "Invalid contract");
        require(recipients.length == royaltyFractions.length, "Length mismatch");
        require(recipients.length <= MAX_RECIPIENTS, "Too many recipients");
        require(referenceDepth <= 3, "Depth too high");
        for (uint256 i = 0; i < recipients.length; ++i) {
            require(recipients[i] != address(0), "Zero recipient");
        }
    }

    function _configureRoyalty(
        address rNFTContract,
        uint256 tokenId,
        address[] calldata recipients,
        uint256[] calldata royaltyFractions,
        uint256 referenceDepth
    ) internal {
        uint256 totalFraction = 0;
        for (uint256 i = 0; i < royaltyFractions.length; i++) {
            totalFraction += royaltyFractions[i];
        }
        require(totalFraction <= MAX_ROYALTY_FRACTION, "Royalty cap exceeded");

        ReferenceRoyalty memory config;
        config.referenceDepth = referenceDepth;
        config.royaltyInfos = new RoyaltyInfo[](recipients.length);

        for (uint256 i = 0; i < recipients.length; i++) {
            config.royaltyInfos[i] = RoyaltyInfo(recipients[i], royaltyFractions[i]);
        }

        _royalties[rNFTContract][tokenId] = config;
    }

    function _safeOwnerOf(IERC721 rNFT, uint256 tokenId) internal view returns (address) {
        address owner = rNFT.ownerOf(tokenId);
        require(owner != address(0), "No owner");
        return owner;
    }

    function _calculateChainRoyalties(
        address rNFTContract,
        uint256 tokenId,
        uint256 salePrice
    ) internal view returns (RoyaltyInfo[] memory) {
        ReferenceRoyalty memory currentRoyalty = _royalties[rNFTContract][tokenId];
        if (currentRoyalty.royaltyInfos.length == 0) {
            return new RoyaltyInfo[](0);
        }

        RoyaltyInfo[] memory staged = new RoyaltyInfo[](MAX_CHAIN_STEPS * 32 + 32);
        uint256 count = 0;

        uint256 totalShare = _sumShares(currentRoyalty);
        (uint256 netPrimary, uint256 remainder) = _splitRoyalty(totalShare, salePrice, currentRoyalty.referenceDepth > 0);
        count = _appendDistribution(staged, count, currentRoyalty, netPrimary);

        if (remainder == 0) {
            return _shrink(staged, count);
        }

        uint256 maxItems = MAX_CHAIN_STEPS * 32 + 32;
        address[] memory curContracts = new address[](maxItems);
        uint256[] memory curIds = new uint256[](maxItems);
        uint256[] memory curAmts = new uint256[](maxItems);
        uint256[] memory curDepths = new uint256[](maxItems);
        uint256 curCount = 0;
        if (remainder > 0 && currentRoyalty.referenceDepth > 0) {
            curContracts[0] = rNFTContract;
            curIds[0] = tokenId;
            curAmts[0] = remainder;
            curDepths[0] = currentRoyalty.referenceDepth;
            curCount = 1;
        }

        address[] memory processedContracts = new address[](maxItems);
        uint256[] memory processed = new uint256[](maxItems);
        uint256 processedCount = 0;

        while (curCount > 0) {
            address[] memory nextContracts = new address[](maxItems);
            uint256[] memory nextIds = new uint256[](maxItems);
            uint256[] memory nextAmts = new uint256[](maxItems);
            uint256[] memory nextDepths = new uint256[](maxItems);
            uint256 nextCount = 0;

            for (uint256 iL = 0; iL < curCount; iL++) {
                address curContract = curContracts[iL];
                uint256 curId = curIds[iL];
                uint256 amt = curAmts[iL];
                uint256 depth = curDepths[iL];
                if (amt == 0) continue;

                IERC_5521 curRNFT = IERC_5521(curContract);
                IERC721 curRNFT721 = IERC721(curContract);

                bool seen = false;
                for (uint256 p = 0; p < processedCount; p++) {
                    if (processed[p] == curId && processedContracts[p] == curContract) {
                        seen = true;
                        break;
                    }
                }
                if (seen) {
                    address cycOwner = _safeOwnerOf(curRNFT721, curId);
                    staged[count++] = RoyaltyInfo(cycOwner, amt);
                    continue;
                }

                uint256 maxChildren = 32;
                address[] memory childContracts = new address[](maxChildren);
                uint256[] memory childIds = new uint256[](maxChildren);
                uint256 children = _collectReferring(curRNFT, curContract, curId, childContracts, childIds);
                if (depth == 0 || children == 0) {
                    address fallbackOwner = _safeOwnerOf(curRNFT721, curId);
                    staged[count++] = RoyaltyInfo(fallbackOwner, amt);
                    processedContracts[processedCount] = curContract;
                    processed[processedCount++] = curId;
                    continue;
                }

                uint256 keepBase = (amt * (10_000 - REFERRED_ROYALTY_FRACTION)) / 10_000;
                uint256 passBase = amt - keepBase;

                uint256[] memory childWeights = new uint256[](maxChildren);
                ReferenceRoyalty[] memory childConfigs = new ReferenceRoyalty[](maxChildren);
                uint256 sumWeights = 0;

                for (uint256 j = 0; j < children; j++) {
                    address childContract = childContracts[j];
                    uint256 cid = childIds[j];
                    ReferenceRoyalty memory cfg = _royalties[childContract][cid];
                    childConfigs[j] = cfg;
                    if (cfg.royaltyInfos.length > 0) {
                        uint256 w = _sumShares(cfg);
                        childWeights[j] = w;
                        sumWeights += w;
                    }
                }

                if (sumWeights == 0) {
                    uint256 each = amt / children;
                    uint256 rem = amt - (each * children);
                    for (uint256 j = 0; j < children; j++) {
                        address ow = _safeOwnerOf(IERC721(childContracts[j]), childIds[j]);
                        uint256 share = each + (j == children - 1 ? rem : 0);
                        staged[count++] = RoyaltyInfo(ow, share);
                    }
                    processedContracts[processedCount] = curContract;
                    processed[processedCount++] = curId;
                    continue;
                }

                uint256 passDistributed = 0;
                uint256 lastWeightedIdx = 0;
                uint256[] memory keepShares = new uint256[](children);
                uint256[] memory passShares = new uint256[](children);
                for (uint256 j = 0; j < children; j++) {
                    if (childWeights[j] == 0) continue;
                    lastWeightedIdx = j;
                    uint256 kShare = (keepBase * childWeights[j]) / sumWeights;
                    uint256 pShare = (passBase * childWeights[j]) / sumWeights;
                    keepShares[j] = kShare;
                    passShares[j] = pShare;
                    passDistributed += pShare;
                }
                uint256 passRemainder = passBase - passDistributed;
                if (passRemainder > 0) {
                    passShares[lastWeightedIdx] += passRemainder;
                }
                uint256 keepDistributed = 0;
                for (uint256 j2 = 0; j2 < children; j2++) {
                    keepDistributed += keepShares[j2];
                }
                uint256 keepRemainder = keepBase - keepDistributed;
                if (keepRemainder > 0) {
                    keepShares[lastWeightedIdx] += keepRemainder;
                }

                for (uint256 j = 0; j < children; j++) {
                    if (childWeights[j] == 0) continue;
                    uint256 kShare = keepShares[j];
                    uint256 pShare = passShares[j];
                    ReferenceRoyalty memory cfgj = childConfigs[j];
                    uint256 cid2 = childIds[j];
                    address childContract = childContracts[j];
                    uint256 nextDepth = depth > 0 ? depth - 1 : 0;
                    if (nextDepth == 0) {
                        count = _appendDistribution(staged, count, cfgj, kShare + pShare);
                    } else {
                        if (kShare > 0) {
                            count = _appendDistribution(staged, count, cfgj, kShare);
                        }
                        if (pShare > 0) {
                            bool merged = false;
                            for (uint256 nx = 0; nx < nextCount; nx++) {
                                if (nextIds[nx] == cid2 && nextContracts[nx] == childContract) {
                                    nextAmts[nx] += pShare;
                                    if (nextDepth > nextDepths[nx]) {
                                        nextDepths[nx] = nextDepth;
                                    }
                                    merged = true;
                                    break;
                                }
                            }
                            if (!merged) {
                                nextContracts[nextCount] = childContract;
                                nextIds[nextCount] = cid2;
                                nextAmts[nextCount] = pShare;
                                nextDepths[nextCount] = nextDepth;
                                nextCount++;
                            }
                        }
                    }
                }

                processedContracts[processedCount] = curContract;
                processed[processedCount++] = curId;
            }

            for (uint256 k = 0; k < nextCount; k++) {
                curContracts[k] = nextContracts[k];
                curIds[k] = nextIds[k];
                curAmts[k] = nextAmts[k];
                curDepths[k] = nextDepths[k];
            }
            curCount = nextCount;
        }

        return _shrink(staged, count);
    }

    function _splitRoyalty(uint256 totalRate, uint256 salePrice, bool canPropagate)
        internal
        pure
        returns (uint256 netPrimary, uint256 forwardedAmount)
    {
        if (totalRate == 0) {
            return (0, 0);
        }
        if (!canPropagate) {
            if (salePrice == 0) {
                return (totalRate, 0);
            }
            return ((salePrice * totalRate) / 10_000, 0);
        }
        if (salePrice == 0) {
            if (totalRate <= REFERRED_ROYALTY_FRACTION) {
                return (0, totalRate);
            }
            return (totalRate - REFERRED_ROYALTY_FRACTION, REFERRED_ROYALTY_FRACTION);
        }
        uint256 gross = (salePrice * totalRate) / 10_000;
        uint256 forwarded = (salePrice * REFERRED_ROYALTY_FRACTION) / 10_000;
        if (forwarded > gross) {
            forwarded = gross;
        }
        return (gross > forwarded ? gross - forwarded : 0, forwarded);
    }

    function _sumShares(ReferenceRoyalty memory config) internal pure returns (uint256 total) {
        for (uint256 i = 0; i < config.royaltyInfos.length; i++) {
            total += config.royaltyInfos[i].royaltyAmount;
        }
    }

    function _collectReferring(
        IERC_5521 rNFT,
        address rNFTContract,
        uint256 tokenId,
        address[] memory childContracts,
        uint256[] memory childIds
    ) internal view returns (uint256 childCount) {
        (address[] memory refContracts, uint256[][] memory refTokenIds) =
            rNFT.referringOf(rNFTContract, tokenId);

        uint256 maxChildren = childIds.length;
        uint256 listLen = refContracts.length;
        if (refTokenIds.length < listLen) {
            listLen = refTokenIds.length;
        }

        for (uint256 i = 0; i < listLen && childCount < maxChildren; i++) {
            uint256[] memory ids = refTokenIds[i];
            for (uint256 j = 0; j < ids.length && childCount < maxChildren; j++) {
                childContracts[childCount] = refContracts[i];
                childIds[childCount] = ids[j];
                childCount++;
            }
        }
    }

    function _appendDistribution(
        RoyaltyInfo[] memory staged,
        uint256 count,
        ReferenceRoyalty memory config,
        uint256 amount
    ) internal pure returns (uint256) {
        uint256 len = config.royaltyInfos.length;
        if (len == 0) {
            return count;
        }
        require(count + len <= staged.length, "royalty overflow");
        if (amount == 0) {
            for (uint256 i = 0; i < len; i++) {
                staged[count++] = RoyaltyInfo(config.royaltyInfos[i].recipient, 0);
            }
            return count;
        }
        uint256 totalShare = _sumShares(config);
        if (totalShare == 0) {
            staged[count++] = RoyaltyInfo(config.royaltyInfos[0].recipient, amount);
            for (uint256 i = 1; i < len; i++) {
                staged[count++] = RoyaltyInfo(config.royaltyInfos[i].recipient, 0);
            }
            return count;
        }
        uint256 remaining = amount;
        for (uint256 i = 0; i < len; i++) {
            uint256 share = config.royaltyInfos[i].royaltyAmount;
            if (share == 0) {
                staged[count++] = RoyaltyInfo(config.royaltyInfos[i].recipient, 0);
                continue;
            }
            uint256 portion = (amount * share) / totalShare;
            if (portion > remaining) {
                portion = remaining;
            }
            remaining -= portion;
            staged[count++] = RoyaltyInfo(config.royaltyInfos[i].recipient, portion);
        }
        if (remaining > 0) {
            staged[count - 1].royaltyAmount += remaining;
        }
        return count;
    }

    function _shrink(RoyaltyInfo[] memory staged, uint256 count)
        internal
        pure
        returns (RoyaltyInfo[] memory out)
    {
        out = new RoyaltyInfo[](count);
        for (uint256 i = 0; i < count; i++) {
            out[i] = staged[i];
        }
    }

    function recordRoyaltyPayment(
        address rNFTContract,
        uint256 tokenId,
        address buyer,
        ReferenceRoyalty memory royalties
    ) external {
        emit ReferenceRoyaltiesPaid(rNFTContract, tokenId, buyer, msg.sender, royalties);
    }
}

The reference implementation uses breadth-first search (BFS) to traverse the DAG. The core function is _calculateChainRoyalties. In addition to calculating primary royalties, it follows reference chains in stages based on referenceDepth and calculates the allocations at each depth.

Implementation details

The _splitRoyalty function separates primary royalties from reference royalties. It carves REFERRED_ROYALTY_FRACTION (200 bps) out of the total primary royalty, forwards it to references, and distributes the remainder to primary recipients.

If BFS reaches the same NFT through multiple paths, the amounts are merged. This prevents duplicate payments within the DAG.

Cycle detection is also implemented. If traversal reaches an NFT that has already been processed, the amount is paid to that NFT's owner as a fallback, avoiding an infinite loop.

Security considerations

Access control

Direct calls to setReferenceRoyalty are restricted to addresses holding CONFIGURATOR_ROLE. Signature-based calls verify that the signer either holds CONFIGURATOR_ROLE or is the address returned by ownerOf for the target token. This prevents unauthorized addresses from tampering with royalty settings.

Primary royalty cap

The sum of primary-level royaltyFractions is limited to 1,000 bps (10%). This limit prevents excessive royalty settings from undermining the economics of NFT sales. Reference royalties are controlled separately through REFERRED_ROYALTY_FRACTION and referenceDepth.

Gas limit safeguards

referenceDepth is capped at 3 to keep the gas cost of DAG traversal predictable. MAX_CHAIN_STEPS (32) and MAX_RECIPIENTS (64) are also hard limits intended to prevent attacks that deliberately construct an enormous DAG to exhaust gas.

Signature replay prevention

An EIP712 signature includes a nonce maintained for each combination of signer, rNFT contract, and token ID. Because successful signature verification increments the nonce, the same signature cannot be reused. The deadline parameter also ensures expired signatures are rejected.

Reentrancy protection

Signature-based setReferenceRoyalty uses the nonReentrant modifier. This is intended to prevent a malicious rNFT contract from attempting a reentrancy attack during an ownerOf call.

Interface signaling

Implementations of supportsInterface are recommended to call super.supportsInterface(interfaceId) to correctly forward interface detection for parent contracts such as AccessControl. This allows marketplaces and wallets to detect supported interfaces accurately.

References

Conclusion

This article examined how ERC8034 automatically distributes royalties based on NFT reference relationships. What do you think of this approach?

Leveraging the DAG formed by ERC5521 rNFTs to distribute royalties to creators, collaborators, and referenced NFT owners offers a new model for the NFT creator economy. Practical features such as gas-efficient configuration through EIP712 signatures and transparent basis-point queries are also noteworthy.

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

Twitter @cardene777

I also publish articles on other platforms, so feel free to explore them.