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 covers ERC-5006, an extension to ERC-1155 that introduces a user role to separate NFT ownership from usage rights.

This explanation translates, summarizes and expands on the original proposal with assistance from ChatGPT.

See the following article for more on ERC-1155.

https://chaldene.net/erc1155

Motivation

Like ERC-721 tokens, ERC-1155 tokens have a wide range of potential use cases. For example, the address entitled to use a token may differ from its owner's address, as in a rental arrangement. Separate owner and user roles are useful here because a user must not be able to perform actions reserved for the owner, such as transferring an NFT.

Diagram illustrating separate NFT ownership and usage rights

The original Japanese edition's figures are reused throughout this article without translating their embedded labels.

See the following article for more on ERC-721.

https://chaldene.net/erc721

See the following article for more on ERC-1155.

https://chaldene.net/erc1155

Specification

javascript
// SPDX-License-Identifier: CC0-1.0

pragma solidity ^0.8.0;

interface IERC5006 {
    struct UserRecord {
        uint256 tokenId;
        address owner;
        uint64 amount;
        address user;
        uint64 expiry;
    }
    
    event CreateUserRecord(
        uint256 recordId,
        uint256 tokenId,
        uint64  amount,
        address owner,
        address user,
        uint64  expiry
    );

    event DeleteUserRecord(uint256 recordId);

    function usableBalanceOf(address account, uint256 tokenId)
        external
        view
        returns (uint256);

    function frozenBalanceOf(address account, uint256 tokenId)
        external
        view
        returns (uint256);

    function userRecordOf(uint256 recordId)
        external
        view
        returns (UserRecord memory);

    function createUserRecord(
        address owner,
        address user,
        uint256 tokenId,
        uint64 amount,
        uint64 expiry
    ) external returns (uint256);

    function deleteUserRecord(uint256 recordId) external;
}

ERC-5006 introduces a user role that separates the right to use a token from its ownership. An owner can therefore authorize a user to use the token for a limited period.

Diagram illustrating the ERC-5006 user role and time-limited usage

Structs

UserRecord

A struct representing a user record. Each record contains the following information.

  • tokenId
    • A uint256 value representing the token ID.
  • owner
    • An address value representing the token owner's address.
  • amount
    • A uint64 value representing the number of tokens the user may use.
  • user
    • An address value representing the address of the user entitled to use the tokens.
  • expiry
    • A uint64 value representing the expiration time of the usage rights, compared against the block timestamp.

Events

CreateUserRecord

Emitted when a new user record is created. The event indicates that the user has been granted permission to use some or all of the tokens identified by tokenId and owned by owner until expiry.

DeleteUserRecord

Emitted when the user record corresponding to a record ID is deleted.

Functions

usableBalanceOf

Returns the total usable balance associated with an account for the specified tokenId.

frozenBalanceOf

Returns the total frozen balance (the amount that cannot be used by the owner) for an account and the specified tokenId.

userRecordOf

Returns the user record corresponding to a given record ID.

createUserRecord

Authorizes a user to use some or all of the tokens identified by tokenId and owned by owner until expiry. A new user record is created if the required conditions are met.

deleteUserRecord

Allows an authorized caller to delete the user record corresponding to a particular record ID.

Additional notes

Clear allocation of rights

The two roles, owner and user, make it easier to manage what NFT (non-fungible token) lenders and borrowers are and are not allowed to do. For example, the owner may own the NFT while a separate user has the right to use it for a limited time. The owner can grant usage rights for a particular period, while rights reserved for the owner, such as selling or transferring the NFT, remain under the owner's control.

Straightforward third-party integration

The proposal enables third-party protocols to manage NFT usage rights without permission from the NFT issuer or application. Once a project adds the user role, other projects can use that role to implement their own transactions. For example, a PFP (profile picture) NFT implementing the standard could integrate with both a rental platform where a user can rent the NFT for 30 days and a platform where a user can use the NFT while purchasing ownership in installments. Neither integration requires permission from the original PFP project.

Backward compatibility

The extension is fully compatible with ERC-1155.

Test cases

The tests can be run using the following commands in a terminal.

text
cd ../assets/eip-5006
npm install
npx hardhat test
javascript
import { expect } from "chai";
import { ethers } from "hardhat";
import hre from "hardhat";

describe("Test 1155 User Role", function () {
    let alice, bob, carl;
    let contract;
    let expiry;

    async function checkRecord(rid,tokenId,amount,owner,user,expiry_) {
        let record = await contract.userRecordOf(rid);
            expect(record[0]).equals(tokenId,"tokenId");
            expect(record[1]).equals(owner,"owner");
            expect(record[2]).equals(amount,"amount");
            expect(record[3]).equals(user,"user");
            expect(record[4]).equals(expiry_,"expiry_");
    }

    beforeEach(async function () {
        [alice, bob, carl] = await ethers.getSigners();

        const ERC5006Demo = await ethers.getContractFactory("ERC5006Demo");

        contract = await ERC5006Demo.deploy("", 3);

        expiry = Math.floor(new Date().getTime() / 1000) + 3600;
    });

    

    describe("", function () {
        
        it("InterfaceId should equals 0xc26d96cc", async function () {
            expect(await contract.getInterfaceId()).equals("0xc26d96cc");
        });

        it("Should set user to bob success", async function () {

            await contract.mint(alice.address, 1, 100);

            await contract.createUserRecord(alice.address, bob.address, 1, 10, expiry);

            await checkRecord(1,1,10,alice.address,bob.address,expiry);

            expect(await contract.usableBalanceOf(bob.address, 1)).equals(10);

            expect(await contract.balanceOf(alice.address, 1)).equals(90);

            expect(await contract.frozenBalanceOf(alice.address, 1)).equals(10);

        });

        it("Should set user to bob fail", async function () {

            await contract.mint(alice.address, 1, 100);

            await contract.createUserRecord(alice.address, bob.address, 1, 10, expiry);
            await contract.createUserRecord(alice.address, bob.address, 1, 10, expiry);
            await contract.createUserRecord(alice.address, bob.address, 1, 10, expiry);
            await expect(contract.createUserRecord(alice.address, bob.address, 1, 10, expiry)).to.be.revertedWith("user cannot have more records");

        });

        it("Should set user to bob fail : balance is not enough", async function () {

            await contract.mint(alice.address, 1, 100);

            await expect(contract.createUserRecord(alice.address, bob.address, 1, 101, expiry)).to.be.revertedWith('ERC1155: insufficient balance for transfer');

        });

        it("Should set user to bob fail : only owner or approved", async function () {

            await contract.mint(alice.address, 1, 100);
            await contract.mint(carl.address, 1, 100);

            await expect(contract.createUserRecord(carl.address, bob.address, 1, 110, expiry)).to.be.revertedWith('only owner or approved');

        });

        it("Should deleteUserRecord success", async function () {

            await contract.mint(alice.address, 1, 100);

            await contract.createUserRecord(alice.address, bob.address, 1, 10, expiry);

            // await hre.network.provider.send("hardhat_mine", ["0x5a0", "0x3c"]);

            await contract.deleteUserRecord(1);

            await checkRecord(1,0,0,"0x0000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000",0);

            expect(await contract.usableBalanceOf(bob.address, 1)).equals(0);

            expect(await contract.balanceOf(alice.address, 1)).equals(100);

            expect(await contract.frozenBalanceOf(alice.address, 1)).equals(0);

        });


        it("bob should deleteUserRecord fail", async function () {

            await contract.mint(alice.address, 1, 100);

            await contract.createUserRecord(alice.address, bob.address, 1, 10, expiry);

            await expect(contract.connect(bob).deleteUserRecord(1)).to.be.revertedWith("only owner or approved");

        });


    });


});

Reference implementation

javascript
// SPDX-License-Identifier: CC0-1.0

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./IERC5006.sol";

contract ERC5006 is ERC1155, ERC1155Receiver, IERC5006 {
    using EnumerableSet for EnumerableSet.UintSet;
    mapping(uint256 => mapping(address => uint256)) private _frozens;
    mapping(uint256 => UserRecord) private _records;
    mapping(uint256 => mapping(address => EnumerableSet.UintSet))
        private _userRecordIds;
    uint256 _curRecordId;
    uint256 recordLimit;

    constructor(string memory uri_, uint256 recordLimit_) ERC1155(uri_) {
        recordLimit = recordLimit_;
    }

    function isOwnerOrApproved(address owner) public view returns (bool) {
        require(
            owner == msg.sender || isApprovedForAll(owner, msg.sender),
            "only owner or approved"
        );
        return true;
    }

    function usableBalanceOf(address account, uint256 tokenId)
        public
        view
        override
        returns (uint256 amount)
    {
        uint256[] memory recordIds = _userRecordIds[tokenId][account].values();
        for (uint256 i = 0; i < recordIds.length; i++) {
            if (block.timestamp <= _records[recordIds[i]].expiry) {
                amount += _records[recordIds[i]].amount;
            }
        }
    }

    function frozenBalanceOf(address account, uint256 tokenId)
        public
        view
        override
        returns (uint256)
    {
        return _frozens[tokenId][account];
    }

    function userRecordOf(uint256 recordId)
        public
        view
        override
        returns (UserRecord memory)
    {
        return _records[recordId];
    }

    function createUserRecord(
        address owner,
        address user,
        uint256 tokenId,
        uint64 amount,
        uint64 expiry
    ) public override returns (uint256) {
        require(isOwnerOrApproved(owner));
        require(user != address(0), "user cannot be the zero address");
        require(amount > 0, "amount must be greater than 0");
        require(expiry > block.timestamp, "expiry must after the block timestamp");
        require(
            _userRecordIds[tokenId][user].length() < recordLimit,
            "user cannot have more records"
        );
        _safeTransferFrom(owner, address(this), tokenId, amount, "");
        _frozens[tokenId][owner] += amount;
        _curRecordId++;
        _records[_curRecordId] = UserRecord(
            tokenId,
            owner,
            amount,
            user,
            expiry
        );
        _userRecordIds[tokenId][user].add(_curRecordId);
        emit CreateUserRecord(
            _curRecordId,
            tokenId,
            amount,
            owner,
            user,
            expiry
        );
        return _curRecordId;
    }

    function deleteUserRecord(uint256 recordId) public override {
        UserRecord storage _record = _records[recordId];
        require(isOwnerOrApproved(_record.owner));
        _safeTransferFrom(
            address(this),
            _record.owner,
            _record.tokenId,
            _record.amount,
            ""
        );
        _frozens[_record.tokenId][_record.owner] -= _record.amount;
        _userRecordIds[_record.tokenId][_record.user].remove(recordId);
        delete _records[recordId];
        emit DeleteUserRecord(recordId);
    }

    function supportsInterface(bytes4 interfaceId)
        public
        view
        override(ERC1155, ERC1155Receiver)
        returns (bool)
    {
        return
            interfaceId == type(IERC5006).interfaceId ||
            ERC1155.supportsInterface(interfaceId) ||
            ERC1155Receiver.supportsInterface(interfaceId);
    }

    function onERC1155Received(
        address operator,
        address from,
        uint256 tokenId,
        uint256 value,
        bytes calldata data
    ) external pure override returns (bytes4) {
        return IERC1155Receiver.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external pure override returns (bytes4) {
        return IERC1155Receiver.onERC1155BatchReceived.selector;
    }
}

Structs

UserRecord

A struct representing a user record. It stores information about the user's right to use the tokens, including the token ID, owner address, usable quantity, user address and expiration time.

Variables

_frozens

A mapping that tracks the quantity of frozen tokens for each account and token ID. It makes it possible to freeze (lock) tokens temporarily in connection with a user's usage rights.

_records

A mapping used to track user records. Each user record holds the information defined by the UserRecord struct. In the example implementation, this mapping is keyed by record ID, rather than token ID as stated in the original Japanese explanation.

_userRecordIds

A mapping that tracks the IDs of the user records associated with a user address and token ID. A set of IDs is maintained because a user can use tokens under multiple records.

_curRecordId

A variable tracking the current user record ID.

recordLimit

A variable specifying the maximum number of user records. Although the original explanation describes this as a per-user limit, the reference implementation applies it to each user and token ID pair.

Constructor

An initialization function executed when the contract is deployed. It takes a URI (Uniform Resource Identifier) and a maximum user record limit as arguments.

Functions

createUserRecord

Authorizes a user to use some or all of an owner's tokens. A new user record is created if the required conditions are met.

deleteUserRecord

Deletes a user record. The reference implementation requires the record's owner or an approved operator to call this function.

usableBalanceOf

Returns the total usable balance for an account and token ID. It calculates the amount covered by user records that have not expired.

frozenBalanceOf

Returns the total frozen balance (locked tokens) owned by an account for a particular token ID.

supportsInterface

Supports the ERC-5006 and ERC-1155Receiver interfaces in addition to the ERC-1155 interface.

See the following article for more on ERC-165.

[ERC165] How to check whether a contract supports a particular interface

Security

This standard can help protect the owner's rights. The owner can change the user associated with the NFT, but the user cannot transfer the NFT simply by virtue of that role.

Discussion

I find the approach of separating NFT ownership from usage rights particularly interesting. It could make NFT rentals, for example, straightforward to implement. Because ERC-1155 allows multiple units of the same token ID, game items are a natural use case. Players could rent in-game items to other users for a fixed period, or a game could distribute items to each user every month with a time-limited right to use them. There are many possible applications, and I would be interested in building something with this standard.

Conclusion

This article covered ERC-5006, an extension to ERC-1155 that introduces a user role to separate NFT ownership from usage rights.

I plan to add more implementation details in the future.

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

Twitter @cardene777