---
eip: 5646
label: ERC-5646
title: Token State Fingerprint
status: Final
type: Standards Track
category: ERC
created: 2022-09-11
requires: 165
official: https://eips.ethereum.org/EIPS/eip-5646
source: https://github.com/ethereum/ERCs/blob/master/ERCS/erc-5646.md
canonical: https://eips.huatuo.xyz/zh/eip-5646/
lang: zh
tldr: 增加 getStateFingerprint(tokenId)，让协议无需理解某个代币如何存储状态，就能检测可变 NFT 的状态是否发生了变化。
tags: [nft, token, mutable, marketplace, interface]
---

# ERC-5646: Token State Fingerprint

> Unambiguous token state identifier

**TL;DR:** 增加 getStateFingerprint(tokenId)，让协议无需理解某个代币如何存储状态，就能检测可变 NFT 的状态是否发生了变化。

## 它解决什么问题？

许多 NFT 并不是静态图片。LP 头寸 NFT 持有会变化的数量，债券 NFT 会到期，游戏道具会提升属性。如果市场或借贷协议对"代币 #42"发出报价，所有者可以在接受报价之前改变代币的状态（比如提取流动性），对手方最终得到的东西价值要低得多。

为防止这种情况，协议需要一个标识符来表示"处于*这个确切状态*的代币 #42"。此前，协议必须理解每种代币的内部字段并自行计算哈希，这意味着每出现一种新代币类型就要做定制集成。

ERC-5646 把这项工作移到代币内部：由代币自己发布其当前状态的指纹。

## 它如何运作

代币合约实现一个 view 函数：

```solidity
function getStateFingerprint(uint256 tokenId) external view returns (bytes32);
```

规则如下：

- 只要代币的状态发生变化，该值就**必须改变**；状态不变，则**不得改变**。
- 它必须涵盖代币生命周期中可能变化的每一项属性。不可变的属性可以省略，因为 token id 已经标识了它们。
- 它**可以**包含计算得出的值（例如根据当前时间戳判断代币是否已过期）以及元数据 URI。
- `supportsInterface(0xf5112315)` 必须返回 `true`（[ERC-165](/eip-165/)）。

协议在发出报价时保存指纹，并在执行时再次检查。如果两者不同，说明代币在此期间发生了变化，交易将被拒绝。

## 示例代码

一个计算自身指纹的代币（改编自规范的参考实现）：

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface IERC5646 {
    function getStateFingerprint(uint256 tokenId) external view returns (bytes32);
}

contract LPPosition is IERC5646 {
    struct State {
        address asset1;
        address asset2;
        uint256 amount1;
        uint256 amount2;
        uint256 fee;         // immutable -> not in fingerprint
        uint256 expiration;  // fingerprint uses "expired or not"
    }
    mapping(uint256 => State) internal states;

    function getStateFingerprint(uint256 tokenId) public view returns (bytes32) {
        State storage s = states[tokenId];
        return keccak256(abi.encode(
            s.asset1, s.asset2, s.amount1, s.amount2,
            block.timestamp >= s.expiration
        ));
    }

    function supportsInterface(bytes4 id) public pure returns (bool) {
        return id == 0x01ffc9a7 || id == 0xf5112315;
    }
}
```

一个保护报价不受状态变化影响的市场：

```solidity
struct Offer { address collection; uint256 tokenId; bytes32 fingerprint; uint256 price; }

function accept(Offer calldata o) external {
    require(
        IERC5646(o.collection).getStateFingerprint(o.tokenId) == o.fingerprint,
        "token state changed"
    );
    // ... transfer NFT and payment
}
```

## 需要注意

- **状态：Final。**
- 指纹只在单个合约内才有意义。两个不同的合约可能产生相同的值，因此务必连同合集地址一起比较。
- 该方案的安全性完全取决于代币的实现。如果某个可变字段没有纳入哈希，所有者就可以修改它而不改变指纹。
- 当协议确实需要*读取*特定的状态属性（例如为代币估值）时，它帮不上忙；它只告诉你"相同还是不同"。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-5646
