Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article examines ERC7962, a proposal for managing token ownership using public-key hashes (keyHash) instead of Ethereum addresses to improve privacy and allow third parties to pay transaction fees.

This article explains the proposal below.

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

Overview

ERC7962 proposes token interfaces that use a hash of a public key (keyHash = keccak256(key)) to manage ownership rather than the Ethereum addresses used by traditional ERC721 non-fungible tokens and ERC20 fungible tokens.

For an introduction to ERC721, see the following article.

[ERC721] Understanding ERC721 from the Ground Up

For an introduction to ERC20, see the following article.

[ERC20] Understanding ERC20 from the Ground Up

In traditional token contracts, ownership and balances are associated with Ethereum addresses through functions such as ownerOf and balanceOf. Anyone can inspect which addresses hold tokens on-chain. Under ERC7962, ownerOf returns a bytes32 keyHash, and balanceOf takes a bytes32 keyHash instead of an address and returns a numeric balance. Owner addresses are not stored as the ownership identifiers. To transfer a token, a caller supplies the owner's public key (key) and an EIP712 signature generated with the corresponding private key to prove ownership.

This design has two main benefits. First, using key hashes instead of addresses improves privacy. Second, anyone with a valid signature can call transfer, allowing a third party to pay the gas fees. Separating proof of ownership from transaction submission makes batching and gas sponsorship possible without requiring the token owner to submit the transaction.

The proposal defines two interfaces: ERC-KeyHash721 for NFTs and ERC-KeyHash20 for fungible tokens.

Motivation

Privacy challenges of address-based ownership

In traditional ERC721 and ERC20 tokens, ownership is tied to Ethereum addresses. Because Ethereum addresses are publicly visible on the blockchain, anyone can see which tokens an address holds and when and to whom it transferred tokens.

This becomes a problem when an address is linked to an individual's identity. For example, withdrawing tokens from an exchange that performs KYC (Know Your Customer) checks can associate the withdrawal address with that individual. Subsequent transaction history can then be traced, potentially revealing the individual's holdings and trading patterns to third parties.

Anonymous collectibles, private transactions, and decentralized identity applications need mechanisms that let users hold and operate tokens without immediately disclosing their identities.

Separating gas payments from ownership

With traditional tokens, the caller (msg.sender) of transfer must be the owner of the tokens being transferred. Alternatively, an approved third party can use the relevant delegated transfer function. In other words, the owner generally submits a transaction and pays gas or authorizes another party beforehand through approve.

However, when gas prices are high or many tokens need to be processed together, it is useful to let someone other than the owner pay the gas fees.

With ERC7962, transfer does not restrict the caller based on msg.sender. Ownership is established using the public key and signature, while anyone can submit the transaction. Relayers and sponsors can therefore pay gas on behalf of token owners.

This approach shares privacy principles with ERC5564 (stealth addresses). ERC7962 applies those principles to token ownership management.

Specification

Basic mechanism

ERC7962 revolves around two concepts: key and keyHash.

A key is a 65-byte uncompressed secp256k1 public key. It starts with the 0x04 prefix, followed by the X coordinate (32 bytes) and the Y coordinate (32 bytes).

secp256k1

This is the elliptic curve used by Ethereum for public-key cryptography. A public key is derived from a private key and is in turn used to derive an Ethereum address. An uncompressed public key includes both X and Y coordinates and occupies 65 bytes including the prefix.

A keyHash is the keccak256 hash of this key, represented as bytes32. Token ownership is associated with this hash. The contract records the keyHash as the ownership identifier, and the public key (key) itself is revealed when spending the token.

A transfer works as follows.

  1. The owner signs the transfer details as EIP712 structured data.
  2. A caller invokes transfer with the signature and public key (key). The caller need not be the owner.
  3. The contract checks that keccak256(key) matches the current keyHash.
  4. The contract verifies the signature to establish that the legitimate owner authorized the action.
  5. Ownership moves to the new keyHash.
Why there is no approve function

ERC7962 deliberately omits approve. Because key is revealed in transaction calldata during a transfer, the design assumes that a key is used once. Once it is revealed, holdings are normally migrated to a fresh keyHash. Implementations may prohibit reuse of a previously revealed keyHash.

Rather than requiring approve, the contract allows anyone to call transfer with a valid signature. The signature must come from the private key corresponding to the address derived from key, so third parties cannot authorize transfers of their own accord.

ERC-KeyHash721

This is the interface for NFTs. Each token is identified by a tokenId, and ownership is managed using a keyHash.

javascript
interface IERCKeyHash721 {
    // イベント
    event KeyHashTransfer721(uint256 indexed tokenId, bytes32 indexed fromKeyHash, bytes32 indexed toKeyHash);
    event KeyHashBurn721(uint256 indexed tokenId, bytes32 indexed ownerKeyHash);

    // View関数(ERC721と対応)
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function tokenURI(uint256 tokenId) external view returns (string memory);
    function totalSupply() external view returns (uint256);
    function ownerOf(uint256 tokenId) external view returns (bytes32);

    // 状態変更関数
    function mint(uint256 tokenId, bytes32 keyHash) external;
    function transfer(uint256 tokenId, bytes32 toKeyHash, bytes memory key, bytes memory signature, uint256 deadline) external;
    function destroy(uint256 tokenId, bytes memory key, bytes memory signature, uint256 deadline) external;
}

The principal difference from traditional ERC721 is the return value of ownerOf. ERC721 returns an address, while ERC-KeyHash721 returns a bytes32 (keyHash). The owner's Ethereum address is therefore not directly disclosed by the ownership record.

name, symbol, tokenURI, and totalSupply follow the same formats as their ERC721 counterparts, including the metadata and supply interfaces. tokenURI is part of the core interface but may return an empty string when metadata is unnecessary.

transfer
javascript
function transfer(
    uint256 tokenId,
    bytes32 toKeyHash,
    bytes memory key,
    bytes memory signature,
    uint256 deadline
) external;

This function transfers the specified token from the current owner's keyHash to a new toKeyHash. The caller supplies the owner's public key (key) as evidence of ownership, and the contract verifies authorization through an EIP712 structured-data signature.

Parameter Type Description
tokenId uint256 ID of the token to transfer.
toKeyHash bytes32 New owner's key hash. Must not be zero.
key bytes Current owner's 65-byte uncompressed secp256k1 public key, starting with 0x04.
signature bytes ECDSA signature generated using the private key corresponding to key, preventing unauthorized relay modifications.
deadline uint256 Signature expiration time (Unix timestamp in seconds).

The signature message consists of the following EIP712 structured data.

javascript
struct Transfer {
    uint256 tokenId;
    bytes32 toKeyHash;
    uint256 nonce;
    uint256 deadline;
}

When this function succeeds, it emits KeyHashTransfer721(tokenId, fromKeyHash, toKeyHash).

The following conditions must be satisfied.

  • The token exists (its fromKeyHash is nonzero).
  • keccak256(key) matches the current fromKeyHash.
  • The signature is valid.
  • block.timestamp is less than or equal to deadline.
  • toKeyHash is nonzero.
destroy
javascript
function destroy(
    uint256 tokenId,
    bytes memory key,
    bytes memory signature,
    uint256 deadline
) external;

This function permanently removes (burns) the specified token. As with transfer, ownership is proven with the owner's public key and signature. It is an optional extension, not part of the core interface.

  • Arguments
Parameter Type Description
tokenId uint256 ID of the token to remove.
key bytes Current owner's 65-byte uncompressed secp256k1 public key.
signature bytes ECDSA signature produced using the private key corresponding to key.
deadline uint256 Signature expiration time (Unix timestamp in seconds).

The signature message consists of the following EIP712 structured data.

javascript
struct Destroy {
    uint256 tokenId;
    uint256 nonce;
    uint256 deadline;
}

In the historical implementation described here, the function emits KeyHashBurn721(tokenId, ownerKeyHash). Destroyed tokens are recorded in the _destroyedTokens mapping, and subsequent calls to ownerOf or transfer fail.

The current proposal requires a KeyHashTransfer721 event with a zero destination key hash when a token is destroyed; the historical burn event alone does not satisfy that indexing requirement.

destroy uses a different type hash (DESTROY_TYPEHASH) from transfer. A transfer signature therefore cannot be reused as a destruction signature, or vice versa.

ERC-KeyHash20

This interface is for fungible tokens (FTs). Balances are associated with key hashes.

javascript
interface IERCKeyHash20 {
    // イベント
    event KeyHashTransfer20(bytes32 indexed fromKeyHash, bytes32 indexed toKeyHash, uint256 amount);

    // View関数(ERC20と対応)
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);
    function totalSupply() external view returns (uint256);
    function balanceOf(bytes32 keyHash) external view returns (uint256);

    // 状態変更関数
    function mint(bytes32 keyHash, uint256 amount) external;
    function transfer(bytes32 fromKeyHash, bytes32 toKeyHash, uint256 amount, bytes memory key, bytes memory signature, uint256 deadline, bytes32 leftKeyHash) external;
}

The difference from traditional ERC20 is that balanceOf accepts a bytes32 keyHash instead of an address.

transfer
javascript
function transfer(
    bytes32 fromKeyHash,
    bytes32 toKeyHash,
    uint256 amount,
    bytes memory key,
    bytes memory signature,
    uint256 deadline,
    bytes32 leftKeyHash
) external;

This function transfers amount tokens from fromKeyHash to toKeyHash and assigns the remaining balance to leftKeyHash.

Parameter Type Description
fromKeyHash bytes32 Token owner's key hash.
toKeyHash bytes32 Recipient's key hash.
amount uint256 Amount to transfer.
key bytes Owner's 65-byte uncompressed secp256k1 public key, starting with 0x04.
signature bytes ECDSA signature.
deadline uint256 Signature expiration time.
leftKeyHash bytes32 Key hash to which the remaining balance is assigned. Must differ from both toKeyHash and fromKeyHash to enforce change-key rotation and reduce linkability.

The leftKeyHash mechanism resembles Bitcoin's UTXO (Unspent Transaction Output) model. Suppose a keyHash holds 100 tokens and its owner wants to send 30. The transfer sends 30 tokens to toKeyHash and assigns the remaining 70 to leftKeyHash. The balance of fromKeyHash becomes zero.

graph LR
    A["fromKeyHash<br/>残高: 100"] --> B["toKeyHash<br/>+30"]
    A --> C["leftKeyHash<br/>+70"]
    A --> D["fromKeyHash<br/>残高: 0"]

leftKeyHash must differ from both fromKeyHash and toKeyHash. This constraint is called strict mode and prevents change from being consolidated with the original account or the recipient. Using a fresh keyHash each time avoids reusing the same exposed public key and reduces linkability, although the change path within the contract remains publicly visible.

The signature message has the following structure.

javascript
struct Transfer {
    bytes32 fromKeyHash;
    bytes32 toKeyHash;
    uint256 amount;
    uint256 nonce;
    uint256 deadline;
    bytes32 leftKeyHash;
}

Execution requires the following conditions.

  • The balance of fromKeyHash is at least amount.
  • keccak256(key) matches fromKeyHash.
  • The signature is valid.
  • block.timestamp is less than or equal to deadline.
  • toKeyHash and leftKeyHash are nonzero.
  • leftKeyHash differs from both toKeyHash and fromKeyHash.

Signature verification flow

Signature verification in transfer proceeds in six steps.

sequenceDiagram
    participant Caller as 呼び出し者
    participant Contract as コントラクト
    participant EIP712 as EIP712ハッシュ
    participant ECDSA as ecrecover

    Caller->>Contract: transfer(key, signature, ...)
    Contract->>Contract: 1. keccak256(key) == keyHash を確認
    Contract->>EIP712: 2. 構造化データのダイジェストを計算
    EIP712-->>Contract: digest
    Contract->>ECDSA: 3. ecrecover(digest, signature)
    ECDSA-->>Contract: signer address
    Contract->>Contract: 4. signer == address(keccak256(key[1:])) を確認
    Contract->>Contract: 5. nonce をインクリメント
    Contract->>Contract: 6. block.timestamp <= deadline を確認

The steps are as follows.

  1. Check that keccak256(key) matches the current keyHash. This verifies that the caller supplied the correct public key.
  2. Compute the digest (hash) from the EIP712 structured data, including the transfer parameters, nonce, and deadline.
  3. Recover an address from the signature using ecrecover.
  4. Check that the recovered address matches the address derived from key: the last 20 bytes of the keccak256 hash of the 64-byte payload after removing the first byte (0x04).
  5. Increment _keyNonces[keyHash] to prevent reuse of the same signature (a replay attack).
  6. Check that block.timestamp is less than or equal to deadline and reject expired signatures.

The EIP712 digest is calculated as follows.

javascript
bytes32 digest = keccak256(abi.encodePacked(
    "\x19\x01",
    DOMAIN_SEPARATOR,
    keccak256(abi.encode(
        TYPE_HASH,
        params // 構造体のフィールド(tokenId, toKeyHash, nonce, deadlineなど)
    ))
));

DOMAIN_SEPARATOR incorporates the contract address and chainId, binding signatures to a particular contract and chain and preventing cross-contract and cross-chain replay. Nonces are tracked per keyHash and per contract. Operations for the same keyHash must be serialized.

Contract requirements

The following table summarizes the contract requirements described by ERC7962.

Requirement ERC-KeyHash721 ERC-KeyHash20
Ownership mapping tokenId → keyHash keyHash → balance
Nonce mapping keyHash → uint256 keyHash → uint256
EIP712 signature hashing Required Required
deadline validation Required Required
Key and signature verification Required in transfer Required in transfer
leftKeyHash constraint Not applicable Must differ from toKeyHash and fromKeyHash

mint (creation) and destroy (removal) are optional administrative functions. If implemented, they should enforce appropriate access control, maintain correct supply accounting, and preserve the key-hash privacy model without directly exposing owner addresses.

The current specification also requires public nonce lookup, ERC5267 domain discovery, and the prescribed transfer events for all ownership and balance changes. These are important when evaluating the historical examples below.

Additional details

Benefits of the key-hash approach

The key-hash approach adopted by ERC7962 offers the following benefits.

Comparison of ownership models

  • Privacy ownerOf returns a keyHash and balanceOf uses a keyHash as its lookup key, rather than exposing owner addresses. Users can reduce linkability across tokens by using different key pairs for different holdings.
  • Separation of gas payments Anyone with a valid signature can invoke transfer, allowing batching and gas sponsorship. Even if the owner holds no ETH, a relayer can pay gas to move the tokens.
  • Flexibility The design aligns with the principles of ERC5564 (stealth addresses) and is suitable for token systems that emphasize privacy.

Rationale for the transfer design

The decision to allow anyone to invoke transfer is deliberate. Signatures ensure that only the owner can authorize the action while allowing third parties to pay gas.

The EIP712 structured signature covers all critical parameters, such as tokenId, toKeyHash, amount, and leftKeyHash, so a relayer cannot alter these parameters without invalidating the signature. Per-keyHash nonces and deadline also protect against replay attacks and misuse of expired signatures.

Compatibility

ERC7962 is not compatible with the standard ERC721 or ERC20 interfaces. It uses bytes32 key hashes instead of addresses to manage ownership and balances.

Adapter contracts may nevertheless bridge key-hash tokens to existing systems. For example, an adapter implementing the ERC721 ownerOf interface could retrieve ownership information from the key-hash contract and return an appropriate address through a separately established mapping. An address cannot generally be recovered from a key hash alone; the adapter would need an explicit mapping or another mechanism and could affect privacy. This approach can be particularly useful in privacy-oriented applications.

Security

Replay attacks

A replay attack reuses a previously valid signature to execute an unauthorized action.

ERC7962 tracks a nonce per keyHash (_keyNonces[keyHash]). The nonce increases after each successful operation, preventing the same signature from being used again. This resembles the nonce management of ERC2612 (permit).

For more information about ERC2612, see the following article.

[ERC2612] Combining ERC20 Approval and Transfer in One Transaction

Message tampering

A malicious relayer might intercept a signature and attempt to steal tokens by changing the recipient or token ID.

Because the EIP712 structured signature covers all critical parameters, changing even one parameter changes the message hash and causes signature verification to fail. Using separate type hashes such as TRANSFER_TYPEHASH and DESTROY_TYPEHASH also prevents a signature intended for one function from being reused for another.

Contract audits should check for omitted parameters and ambiguous or colliding hash encodings.

Signature expiration

If a signature leaks and has no expiration time, it may be misused indefinitely.

ERC7962 uses the deadline parameter to limit signature validity. A signature is rejected if block.timestamp exceeds deadline, reducing the risk that a leaked signature is exploited after it expires.

Privacy limitations

The scheme does not guarantee complete anonymity. When transfer is invoked, the public key (key) appears in calldata (transaction data). Anyone can derive the corresponding Ethereum address off-chain from keccak256(key[1:]) by taking the last 20 bytes.

Thus, after a transfer reveals the key, the address corresponding to that keyHash can be derived. Using a fresh key pair for each token or transaction reduces linkability. The corresponding private key must be stored securely, and an unrevealed public key should not be disclosed prematurely if its concealment matters.

The proposal does not hide amounts or the intra-contract transfer graph: observers can still trace transfers and follow the sequence of change key hashes.

Key management

Losing or compromising the private key corresponding to key can result in loss of control over the token. Users must manage keyHash-specific key pairs in addition to any conventional Ethereum wallet keys, increasing the key-management burden. Private keys should be stored in a secure system.

Signature malleability

Signature Malleability

Signature malleability allows different byte representations of a mathematically valid signature for the same message. An attacker may exploit this to change a signature hash and attempt to resubmit an operation as a distinct transaction.

Implementations must reject malleable signatures, including signatures with a non-canonical high s value or a v value other than 27 or 28 in the expected signature format. OpenZeppelin's ECDSA helpers perform these checks by default.

Gas costs

Signature verification and EIP712 hashing increase gas costs compared with a conventional transfer function. Implementations should be optimized where practical, and gas sponsorship can shift the cost away from the token owner when appropriate.

Reference implementations

ERC-KeyHash721 implementation

The following is the complete historical ERC-KeyHash721 reference implementation reproduced in the original article. It uses OpenZeppelin's ECDSA and EIP712 utilities.

KeyHashERC721.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";

contract KeyHashERC721 is EIP712 {
    using ECDSA for bytes32;

    string public name;
    string public symbol;
    mapping(uint256 => bytes32) private _tokenKeyHashes;
    mapping(uint256 => bool) private _destroyedTokens;
    uint256 public totalSupply;
    mapping(bytes32 => uint256) private _keyNonces;

    event KeyHashTransfer721(uint256 indexed tokenId, bytes32 indexed fromKeyHash, bytes32 indexed toKeyHash);
    event KeyHashBurn721(uint256 indexed tokenId, bytes32 indexed ownerKeyHash);

    bytes32 private constant TRANSFER_TYPEHASH = keccak256(
        "Transfer(uint256 tokenId,bytes32 toKeyHash,uint256 nonce,uint256 deadline)"
    );
    bytes32 private constant DESTROY_TYPEHASH = keccak256(
        "Destroy(uint256 tokenId,uint256 nonce,uint256 deadline)"
    );

    constructor(string memory _name, string memory _symbol)
        EIP712("KeyHashERC721", "1")
    {
        name = _name;
        symbol = _symbol;
    }

    function ownerOf(uint256 tokenId) external view returns (bytes32) {
        require(_tokenKeyHashes[tokenId] != 0 && !_destroyedTokens[tokenId], "Token does not exist");
        return _tokenKeyHashes[tokenId];
    }

    function tokenURI(uint256) external pure returns (string memory) { return ""; }

    function transfer(
        uint256 tokenId,
        bytes32 toKeyHash,
        bytes memory key,
        bytes memory signature,
        uint256 deadline
    ) external {
        require(toKeyHash != bytes32(0), "Invalid recipient hash");
        require(_tokenKeyHashes[tokenId] != 0 && !_destroyedTokens[tokenId], "Token does not exist");
        require(block.timestamp <= deadline, "Signature expired");
        require(key.length == 65 && key[0] == 0x04, "BAD_KEY_FMT");
        bytes32 currentKeyHash = _tokenKeyHashes[tokenId];
        require(keccak256(key) == currentKeyHash, "BAD_KEYHASH");

        uint256 nonce = _keyNonces[currentKeyHash];
        bytes32 structHash = keccak256(abi.encode(
            TRANSFER_TYPEHASH,
            tokenId,
            toKeyHash,
            nonce,
            deadline
        ));
        bytes32 digest = _hashTypedDataV4(structHash);
        address signer = digest.recover(signature);
        address expectedAddress = _addressFromUncompressedKey(key);
        require(signer == expectedAddress, "Invalid signature");
        _keyNonces[currentKeyHash] = nonce + 1;

        _tokenKeyHashes[tokenId] = toKeyHash;
        emit KeyHashTransfer721(tokenId, currentKeyHash, toKeyHash);
    }

    function getNonce(bytes32 keyHash) external view returns (uint256) {
        return _keyNonces[keyHash];
    }

    function _addressFromUncompressedKey(bytes memory key) internal pure returns (address) {
        require(key.length == 65 && key[0] == 0x04, "BAD_KEY_FMT");
        bytes32 x;
        bytes32 y;
        assembly {
            x := mload(add(key, 0x21))
            y := mload(add(key, 0x41))
        }
        bytes32 h = keccak256(abi.encodePacked(x, y));
        return address(uint160(uint256(h)));
    }
}

The _addressFromUncompressedKey helper derives an Ethereum address from a 65-byte uncompressed public key. The address is the last 20 bytes of the keccak256 hash of the 64-byte payload (X coordinate + Y coordinate), excluding the leading 0x04 prefix. This is how Ethereum derives a conventional externally owned account (EOA) address.

The transfer function first validates the public-key format (65 bytes, starting with 0x04), then checks that keccak256(key) matches the current owner's keyHash. It computes the digest from the EIP712 structured data and verifies that the address recovered through ECDSA recovery matches the address derived from the public key. After successful verification, it increments the nonce and transfers ownership to the new keyHash.

ERC-KeyHash20 implementation

The following is the complete historical ERC-KeyHash20 reference implementation reproduced in the original article.

KeyHashERC20.sol
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";

contract KeyHashERC20 is EIP712 {
    using ECDSA for bytes32;

    string public name;
    string public symbol;
    uint8 public decimals;
    mapping(bytes32 => uint256) public balanceOf;
    uint256 public totalSupply;
    mapping(bytes32 => uint256) private _keyNonces;

    event KeyHashTransfer20(bytes32 indexed fromKeyHash, bytes32 indexed toKeyHash, uint256 amount);

    bytes32 private constant TRANSFER_TYPEHASH = keccak256(
        "Transfer(bytes32 fromKeyHash,bytes32 toKeyHash,uint256 amount,uint256 nonce,uint256 deadline,bytes32 leftKeyHash)"
    );

    constructor(string memory _name, string memory _symbol)
        EIP712("KeyHashERC20", "1")
    {
        name = _name;
        symbol = _symbol;
        decimals = 18;
    }

    function transfer(
        bytes32 fromKeyHash,
        bytes32 toKeyHash,
        uint256 amount,
        bytes memory key,
        bytes memory signature,
        uint256 deadline,
        bytes32 leftKeyHash
    ) external {
        require(balanceOf[fromKeyHash] >= amount, "Insufficient balance");
        require(toKeyHash != bytes32(0), "Invalid recipient hash");
        require(leftKeyHash != bytes32(0), "Invalid leftKeyHash");
        require(leftKeyHash != toKeyHash, "LEFT_EQ_TO");
        require(leftKeyHash != fromKeyHash, "LEFT_EQ_FROM");
        require(block.timestamp <= deadline, "Signature expired");
        require(key.length == 65 && key[0] == 0x04, "BAD_KEY_FMT");
        require(keccak256(key) == fromKeyHash, "BAD_KEYHASH");

        uint256 nonce = _keyNonces[fromKeyHash];
        bytes32 structHash = keccak256(abi.encode(
            TRANSFER_TYPEHASH,
            fromKeyHash,
            toKeyHash,
            amount,
            nonce,
            deadline,
            leftKeyHash
        ));
        bytes32 digest = _hashTypedDataV4(structHash);
        address signer = digest.recover(signature);
        address expectedAddress = _addressFromUncompressedKey(key);
        require(signer == expectedAddress, "Invalid signature");
        _keyNonces[fromKeyHash] = nonce + 1;

        uint256 remaining = balanceOf[fromKeyHash] - amount;
        balanceOf[fromKeyHash] = 0;
        balanceOf[toKeyHash] += amount;
        balanceOf[leftKeyHash] += remaining;
        emit KeyHashTransfer20(fromKeyHash, toKeyHash, amount);
    }

    function getNonce(bytes32 keyHash) external view returns (uint256) {
        return _keyNonces[keyHash];
    }

    function _addressFromUncompressedKey(bytes memory key) internal pure returns (address) {
        require(key.length == 65 && key[0] == 0x04, "BAD_KEY_FMT");
        bytes32 x;
        bytes32 y;
        assembly {
            x := mload(add(key, 0x21))
            y := mload(add(key, 0x41))
        }
        bytes32 h = keccak256(abi.encodePacked(x, y));
        return address(uint160(uint256(h)));
    }
}

The distinctive aspect of the ERC-KeyHash20 transfer function is its balance handling. The entire balance under fromKeyHash is reset to zero, amount is assigned to toKeyHash, and the remainder is assigned to leftKeyHash. This allows the original key hash to be treated as single-use and avoids keeping funds under the just-revealed public key.

leftKeyHash must differ from both toKeyHash and fromKeyHash. This strict mode constraint prevents change from being consolidated with the original account or recipient and is intended to encourage use of a fresh change key pair each time.

These code samples preserve the original article's historical interfaces and implementations. They are not verified implementations of the latest ERC7962 draft. In particular, the current draft requires nonces(bytes32) and a five-argument KeyHashTransfer20 event that accounts for the change key hash and amount, rather than the older three-argument event shown here. Review the current specification and audit an updated implementation before using it in production.

References

Conclusion

This article examined ERC7962, the Key Hash Based Tokens proposal that manages token ownership using key hashes instead of Ethereum addresses.

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

I also write on the following platforms.