From 60bc288c41247e26e39ba36826486e28e8c8672f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20Daubensch=C3=BCtz?= Date: Mon, 1 Aug 2022 12:34:39 +0200 Subject: [PATCH] Adjust EIP-4973 interface to add `function give(...)` and `function take(...)` (#5209) * Add new interface definition * Add flat file reference implementation * Replace Attest/Revoke with Transfer event * Change burn to unequip * Fix transfer requirement of take fn * Add security considerations section * Require EIP-1271 * Describe EIP-712 signature creation * Fix tabs * Link to EIP-712 * Adjust code type to js * Finalize flat file reference impl. * Require 2098 not 2089 --- EIPS/eip-4973.md | 197 ++++++-- assets/eip-4973/ERC-4973.sol | 902 +++++++++++++++++++++++++++++++++-- 2 files changed, 1043 insertions(+), 56 deletions(-) diff --git a/EIPS/eip-4973.md b/EIPS/eip-4973.md index cb97700a5bacd5..531b0e8f07c473 100644 --- a/EIPS/eip-4973.md +++ b/EIPS/eip-4973.md @@ -1,14 +1,14 @@ --- eip: 4973 title: Account-bound Tokens -description: A standard interface for non-transferrable NFTs binding to an Ethereum account like a legendary World of Warcraft item binds to a character. +description: An interface for non-transferrable NFTs binding to an Ethereum account like a legendary World of Warcraft item binds to a character. author: Tim Daubenschütz (@TimDaub), Raphael Roullet (@ra-phael) discussions-to: https://ethereum-magicians.org/t/eip-4973-non-transferrable-non-fungible-tokens-soulbound-tokens-or-badges/8825 status: Draft type: Standards Track category: ERC created: 2022-04-01 -requires: 165, 721 +requires: 165, 712, 721, 1271, 2098 --- ## Abstract @@ -21,11 +21,11 @@ In the popular MMORPG World of Warcraft, its game designers intentionally took s Vanilla WoW's "Thunderfury, Blessed Blade of the Windseeker" was one such legendary item, and it required a forty-person raid, among other sub-tasks, to slay the firelord "Ragnaros" to gain the "Essence of the Firelord," a material needed to craft the sword once. -Upon voluntary pickup, the sword permanently binds to a character's "soul," making it impossible to trade, sell or even swap it between a player's characters. +Upon voluntary pickup, the sword permanently **binds** to a character's "soul," making it impossible to trade, sell or even swap it between a player's characters. In other words, "Thunderfury"'s price was the aggregate of all social costs related to completing the difficult quest line with friends and guild members. Other players spotting Thunderfuries could be sure their owner had slain "Ragnaros," the blistering firelord. -World of Warcraft players could trash legendary and soulbound items like the Thunderfury to permanently remove them from their account. +World of Warcraft players could **trash** legendary and soulbound items like the Thunderfury to permanently remove them from their account. It was their choice to visibly **equip** or **unequip** an item and hence show their achievements to everyone. The Ethereum community has expressed a need for non-transferrable, non-fungible, and socially-priced tokens similar to WoW's soulbound items. Popular contracts implicitly implement account-bound interaction rights today. A principled standardization helps interoperability and improves on-chain data indexing. @@ -44,7 +44,7 @@ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "S - [EIP-721](./eip-721.md)'s `ERC721` (`0x80ac58cd`) -An ABT receiver must be able to always call `function burn(address _tokenId)` to disassociate themselves from an ABT publicly. +An ABT receiver must be able to always call `function unequip(address _tokenId)` to take their ABT off-chain. ```solidity // SPDX-License-Identifier: CC0-1.0 @@ -52,37 +52,172 @@ pragma solidity ^0.8.6; /// @title Account-bound tokens /// @dev See https://eips.ethereum.org/EIPS/eip-4973 -/// Note: the ERC-165 identifier for this interface is 0x5164cf47. -interface IERC4973 /* is ERC165, ERC721Metadata */ { - /// @dev This emits when a new token is created and bound to an account by - /// any mechanism. - /// Note: For a reliable `from` parameter, retrieve the transaction's - /// authenticated `from` field. - event Attest(address indexed to, uint256 indexed tokenId); - /// @dev This emits when an existing ABT is revoked from an account and - /// destroyed by any mechanism. - /// Note: For a reliable `from` parameter, retrieve the transaction's - /// authenticated `from` field. - event Revoke(address indexed to, uint256 indexed tokenId); +/// Note: the ERC-165 identifier for this interface is 0x5164cf47 +interface IERC4973 { + /// @dev This emits when ownership of any ABT changes by any mechanism. + /// This event emits when ABTs are given or equipped and unequipped + /// (`to` == 0). + event Transfer( + address indexed from, + address indexed to, + uint256 indexed tokenId + ); /// @notice Count all ABTs assigned to an owner /// @dev ABTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param owner An address for whom to query the balance - /// @return The number of ABTs owned by `owner`, possibly zero + /// @return The number of ABTs owned by `address owner`, possibly zero function balanceOf(address owner) external view returns (uint256); /// @notice Find the address bound to an ERC4973 account-bound token /// @dev ABTs assigned to zero address are considered invalid, and queries /// about them do throw. - /// @param tokenId The identifier for an ABT - /// @return The address of the owner bound to the ABT + /// @param tokenId The identifier for an ABT. + /// @return The address of the owner bound to the ABT. function ownerOf(uint256 tokenId) external view returns (address); - /// @notice Destroys `tokenId`. At any time, an ABT receiver must be able to - /// disassociate themselves from an ABT publicly through calling this - /// function. - /// @dev Must emit a `event Revoke` with the `address to` field pointing to + /// @notice Removes the `uint256 tokenId` from an account. At any time, an + /// ABT receiver must be able to disassociate themselves from an ABT + /// publicly through calling this function. After successfully executing this + /// function, given the parameters for calling `function give` or + /// `function take` a token must be re-equipable. + /// @dev Must emit a `event Transfer` with the `address to` field pointing to /// the zero address. - /// @param tokenId The identifier for an ABT - function burn(uint256 tokenId) external; + /// @param tokenId The identifier for an ABT. + function unequip(uint256 tokenId) external; + /// @notice Creates and transfers the ownership of an ABT from the + /// transaction's `msg.sender` to `address to`. + /// @dev Throws unless `bytes signature` represents an EIP-2098 Compact + /// Signature of the EIP-712 structured data hash + /// `Agreement(address active,address passive,string tokenURI)` expressing + /// `address to`'s explicit agreement to be publicly associated with + /// `msg.sender` and `string tokenURI`. A unique `uint256 tokenId` must be + /// generated by type-casting the `bytes32` EIP-712 structured data hash to a + /// `uint256`. If `bytes signature` is empty or `address to` is a contract, + /// an EIP-1271-compatible call to `function isValidSignatureNow(...)` must + /// be made to `address to`. A successful execution must result in the + /// `event Transfer(msg.sender, to, tokenId)`. Once an ABT exists as an + /// `uint256 tokenId` in the contract, `function give(...)` must throw. + /// @param to The receiver of the ABT. + /// @param uri A distinct Uniform Resource Identifier (URI) for a given ABT. + /// @param signature A EIP-2098-compatible Compact Signature of the EIP-712 + /// structured data hash + /// `Agreement(address active,address passive,string tokenURI)` signed by + /// `address to`. + /// @return A unique `uint256 tokenId` generated by type-casting the `bytes32` + /// EIP-712 structured data hash to a `uint256`. + function give( + address to, + string calldata uri, + bytes calldata signature + ) external returns (uint256); + /// @notice Creates and transfers the ownership of an ABT from an + /// `address from` to the transaction's `msg.sender`. + /// @dev Throws unless `bytes signature` represents an EIP-2098 Compact + /// Signature of the EIP-712 structured data hash + /// `Agreement(address active,address passive,string tokenURI)` expressing + /// `address from`'s explicit agreement to be publicly associated with + /// `msg.sender` and `string tokenURI`. A unique `uint256 tokenId` must be + /// generated by type-casting the `bytes32` EIP-712 structured data hash to a + /// `uint256`. If `bytes signature` is empty or `address from` is a contract, + /// an EIP-1271-compatible call to `function isValidSignatureNow(...)` must + /// be made to `address from`. A successful execution must result in the + /// emission of an `event Transfer(from, msg.sender, tokenId)`. Once an ABT + /// exists as an `uint256 tokenId` in the contract, `function take(...)` must + /// throw. + /// @param from The origin of the ABT. + /// @param uri A distinct Uniform Resource Identifier (URI) for a given ABT. + /// @param signature A EIP-2098-compatible Compact Signature of the EIP-712 + /// structured data hash + /// `Agreement(address active,address passive,string tokenURI)` signed by + /// `address from`. + /// @return A unique `uint256 tokenId` generated by type-casting the `bytes32` + /// EIP-712 structured data hash to a `uint256`. + function take( + address from, + string calldata uri, + bytes calldata signature + ) external returns (uint256); +} +``` + +[`EIP-712`](./eip-712.md) typed structure for generating a `bytes signature`: + +```js +keccak256(abi.encodePacked( + hex"1901", + DOMAIN_SEPARATOR, + keccak256(abi.encode( + keccak256("Agreement(address active,address passive,string tokenURI)"), + activeAddress, + passiveAddress, + tokenURI + )) +)) +``` + +`DOMAIN_SEPARATOR` should be unique to the contract and chain to prevent replay attacks from other domains, and satisfy the requirements of [`EIP-712`](./eip-712.md): + +```js +DOMAIN_SEPARATOR = keccak256( + abi.encode( + keccak256( + "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" + ), + keccak256(bytes(name)), + keccak256(bytes(version)), + chainid, + address(this) + ) +); +``` + +```js +{ + "types": { + "EIP712Domain": [ + { + "name": "name", + "type": "string" + }, + { + "name": "version", + "type": "string" + }, + { + "name": "chainId", + "type": "uint256" + }, + { + "name": "verifyingContract", + "type": "address" + } + ], + "Agreement": [ + { + "name": "active", + "type": "address" + }, + { + "name": "passive", + "type": "address" + }, + { + "name": "tokenURI", + "type": "string" + } + ], + "primaryType": "Agreement", + "domain": { + "name": name, + "version": version, + "chainId": chainid, + "verifyingContract": address(this) + }, + "message": { + "active": activeAddress, + "passive": passiveAddress, + "tokenURI": tokenURI + } + } } ``` @@ -102,7 +237,7 @@ Still, since `EIP-4973` supports [`EIP-721`](./eip-721.md)'s `ERC721Metadata` ex Although other implementations of account-bound tokens are possible, e.g., by having all transfer functions revert, `EIP-4973` is superior as it supports feature detection through [`EIP-165`](./eip-165.md). -We expose `function burn(address _tokenId)` and require it to be callable at any time by an ABT's owner as it ensures an owner's right to publicly disassociate themselves from what has been issued towards their account. +We expose `function unequip(address _tokenId)` and require it to be callable at any time by an ABT's owner as it ensures an owner's right to publicly disassociate themselves from what has been issued towards their account. ### Exception handling @@ -114,16 +249,20 @@ In cases where implementers want to make account-bound tokens shareable among di ### Provenance Indexing -ABTs can be indexed by tracking the emission of `event Attest` and `event Revoke`. To guarantee reliable and implementation-independent indexable information, neither `event Attest` nor `event Revoke` include a `from` argument to depict the transaction sender. Instead, as a `from` property wouldn't be authenticated and hence opens a security vector, we omit it and advise indexers to substitute it with the transaction-level `from` field which gets authenticated through Ethereum's transaction signature validation prior to inclusion in a block. +ABTs can be indexed by tracking the emission of `event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)`. As with [`EIP-721`](./eip-721.md), transfers between two accounts are represented by `address from` and `address to` being non-zero addresses. Unequipping a token is represented through emitting a transfer with `address to` being set to the zero address. Mint operations where `address from` is set to zero don't exist. To avoid being spoofed by maliciously-implemented `event Transfer` emitting contracts, an indexer should ensure that the transaction's sender is equal to `event Transfer`'s `from` value. ## Backwards Compatibility -We have adopted the [`EIP-165`](./eip-165.md) and `ERC721Metadata` functions purposefully to create a high degree of backward compatibility with [`EIP-721`](./eip-721.md). We have deliberately used [`EIP-721`](./eip-721.md) terminology such as `function ownerOf(...)` or `function balanceOf(...)` to minimize the effort of familiarization for `EIP-4973` implementers already familiar with, e.g., [`EIP-20`](./eip-20.md) or [`EIP-721`](./eip-721.md). +We have adopted the [`EIP-165`](./eip-165.md) and `ERC721Metadata` functions purposefully to create a high degree of backward compatibility with [`EIP-721`](./eip-721.md). We have deliberately used [`EIP-721`](./eip-721.md) terminology such as `function ownerOf(...)`, `function balanceOf(...)` to minimize the effort of familiarization for `EIP-4973` implementers already familiar with, e.g., [`EIP-20`](./eip-20.md) or [`EIP-721`](./eip-721.md). For indexers, we've re-used the widely-implemented `event Transfer` event signature. ## Reference Implementation You can find an implementation of this standard in [../assets/eip-4973](../assets/eip-4973/ERC-4973.sol). +## Security Considerations + +There are no security considerations related directly to the implementation of this standard. + ## Copyright Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/assets/eip-4973/ERC-4973.sol b/assets/eip-4973/ERC-4973.sol index 434671b1b9f6e5..c7cceef1051a67 100644 --- a/assets/eip-4973/ERC-4973.sol +++ b/assets/eip-4973/ERC-4973.sol @@ -1,6 +1,732 @@ // SPDX-License-Identifier: CC0-1.0 pragma solidity ^0.8.8; +// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol) + +// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) + +// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) + +/** + * @dev String operations. + */ +library Strings { + bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; + uint8 private constant _ADDRESS_LENGTH = 20; + + /** + * @dev Converts a `uint256` to its ASCII `string` decimal representation. + */ + function toString(uint256 value) internal pure returns (string memory) { + // Inspired by OraclizeAPI's implementation - MIT licence + // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol + + if (value == 0) { + return "0"; + } + uint256 temp = value; + uint256 digits; + while (temp != 0) { + digits++; + temp /= 10; + } + bytes memory buffer = new bytes(digits); + while (value != 0) { + digits -= 1; + buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); + value /= 10; + } + return string(buffer); + } + + /** + * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. + */ + function toHexString(uint256 value) internal pure returns (string memory) { + if (value == 0) { + return "0x00"; + } + uint256 temp = value; + uint256 length = 0; + while (temp != 0) { + length++; + temp >>= 8; + } + return toHexString(value, length); + } + + /** + * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. + */ + function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { + bytes memory buffer = new bytes(2 * length + 2); + buffer[0] = "0"; + buffer[1] = "x"; + for (uint256 i = 2 * length + 1; i > 1; --i) { + buffer[i] = _HEX_SYMBOLS[value & 0xf]; + value >>= 4; + } + require(value == 0, "Strings: hex length insufficient"); + return string(buffer); + } + + /** + * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. + */ + function toHexString(address addr) internal pure returns (string memory) { + return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); + } +} + +/** + * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. + * + * These functions can be used to verify that a message was signed by the holder + * of the private keys of a given address. + */ +library ECDSA { + enum RecoverError { + NoError, + InvalidSignature, + InvalidSignatureLength, + InvalidSignatureS, + InvalidSignatureV + } + + function _throwError(RecoverError error) private pure { + if (error == RecoverError.NoError) { + return; // no error: do nothing + } else if (error == RecoverError.InvalidSignature) { + revert("ECDSA: invalid signature"); + } else if (error == RecoverError.InvalidSignatureLength) { + revert("ECDSA: invalid signature length"); + } else if (error == RecoverError.InvalidSignatureS) { + revert("ECDSA: invalid signature 's' value"); + } else if (error == RecoverError.InvalidSignatureV) { + revert("ECDSA: invalid signature 'v' value"); + } + } + + /** + * @dev Returns the address that signed a hashed message (`hash`) with + * `signature` or error string. This address can then be used for verification purposes. + * + * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: + * this function rejects them by requiring the `s` value to be in the lower + * half order, and the `v` value to be either 27 or 28. + * + * IMPORTANT: `hash` _must_ be the result of a hash operation for the + * verification to be secure: it is possible to craft signatures that + * recover to arbitrary addresses for non-hashed data. A safe way to ensure + * this is by receiving a hash of the original message (which may otherwise + * be too long), and then calling {toEthSignedMessageHash} on it. + * + * Documentation for signature generation: + * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] + * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] + * + * _Available since v4.3._ + */ + function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { + // Check the signature length + // - case 65: r,s,v signature (standard) + // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ + if (signature.length == 65) { + bytes32 r; + bytes32 s; + uint8 v; + // ecrecover takes the signature parameters, and the only way to get them + // currently is to use assembly. + /// @solidity memory-safe-assembly + assembly { + r := mload(add(signature, 0x20)) + s := mload(add(signature, 0x40)) + v := byte(0, mload(add(signature, 0x60))) + } + return tryRecover(hash, v, r, s); + } else if (signature.length == 64) { + bytes32 r; + bytes32 vs; + // ecrecover takes the signature parameters, and the only way to get them + // currently is to use assembly. + /// @solidity memory-safe-assembly + assembly { + r := mload(add(signature, 0x20)) + vs := mload(add(signature, 0x40)) + } + return tryRecover(hash, r, vs); + } else { + return (address(0), RecoverError.InvalidSignatureLength); + } + } + + /** + * @dev Returns the address that signed a hashed message (`hash`) with + * `signature`. This address can then be used for verification purposes. + * + * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: + * this function rejects them by requiring the `s` value to be in the lower + * half order, and the `v` value to be either 27 or 28. + * + * IMPORTANT: `hash` _must_ be the result of a hash operation for the + * verification to be secure: it is possible to craft signatures that + * recover to arbitrary addresses for non-hashed data. A safe way to ensure + * this is by receiving a hash of the original message (which may otherwise + * be too long), and then calling {toEthSignedMessageHash} on it. + */ + function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { + (address recovered, RecoverError error) = tryRecover(hash, signature); + _throwError(error); + return recovered; + } + + /** + * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. + * + * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] + * + * _Available since v4.3._ + */ + function tryRecover( + bytes32 hash, + bytes32 r, + bytes32 vs + ) internal pure returns (address, RecoverError) { + bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); + uint8 v = uint8((uint256(vs) >> 255) + 27); + return tryRecover(hash, v, r, s); + } + + /** + * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. + * + * _Available since v4.2._ + */ + function recover( + bytes32 hash, + bytes32 r, + bytes32 vs + ) internal pure returns (address) { + (address recovered, RecoverError error) = tryRecover(hash, r, vs); + _throwError(error); + return recovered; + } + + /** + * @dev Overload of {ECDSA-tryRecover} that receives the `v`, + * `r` and `s` signature fields separately. + * + * _Available since v4.3._ + */ + function tryRecover( + bytes32 hash, + uint8 v, + bytes32 r, + bytes32 s + ) internal pure returns (address, RecoverError) { + // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature + // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines + // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most + // signatures from current libraries generate a unique signature with an s-value in the lower half order. + // + // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value + // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or + // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept + // these malleable signatures as well. + if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { + return (address(0), RecoverError.InvalidSignatureS); + } + if (v != 27 && v != 28) { + return (address(0), RecoverError.InvalidSignatureV); + } + + // If the signature is valid (and not malleable), return the signer address + address signer = ecrecover(hash, v, r, s); + if (signer == address(0)) { + return (address(0), RecoverError.InvalidSignature); + } + + return (signer, RecoverError.NoError); + } + + /** + * @dev Overload of {ECDSA-recover} that receives the `v`, + * `r` and `s` signature fields separately. + */ + function recover( + bytes32 hash, + uint8 v, + bytes32 r, + bytes32 s + ) internal pure returns (address) { + (address recovered, RecoverError error) = tryRecover(hash, v, r, s); + _throwError(error); + return recovered; + } + + /** + * @dev Returns an Ethereum Signed Message, created from a `hash`. This + * produces hash corresponding to the one signed with the + * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] + * JSON-RPC method as part of EIP-191. + * + * See {recover}. + */ + function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { + // 32 is the length in bytes of hash, + // enforced by the type signature above + return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); + } + + /** + * @dev Returns an Ethereum Signed Message, created from `s`. This + * produces hash corresponding to the one signed with the + * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] + * JSON-RPC method as part of EIP-191. + * + * See {recover}. + */ + function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { + return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); + } + + /** + * @dev Returns an Ethereum Signed Typed Data, created from a + * `domainSeparator` and a `structHash`. This produces hash corresponding + * to the one signed with the + * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] + * JSON-RPC method as part of EIP-712. + * + * See {recover}. + */ + function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { + return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); + } +} + +// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) + +/** + * @dev Collection of functions related to the address type + */ +library Address { + /** + * @dev Returns true if `account` is a contract. + * + * [IMPORTANT] + * ==== + * It is unsafe to assume that an address for which this function returns + * false is an externally-owned account (EOA) and not a contract. + * + * Among others, `isContract` will return false for the following + * types of addresses: + * + * - an externally-owned account + * - a contract in construction + * - an address where a contract will be created + * - an address where a contract lived, but was destroyed + * ==== + * + * [IMPORTANT] + * ==== + * You shouldn't rely on `isContract` to protect against flash loan attacks! + * + * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets + * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract + * constructor. + * ==== + */ + function isContract(address account) internal view returns (bool) { + // This method relies on extcodesize/address.code.length, which returns 0 + // for contracts in construction, since the code is only stored at the end + // of the constructor execution. + + return account.code.length > 0; + } + + /** + * @dev Replacement for Solidity's `transfer`: sends `amount` wei to + * `recipient`, forwarding all available gas and reverting on errors. + * + * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost + * of certain opcodes, possibly making contracts go over the 2300 gas limit + * imposed by `transfer`, making them unable to receive funds via + * `transfer`. {sendValue} removes this limitation. + * + * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. + * + * IMPORTANT: because control is transferred to `recipient`, care must be + * taken to not create reentrancy vulnerabilities. Consider using + * {ReentrancyGuard} or the + * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. + */ + function sendValue(address payable recipient, uint256 amount) internal { + require(address(this).balance >= amount, "Address: insufficient balance"); + + (bool success, ) = recipient.call{value: amount}(""); + require(success, "Address: unable to send value, recipient may have reverted"); + } + + /** + * @dev Performs a Solidity function call using a low level `call`. A + * plain `call` is an unsafe replacement for a function call: use this + * function instead. + * + * If `target` reverts with a revert reason, it is bubbled up by this + * function (like regular Solidity function calls). + * + * Returns the raw returned data. To convert to the expected return value, + * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. + * + * Requirements: + * + * - `target` must be a contract. + * - calling `target` with `data` must not revert. + * + * _Available since v3.1._ + */ + function functionCall(address target, bytes memory data) internal returns (bytes memory) { + return functionCallWithValue(target, data, 0, "Address: low-level call failed"); + } + + /** + * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with + * `errorMessage` as a fallback revert reason when `target` reverts. + * + * _Available since v3.1._ + */ + function functionCall( + address target, + bytes memory data, + string memory errorMessage + ) internal returns (bytes memory) { + return functionCallWithValue(target, data, 0, errorMessage); + } + + /** + * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], + * but also transferring `value` wei to `target`. + * + * Requirements: + * + * - the calling contract must have an ETH balance of at least `value`. + * - the called Solidity function must be `payable`. + * + * _Available since v3.1._ + */ + function functionCallWithValue( + address target, + bytes memory data, + uint256 value + ) internal returns (bytes memory) { + return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); + } + + /** + * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but + * with `errorMessage` as a fallback revert reason when `target` reverts. + * + * _Available since v3.1._ + */ + function functionCallWithValue( + address target, + bytes memory data, + uint256 value, + string memory errorMessage + ) internal returns (bytes memory) { + require(address(this).balance >= value, "Address: insufficient balance for call"); + require(isContract(target), "Address: call to non-contract"); + + (bool success, bytes memory returndata) = target.call{value: value}(data); + return verifyCallResult(success, returndata, errorMessage); + } + + /** + * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], + * but performing a static call. + * + * _Available since v3.3._ + */ + function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { + return functionStaticCall(target, data, "Address: low-level static call failed"); + } + + /** + * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], + * but performing a static call. + * + * _Available since v3.3._ + */ + function functionStaticCall( + address target, + bytes memory data, + string memory errorMessage + ) internal view returns (bytes memory) { + require(isContract(target), "Address: static call to non-contract"); + + (bool success, bytes memory returndata) = target.staticcall(data); + return verifyCallResult(success, returndata, errorMessage); + } + + /** + * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], + * but performing a delegate call. + * + * _Available since v3.4._ + */ + function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { + return functionDelegateCall(target, data, "Address: low-level delegate call failed"); + } + + /** + * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], + * but performing a delegate call. + * + * _Available since v3.4._ + */ + function functionDelegateCall( + address target, + bytes memory data, + string memory errorMessage + ) internal returns (bytes memory) { + require(isContract(target), "Address: delegate call to non-contract"); + + (bool success, bytes memory returndata) = target.delegatecall(data); + return verifyCallResult(success, returndata, errorMessage); + } + + /** + * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the + * revert reason using the provided one. + * + * _Available since v4.3._ + */ + function verifyCallResult( + bool success, + bytes memory returndata, + string memory errorMessage + ) internal pure returns (bytes memory) { + if (success) { + return returndata; + } else { + // Look for revert reason and bubble it up if present + if (returndata.length > 0) { + // The easiest way to bubble the revert reason is using memory via assembly + /// @solidity memory-safe-assembly + assembly { + let returndata_size := mload(returndata) + revert(add(32, returndata), returndata_size) + } + } else { + revert(errorMessage); + } + } + } +} + +// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) + +/** + * @dev Interface of the ERC1271 standard signature validation method for + * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. + * + * _Available since v4.1._ + */ +interface IERC1271 { + /** + * @dev Should return whether the signature provided is valid for the provided data + * @param hash Hash of the data to be signed + * @param signature Signature byte array associated with _data + */ + function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); +} + +/** + * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA + * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like + * Argent and Gnosis Safe. + * + * _Available since v4.1._ + */ +library SignatureChecker { + /** + * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the + * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. + * + * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus + * change through time. It could return true at block N and false at block N+1 (or the opposite). + */ + function isValidSignatureNow( + address signer, + bytes32 hash, + bytes memory signature + ) internal view returns (bool) { + (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); + if (error == ECDSA.RecoverError.NoError && recovered == signer) { + return true; + } + + (bool success, bytes memory result) = signer.staticcall( + abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) + ); + return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); + } +} + +// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) + +/** + * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. + * + * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, + * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding + * they need in their contracts using a combination of `abi.encode` and `keccak256`. + * + * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding + * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA + * ({_hashTypedDataV4}). + * + * The implementation of the domain separator was designed to be as efficient as possible while still properly updating + * the chain id to protect against replay attacks on an eventual fork of the chain. + * + * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method + * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. + * + * _Available since v3.4._ + */ +abstract contract EIP712 { + /* solhint-disable var-name-mixedcase */ + // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to + // invalidate the cached domain separator if the chain id changes. + bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; + uint256 private immutable _CACHED_CHAIN_ID; + address private immutable _CACHED_THIS; + + bytes32 private immutable _HASHED_NAME; + bytes32 private immutable _HASHED_VERSION; + bytes32 private immutable _TYPE_HASH; + + /* solhint-enable var-name-mixedcase */ + + /** + * @dev Initializes the domain separator and parameter caches. + * + * The meaning of `name` and `version` is specified in + * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: + * + * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. + * - `version`: the current major version of the signing domain. + * + * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart + * contract upgrade]. + */ + constructor(string memory name, string memory version) { + bytes32 hashedName = keccak256(bytes(name)); + bytes32 hashedVersion = keccak256(bytes(version)); + bytes32 typeHash = keccak256( + "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" + ); + _HASHED_NAME = hashedName; + _HASHED_VERSION = hashedVersion; + _CACHED_CHAIN_ID = block.chainid; + _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); + _CACHED_THIS = address(this); + _TYPE_HASH = typeHash; + } + + /** + * @dev Returns the domain separator for the current chain. + */ + function _domainSeparatorV4() internal view returns (bytes32) { + if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { + return _CACHED_DOMAIN_SEPARATOR; + } else { + return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); + } + } + + function _buildDomainSeparator( + bytes32 typeHash, + bytes32 nameHash, + bytes32 versionHash + ) private view returns (bytes32) { + return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); + } + + /** + * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this + * function returns the hash of the fully encoded EIP712 message for this domain. + * + * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: + * + * ```solidity + * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( + * keccak256("Mail(address to,string contents)"), + * mailTo, + * keccak256(bytes(mailContents)) + * ))); + * address signer = ECDSA.recover(digest, signature); + * ``` + */ + function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { + return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); + } +} + +// OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol) + +/** + * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. + * Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor]. + */ +library BitMaps { + struct BitMap { + mapping(uint256 => uint256) _data; + } + + /** + * @dev Returns whether the bit at `index` is set. + */ + function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { + uint256 bucket = index >> 8; + uint256 mask = 1 << (index & 0xff); + return bitmap._data[bucket] & mask != 0; + } + + /** + * @dev Sets the bit at `index` to the boolean `value`. + */ + function setTo( + BitMap storage bitmap, + uint256 index, + bool value + ) internal { + if (value) { + set(bitmap, index); + } else { + unset(bitmap, index); + } + } + + /** + * @dev Sets the bit at `index`. + */ + function set(BitMap storage bitmap, uint256 index) internal { + uint256 bucket = index >> 8; + uint256 mask = 1 << (index & 0xff); + bitmap._data[bucket] |= mask; + } + + /** + * @dev Unsets the bit at `index`. + */ + function unset(BitMap storage bitmap, uint256 index) internal { + uint256 bucket = index >> 8; + uint256 mask = 1 << (index & 0xff); + bitmap._data[bucket] &= ~mask; + } +} + // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) @@ -59,40 +785,101 @@ interface IERC721Metadata { /// @dev See https://eips.ethereum.org/EIPS/eip-4973 /// Note: the ERC-165 identifier for this interface is 0x5164cf47 interface IERC4973 { - /// @dev This emits when a new token is created and bound to an account by - /// any mechanism. - /// Note: For a reliable `from` parameter, retrieve the transaction's - /// authenticated `from` field. - event Attest(address indexed to, uint256 indexed tokenId); - /// @dev This emits when an existing ABT is revoked from an account and - /// destroyed by any mechanism. - /// Note: For a reliable `from` parameter, retrieve the transaction's - /// authenticated `from` field. - event Revoke(address indexed to, uint256 indexed tokenId); + /// @dev This emits when ownership of any ABT changes by any mechanism. + /// This event emits when ABTs are given or equipped and unequipped + /// (`to` == 0). + event Transfer( + address indexed from, + address indexed to, + uint256 indexed tokenId + ); /// @notice Count all ABTs assigned to an owner /// @dev ABTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param owner An address for whom to query the balance - /// @return The number of ABTs owned by `owner`, possibly zero + /// @return The number of ABTs owned by `address owner`, possibly zero function balanceOf(address owner) external view returns (uint256); /// @notice Find the address bound to an ERC4973 account-bound token /// @dev ABTs assigned to zero address are considered invalid, and queries /// about them do throw. - /// @param tokenId The identifier for an ABT - /// @return The address of the owner bound to the ABT + /// @param tokenId The identifier for an ABT. + /// @return The address of the owner bound to the ABT. function ownerOf(uint256 tokenId) external view returns (address); - /// @notice Destroys `tokenId`. At any time, an ABT receiver must be able to - /// disassociate themselves from an ABT publicly through calling this - /// function. - /// @dev Must emit a `event Revoke` with the `address to` field pointing to + /// @notice Removes the `uint256 tokenId` from an account. At any time, an + /// ABT receiver must be able to disassociate themselves from an ABT + /// publicly through calling this function. After successfully executing this + /// function, given the parameters for calling `function give` or + /// `function take` a token must be re-equipable. + /// @dev Must emit a `event Transfer` with the `address to` field pointing to /// the zero address. - /// @param tokenId The identifier for an ABT - function burn(uint256 tokenId) external; + /// @param tokenId The identifier for an ABT. + function unequip(uint256 tokenId) external; + /// @notice Creates and transfers the ownership of an ABT from the + /// transaction's `msg.sender` to `address to`. + /// @dev Throws unless `bytes signature` represents an EIP-2098 Compact + /// Signature of the EIP-712 structured data hash + /// `Agreement(address active,address passive,string tokenURI)` expressing + /// `address to`'s explicit agreement to be publicly associated with + /// `msg.sender` and `string tokenURI`. A unique `uint256 tokenId` must be + /// generated by type-casting the `bytes32` EIP-712 structured data hash to a + /// `uint256`. If `bytes signature` is empty or `address to` is a contract, + /// an EIP-1271-compatible call to `function isValidSignatureNow(...)` must + /// be made to `address to`. A successful execution must result in the + /// `event Transfer(msg.sender, to, tokenId)`. Once an ABT exists as an + /// `uint256 tokenId` in the contract, `function give(...)` must throw. + /// @param to The receiver of the ABT. + /// @param uri A distinct Uniform Resource Identifier (URI) for a given ABT. + /// @param signature A EIP-2098-compatible Compact Signature of the EIP-712 + /// structured data hash + /// `Agreement(address active,address passive,string tokenURI)` signed by + /// `address to`. + /// @return A unique `uint256 tokenId` generated by type-casting the `bytes32` + /// EIP-712 structured data hash to a `uint256`. + function give( + address to, + string calldata uri, + bytes calldata signature + ) external returns (uint256); + /// @notice Creates and transfers the ownership of an ABT from an + /// `address from` to the transaction's `msg.sender`. + /// @dev Throws unless `bytes signature` represents an EIP-2098 Compact + /// Signature of the EIP-712 structured data hash + /// `Agreement(address active,address passive,string tokenURI)` expressing + /// `address from`'s explicit agreement to be publicly associated with + /// `msg.sender` and `string tokenURI`. A unique `uint256 tokenId` must be + /// generated by type-casting the `bytes32` EIP-712 structured data hash to a + /// `uint256`. If `bytes signature` is empty or `address from` is a contract, + /// an EIP-1271-compatible call to `function isValidSignatureNow(...)` must + /// be made to `address from`. A successful execution must result in the + /// emission of an `event Transfer(from, msg.sender, tokenId)`. Once an ABT + /// exists as an `uint256 tokenId` in the contract, `function take(...)` must + /// throw. + /// @param from The origin of the ABT. + /// @param uri A distinct Uniform Resource Identifier (URI) for a given ABT. + /// @param signature A EIP-2098-compatible Compact Signature of the EIP-712 + /// structured data hash + /// `Agreement(address active,address passive,string tokenURI)` signed by + /// `address from`. + /// @return A unique `uint256 tokenId` generated by type-casting the `bytes32` + /// EIP-712 structured data hash to a `uint256`. + function take( + address from, + string calldata uri, + bytes calldata signature + ) external returns (uint256); } +bytes32 constant AGREEMENT_HASH = + keccak256( + "Agreement(address active,address passive,string tokenURI)" +); + /// @notice Reference implementation of EIP-4973 tokens. -/// @author TimDaub (https://github.com/rugpullindex/ERC4973/blob/master/src/ERC4973.sol) -abstract contract ERC4973 is ERC165, IERC721Metadata, IERC4973 { +/// @author Tim Daubenschütz, Rahul Rumalla (https://github.com/rugpullindex/ERC4973/blob/master/src/ERC4973.sol) +abstract contract ERC4973 is EIP712, ERC165, IERC721Metadata, IERC4973 { + using BitMaps for BitMaps.BitMap; + BitMaps.BitMap private _usedHashes; + string private _name; string private _symbol; @@ -102,8 +889,9 @@ abstract contract ERC4973 is ERC165, IERC721Metadata, IERC4973 { constructor( string memory name_, - string memory symbol_ - ) { + string memory symbol_, + string memory version + ) EIP712(name_, version) { _name = name_; _symbol = symbol_; } @@ -128,8 +916,9 @@ abstract contract ERC4973 is ERC165, IERC721Metadata, IERC4973 { return _tokenURIs[tokenId]; } - function burn(uint256 tokenId) public virtual override { - require(msg.sender == ownerOf(tokenId), "burn: sender must be owner"); + function unequip(uint256 tokenId) public virtual override { + require(msg.sender == ownerOf(tokenId), "unequip: sender must be owner"); + _usedHashes.unset(tokenId); _burn(tokenId); } @@ -144,11 +933,69 @@ abstract contract ERC4973 is ERC165, IERC721Metadata, IERC4973 { return owner; } + function give( + address to, + string calldata uri, + bytes calldata signature + ) external virtual returns (uint256) { + require(msg.sender != to, "give: cannot give from self"); + uint256 tokenId = _safeCheckAgreement(msg.sender, to, uri, signature); + _mint(msg.sender, to, tokenId, uri); + _usedHashes.set(tokenId); + return tokenId; + } + + function take( + address from, + string calldata uri, + bytes calldata signature + ) external virtual returns (uint256) { + require(msg.sender != from, "take: cannot take from self"); + uint256 tokenId = _safeCheckAgreement(msg.sender, from, uri, signature); + _mint(from, msg.sender, tokenId, uri); + _usedHashes.set(tokenId); + return tokenId; + } + + function _safeCheckAgreement( + address active, + address passive, + string calldata uri, + bytes calldata signature + ) internal virtual returns (uint256) { + bytes32 hash = _getHash(active, passive, uri); + uint256 tokenId = uint256(hash); + + require( + SignatureChecker.isValidSignatureNow(passive, hash, signature), + "_safeCheckAgreement: invalid signature" + ); + require(!_usedHashes.get(tokenId), "_safeCheckAgreement: already used"); + return tokenId; + } + + function _getHash( + address active, + address passive, + string calldata uri + ) internal view returns (bytes32) { + bytes32 structHash = keccak256( + abi.encode( + AGREEMENT_HASH, + active, + passive, + keccak256(bytes(uri)) + ) + ); + return _hashTypedDataV4(structHash); + } + function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _mint( + address from, address to, uint256 tokenId, string memory uri @@ -157,7 +1004,7 @@ abstract contract ERC4973 is ERC165, IERC721Metadata, IERC4973 { _balances[to] += 1; _owners[tokenId] = to; _tokenURIs[tokenId] = uri; - emit Attest(to, tokenId); + emit Transfer(from, to, tokenId); return tokenId; } @@ -168,6 +1015,7 @@ abstract contract ERC4973 is ERC165, IERC721Metadata, IERC4973 { delete _owners[tokenId]; delete _tokenURIs[tokenId]; - emit Revoke(owner, tokenId); + emit Transfer(owner, address(0), tokenId); } } +