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 ERC7496, a proposal from OpenSea for managing metadata on-chain.

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

The original article describes the proposal as being in the Idea stage as of September 7, 2023, but mistakenly refers to ERC5008. The discussion below concerns ERC7496 and reflects the historical proposal.

Overview

This specification introduces new rules for managing NFTs. Specifically, it extends the existing ERC721 and ERC1155 token standards, both of which are used to represent NFTs.

The proposed specification allows NFTs to be associated with dynamic traits. Dynamic traits are pieces of information associated with a token that can change over time. They can represent token attributes, particular benefits, or other properties. Smart contracts can set and retrieve these traits.

For example, information about a new skill acquired by an in-game NFT character can be associated with its token. Similarly, information about a digital artwork NFT that changes on a particular date can be associated with the token. Other smart contracts can then read these traits and, where authorized, modify them.

The specification is intended to make NFTs more flexible and useful across a variety of applications. This lets them serve purposes beyond simple collectibles.

Motivation

Detailed information about NFTs (metadata) is typically stored off-chain. Managing NFT traits and attributes directly in a blockchain smart contract can be difficult because of the associated costs, including gas fees. This new specification allows information associated with NFTs to be managed directly on-chain.

It lets applications set and retrieve NFT traits on-chain, enabling use cases such as the following.

  1. Transactions based on token traits A token can be traded according to its particular traits. For example, if an artwork NFT has a limited edition trait, special conditions can be applied when trading it.

  2. Redeeming benefits on-chain A holder of an NFT with a specific trait can use it to claim benefits on-chain. For example, an NFT with a VIP access trait might grant access to a particular service.

Specification

javascript
interface IERC7496 {
    /* Events */
    event TraitUpdated(bytes32 indexed traitKey, uint256 indexed tokenId, bytes32 value);
    event TraitUpdatedBulkConsecutive(bytes32 indexed traitKeyPattern, uint256 fromTokenId, uint256 toTokenId);
    event TraitUpdatedBulkList(bytes32 indexed traitKeyPattern, uint256[] tokenIds);
    event TraitLabelsURIUpdated(string uri);

    /* Getters */
    function getTraitValue(bytes32 traitKey, uint256 tokenId) external view returns (bytes32);
    function getTraitValues(bytes32 traitKey, uint256[] calldata tokenIds) external view returns (bytes32[] memory);
    function getTraitKeys() external view returns (bytes32[] memory);
    function getTotalTraitKeys() external view returns (uint256);
    function getTraitKeyAt(uint256 index) external view returns (bytes32);
    function getTraitLabelsURI() external view returns (string memory);

    /* Setters */
    function setTrait(bytes32 traitKey, uint256 tokenId, bytes32 value) external;
    function setTraitLabelsURI(string calldata uri) external;
}

Trait Keys

A trait key is a name-like identifier for an individual trait on the blockchain. It identifies the trait's name or location; arbitrary values can be used as trait keys. When trait data has a complex hierarchical structure, a trait key is typically expressed in dot-separated form. For example, the trait key "foo.bar.baz" identifies "baz" within the "bar" object inside the "foo" object.

For particularly long or complex trait keys, hashing the key with keccak256 and using the resulting hash is recommended. This keeps the trait key compact and distinct.

A trait key cannot contain an asterisk (*). If a smart contract is queried for a trait key that has not been set, it raises the UnknownTraitKey() error to indicate that the key does not exist.

Trait Labels

Trait labels provide human-readable values for trait keys on user-facing websites. The trait labels URI may point to an off-chain URL or an on-chain data URI. The trait labels URI format is defined as follows.

json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "traitKey": {
        "type": "string"
      },
      "fullTraitKey": {
        "type": "string"
      },
      "traitLabel": {
        "type": ["string"]
      },
      "displayType": {
        "type": ["number"]
      },
      "editors": {
        "type": "array",
        "items": {
          "type": "number"
        }
      },
      "editorsAddressList": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "acceptableValues": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "fullTraitValues": {
        "type": "object",
        "properties": {
          "traitValue": {
            "type": "string"
          },
          "fullTraitValue": {
            "type": "string"
          }
        }
      }
    },
    "required": ["traitKey", "traitLabel"]
  }
}
  • traitKey

    • The recommended on-chain trait key is a bytes32 value.
    • If traitKey is a keccak256 hash that cannot be directly decoded into ASCII characters, fullTraitKey must be defined.
    • This allows off-chain indexers to understand the value of traitKey, including its nested structure.
  • displayType

    • Specifies how trait values should be displayed to frontend users.
    • If displayType is not defined, it defaults to 0.
    • The following table defines displayType values and the corresponding metadata display types. Future EIPs may introduce additional types.
Integer Metadata display type
0 Normal value
1 Number / percentage
2 Date
3 Hidden
  • editors

    • An array of integers identifying the entities that can edit a trait.
    • The editor types are as follows.
    Integer Editor
    0 Internal (contract address)
    1 Contract owner
    2 Token owner
    3 Custom address list
  • acceptableValues

    • A predefined set of values that may be assigned to a trait.
    • If any value is acceptable, the * character should be used.
    • acceptableValues may also be validated with regular expressions, in which case the expression must begin with regex:.
  • fullTraitValues

    • Human-readable representations of full trait values can be specified when the values exceed the supported bytes32 size.
    • The encoded values should be integers mapped to the full trait values.

Events

  • When trait information is updated, emit TraitUpdated, TraitUpdatedBulkConsecutive, or TraitUpdatedBulkList.
  • For TraitUpdatedBulkConsecutive, fromTokenId and toTokenId specify a consecutive range of token IDs, covering every ID in the range.
  • For TraitUpdatedBulkList, tokenIds can be specified in any order.
  • When the trait labels URI or the content at that URI is updated, emit TraitLabelsURIUpdated.
    • This allows off-chain indexers to process the changes.

Trait Key Patterns (traitKeyPattern)

  • Used to identify an individual trait or a range of traits.
  • If traitKeyPattern does not contain *, it is treated as a single trait.
  • If traitKeyPattern contains *, the pattern uses dot-separated notation and * represents possible values at that nesting level.
    • For example, foo.bar.* identifies all traits in the bar object inside the foo object.
  • traitKeyPattern must not contain more than one *, and * must be the final character of the pattern.

Conflicting Values in the Metadata URI

  • Traits specified by this specification take precedence over conflicting values specified in the ERC721 metadata URI.
    • If a trait label exactly matches a trait returned through tokenURI, the values returned under this EIP should match as well.
    • If they do not match, the on-chain dynamic trait value takes precedence for display and use.
  • If on-chain trait values differ from those in the metadata URI, data providers and websites should warn users about conflicting values and indicate that the on-chain traits should be used for marketplace transaction guarantees and similar purposes.

The setTrait Method

  • If a smart contract exposes setTrait and setTraitLabelsURI, only authorized users, such as token owners or approved contracts, should be able to call these methods.
    • For example, a benefits contract might call the methods programmatically when a benefit is redeemed.
  • If setTrait does not change the existing trait value, it raises the custom error TraitValueUnchanged().

Registry Functionality

  • If this EIP is used as a registry storing on-chain metadata for multiple token addresses, the first 20 bytes of traitKey must be the token address.
    • The remaining 12 bytes may contain ASCII characters representing the trait key or the first 12 bytes of the keccak256 hash of a longer key.
    • When used in this format, the registry should not return support for ERC721 through supportsInterface.
    • This lets external providers understand that the traits do not belong to tokens issued by the registry contract itself.
  • When implemented as a registry, the trait labels URI JSON may specify traitKey using only its final 12 bytes, simplifying the labels.

ERC1155 (Semi-Fungible Tokens)

  • The standard can be applied to ERC1155, but traits apply to all units of a given token identifier.
  • If an ERC1155 contract has only 1 unit of a particular token, the specification can be used without modification for that token.

Rationale

Off-chain trait information provided through an ERC721 metadata URI is useful, but it has limitations when traits are needed on-chain. On-chain trait information lets internal and external smart contracts retrieve and modify traits in a variety of scenarios. For example, a smart contract that offers redeemable benefits can check the benefit value and update the corresponding trait after redemption. This lets on-chain peer-to-peer marketplaces enforce specific trait values during order fulfillment, preventing a front-running transaction that changes a relevant trait before the sale from silently invalidating those conditions.

Backward Compatibility

The proposal introduces a new EIP and does not present backward-compatibility issues with existing standards. One point to note is that when on-chain trait information conflicts with trait information specified by an ERC721 metadata URI, the specification requires the on-chain information to take precedence. This resolves conflicting trait information by prioritizing the on-chain value.

Tests

The tests are available in the following GitHub repository.

Reference Implementation

javascript
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {EnumerableSet} from "openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol";
import {IERCDynamicTraits} from "../interfaces/IERCDynamicTraits.sol";
import {Ownable} from 'openzeppelin/access/Ownable.sol';

contract DynamicTraits is IERCDynamicTraits {
    using EnumerableSet for EnumerableSet.Bytes32Set;

    EnumerableSet.Bytes32Set internal _traitKeys;
    mapping(uint256 tokenId => mapping(bytes32 traitKey => bytes32 traitValue)) internal _traits;
    string internal _traitLabelsURI;

    error TraitValueUnchanged();


  
    function getTraitValue( bytes32 traitKey, uint256 tokenId) external virtual view returns (bytes32 traitValue) {
        return _traits[tokenId][traitKey];
    }

    function getTraitValues(bytes32 traitKey,uint256[] calldata tokenIds) external virtual view returns (bytes32[] memory traitValues) {
        uint256 length = tokenIds.length;
        bytes32[] memory result = new bytes32[](length);
        for (uint256 i = 0; i < length; i++) {
            result[i] = _traits[tokenIds[i]][traitKey];
        }
        return result;
    }

    function getTotalTraitKeys() external virtual view returns (uint256) {
        return _traitKeys.length();
    }

    function getTraitKeyAt(uint256 index) external virtual view returns (bytes32 traitKey) {
        return _traitKeys.at(index);
    }

    function getTraitKeys() external virtual view returns (bytes32[] memory traitKeys) {
        return _traitKeys._inner._values;
    }

    function getTraitLabelsURI() external virtual view returns (string memory labelsURI) {
        return _traitLabelsURI;
    }

    function _setTrait( bytes32 traitKey, uint256 tokenId,bytes32 value) internal {
        bytes32 oldValue = _traits[tokenId][traitKey];
        if (oldValue == value) {
            revert TraitValueUnchanged();
        }

        _traits[tokenId][traitKey] = value;

        if (!_traitKeys.contains(traitKey)) {
            _traitKeys.add(traitKey);
        }

        emit TraitUpdated( traitKey, tokenId, value);
    }


    function _setTraitLabelsURI(string calldata uri) internal virtual {
        _traitLabelsURI = uri;
        emit TraitLabelsURIUpdated(uri);
    }


    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERCDynamicTraits).interfaceId;
    }
}

_traitKeys

javascript
EnumerableSet.Bytes32Set internal _traitKeys;

Overview A data structure for storing trait keys. Trait keys are unique identifiers used to manage and look up traits.

Parameters

  • _traitKeys
    • An internal variable of type EnumerableSet.Bytes32Set containing a set of trait keys.
    • EnumerableSet is a data structure for managing unique values.
    • The variable is used internally to keep track of the list of trait keys.

_traits

javascript
mapping(uint256 tokenId => mapping(bytes32 traitKey => bytes32 traitValue)) internal _traits;

Overview A mapping for storing trait information for each token. Each token's traits are represented by trait keys and their corresponding values.

Details The information for each token is represented by a trait key (traitKey) and its value (traitValue).

Parameters

  • tokenId
    • The token's unique identifier.
  • traitKey
    • The key identifying the trait.
  • traitValue
    • The trait value.

_traitLabelsURI

javascript
string internal _traitLabelsURI;

Overview A variable storing the trait labels URI (Uniform Resource Identifier).

Details Used to provide human-readable labels for trait keys when displaying trait information.


TraitValueUnchanged

javascript
error TraitValueUnchanged();

Overview An error raised when an attempt to change a trait value leaves it unchanged.

Details The error occurs when a trait update is attempted but the value would remain the same. It is used to reject unnecessary updates.


getTraitValue

javascript
function getTraitValue(bytes32 traitKey, uint256 tokenId) external virtual view returns (bytes32 traitValue) {
    return _traits[tokenId][traitKey];
}

Overview Retrieves the trait value (traitValue) for a specified token.

Arguments

  • traitKey
    • The key uniquely identifying the trait value.
  • tokenId
    • The identifier of the token whose trait value is being retrieved.

Return Value

  • traitValue
    • The specified token's trait value.

getTraitValues

javascript
function getTraitValues(bytes32 traitKey, uint256[] calldata tokenIds) external virtual view returns (bytes32[] memory traitValues) {
    uint256 length = tokenIds.length;
    bytes32[] memory result = new bytes32[](length);
    for (uint256 i = 0; i < length; i++) {
        result[i] = _traits[tokenIds[i]][traitKey];
    }
    return result;
}

Overview Retrieves the list of trait values (traitValues) associated with a specified trait key (traitKey) across multiple tokens.

Arguments

  • traitKey
    • The key uniquely identifying the trait.
  • tokenIds
    • An array containing the identifiers of the tokens whose trait values are being retrieved.

Return Value

  • traitValues
    • An array of trait values for the specified key across the requested tokens.

getTotalTraitKeys

javascript
function getTotalTraitKeys() external virtual view returns (uint256) {
    return _traitKeys.length();
}

Overview Retrieves the total number of registered trait keys (traitKey).

Return Value

  • The total number of trait keys.

getTraitKeyAt

javascript
function getTraitKeyAt(uint256 index) external virtual view returns (bytes32 traitKey) {
    return _traitKeys.at(index);
}

Overview Retrieves the trait key at the specified index.

Arguments

  • index
    • The position of the trait key to retrieve.

Return Value

  • traitKey
    • The trait key at the specified index.

getTraitKeys

javascript
function getTraitKeys() external virtual view returns (bytes32[] memory traitKeys) {
    return _traitKeys._inner._values;
}

Overview Retrieves all registered trait keys.

Return Value

  • traitKeys
    • An array containing the registered trait keys.

getTraitLabelsURI

javascript
function getTraitLabelsURI() external virtual view returns (string memory labelsURI) {
    return _traitLabelsURI;
}

Overview Retrieves the trait labels URI (Uniform Resource Identifier).

Return Value

  • labelsURI
    • The trait labels URI.

_setTrait

javascript
function _setTrait(bytes32 traitKey, uint256 tokenId, bytes32 value) internal {
    bytes32 oldValue = _traits[tokenId][traitKey];
    if (oldValue == value) {
        revert TraitValueUnchanged();
    }

    _traits[tokenId][traitKey] = value;

    if (!_traitKeys.contains(traitKey)) {
        _traitKeys.add(traitKey);
    }

    emit TraitUpdated(traitKey, tokenId, value);
}

Overview An internal function that sets or updates a trait value (traitValue).

Arguments

  • traitKey
    • The key uniquely identifying the trait.
  • tokenId
    • The identifier of the token whose trait value is being set or updated.
  • value
    • The trait value to set or update.

_setTraitLabelsURI

javascript
function _setTraitLabelsURI(string calldata uri) internal virtual {
    _traitLabels

URI = uri;
    emit TraitLabelsURIUpdated(uri);
}

Overview Sets the trait labels URI.

Arguments

  • uri
    • The trait labels URI (Uniform Resource Identifier) to set.

supportsInterface

javascript
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
    return interfaceId == type(IERCDynamicTraits).interfaceId;
}

Overview Checks whether the specified interface is supported.

Arguments

  • interfaceId
    • The identifier of the interface to check.

Return Value

  • true if the interface is supported, or false otherwise.

Security Considerations

Access Control

Externally callable set* methods must not be freely accessible to everyone. Instead, only users or contracts with permissions restricted to specific roles or addresses should be able to execute them. These restrictions prevent unauthorized changes and transactions and improve contract security.

Risks of Relying on Off-Chain Traits

Applications such as marketplaces should not rely too heavily on off-chain trait information. Off-chain trait information can become stale or fail to reflect a change made through a front-running transaction. Front-running exploits transaction ordering to produce undesirable outcomes; block producers may influence that ordering. Even when trait information is stored off-chain, applications should therefore verify the current on-chain trait values at transaction execution time.

Using On-Chain Trait Information

When a trait affects the value or state of a token, such as the status of a redeemable benefit, applications should check the on-chain trait at transaction execution time. This helps protect the token's value against unwanted changes and attacks. Another security measure to consider is hashing all trait values and verifying that they still match the state recorded when an order was created.

Conclusion

This article covered ERC7496, OpenSea's proposal for managing metadata on-chain.

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

Twitter @cardene777