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 explores ERC7857, which proposes a new NFT mechanism for securely managing and transferring AI models, memories, configurations, and other data.

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

Other articles cover a range of EIPs, BIPs, SLIPs, CAIPs, ENSIPs, RFCs, and ACPs.

Overview

ERC7857 defines a new standard interface for non-fungible tokens (NFTs) representing AI agents (autonomous actors powered by artificial intelligence). Where conventional NFTs deal with static metadata (information that does not change), ERC7857 introduces mechanisms for managing dynamic, highly confidential metadata representing an AI agent's capabilities.

The distinguishing feature of this NFT standard is that it enables privacy-preserving transfers while ensuring data authenticity and integrity. Specifically, it defines a unified interface supporting verification methods such as the following.

  • TEE(Trusted Execution Environment) A mechanism for running programs in a secure execution environment to protect against external tampering and information leakage.
  • ZKP (Zero-Knowledge Proof) A technique for proving knowledge of information without revealing the information itself.

These techniques enable secure management and transfer of sensitive information such as an AI agent's model, memories, and character configuration. The standard aims to enable secure ownership and transfer of valuable agent data while preserving both confidentiality and verifiability.

Motivation

As AI technology advances, agents (AI systems that perform tasks autonomously) have become increasingly practical in everyday life. Meanwhile, projects combining blockchain technology with agents have emerged, allowing users to create and own their own agents. However, an important missing component is decentralized management of agent ownership.

AI agents have the following characteristics.

Characteristic Description
Uniqueness Each agent has its own model, memories, and character, making it unique.
Clearly defined ownership Agent development requires computing resources and intellectual property, so ownership needs to be clearly established.
Confidential metadata Models, memories, and character configurations are highly sensitive and should not be publicly disclosed.

For these reasons, NFTs are well suited to representing AI agents as non-fungible (unique) assets. However, existing NFT standards such as ERC721 cannot adequately represent AI agents. The main reason is that their approach to metadata assumes static, publicly accessible information.

Limitations of existing NFTs

Conventional NFTs provide a mechanism for owning digital assets such as images and music, but this is insufficient when the underlying metadata itself is the asset, as with AI agents. AI agent metadata has the following properties.

  • The value resides in the data itself, including the model, memories, and character structure.
  • Intellectual property can leak unless the data is encrypted and protected.
  • Ownership transfers must remain verifiable without compromising confidentiality.

NFT transfers must therefore meet the following requirements.

Requirement Description
Verifiable transfer of encrypted metadata It must be possible to confirm during a transfer that the encrypted agent data has been correctly transferred.
Secure access for the new owner Only the new owner should be able to access the agent's underlying data with the appropriate authorization.
Ownership verification in the execution environment The environment running the agent (such as an AI runtime) must be able to verify the owner and load the correct data.

Specification

ERC7857 consists of three main interfaces.

  • Main NFT interface
  • Metadata interface
  • Data verification interface

They work together to enable secure management and transfer of encrypted agent data.

Data verification system

This system verifies the legitimacy of ownership and transfers of confidential data associated with an NFT. It consists primarily of two components: on-chain verification and off-chain proof generation.

Component Description
On-chain verification (Verifier) Implemented as a smart contract that verifies submitted proofs. It can use TEE- or ZKP-based verification.
Off-chain proof generation (Prover) Generates cryptographic proofs concerning data ownership and transfers. It handles encrypted data and keys.

How the off-chain Prover works

Verification method Description
TEE-based Generates proofs within trusted hardware. It can handle private keys securely and directly re-encrypt data.
ZKP-based Generates cryptographic zero-knowledge proofs. Unlike the TEE approach, it cannot simultaneously handle private keys belonging to multiple parties, and the re-encryption key is known to the Prover.

Two supported proof types

Proof type Purpose Verification method
Ownership Proof Proves actual possession of the data. On-chain verification with verifyOwnership().
Transfer Validity Proof Proves that data has been transferred correctly. On-chain verification with verifyTransferValidity().

Verification flow

  1. The Prover generates a proof based on the original data and the newly encrypted data.
  2. The new key is encrypted using the recipient's public key.
  3. The on-chain Verifier verifies the submitted proof.
  4. Data integrity, encryption validity, and the existence of the data in storage are checked.

Ownership proofs are optional, but are recommended when minting or updating an NFT.

Data verification interface

OracleType

javascript
enum OracleType {
    TEE,
    ZKP
}

An enumeration representing the oracle types used for verification. Specifies whether the TEE (Trusted Execution Environment) or ZKP (Zero-Knowledge Proof) approach is used.

AccessProof

javascript
struct AccessProof {
    bytes32 oldDataHash;
    bytes32 newDataHash;
    bytes nonce;
    bytes encryptedPubKey;
    bytes proof;
}

An access proof signed by the recipient (or an assistant acting on their behalf) when accessing data. It includes the relationship between the old and new data, the encrypted public key, and related information. It is used when transferring or verifying access rights.

Parameters

  • oldDataHash
    • Hash of the old data.
  • newDataHash
    • Hash of the new data.
  • nonce
    • Value ensuring the uniqueness of the proof.
  • encryptedPubKey
    • Recipient's public key used to encrypt the new data key (if empty, the public key associated with the Ethereum address is used).
  • proof
    • Proof data itself.

OwnershipProof

javascript
struct OwnershipProof {
    OracleType oracleType;
    bytes32 oldDataHash;
    bytes32 newDataHash;
    bytes sealedKey;
    bytes encryptedPubKey;
    bytes nonce;
    bytes proof;
}

A struct representing proof of data ownership. It stores the ownership proof generated by the off-chain Prover. It uses a TEE or ZKP to securely prove legitimate ownership of the data.

Parameters

  • oracleType
    • Oracle type (TEE or ZKP).
  • oldDataHash
    • Hash of the original data.
  • newDataHash
    • Hash of the new data.
  • sealedKey
    • Cryptographically protected value of the new data key.
  • encryptedPubKey
    • Encrypted value of the recipient's public key.
  • nonce
    • Value making the proof unique.
  • proof
    • Actual proof data.

TransferValidityProof

javascript
struct TransferValidityProof {
    AccessProof accessProof;
    OwnershipProof ownershipProof;
}

A struct representing proof of transfer validity. It includes both an access proof and an ownership proof and is used to verify that the data transfer occurred correctly.

TransferValidityProofOutput

javascript
struct TransferValidityProofOutput {
    bytes32 oldDataHash;
    bytes32 newDataHash;
    bytes sealedKey;
    bytes encryptedPubKey;
    bytes wantedKey;
    address accessAssistant;
    bytes accessProofNonce;
    bytes ownershipProofNonce;
}

Stores the verification result produced after transfer verification. It includes old and new data hashes, encryption keys, access assistant information, and related fields.

verifyTransferValidity

javascript
function verifyTransferValidity(
    TransferValidityProof[] calldata _proofs
) external returns (TransferValidityProofOutput[] memory);

Verifies the validity of a transfer. It verifies TEE- or ZKP-generated proofs to confirm that the data has been correctly re-encrypted, transferred, and registered in storage.

Arguments

  • _proofs
    • Array of proofs generated by the Prover.

Return value

  • TransferValidityProofOutput[]
    • Array of verification results.

Metadata interface

IntelligentData

javascript
struct IntelligentData {
    string dataDescription;
    bytes32 dataHash;
}

A struct storing metadata about an AI agent. It holds a description and data hash for the data associated with each NFT token.

Parameters

  • dataDescription
    • Data description.
  • dataHash
    • Data hash.

IERC7857Metadata

javascript
interface IERC7857Metadata {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function intelligentDataOf(uint256 _tokenId) external view returns (IntelligentData[] memory);
}
name

Retrieves the NFT collection's name. Returns the name of the collection as a whole.

Return value

  • string
    • NFT collection name.
symbol

Retrieves the NFT collection's symbol. Returns a short symbol identifying the collection.

Return value

  • string
    • Collection symbol.
intelligentDataOf

Retrieves the intelligent data of a specified token. Returns the metadata (descriptions and hashes) corresponding to the token ID.

Arguments

  • _tokenId
    • Token identifier.

Return value

  • IntelligentData[]
    • Array of metadata associated with the token.

Main NFT interface

This interface defines the primary NFT operations, including issuance, transfer, cloning, and approval management.

Approval

javascript
event Approval(
    address indexed _from,
    address indexed _to,
    uint256 indexed _tokenId
);

Event emitted when a token transfer is approved. It is emitted when an address authorizes another party to transfer a particular token.

Parameters

  • _from
    • Address granting approval.
  • _to
    • Address receiving approval.
  • _tokenId
    • Token ID in question.

ApprovalForAll

javascript
event ApprovalForAll(
    address indexed _owner,
    address indexed _operator,
    bool _approved
);

Event emitted when approval for all tokens is set. It is emitted when the owner grants a particular operator permission to manage all of their tokens at once.

Parameters

  • _owner
    • Token owner.
  • _operator
    • Operator receiving approval.
  • _approved
    • Approval status (true if approved).

Authorization

javascript
event Authorization(
    address indexed _from,
    address indexed _to,
    uint256 indexed _tokenId
);

Event emitted when an address is authorized to use a token. It is emitted when the owner grants another address permission to use a token. This allows authorized users to access NFT functionality, such as access to an AI agent.

Parameters

  • _from
    • Address granting authorization.
  • _to
    • Address receiving authorization.
  • _tokenId
    • Token ID in question.

AuthorizationRevoked

javascript
event AuthorizationRevoked(
    address indexed _from,
    address indexed _to,
    uint256 indexed _tokenId
);

Event emitted when authorization is revoked. It is emitted when a previously authorized address loses permission to use a token.

Parameters

  • _from
    • Address revoking authorization.
  • _to
    • Address losing authorization.
  • _tokenId
    • Token ID in question.

Transferred

javascript
event Transferred(
    uint256 _tokenId,
    address indexed _from,
    address indexed _to
);

Event emitted when a token is transferred. It is emitted when the token owner transfers the token to another party. It serves as notification that the data transfer has completed.

Parameters

  • _tokenId
    • ID of the transferred token.
  • _from
    • Sender address.
  • _to
    • Recipient address.

Cloned

javascript
event Cloned(
    uint256 indexed _tokenId,
    uint256 indexed _newTokenId,
    address _from,
    address _to
);

Event emitted when a token is cloned. It is emitted when a new token is created from an existing token. It can be used for duplicating an AI agent or creating derivative versions.

Parameters

  • _tokenId
    • Original token ID.
  • _newTokenId
    • Newly created token ID.
  • _from
    • Address performing the cloning operation.
  • _to
    • Owner of the new token.

PublishedSealedKey

javascript
event PublishedSealedKey(
    address indexed _to,
    uint256 indexed _tokenId,
    bytes[] _sealedKeys
);

Event emitted when an encrypted key (Sealed Key) is published. During transfer or cloning, it is emitted when encrypted key information is published on-chain so that the recipient can securely obtain the key needed to decrypt the data.

Parameters

  • _to
    • Address receiving the key.
  • _tokenId
    • Associated token ID.
  • _sealedKeys
    • Array of encrypted keys.

DelegateAccess

javascript
event DelegateAccess(address indexed _user, address indexed _assistant);

Event emitted when a user delegates access rights to an assistant (a representative). It is emitted when a user designates an access assistant that can access data on their behalf. It can be used in mechanisms where access signatures are produced on a user's behalf, including ZKP-based mechanisms.

Parameters

  • _user
    • User delegating access.
  • _assistant
    • Assistant receiving delegated rights.

verifier

javascript
function verifier() external view returns (IERC7857DataVerifier);

Retrieves the data verification contract used by the NFT. Returns the address of the data verification logic (TEE/ZKP) associated with the NFT.

Return value

  • IERC7857DataVerifier
    • Verification contract address.

iTransfer

javascript
function iTransfer(
    address _to,
    uint256 _tokenId,
    TransferValidityProof[] calldata _proofs
) external;

Securely transfers data and ownership. It securely transfers encrypted data associated with the specified token to the recipient. It uses TEE- or ZKP-based proofs (_proofs) to verify the legitimacy of the transfer.

Arguments

  • _to
    • Recipient address.
  • _tokenId
    • Token ID in question.
  • _proofs
    • Array of proofs verifying transfer validity.

iClone

javascript
function iClone(
    address _to,
    uint256 _tokenId,
    TransferValidityProof[] calldata _proofs
) external returns (uint256 _newTokenId);

Clones a token's data. Creates a new token based on the specified token. Data integrity and ownership are also verified cryptographically during cloning.

Arguments

  • _to
    • Address receiving the clone.
  • _tokenId
    • Original token ID.
  • _proofs
    • Proof of data transfer.

Return value

  • _newTokenId
    • ID of the newly generated token.

authorizeUsage

javascript
function authorizeUsage(uint256 _tokenId, address _user) external;

Grants a particular user permission to use a token. It gives the specified user access to functionality associated with the token, such as an AI agent.

Arguments

  • _tokenId
    • ID of the token for which authorization is granted.
  • _user
    • Address receiving authorization.

revokeAuthorization

javascript
function revokeAuthorization(uint256 _tokenId, address _user) external;

Revokes a particular user's permission to use a token. Removes access rights from a previously authorized token user.

Arguments

  • _tokenId
    • ID of the token for which authorization is revoked.
  • _user
    • Address losing authorization.

approve

javascript
function approve(address _to, uint256 _tokenId) external;

Approves the transfer of a particular token. The NFT owner authorizes another address to transfer the specified token.

Arguments

  • _to
    • Address receiving approval.
  • _tokenId
    • Token ID in question.

setApprovalForAll

javascript
function setApprovalForAll(address _operator, bool _approved) external;

Sets transfer approvals for all tokens at once. Grants or revokes a particular operator's authority to manage all tokens owned by the user.

Arguments

  • _operator
    • Address whose authorization is granted or removed.
  • _approved
    • Approval status to set (true to authorize).

delegateAccess

javascript
function delegateAccess(address _assistant) external;

Delegates access rights to an assistant. Allows the user to entrust operations such as access signing to a representative (assistant).

Arguments

  • _assistant
    • Address receiving delegated rights.

ownerOf

javascript
function ownerOf(uint256 _tokenId) external view returns (address);

Retrieves a token's owner. Returns the current owner of the specified token.

Arguments

  • _tokenId
    • Token identifier.

Return value

  • address
    • Current owner's address.

authorizedUsersOf

javascript
function authorizedUsersOf(uint256 _tokenId) external view returns (address[] memory);

Retrieves the list of users authorized to use a token. Returns all user addresses permitted to use the specified token.

Arguments

  • _tokenId
    • Token identifier.

Return value

  • address[]
    • List of authorized users.

getApproved

javascript
function getApproved(uint256 _tokenId) external view returns (address);

Retrieves the address approved to transfer a particular token. Identifies which address has been approved to transfer the token.

Arguments

  • _tokenId
    • Token identifier.

Return value

  • address
    • Approved address.

isApprovedForAll

javascript
function isApprovedForAll(address _owner, address _operator) external view returns (bool);

Checks whether an operator has approval for all tokens belonging to an owner. Determines whether the specified operator is authorized to transfer all of the owner's NFTs.

Arguments

  • _owner
    • NFT owner.
  • _operator
    • Address whose approval status is being checked.

Return value

  • bool
    • true if approved.

getDelegateAccess

javascript
function getDelegateAccess(address _user) external view returns (address);

Retrieves the access assistant configured for a user. Returns the assistant to whom the specified user has delegated access rights.

Arguments

  • _user
    • Address of the user in question.

Return value

  • address
    • Address of the delegated assistant.

Additional explanation

Verification abstraction

The standard separates verification logic from the NFT itself and defines an independent interface called IDataVerifier. This allows implementations to switch flexibly between verification methods (TEE or ZKP).

Verification method Description
TEE (Trusted Execution Environment) Generates proofs inside trusted hardware and securely handles keys and data.
ZKP (Zero-Knowledge Proof) A cryptographic technique for proving that a statement is correct without disclosing the underlying data.

The verification system supports two proof types.

Ownership proof

A proof that the Prover actually possesses the original data. Specifically, it proves knowledge of the original data (pre-image) from which the data hash was generated. This proof establishes the authenticity of the NFT and supports a legitimate claim of data ownership.

Transfer validity proof

A proof intended to ensure the integrity and security of a data transfer. It verifies the following properties.

Verification item Description
Knowledge of original data The Prover knows the original data used to generate the old data hash.
Valid encryption The data can be decrypted with the old key and re-encrypted with the new key.
Secure key delivery The new data key is encrypted and sent using the recipient's public key.
Data integrity The hash of the newly encrypted data is correct.
Data availability The recipient signs to confirm that the data has been stored.

The mechanism thus ensures not only NFT ownership but also secure transfer and availability of the underlying data.

Data protection

The AI agent metadata associated with an NFT is highly valuable and represents intellectual property. Rather than placing the data directly on the blockchain, the standard handles it indirectly through hashes and encrypted keys.

This approach provides both of the following properties to help prevent unauthorized access and theft.

  • Data authenticity (verification by comparing hashes)
  • Data confidentiality (protection through encryption)

Flexible data management

ERC7857 supports three operation modes for handling NFT data. Given the nature of AI agents, these mechanisms clearly distinguish ownership from use.

Operation mode Description
Full Transfer Transfers both data and ownership to the new owner. Used when an NFT is transferred outright.
Data Cloning Copies data to a new token while preserving ownership of the original. Used for creating derivative versions of an agent.
Data Usage Authorization Grants a particular user permission to use the data while preserving ownership. The user cannot access the data directly and instead submits private usage requests.

A Sealed Executor plays a central role in this last mode.

Sealed Executor

A Sealed Executor is an environment for securely authenticating users and performing confidential computations. Although its definition is outside the scope of the standard, it is an essential component of the envisioned system.

Overview

The Sealed Executor retrieves the authorization group for the NFT's tokenId and verifies requests signed by users in that group using their public keys. If verification succeeds, it securely executes the user's request and returns the result.

Example implementation approaches
Implementation approach Description
Trusted third party An authorized service performs computation in a secure environment.
TEE (Trusted Execution Environment) Performs confidential computation using hardware-based protections.
FHE (Fully Homomorphic Encryption) Maintains privacy by performing computations on encrypted data.

This mechanism lets users operate an AI agent safely without knowing the underlying data. It is a core concept for securely lending agents or allowing other parties to use them on an owner's behalf.

Compatibility

ERC7857 does not directly inherit existing NFT standards such as ERC721. This is because ERC7857 focuses on data management as well as ownership. Existing NFTs primarily provide a framework for proving ownership and do not include functionality such as data encryption, re-encryption, or key management.

However, implementers can implement ERC721 alongside it if desired. This enables integration with existing NFT-compatible environments, including wallets and marketplaces. For example, a token could appear as an ERC721 NFT on OpenSea while using ERC7857 extensions internally to manage data securely.

Reference implementation

Verifier

js
abstract contract BaseVerifier is IERC7857DataVerifier {
    // prevent replay attack
    mapping(bytes32 => bool) internal usedProofs;
    
    // prevent replay attack
    mapping(bytes32 => uint256) internal proofTimestamps;
    
    function _checkAndMarkProof(bytes32 proofNonce) internal {
        require(!usedProofs[proofNonce], "Proof already used");
        usedProofs[proofNonce] = true;
        proofTimestamps[proofNonce] = block.timestamp;
    }
    
    // clean expired proof records (save gas)
    function cleanExpiredProofs(bytes32[] calldata proofNonces) external {
        for (uint256 i = 0; i < proofNonces.length; i++) {
            bytes32 nonce = proofNonces[i];
            if (usedProofs[nonce] && 
                block.timestamp > proofTimestamps[nonce] + 7 days) {
                delete usedProofs[nonce];
                delete proofTimestamps[nonce];
            }
        }
    }

    uint256[50] private __gap;
}

struct AttestationConfig {
    OracleType oracleType;
    address contractAddress;
}

contract Verifier is
    BaseVerifier,
    Initializable,
    AccessControlUpgradeable,
    PausableUpgradeable
{
    using ECDSA for bytes32;
    using MessageHashUtils for bytes32;

    event AttestationContractUpdated(AttestationConfig[] attestationConfigs);

    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

    mapping(OracleType => address) public attestationContract;

    uint256 public maxProofAge;

    string public constant VERSION = "2.0.0";

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize(
        AttestationConfig[] calldata _attestationConfigs,
        address _admin
    ) external initializer {
        __AccessControl_init();
        __Pausable_init();

        for (uint256 i = 0; i < _attestationConfigs.length; i++) {
            attestationContract[
                _attestationConfigs[i].oracleType
            ] = _attestationConfigs[i].contractAddress;
        }
        maxProofAge = 7 days;

        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
        _grantRole(ADMIN_ROLE, _admin);
        _grantRole(PAUSER_ROLE, _admin);

        emit AttestationContractUpdated(_attestationConfigs);
    }

    function updateAttestationContract(
        AttestationConfig[] calldata _attestationConfigs
    ) external onlyRole(ADMIN_ROLE) {
        for (uint256 i = 0; i < _attestationConfigs.length; i++) {
            attestationContract[
                _attestationConfigs[i].oracleType
            ] = _attestationConfigs[i].contractAddress;
        }

        emit AttestationContractUpdated(_attestationConfigs);
    }

    function updateMaxProofAge(
        uint256 _maxProofAge
    ) external onlyRole(ADMIN_ROLE) {
        maxProofAge = _maxProofAge;
    }

    function pause() external onlyRole(PAUSER_ROLE) {
        _pause();
    }

    function unpause() external onlyRole(PAUSER_ROLE) {
        _unpause();
    }

    function hashNonce(bytes memory nonce) private pure returns (bytes32) {
        return keccak256(nonce);
    }

    function teeOracleVerify(
        bytes32 messageHash,
        bytes memory signature
    ) internal view returns (bool) {
        return
            TEEVerifier(attestationContract[OracleType.TEE]).verifyTEESignature(
                messageHash,
                signature
            );
    }

    /// @notice Extract and verify signature from the access proof
    /// @param accessProof The access proof
    /// @return The recovered access assistant address
    function verifyAccessibility(
        AccessProof memory accessProof
    ) private pure returns (address) {
        bytes32 messageHash = keccak256(
            abi.encodePacked(
                "\x19Ethereum Signed Message:\n66",
                Strings.toHexString(
                    uint256(
                        keccak256(
                            abi.encodePacked(
                                accessProof.oldDataHash,
                                accessProof.newDataHash,
                                accessProof.encryptedPubKey,
                                accessProof.nonce
                            )
                        )
                    ),
                    32
                )
            )
        );

        address accessAssistant = messageHash.recover(accessProof.proof);
        require(accessAssistant != address(0), "Invalid access assistant");
        return accessAssistant;
    }

    function verfifyOwnershipProof(
        OwnershipProof memory ownershipProof
    ) private view returns (bool) {
        if (ownershipProof.oracleType == OracleType.TEE) {
            bytes32 messageHash = keccak256(
                abi.encodePacked(
                    "\x19Ethereum Signed Message:\n66",
                    Strings.toHexString(
                        uint256(
                            keccak256(
                                abi.encodePacked(
                                    ownershipProof.oldDataHash,
                                    ownershipProof.newDataHash,
                                    ownershipProof.sealedKey,
                                    ownershipProof.encryptedPubKey,
                                    ownershipProof.nonce
                                )
                            )
                        ),
                        32
                    )
                )
            );

            return teeOracleVerify(messageHash, ownershipProof.proof);
        }
        // TODO: add ZKP verification
        else {
            return false;
        }
    }

    /// @notice Process a single transfer validity proof
    /// @param proof The proof data
    /// @return output The processed proof data as a struct
    function processTransferProof(
        TransferValidityProof calldata proof
    ) private view returns (TransferValidityProofOutput memory output) {
        // compare the proof data in access proof and ownership proof
        require(
            proof.accessProof.oldDataHash == proof.ownershipProof.oldDataHash,
            "Invalid oldDataHashes"
        );
        output.oldDataHash = proof.accessProof.oldDataHash;
        require(
            proof.accessProof.newDataHash == proof.ownershipProof.newDataHash,
            "Invalid newDataHashes"
        );
        output.newDataHash = proof.accessProof.newDataHash;

        output.wantedKey = proof.accessProof.encryptedPubKey;
        output.accessProofNonce = proof.accessProof.nonce;
        output.encryptedPubKey = proof.ownershipProof.encryptedPubKey;
        output.sealedKey = proof.ownershipProof.sealedKey;
        output.ownershipProofNonce = proof.ownershipProof.nonce;

        // verify the access assistant
        output.accessAssistant = verifyAccessibility(proof.accessProof);

        bool isOwn = verfifyOwnershipProof(proof.ownershipProof);

        require(isOwn, "Invalid ownership proof");

        return output;
    }

    /// @notice Verify data transfer validity, the _proof prove:
    ///         1. The pre-image of oldDataHashes
    ///         2. The oldKey can decrypt the pre-image and the new key re-encrypt the plaintexts to new ciphertexts
    ///         3. The newKey is encrypted with the receiver's pubKey to get the sealedKey
    ///         4. The hashes of new ciphertexts is newDataHashes (key to note: TEE could support a private key of the receiver)
    ///         5. The newDataHashes identified ciphertexts are available in the storage: need the signature from the receiver signing oldDataHashes and newDataHashes
    /// @param proofs Proof generated by TEE/ZKP oracle
    function verifyTransferValidity(
        TransferValidityProof[] calldata proofs
    )
        public
        virtual
        override
        whenNotPaused
        returns (TransferValidityProofOutput[] memory)
    {
        TransferValidityProofOutput[]
            memory outputs = new TransferValidityProofOutput[](proofs.length);

        for (uint256 i = 0; i < proofs.length; i++) {
            TransferValidityProofOutput memory output = processTransferProof(
                proofs[i]
            );

            outputs[i] = output;

            bytes32 accessProofNonce = hashNonce(output.accessProofNonce);
            _checkAndMarkProof(accessProofNonce);

            bytes32 ownershipProofNonce = hashNonce(output.ownershipProofNonce);
            _checkAndMarkProof(ownershipProofNonce);
        }

        return outputs;
    }

    uint256[50] private __gap;
}

Main NFT

js
contract AgentNFT is
    AccessControlEnumerableUpgradeable,
    IERC7857,
    IERC7857Metadata
{
    event Updated(
        uint256 indexed _tokenId,
        IntelligentData[] _oldDatas,
        IntelligentData[] _newDatas
    );

    event Minted(
        uint256 indexed _tokenId,
        address indexed _creator,
        address indexed _owner
    );

    struct TokenData {
        address owner;
        address[] authorizedUsers;
        address approvedUser;
        IntelligentData[] iDatas;
    }

    /// @custom:storage-location erc7201:agent.storage.AgentNFT
    struct AgentNFTStorage {
        // Token data
        mapping(uint256 => TokenData) tokens;
        mapping(address owner => mapping(address operator => bool)) operatorApprovals;
        mapping(address user => address accessAssistant) accessAssistants;
        uint256 nextTokenId;
        // Contract metadata
        string name;
        string symbol;
        string storageInfo;
        // Core components
        IERC7857DataVerifier verifier;
    }

    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

    string public constant VERSION = "2.0.0";

    // keccak256(abi.encode(uint(keccak256("agent.storage.AgentNFT")) - 1)) & ~bytes32(uint(0xff))
    bytes32 private constant AGENT_NFT_STORAGE_LOCATION =
        0x4aa80aaafbe0e5fe3fe1aa97f3c1f8c65d61f96ef1aab2b448154f4e07594600;

    function _getAgentStorage()
        private
        pure
        returns (AgentNFTStorage storage $)
    {
        assembly {
            $.slot := AGENT_NFT_STORAGE_LOCATION
        }
    }

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize(
        string memory name_,
        string memory symbol_,
        string memory storageInfo_,
        address verifierAddr,
        address admin_
    ) public virtual initializer {
        require(verifierAddr != address(0), "Zero address");

        __AccessControlEnumerable_init();

        _grantRole(DEFAULT_ADMIN_ROLE, admin_);
        _grantRole(ADMIN_ROLE, admin_);
        _grantRole(PAUSER_ROLE, admin_);

        AgentNFTStorage storage $ = _getAgentStorage();
        $.name = name_;
        $.symbol = symbol_;
        $.storageInfo = storageInfo_;
        $.verifier = IERC7857DataVerifier(verifierAddr);
    }

    // Basic getters
    function name() public view virtual returns (string memory) {
        return _getAgentStorage().name;
    }

    function symbol() public view virtual returns (string memory) {
        return _getAgentStorage().symbol;
    }

    function verifier() public view virtual returns (IERC7857DataVerifier) {
        return _getAgentStorage().verifier;
    }

    // Admin functions
    function updateVerifier(
        address newVerifier
    ) public virtual onlyRole(ADMIN_ROLE) {
        require(newVerifier != address(0), "Zero address");
        _getAgentStorage().verifier = IERC7857DataVerifier(newVerifier);
    }

    function update(
        uint256 tokenId,
        IntelligentData[] calldata newDatas
    ) public virtual {
        AgentNFTStorage storage $ = _getAgentStorage();
        TokenData storage token = $.tokens[tokenId];
        require(token.owner == msg.sender, "Not owner");
        require(newDatas.length > 0, "Empty data array");

        IntelligentData[] memory oldDatas = new IntelligentData[](
            token.iDatas.length
        );
        for (uint i = 0; i < token.iDatas.length; i++) {
            oldDatas[i] = token.iDatas[i];
        }

        delete token.iDatas;

        for (uint i = 0; i < newDatas.length; i++) {
            token.iDatas.push(newDatas[i]);
        }

        emit Updated(tokenId, oldDatas, newDatas);
    }

    function mint(
        IntelligentData[] calldata iDatas,
        address to
    ) public payable virtual returns (uint256 tokenId) {
        require(to != address(0), "Zero address");
        require(iDatas.length > 0, "Empty data array");

        AgentNFTStorage storage $ = _getAgentStorage();

        tokenId = $.nextTokenId++;
        TokenData storage newToken = $.tokens[tokenId];
        newToken.owner = to;
        newToken.approvedUser = address(0);

        for (uint i = 0; i < iDatas.length; i++) {
            newToken.iDatas.push(iDatas[i]);
        }

        emit Minted(tokenId, msg.sender, to);
    }

    function _proofCheck(
        address from,
        address to,
        uint256 tokenId,
        TransferValidityProof[] calldata proofs
    )
        internal
        returns (bytes[] memory sealedKeys, IntelligentData[] memory newDatas)
    {
        AgentNFTStorage storage $ = _getAgentStorage();
        require(to != address(0), "Zero address");
        require($.tokens[tokenId].owner == from, "Not owner");
        require(proofs.length > 0, "Empty proofs array");

        TransferValidityProofOutput[] memory proofOutput = $
            .verifier
            .verifyTransferValidity(proofs);

        require(
            proofOutput.length == $.tokens[tokenId].iDatas.length,
            "Proof count mismatch"
        );

        sealedKeys = new bytes[](proofOutput.length);
        newDatas = new IntelligentData[](proofOutput.length);

        for (uint i = 0; i < proofOutput.length; i++) {
            // require the initial data hash is the same as the old data hash
            require(
                proofOutput[i].oldDataHash ==
                    $.tokens[tokenId].iDatas[i].dataHash,
                "Old data hash mismatch"
            );

            // only the receiver itself or the access assistant can sign the access proof
            require(
                proofOutput[i].accessAssistant == $.accessAssistants[to] ||
                    proofOutput[i].accessAssistant == to,
                "Access assistant mismatch"
            );

            bytes memory wantedKey = proofOutput[i].wantedKey;
            bytes memory encryptedPubKey = proofOutput[i].encryptedPubKey;
            if (wantedKey.length == 0) {
                // if the wanted key is empty, the default wanted receiver is receiver itself
                address defaultWantedReceiver = Utils.pubKeyToAddress(
                    encryptedPubKey
                );
                require(
                    defaultWantedReceiver == to,
                    "Default wanted receiver mismatch"
                );
            } else {
                // if the wanted key is not empty, the data is private
                require(
                    Utils.bytesEqual(encryptedPubKey, wantedKey),
                    "encryptedPubKey mismatch"
                );
            }

            sealedKeys[i] = proofOutput[i].sealedKey;
            newDatas[i] = IntelligentData({
                dataDescription: $.tokens[tokenId].iDatas[i].dataDescription,
                dataHash: proofOutput[i].newDataHash
            });
        }
        return (sealedKeys, newDatas);
    }

    function _transfer(
        address from,
        address to,
        uint256 tokenId,
        TransferValidityProof[] calldata proofs
    ) internal {
        AgentNFTStorage storage $ = _getAgentStorage();
        (
            bytes[] memory sealedKeys,
            IntelligentData[] memory newDatas
        ) = _proofCheck(from, to, tokenId, proofs);

        TokenData storage token = $.tokens[tokenId];
        token.owner = to;
        token.approvedUser = address(0);

        delete token.iDatas;
        for (uint i = 0; i < newDatas.length; i++) {
            token.iDatas.push(newDatas[i]);
        }

        emit Transferred(tokenId, from, to);
        emit PublishedSealedKey(to, tokenId, sealedKeys);
    }

    function iTransfer(
        address to,
        uint256 tokenId,
        TransferValidityProof[] calldata proofs
    ) public virtual {
        require(_isApprovedOrOwner(msg.sender, tokenId), "Not authorized");
        _transfer(ownerOf(tokenId), to, tokenId, proofs);
    }

    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual {
        TokenData storage token = _getAgentStorage().tokens[tokenId];
        require(_isApprovedOrOwner(msg.sender, tokenId), "Not authorized");
        require(to != address(0), "Zero address");
        require(token.owner == from, "Not owner");
        token.owner = to;
        token.approvedUser = address(0);

        emit Transferred(tokenId, from, to);
    }

    function iTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        TransferValidityProof[] calldata proofs
    ) public virtual {
        require(_isApprovedOrOwner(msg.sender, tokenId), "Not authorized");
        _transfer(from, to, tokenId, proofs);
    }

    function _clone(
        address from,
        address to,
        uint256 tokenId,
        TransferValidityProof[] calldata proofs
    ) internal returns (uint256) {
        AgentNFTStorage storage $ = _getAgentStorage();

        (
            bytes[] memory sealedKeys,
            IntelligentData[] memory newDatas
        ) = _proofCheck(from, to, tokenId, proofs);

        uint256 newTokenId = $.nextTokenId++;
        TokenData storage newToken = $.tokens[newTokenId];
        newToken.owner = to;
        newToken.approvedUser = address(0);

        for (uint i = 0; i < newDatas.length; i++) {
            newToken.iDatas.push(newDatas[i]);
        }

        emit Cloned(tokenId, newTokenId, from, to);
        emit PublishedSealedKey(to, newTokenId, sealedKeys);

        return newTokenId;
    }

    function iClone(
        address to,
        uint256 tokenId,
        TransferValidityProof[] calldata proofs
    ) public virtual returns (uint256) {
        require(_isApprovedOrOwner(msg.sender, tokenId), "Not authorized");
        return _clone(ownerOf(tokenId), to, tokenId, proofs);
    }

    function iCloneFrom(
        address from,
        address to,
        uint256 tokenId,
        TransferValidityProof[] calldata proofs
    ) public virtual returns (uint256) {
        require(_isApprovedOrOwner(msg.sender, tokenId), "Not authorized");
        return _clone(from, to, tokenId, proofs);
    }

    function authorizeUsage(uint256 tokenId, address to) public virtual {
        require(to != address(0), "Zero address");
        AgentNFTStorage storage $ = _getAgentStorage();
        require($.tokens[tokenId].owner == msg.sender, "Not owner");

        address[] storage authorizedUsers = $.tokens[tokenId].authorizedUsers;
        for (uint i = 0; i < authorizedUsers.length; i++) {
            require(authorizedUsers[i] != to, "Already authorized");
        }

        authorizedUsers.push(to);
        emit Authorization(msg.sender, to, tokenId);
    }

    function ownerOf(uint256 tokenId) public view virtual returns (address) {
        AgentNFTStorage storage $ = _getAgentStorage();
        address owner = $.tokens[tokenId].owner;
        require(owner != address(0), "Token does not exist");
        return owner;
    }

    function authorizedUsersOf(
        uint256 tokenId
    ) public view virtual returns (address[] memory) {
        AgentNFTStorage storage $ = _getAgentStorage();
        require(_exists(tokenId), "Token does not exist");
        return $.tokens[tokenId].authorizedUsers;
    }

    function storageInfo(
        uint256 tokenId
    ) public view virtual returns (string memory) {
        require(_exists(tokenId), "Token does not exist");
        return _getAgentStorage().storageInfo;
    }

    function _exists(uint256 tokenId) internal view returns (bool) {
        return _getAgentStorage().tokens[tokenId].owner != address(0);
    }

    function intelligentDataOf(
        uint256 tokenId
    ) public view virtual returns (IntelligentData[] memory) {
        AgentNFTStorage storage $ = _getAgentStorage();
        require(_exists(tokenId), "Token does not exist");
        return $.tokens[tokenId].iDatas;
    }

    function approve(address to, uint256 tokenId) public virtual {
        address owner = ownerOf(tokenId);
        require(to != owner, "Approval to current owner");
        require(
            msg.sender == owner || isApprovedForAll(owner, msg.sender),
            "Not authorized"
        );

        _getAgentStorage().tokens[tokenId].approvedUser = to;
        emit Approval(owner, to, tokenId);
    }

    function setApprovalForAll(address operator, bool approved) public virtual {
        require(operator != msg.sender, "Approve to caller");
        _getAgentStorage().operatorApprovals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    function getApproved(
        uint256 tokenId
    ) public view virtual returns (address) {
        require(_exists(tokenId), "Token does not exist");
        return _getAgentStorage().tokens[tokenId].approvedUser;
    }

    function isApprovedForAll(
        address owner,
        address operator
    ) public view virtual returns (bool) {
        return _getAgentStorage().operatorApprovals[owner][operator];
    }

    function delegateAccess(address assistant) public virtual {
        require(assistant != address(0), "Zero address");
        _getAgentStorage().accessAssistants[msg.sender] = assistant;
        emit DelegateAccess(msg.sender, assistant);
    }

    function getDelegateAccess(
        address user
    ) public view virtual returns (address) {
        return _getAgentStorage().accessAssistants[user];
    }

    function _isApprovedOrOwner(
        address spender,
        uint256 tokenId
    ) internal view returns (bool) {
        require(_exists(tokenId), "Token does not exist");
        address owner = ownerOf(tokenId);
        return (spender == owner ||
            getApproved(tokenId) == spender ||
            isApprovedForAll(owner, spender));
    }

    function batchAuthorizeUsage(
        uint256 tokenId,
        address[] calldata users
    ) public virtual {
        require(users.length > 0, "Empty users array");
        AgentNFTStorage storage $ = _getAgentStorage();
        require($.tokens[tokenId].owner == msg.sender, "Not owner");

        for (uint i = 0; i < users.length; i++) {
            require(users[i] != address(0), "Zero address in users");
            $.tokens[tokenId].authorizedUsers.push(users[i]);
            emit Authorization(msg.sender, users[i], tokenId);
        }
    }

    function revokeAuthorization(uint256 tokenId, address user) public virtual {
        AgentNFTStorage storage $ = _getAgentStorage();
        require($.tokens[tokenId].owner == msg.sender, "Not owner");
        require(user != address(0), "Zero address");

        address[] storage authorizedUsers = $.tokens[tokenId].authorizedUsers;
        bool found = false;

        for (uint i = 0; i < authorizedUsers.length; i++) {
            if (authorizedUsers[i] == user) {
                authorizedUsers[i] = authorizedUsers[
                    authorizedUsers.length - 1
                ];
                authorizedUsers.pop();
                found = true;
                break;
            }
        }

        require(found, "User not authorized");
        emit AuthorizationRevoked(msg.sender, user, tokenId);
    }
}

Security

Proof verification

AI agent NFTs use cryptographic technologies such as TEEs (Trusted Execution Environments) and ZKPs (Zero-Knowledge Proofs) to establish data validity. However, all statements made in the proofs must be rigorously verified for the mechanism to operate securely.

Key verification requirements
  • Verify proof completeness The smart contract must verify all statements contained in the proof. Partial verification could result in invalid data being accepted.

  • Prevent replay attacks Attacks that reuse previously submitted proofs to create fraudulent transactions must be prevented. To prevent replay, each proof includes a unique nonce (a single-use value), ensuring the same proof cannot be reused.

Differences between verification approaches and implications for key management

TEEs and ZKPs differ in their ability to handle private keys. This directly affects data re-encryption and who can view data after a transfer.

Verification method Key handling Characteristics and risks
TEE (Trusted Execution Environment) Can securely handle private keys belonging to multiple parties. Enables secure re-encryption and prevents the previous owner from accessing new data after the transfer.
ZKP (Zero-Knowledge Proof) Cannot handle multiple private keys in the described approach. Because the Prover (sender) retains the re-encryption key, re-encryption is necessary at the next update following a transfer or clone. Otherwise, the previous owner may be able to view new data.

When using the ZKP approach, data must therefore be re-encrypted at the next update following a transfer or clone. Otherwise, the previous owner may be able to decrypt some of the new data.

Data privacy

In ERC7857, the NFT's underlying metadata (AI models, memories, and so on) is not stored on the blockchain itself. Only the following two kinds of data are recorded on-chain.

Stored data Description
Hash (dataHash) A fingerprint for verifying data authenticity, allowing integrity checks without revealing the underlying data.
Encrypted key (sealedKey) The data decryption key is encrypted for storage and cannot be decrypted directly without the necessary key.

The actual AI agent data can therefore be securely stored and transmitted off-chain. Because the underlying data is not present on-chain, it cannot be inspected directly by external observers there.

Key management is also critical. A TEE can securely hold a recipient's private key, whereas the ZKP approach cannot do so and therefore requires re-encryption when updating data. This maintains a state in which only the latest owner can access the data.

Access control and state management

AI agent NFT operations such as transfer, cloning, and authorization are restricted to the owner. The design also ensures that changes to the NFT's state remain consistent and verifiable.

Management item Requirement
Data operations Maintain integrity and availability across all data operations.
Ownership and key updates Changes must be atomic (indivisible), with no partially applied failures.
Approval and authorization updates All changes must be traceable and verifiable on-chain.

This keeps the NFT's data, keys, and permissions consistent and helps prevent tampering and unauthorized operations.

Sealed Executor

A Sealed Executor is an essential component for securely operating the standard. Although it is not included in the ERC7857 specification, it is envisioned as an environment responsible for securely processing requests and returning results.

Main responsibilities
  • Authenticate users and check them against the authorized public-key list for each token ID.
  • Execute requests confidentially only after successful signature verification.
  • Return execution results to users securely.

The Sealed Executor thus acts as a trusted confidential computing environment.

Implementation options
Implementation approach Description
Trusted third-party server An operator performs computation in a secure environment. Suitable where regulations permit.
TEE (Trusted Execution Environment) Provides hardware-level protections for computation.
FHE (Fully Homomorphic Encryption) Performs computations on encrypted data to obtain results without learning the contents.

AI agent users can therefore submit requests securely and use the agent's functionality while preserving privacy without knowing the underlying data.

References

Ming Wu (@sparkmiw), Jason Zeng (@zenghbo), Wei Wu (@Wilbert957), Michael Heinrich (@michaelomg), "ERC-7857: AI Agents NFT with Private Metadata [DRAFT]," Ethereum Improvement Proposals, no. 7857, January 2025. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-7857.

Conclusion

This article covered ERC7857, which proposes a new NFT mechanism for securely managing and transferring AI models, memories, configurations, and related data. I hope this explanation was useful.

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

Twitter @cardene777

I also share information on other platforms. Feel free to explore them.

https://chaldene.net/