diff --git a/ERCS/erc-6860.md b/ERCS/erc-6860.md index 63ba35329e..fab03bc6f5 100644 --- a/ERCS/erc-6860.md +++ b/ERCS/erc-6860.md @@ -2,7 +2,7 @@ eip: 6860 title: Web3 URL to EVM Call Message Translation description: A translation of an HTTP-style Web3 URL to an EVM call message -author: Qi Zhou (@qizhou), Chao Pi (@pichaoqkc), Sam Wilson (@SamWilsn) +author: Qi Zhou (@qizhou), Chao Pi (@pichaoqkc), Sam Wilson (@SamWilsn), Nicolas Deschildre (@nand2) discussions-to: https://ethereum-magicians.org/t/eip-4804-web3-url-to-evm-call-message-translation/8300 status: Draft type: Standards Track @@ -57,7 +57,7 @@ domainName = *( unreserved / pct-encoded / sub-delims ) ; As in RFC 3986 The way to resolve the domain name from a domain name service to an address is specified in [ERC-6821](./eip-6821.md) for the Ethereum Name service, and will be discussed in later ERCs for other name services. ``` -chainid = 1*DIGIT +chainid = %x31-39 *DIGIT ``` **chainid** indicates which chain to resolve **contractName** and call the message. If not specified, the protocol will use the primary chain of the name service provider used, e.g., 1 for eth. If no name service provider was used, the default chainid is 1. @@ -184,14 +184,16 @@ attrName = "returns" / "returnTypes" attrValue = [ "(" [ retTypes ] ")" ] retTypes = retType *( "," retType ) -retType = *( "[]" ) retRawType -retRawType = "bool" / "uint" [ intSizes ] / "int" [ intSize ] / "address" / "bytes" [ bytesSizes ] / "string" -bytesSizes = DIGIT - / ( "1" / "2" ) DIGIT - / "31" / "32" +retType = retRawType *( "[" [ %x31-39 *DIGIT ] "]" ) +retRawType = "(" retTypes ")" + / retBaseType +retBaseType = "bool" / "uint" [ intSizes ] / "int" [ intSize ] / "address" / "bytes" [ bytesSizes ] / "string" +bytesSizes = %x31-39 ; 1-9 + / ( "1" / "2" ) DIGIT ; 10-29 + / "31" / "32" ; 31-32 ``` -The "returns" attribute in **aQuery** tells the format of the returned data. +The "returns" attribute in **aQuery** tells the format of the returned data. It follows the syntax of the arguments part of the ethereum ABI function signature (``uint`` and ``int`` aliases are authorized). - If the "returns" attribute value is undefined or empty, the returned message data will be treated as ABI-encoded bytes and the decoded bytes will be returned to the frontend. The MIME type returned to the frontend will be undefined by default, but will be overriden if the last argument is of string type and has a **fileExtension**, in which case the MIME type will be deduced from the filename extension. (Note that **fileExtension** is not excluded from the string argument given to the smartcontract) - If the "returns" attribute value is equal to "()", the raw bytes of the returned message data will be returned, encoded as a "0x"-prefixed hex string in an array in JSON format: ``["0xXXXXX"]`` @@ -288,7 +290,7 @@ schema = "w3" / "web3" userinfo = address contractName = address / domainName -chainid = 1*DIGIT +chainid = %x31-39 *DIGIT pathQuery = mPathQuery ; path+query for manual mode / aPathQuery ; path+query for auto mode @@ -375,11 +377,13 @@ attrName = "returns" / "returnTypes" attrValue = [ "(" [ retTypes ] ")" ] retTypes = retType *( "," retType ) -retType = retRawType *( "[]" ) -retRawType = "bool" / "uint" [ intSizes ] / "int" [ intSize ] / "address" / "bytes" [ bytesSizes ] / "string" -bytesSizes = DIGIT - / ( "1" / "2" ) DIGIT - / "31" / "32" +retType = retRawType *( "[" [ %x31-39 *DIGIT ] "]" ) +retRawType = "(" retTypes ")" + / retBaseType +retBaseType = "bool" / "uint" [ intSizes ] / "int" [ intSize ] / "address" / "bytes" [ bytesSizes ] / "string" +bytesSizes = %x31-39 ; 1-9 + / ( "1" / "2" ) DIGIT ; 10-29 + / "31" / "32" ; 31-32 domainName = *( unreserved / pct-encoded / sub-delims ) ; As in RFC 3986 diff --git a/ERCS/erc-6900.md b/ERCS/erc-6900.md index 70dbe1a4bb..1505452bb3 100644 --- a/ERCS/erc-6900.md +++ b/ERCS/erc-6900.md @@ -94,7 +94,7 @@ Each step is modular, supporting different implementations for each execution fu **Modular Smart Contract Accounts** **MAY** implement -- `IPluginLoupe.sol` to support visibility in plugin configuration on-chain. +- `IAccountLoupe.sol` to support visibility in plugin configuration on-chain. **Plugins** **MUST** implement @@ -123,8 +123,14 @@ interface IPluginManager { uint8 postExecHookFunctionId; } - event PluginInstalled(address indexed plugin, bytes32 manifestHash); - event PluginUninstalled(address indexed plugin, bytes32 manifestHash, bool onUninstallSucceeded); + event PluginInstalled( + address indexed plugin, + bytes32 manifestHash, + FunctionReference[] dependencies, + InjectedHook[] injectedHooks + ); + + event PluginUninstalled(address indexed plugin, bool indexed callbacksSucceeded); /// @notice Install a plugin to the modular account. /// @param plugin The plugin to install. @@ -168,12 +174,12 @@ Standard execute functions SHOULD check whether the call's target implements the **If the target is a plugin, the call SHOULD revert.** This prevents accidental misconfiguration or misuse of plugins (both installed and uninstalled). ```solidity -struct Execution { +struct Call { // The target contract for account to execute. address target; - // The value for the execution. + // The value for the call. uint256 value; - // The call data for the execution. + // The call data for the call. bytes data; } @@ -181,16 +187,16 @@ interface IStandardExecutor { /// @notice Standard execute method. /// @dev If the target is a plugin, the call SHOULD revert. /// @param target The target contract for account to execute. - /// @param value The value for the execution. - /// @param data The call data for the execution. + /// @param value The value for the call. + /// @param data The call data for the call. /// @return The return data from the call. function execute(address target, uint256 value, bytes calldata data) external payable returns (bytes memory); /// @notice Standard executeBatch method. /// @dev If the target is a plugin, the call SHOULD revert. - /// @param executions The array of executions. + /// @param calls The array of calls. /// @return An array containing the return data from the calls. - function executeBatch(Execution[] calldata executions) external payable returns (bytes[] memory); + function executeBatch(Call[] calldata calls) external payable returns (bytes[] memory); } ``` @@ -220,7 +226,7 @@ interface IPluginExecutor { } ``` -#### `IPluginLoupe.sol` +#### `IAccountLoupe.sol` Plugin inspection interface. Modular Smart Contract Accounts **MAY** implement this interface to support visibility in plugin configuration on-chain. @@ -228,32 +234,55 @@ Plugin inspection interface. Modular Smart Contract Accounts **MAY** implement t // Treats the first 20 bytes as an address, and the last byte as a function identifier. type FunctionReference is bytes21; -interface IPluginLoupe { - // Config for a Plugin Execution function +interface IAccountLoupe { + /// @notice Config for an execution function, given a selector struct ExecutionFunctionConfig { address plugin; FunctionReference userOpValidationFunction; FunctionReference runtimeValidationFunction; } + /// @notice Pre and post hooks for a given selector + /// @dev It's possible for one of either `preExecHook` or `postExecHook` to be empty struct ExecutionHooks { FunctionReference preExecHook; FunctionReference postExecHook; } + /// @notice Gets the validation functions and plugin address for a selector + /// @dev If the selector is a native function, the plugin address will be the address of the account + /// @param selector The selector to get the configuration for + /// @return The configuration for this selector function getExecutionFunctionConfig(bytes4 selector) external view returns (ExecutionFunctionConfig memory); + /// @notice Gets the pre and post execution hooks for a selector + /// @param selector The selector to get the hooks for + /// @return The pre and post execution hooks for this selector function getExecutionHooks(bytes4 selector) external view returns (ExecutionHooks[] memory); + /// @notice Gets the pre and post permitted call hooks applied for a plugin calling this selector + /// @param callingPlugin The plugin that is calling the selector + /// @param selector The selector the plugin is calling + /// @return The pre and post permitted call hooks for this selector function getPermittedCallHooks(address callingPlugin, bytes4 selector) external view returns (ExecutionHooks[] memory); - function getPreUserOpValidationHooks(bytes4 selector) external view returns (FunctionReference[] memory); - - function getPreRuntimeValidationHooks(bytes4 selector) external view returns (FunctionReference[] memory); + /// @notice Gets the pre user op and runtime validation hooks associated with a selector + /// @param selector The selector to get the hooks for + /// @return preUserOpValidationHooks The pre user op validation hooks for this selector + /// @return preRuntimeValidationHooks The pre runtime validation hooks for this selector + function getPreValidationHooks(bytes4 selector) + external + view + returns ( + FunctionReference[] memory preUserOpValidationHooks, + FunctionReference[] memory preRuntimeValidationHooks + ); + /// @notice Gets an array of all installed plugins + /// @return The addresses of all installed plugins function getInstalledPlugins() external view returns (address[] memory); } ``` @@ -379,11 +408,6 @@ enum ManifestAssociatedFunctionType { PRE_HOOK_ALWAYS_DENY } -struct ManifestExecutionFunction { - bytes4 selector; - string[] permissions; -} - // For functions of type `ManifestAssociatedFunctionType.DEPENDENCY`, the MSCA MUST find the plugin address // of the function at `dependencies[dependencyIndex]` during the call to `installPlugin(config)`. struct ManifestFunction { @@ -403,7 +427,19 @@ struct ManifestExecutionHook { ManifestFunction postExecHook; } -struct PluginManifest { +struct ManifestExternalCallPermission { + address externalAddress; + bool permitAnySelector; + bytes4[] selectors; +} + +struct SelectorPermission { + bytes4 functionSelector; + string permissionDescription; +} + +/// @dev A struct holding fields to describe the plugin in a purely view context. Intended for front end clients. +struct PluginMetadata { // A human-readable name of the plugin. string name; // The version of the plugin, following the semantic versioning scheme. @@ -411,26 +447,28 @@ struct PluginManifest { // The author field SHOULD be a username representing the identity of the user or organization // that created this plugin. string author; + // String desciptions of the relative sensitivity of specific functions. The selectors MUST be selectors for + // functions implemented by this plugin. + SelectorPermission[] permissionDescriptors; +} +/// @dev A struct describing how the plugin should be installed on a modular account. +struct PluginManifest { // List of ERC-165 interfaceIds to add to account to support introspection checks. bytes4[] interfaceIds; - // If this plugin depends on other plugins' validation functions and/or hooks, the interface IDs of // those plugins MUST be provided here, with its position in the array matching the `dependencyIndex` // members of `ManifestFunction` structs used in the manifest. bytes4[] dependencyInterfaceIds; - // Execution functions defined in this plugin to be installed on the MSCA. - ManifestExecutionFunction[] executionFunctions; - - // Native functions or execution functions already installed on the MSCA that this plugin will be - // able to call. + bytes4[] executionFunctions; + // Plugin execution functions already installed on the MSCA that this plugin will be able to call. bytes4[] permittedExecutionSelectors; - - // External contract calls that this plugin will be able to make. - bool permitAnyExternalContract; + // Boolean to indicate whether the plugin can call any external contract addresses. + bool permitAnyExternalAddress; + // Boolean to indicate whether the plugin needs access to spend native tokens of the account. + bool canSpendNativeToken; ManifestExternalCallPermission[] permittedExternalCalls; - ManifestAssociatedFunction[] userOpValidationFunctions; ManifestAssociatedFunction[] runtimeValidationFunctions; ManifestAssociatedFunction[] preUserOpValidationHooks; @@ -438,6 +476,7 @@ struct PluginManifest { ManifestExecutionHook[] executionHooks; ManifestExecutionHook[] permittedCallHooks; } + ``` ### Expected behavior @@ -474,7 +513,7 @@ The function MUST store the plugin's permitted function selectors and external c The function MUST parse through the execution functions, validation functions, and hooks in the manifest and add them to the modular account after resolving each `ManifestFunction` type. - Each function selector MUST be added as a valid execution function on the modular account. If the function selector has already been added or matches the selector of a native function, the function SHOULD revert. -- If an associated function that is to be added already exists, the function SHOULD revert. +- If a validation function is to be added to a selector that already has that type of validation function, the function SHOULD revert. Next, the function MUST call the plugin's `onInstall` callback with the data provided in the `installData` parameter. This serves to initialize the plugin state for the modular account. If `onInstall` reverts, the `installPlugin` function MUST revert. @@ -493,11 +532,11 @@ The function MUST revert if the plugin is not installed on the modular account. The function SHOULD perform the following checks: - Revert if the hash of the manifest used at install time does not match the computed Keccak-256 hash of the plugin's current manifest. This prevents unclean removal of plugins that attempt to force a removal of a different plugin configuration than the one that was originally approved by the client for installation. To allow for removal of such plugins, the modular account MAY implement the capability for the manifest to be encoded in the config field as a parameter. -- Revert if there is at least 1 other installed plugin that depends on execution functions, validation functions, or hooks added by this plugin. Plugins used as dependencies must not be uninstalled while dependent plugins exist. +- Revert if there is at least 1 other installed plugin that depends on validation functions or hooks added by this plugin. Plugins used as dependencies must not be uninstalled while dependent plugins exist. -The function SHOULD update account storage to reflect the uninstall via inspection functions, such as those defined by `IPluginLoupe`. Each dependency's record SHOULD also be updated to reflect that it has no longer has this plugin as a dependent. +The function SHOULD update account storage to reflect the uninstall via inspection functions, such as those defined by `IAccountLoupe`. Each dependency's record SHOULD also be updated to reflect that it has no longer has this plugin as a dependent. -The function MUST remove records for the plugin's dependencies, injected permitted call hooks, permitted function selectors, and external contract calls. The hooks to remove MUST be exactly the same as what was provided during installation. It is up to the implementing modular account to decide how to keep this invariant. The config parameter field MAY be used. +The function MUST remove records for the plugin's dependencies, injected permitted call hooks, permitted function selectors, and permitted external calls. The hooks to remove MUST be exactly the same as what was provided during installation. It is up to the implementing modular account to decide how to keep this invariant. The config parameter field MAY be used. The function MUST parse through the execution functions, validation functions, and hooks in the manifest and remove them from the modular account after resolving each `ManifestFunction` type. @@ -550,7 +589,7 @@ No backward compatibility issues found. ## Reference Implementation -See `https://github.com/alchemyplatform/ERC-6900-Ref-Implementation` +See `https://github.com/erc6900/reference-implementation` ## Security Considerations diff --git a/ERCS/erc-6909.md b/ERCS/erc-6909.md index 39a1344b0b..4c8f4a4409 100644 --- a/ERCS/erc-6909.md +++ b/ERCS/erc-6909.md @@ -2,7 +2,7 @@ eip: 6909 title: Minimal Multi-Token Interface description: A minimal specification for managing multiple tokens by their id in a single contract. -author: JT Riley (@jtriley-eth), Dillon (@d1ll0n), Sara (@snreynolds), Vectorized (@Vectorized) +author: JT Riley (@jtriley-eth), Dillon (@d1ll0n), Sara (@snreynolds), Vectorized (@Vectorized), Neodaoist (@neodaoist) discussions-to: https://ethereum-magicians.org/t/eip-6909-multi-token-standard/13891 status: Draft type: Standards Track @@ -340,7 +340,9 @@ The `name` of the contract. type: function stateMutability: view - inputs: [] + inputs: + - name: id + type: uint256 outputs: - name: name @@ -356,7 +358,9 @@ The ticker `symbol` of the contract. type: function stateMutability: view - inputs: [] + inputs: + - name: id + type: uint256 outputs: - name: symbol @@ -381,10 +385,26 @@ The `amount` of decimals for a token `id`. type: uint8 ``` -### Metadata URI Extension +### Content URI Extension #### Methods +##### contractURI + +The `URI` for a token `id`. + +```yaml +- name: contractURI + type: function + stateMutability: view + + inputs: [] + + outputs: + - name: uri + type: string +``` + ##### tokenURI The `URI` for a token `id`. @@ -434,6 +454,28 @@ MUST replace occurrences of `{id}` in the returned URI string by the client. } ``` +### Token Supply Extension + +#### Methods + +##### totalSupply + +The `totalSupply` for a token `id`. + +```yaml +- name: totalSupply + type: function + stateMutability: view + + inputs: + - name: id + type: uint256 + + outputs: + - name: supply + type: uint256 +``` + ## Backwards Compatibility This is not backwards compatible with ERC-1155 as some methods are removed. However, wrappers can be implemented for the ERC-20, ERC-721, and ERC-1155 standards. diff --git a/ERCS/erc-7410.md b/ERCS/erc-7410.md new file mode 100644 index 0000000000..e3ad4f4964 --- /dev/null +++ b/ERCS/erc-7410.md @@ -0,0 +1,82 @@ +--- +eip: 7410 +title: ERC-20 Update Allowance By Spender +description: Extension to enable revoking and decreasing allowance approval by spender for ERC-20 +author: Mohammad Zakeri Rad (@zakrad), Adam Boudjemaa (@aboudjem), Mohamad Hammoud (@mohamadhammoud) +discussions-to: https://ethereum-magicians.org/t/eip-7410-decrease-allowance-by-spender/15222 +status: Draft +type: Standards Track +category: ERC +created: 2023-07-26 +requires: 20, 165 +--- + +## Abstract + +This extension adds a `decreaseAllowanceBySpender` function to decrease [ERC-20](./eip-20.md) allowances, in which a spender can revoke or decrease a given allowance by a specific address. This ERC extends [ERC-20](./eip-20.md). + +## Motivation + +Currently, [ERC-20](./eip-20.md) tokens offer allowances, enabling token owners to authorize spenders to use a designated amount of tokens on their behalf. However, the process of decreasing an allowance is limited to the owner's side, which can be problematic if the token owner is a treasury wallet or a multi-signature wallet that has granted an excessive allowance to a spender. In such cases, reducing the allowance from the owner's perspective can be time-consuming and challenging. + +To address this issue and enhance security measures, this ERC proposes allowing spenders to decrease or revoke the granted allowance from their end. This feature provides an additional layer of security in the event of a potential hack in the future. It also eliminates the need for a consensus or complex procedures to decrease the allowance from the token owner's side. + +## Specification + +The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119. + +Contracts using this ERC MUST implement the `IERC7410` interface. + +### Interface implementation + +```solidity +pragma solidity ^0.8.0; + +/** + * @title IERC-7410 Update Allowance By Spender Extension + * Note: the ERC-165 identifier for this interface is 0x12860fba + */ +interface IERC7410 is IERC20 { + + /** + * @notice Decreases any allowance by `owner` address for caller. + * Emits an {IERC20-Approval} event. + * + * Requirements: + * - when `subtractedValue` is equal or higher than current allowance of spender the new allowance is set to 0. + * Nullification also MUST be reflected for current allowance being type(uint256).max. + */ + function decreaseAllowanceBySpender(address owner, uint256 subtractedValue) external; + +} +``` + +The `decreaseAllowanceBySpender(address owner, uint256 subtractedValue)` function MUST be either `public` or `external`. + +The `Approval` event MUST be emitted when `decreaseAllowanceBySpender` is called. + +The `supportsInterface` method MUST return `true` when called with `0x12860fba`. + +## Rationale + +The technical design choices within this ERC are driven by the following considerations: + +- The introduction of the `decreaseAllowanceBySpender` function empowers spenders by allowing them to autonomously revoke or decrease allowances. This design choice aligns with the goal of providing more direct control to spenders over their authorization levels. +- The requirement for the `subtractedValue` to be lower than the current allowance ensures a secure implementation. Additionally, nullification is achieved by setting the new allowance to 0 when `subtractedValue` is equal to or exceeds the current allowance. This approach adds an extra layer of security and simplifies the process of decreasing allowances. +- The decision to maintain naming patterns similar to [ERC-20](./eip-20.md)'s approvals is rooted in promoting consistency and ease of understanding for developers familiar with [ERC-20](./eip-20.md) standard. + +## Backwards Compatibility + +This standard is compatible with [ERC-20](./eip-20.md). + +## Reference Implementation + +An minimal implementation is included [here](../assets/eip-7410/ERC7410.sol). + +## Security Considerations + +Users of this ERC must thoroughly consider the amount of tokens they decrease from their allowance for an `owner`. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/ERCS/erc-7417.md b/ERCS/erc-7417.md index 7a7150a92b..33b8b711af 100644 --- a/ERCS/erc-7417.md +++ b/ERCS/erc-7417.md @@ -136,49 +136,117 @@ This service is the first of its kind and therefore does not have any backwards ## Reference Implementation ```solidity - address public ownerMultisig; - mapping (address => ERC223WrapperToken) public erc223Wrappers; // A list of token wrappers. - // First one is [ERC-20](./eip-20.md) origin, - // second one is [ERC-223](./eip-223.md) version. - mapping (address => address) public erc20Origins; - mapping (address => uint256) public erc20Supply; // Token => how much was deposited. + mapping (address => ERC223WrapperToken) public erc223Wrappers; // A list of token wrappers. First one is ERC-20 origin, second one is ERC-223 version. + mapping (address => ERC20WrapperToken) public erc20Wrappers; + + mapping (address => address) public erc223Origins; + mapping (address => address) public erc20Origins; + mapping (address => uint256) public erc20Supply; // Token => how much was deposited. + + function getERC20WrapperFor(address _token) public view returns (address, string memory) + { + if ( address(erc20Wrappers[_token]) != address(0) ) + { + return (address(erc20Wrappers[_token]), "ERC-20"); + } + + return (address(0), "Error"); + } + + function getERC223WrapperFor(address _token) public view returns (address, string memory) + { + if ( address(erc223Wrappers[_token]) != address(0) ) + { + return (address(erc223Wrappers[_token]), "ERC-223"); + } + + return (address(0), "Error"); + } - function getWrapperFor(address _erc20Token) public view returns (address) + function getERC20OriginFor(address _token) public view returns (address) { - return address(erc223Wrappers[_erc20Token]); + return (address(erc20Origins[_token])); } - function getOriginFor(address _erc223WrappedToken) public view returns (address) + function getERC223OriginFor(address _token) public view returns (address) { - return erc20Origins[_erc223WrappedToken]; + return (address(erc223Origins[_token])); } function tokenReceived(address _from, uint _value, bytes memory _data) public override returns (bytes4) { - require(erc20Origins[msg.sender] != address(0), "ERROR: The received token is not a [ERC-223](./eip-223.md) Wrapper for any [ERC-20](./eip-20.md) token."); - safeTransfer(erc20Origins[msg.sender], _from, _value); + require(erc223Origins[msg.sender] == address(0), "Error: creating wrapper for a wrapper token."); + // There are two possible cases: + // 1. A user deposited ERC-223 origin token to convert it to ERC-20 wrapper + // 2. A user deposited ERC-223 wrapper token to unwrap it to ERC-20 origin. + + if(erc20Origins[msg.sender] != address(0)) + { + // Origin for deposited token exists. + // Unwrap ERC-223 wrapper. - erc20Supply[erc20Origins[msg.sender]] -= _value; - erc223Wrappers[msg.sender].burn(_value); + safeTransfer(erc20Origins[msg.sender], _from, _value); - return 0x8943ec02; + erc20Supply[erc20Origins[msg.sender]] -= _value; + //erc223Wrappers[msg.sender].burn(_value); + ERC223WrapperToken(msg.sender).burn(_value); + + return this.tokenReceived.selector; + } + // Otherwise origin for the sender token doesn't exist + // There are two possible cases: + // 1. ERC-20 wrapper for the deposited token exists + // 2. ERC-20 wrapper for the deposited token doesn't exist and must be created. + else if(address(erc20Wrappers[msg.sender]) == address(0)) + { + // Create ERC-20 wrapper if it doesn't exist. + createERC20Wrapper(msg.sender); + } + + // Mint ERC-20 wrapper tokens for the deposited ERC-223 token + // if the ERC-20 wrapper didn't exist then it was just created in the above statement. + erc20Wrappers[msg.sender].mint(_from, _value); + return this.tokenReceived.selector; } - function createERC223Wrapper(address _erc20Token) public returns (address) + function createERC223Wrapper(address _token) public returns (address) { - require(address(erc223Wrappers[_erc20Token]) == address(0), "ERROR: Wrapper already exists."); - require(getOriginFor(_erc20Token) == address(0), "ERROR: Cannot convert [ERC-223](./eip-223.md) to [ERC-223](./eip-223.md)."); + require(address(erc223Wrappers[_token]) == address(0), "ERROR: Wrapper exists"); + require(getERC20OriginFor(_token) == address(0), "ERROR: 20 wrapper creation"); + require(getERC223OriginFor(_token) == address(0), "ERROR: 223 wrapper creation"); - ERC223WrapperToken _newERC223Wrapper = new ERC223WrapperToken(_erc20Token); - erc223Wrappers[_erc20Token] = _newERC223Wrapper; - erc20Origins[address(_newERC223Wrapper)] = _erc20Token; + ERC223WrapperToken _newERC223Wrapper = new ERC223WrapperToken(_token); + erc223Wrappers[_token] = _newERC223Wrapper; + erc20Origins[address(_newERC223Wrapper)] = _token; return address(_newERC223Wrapper); } - function convertERC20toERC223(address _ERC20token, uint256 _amount) public returns (bool) + function createERC20Wrapper(address _token) public returns (address) + { + require(address(erc20Wrappers[_token]) == address(0), "ERROR: Wrapper already exists."); + require(getERC20OriginFor(_token) == address(0), "ERROR: 20 wrapper creation"); + require(getERC223OriginFor(_token) == address(0), "ERROR: 223 wrapper creation"); + + ERC20WrapperToken _newERC20Wrapper = new ERC20WrapperToken(_token); + erc20Wrappers[_token] = _newERC20Wrapper; + erc223Origins[address(_newERC20Wrapper)] = _token; + + return address(_newERC20Wrapper); + } + + function depositERC20(address _token, uint256 _amount) public returns (bool) + { + if(erc223Origins[_token] != address(0)) + { + return unwrapERC20toERC223(_token, _amount); + } + else return wrapERC20toERC223(_token, _amount); + } + + function wrapERC20toERC223(address _ERC20token, uint256 _amount) public returns (bool) { // If there is no active wrapper for a token that user wants to wrap // then create it. @@ -196,10 +264,40 @@ This service is the first of its kind and therefore does not have any backwards "ERROR: The transfer have not subtracted tokens from callers balance."); erc223Wrappers[_ERC20token].mint(msg.sender, _amount); + return true; + } + + function unwrapERC20toERC223(address _ERC20token, uint256 _amount) public returns (bool) + { + require(IERC20(_ERC20token).balanceOf(msg.sender) >= _amount, "Error: Insufficient balance."); + require(erc223Origins[_ERC20token] != address(0), "Error: provided token is not a ERC-20 wrapper."); + + ERC20WrapperToken(_ERC20token).burn(msg.sender, _amount); + IERC223(erc223Origins[_ERC20token]).transfer(msg.sender, _amount); return true; } + function isWrapper(address _token) public view returns (bool) + { + return erc20Origins[_token] != address(0) || erc223Origins[_token] != address(0); + } + +/* + function convertERC223toERC20(address _from, uint256 _amount) public returns (bool) + { + // If there is no active wrapper for a token that user wants to wrap + // then create it. + if(address(erc20Wrappers[msg.sender]) == address(0)) + { + createERC223Wrapper(msg.sender); + } + + erc20Wrappers[msg.sender].mint(_from, _amount); + return true; + } +*/ + function rescueERC20(address _token) external { require(msg.sender == ownerMultisig, "ERROR: Only owner can do this."); uint256 _stuckTokens = IERC20(_token).balanceOf(address(this)) - erc20Supply[_token]; @@ -208,10 +306,15 @@ This service is the first of its kind and therefore does not have any backwards function transferOwnership(address _newOwner) public { - require(msg.sender == ownerMultisig, "ERROR: Only owner can do this."); + require(msg.sender == ownerMultisig, "ERROR: Only owner can call this function."); ownerMultisig = _newOwner; } + // ************************************************************ + // Functions that address problems with tokens that pretend to be ERC-20 + // but in fact are not compatible with the ERC-20 standard transferring methods. + // EIP20 https://eips.ethereum.org/EIPS/eip-20 + // ************************************************************ function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); diff --git a/ERCS/erc-7496.md b/ERCS/erc-7496.md new file mode 100644 index 0000000000..ca0023cc72 --- /dev/null +++ b/ERCS/erc-7496.md @@ -0,0 +1,219 @@ +--- +eip: 7496 +title: NFT Dynamic Traits +description: Extension to ERC-721 and ERC-1155 for dynamic onchain traits +author: Adam Montgomery (@montasaurus), Ryan Ghods (@ryanio), 0age (@0age), James Wenzel (@jameswenzel), Stephan Min (@stephankmin) +discussions-to: https://ethereum-magicians.org/t/erc-7496-nft-dynamic-traits/15484 +status: Draft +type: Standards Track +category: ERC +created: 2023-07-28 +requires: 165, 721, 1155 +--- + +## Abstract + +This specification introduces a new interface that extends [ERC-721](./eip-721.md) and [ERC-1155](./eip-1155.md) that defines methods for setting and getting dynamic onchain traits associated with non-fungible tokens. These dynamic traits can be used to represent properties, characteristics, redeemable entitlements, or other attributes that can change over time. By defining these traits onchain, they can be used and modified by other onchain contracts. + +## Motivation + +Trait values for non-fungible tokens are often stored offchain. This makes it difficult to query and mutate these values in contract code. Specifying the ability to set and get traits onchain allows for new use cases like redeeming onchain entitlements and transacting based on a token's traits. + +Onchain traits can be used by contracts in a variety of different scenarios. For example, a contract that wants to entitle a token to a consumable benefit (e.g. a redeemable) can robustly reflect that onchain. Marketplaces can allow bidding on these tokens based on the trait value without having to rely on offchain state and exposing users to frontrunning attacks. The motivating use case behind this proposal is to protect users from frontrunning attacks on marketplaces where users can list NFTs with certain traits where they are expected to be upheld during fulfillment. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +Contracts implementing this EIP MUST include the events, getters, and setters as defined below, and MUST return `true` for [ERC-165](./eip-165.md) `supportsInterface` for `0xaf332f3e`, the 4 byte `interfaceId` for this ERC. + +```solidity +interface IERC7496 { + /* Events */ + event TraitUpdated(bytes32 indexed traitKey, uint256 tokenId, bytes32 traitValue); + event TraitUpdatedRange(bytes32 indexed traitKey, uint256 fromTokenId, uint256 toTokenId); + event TraitUpdatedRangeUniformValue(bytes32 indexed traitKey, uint256 fromTokenId, uint256 toTokenId, bytes32 traitValue); + event TraitUpdatedList(bytes32 indexed traitKey, uint256[] tokenIds); + event TraitUpdatedListUniformValue(bytes32 indexed traitKey, uint256[] tokenIds, bytes32 traitValue); + event TraitMetadataURIUpdated(); + + /* Getters */ + function getTraitValue(uint256 tokenId, bytes32 traitKey) external view returns (bytes32 traitValue); + function getTraitValues(uint256 tokenId, bytes32[] calldata traitKeys) external view returns (bytes32[] traitValues); + function getTraitMetadataURI() external view returns (string memory uri); + + /* Setters */ + function setTrait(uint256 tokenId, bytes32 traitKey, bytes32 newValue) external; +} +``` + +### Keys & Names + +The `traitKey` is used to identify a trait. The `traitKey` MUST be a unique `bytes32` value identifying a single trait. + +The `traitKey` SHOULD be a `keccak256` hash of a human readable trait name. + +### Metadata + +Trait metadata is an optional way to define additional information about which traits are present in a contract, how to parse and display trait values, and permissions for setting trait values. + +The trait metadata must be compliant with the [specified schema](../assets/eip-7496/DynamicTraitsSchema.json). + +The trait metadata URI MAY be a data URI or point to an offchain resource. + +The keys in the `traits` object MUST be unique trait names. If the trait name is 32 byte hex string starting with `0x` then it is interpreted as a literal `traitKey`. Otherwise, the `traitKey` is defined as the `keccak256` hash of the trait name. A literal `traitKey` MUST NOT collide with the `keccak256` hash of any other traits defined in the metadata. + +The `displayName` values MUST be unique and MUST NOT collide with the `displayName` of any other traits defined in the metadata. + +The `validateOnSale` value provides a signal to marketplaces on how to validate the trait value when a token is being sold. If the validation criteria is not met, the sale MUST not be permitted by the marketplace contract. If specified, the value of `validateOnSale` MUST be one of the following (or it is assumed to be `none`): + +- `none`: No validation is necessary. +- `requireEq`: The `bytes32` `traitValue` MUST be equal to the value at the time the offer to purchase was made. +- `requireUintGte`: The `bytes32` `traitValue` MUST be greater than or equal to the value at the time the offer to purchase was made. This comparison is made using the `uint256` representation of the `bytes32` value. +- `requireUintLte`: The `bytes32` `traitValue` MUST be less than or equal to the value at the time the offer to purchase was made. This comparison is made using the `uint256` representation of the `bytes32` value. + +Note that even though this specification requires marketplaces to validate the required trait values, buyers and sellers cannot fully rely on marketplaces to do this and must also take their own precautions to research the current trait values prior to initiating the transaction. + +Here is an example of the specified schema: + +```json +{ + "traits": { + "color": { + "displayName": "Color", + "dataType": { + "type": "string", + "acceptableValues": ["red", "green", "blue"] + } + }, + "points": { + "displayName": "Total Score", + "dataType": { + "type": "decimal", + "signed": false, + "decimals": 0 + }, + "validateOnSale": "requireUintGte" + }, + "name": { + "displayName": "Name", + "dataType": { + "type": "string", + "minLength": 1, + "maxLength": 32, + "valueMappings": { + "0x0000000000000000000000000000000000000000000000000000000000000000": "Unnamed", + "0x92e75d5e42b80de937d204558acf69c8ea586a244fe88bc0181323fe3b9e3ebf": "🙂" + } + }, + "tokenOwnerCanUpdateValue": true + }, + "birthday": { + "displayName": "Birthday", + "dataType": { + "type": "epochSeconds", + "valueMappings": { + "0x0000000000000000000000000000000000000000000000000000000000000000": null + } + } + }, + "0x77c2fd45bd8bdef5b5bc773f46759bb8d169f3468caab64d7d5f2db16bb867a8": { + "displayName": "🚢 📅", + "dataType": { + "type": "epochSeconds", + "valueMappings": { + "0x0000000000000000000000000000000000000000000000000000000000000000": 1696702201 + } + } + } + } +} +``` + +#### `string` Metadata Type + +The `string` metadata type allows for a string value to be set for a trait. + +The `dataType` object MAY have a `minLength` and `maxLength` value defined. If `minLength` is not specified, it is assumed to be 0. If `maxLength` is not specified, it is assumed to be a reasonable length. + +The `dataType` object MAY have a `valueMappings` object defined. If the `valueMappings` object is defined, the `valueMappings` object MUST be a mapping of `bytes32` values to `string` or unset `null` values. The `bytes32` values SHOULD be the `keccak256` hash of the `string` value. The `string` values MUST be unique. If the trait for a token is updated to `null`, it is expected offchain indexers to delete the trait for the token. + +#### `decimal` Metadata Type + +The `decimal` metadata type allows for a numeric value to be set for a trait in decimal form. + +The `dataType` object MAY have a `signed` value defined. If `signed` is not specified, it is assumed to be `false`. This determines whether the `traitValue` returned is interpreted as a signed or unsigned integer. + +The `dataType` object MAY have `minValue` and `maxValue` values defined. These should be formatted with the decimals specified. If `minValue` is not specified, it is assumed to be the minimum value of `signed` and `decimals`. If `maxValue` is not specified, it is assumed to be the maximum value of the `signed` and `decimals`. + +The `dataType` object MAY have a `decimals` value defined. The `decimals` value MUST be a non-negative integer. The `decimals` value determines the number of decimal places included in the `traitValue` returned onchain. If `decimals` is not specified, it is assumed to be 0. + +The `dataType` object MAY have a `valueMappings` object defined. If the `valueMappings` object is defined, the `valueMappings` object MUST be a mapping of `bytes32` values to numeric or unset `null` values. + +#### `boolean` Metadata Type + +The `boolean` metadata type allows for a boolean value to be set for a trait. + +The `dataType` object MAY have a `valueMappings` object defined. If the `valueMappings` object is defined, the `valueMappings` object MUST be a mapping of `bytes32` values to `boolean` or unset `null` values. The `boolean` values MUST be unique. + +If `valueMappings` is not used, the default trait values for `boolean` should be `bytes32(0)` for `false` and `bytes32(uint256(1))` (`0x0000000000000000000000000000000000000000000000000000000000000001`) for `true`. + +#### `epochSeconds` Metadata Type + +The `epochSeconds` metadata type allows for a numeric value to be set for a trait in seconds since the Unix epoch. + +The `dataType` object MAY have a `valueMappings` object defined. If the `valueMappings` object is defined, the `valueMappings` object MUST be a mapping of `bytes32` values to integer or unset `null` values. + +### Events + +Updating traits MUST emit one of: + +- `TraitUpdated` +- `TraitUpdatedRange` +- `TraitUpdatedRangeUniformValue` +- `TraitUpdatedList` +- `TraitUpdatedListUniformValue` + +For the `Range` events, the `fromTokenId` and `toTokenId` MUST be a consecutive range of tokens IDs and MUST be treated as an inclusive range. + +For the `List` events, the `tokenIds` MAY be in any order. + +It is RECOMMENDED to use the `UniformValue` events when the trait value is uniform across all token ids, so offchain indexers can more quickly process bulk updates rather than fetching each trait value individually. + +Updating the trait metadata MUST emit the event `TraitMetadataURIUpdated` so offchain indexers can be notified to query the contract for the latest changes via `getTraitMetadataURI()`. + +### `setTrait` + +If a trait defines `tokenOwnerCanUpdateValue` as `true`, then the trait value MUST be updatable by the token owner by calling `setTrait`. + +If the value the token owner is attempting to set is not valid, the transaction MUST revert. If the value is valid, the trait value MUST be updated and one of the `TraitUpdated` events MUST be emitted. + +If the trait has a `valueMappings` entry defined for the desired value being set, `setTrait` MUST be called with the corresponding `traitValue`. + +## Rationale + +The design of this specification is primarily a key-value mapping for maximum flexibility. This interface for traits was chosen instead of relying on using regular `getFoo()` and `setFoo()` style functions to allow for brevity in defining, setting, and getting traits. Otherwise, contracts would need to know both the getter and setter function selectors including the parameters that go along with it. In defining general but explicit get and set functions, the function signatures are known and only the trait key and values are needed to query and set the values. Contracts can also add new traits in the future without needing to modify contract code. + +The traits metadata allows for customizability of both display and behavior. The `valueMappings` property can define human-readable values to enhance the traits, for example, the default label of the `0` value (e.g. if the key was "redeemed", "0" could be mapped to "No", and "1" to "Yes"). The `validateOnSale` property lets the token creator define which traits should be protected on order creation and fulfillment, to protect end users against frontrunning. + +## Backwards Compatibility + +As a new EIP, no backwards compatibility issues are present, except for the point in the specification above that it is explicitly required that the onchain traits MUST override any conflicting values specified by the ERC-721 or ERC-1155 metadata URIs. + +## Test Cases + +Authors have included Foundry tests covering functionality of the specification in the [assets folder](../assets/eip-7496/ERC721DynamicTraits.t.sol). + +## Reference Implementation + +Authors have included reference implementations of the specification in the [assets folder](../assets/eip-7496/DynamicTraits.sol). + +## Security Considerations + +The set\* methods exposed externally MUST be permissioned so they are not callable by everyone but only by select roles or addresses. + +Marketplaces SHOULD NOT trust offchain state of traits as they can be frontrunned. Marketplaces SHOULD check the current state of onchain traits at the time of transfer. Marketplaces MAY check certain traits that change the value of the NFT (e.g. redemption status, defined by metadata values with `validateOnSale` property) or they MAY hash all the trait values to guarantee the same state at the time of order creation. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/ERCS/erc-7498.md b/ERCS/erc-7498.md new file mode 100644 index 0000000000..3789c4b3e0 --- /dev/null +++ b/ERCS/erc-7498.md @@ -0,0 +1,310 @@ +--- +eip: 7498 +title: NFT Redeemables +description: Extension to ERC-721 and ERC-1155 for onchain and offchain redeemables +author: Ryan Ghods (@ryanio), 0age (@0age), Adam Montgomery (@montasaurus), Stephan Min (@stephankmin) +discussions-to: https://ethereum-magicians.org/t/erc-7498-nft-redeemables/15485 +status: Draft +type: Standards Track +category: ERC +created: 2023-07-28 +requires: 165, 712, 721, 1155, 1271 +--- + +## Abstract + +This specification introduces a new interface that extends [ERC-721](./eip-721.md) and [ERC-1155](./eip-1155.md) to enable the discovery and use of onchain and offchain redeemables for NFTs. Onchain getters and events facilitate discovery of redeemable campaigns and their requirements. New onchain mints use an interface that gives context to the minting contract of what was redeemed. For redeeming physical products and goods (offchain redeemables) a `redemptionHash` and `signer` can tie onchain redemptions with offchain order identifiers that contain chosen product and shipping information. + +## Motivation + +Creators frequently use NFTs to create redeemable entitlements for digital and physical goods. However, without a standard interface, it is challenging for users and apps to discover and interact with these NFTs in a predictable and standard way. This standard aims to encompass enabling broad functionality for: + +- discovery: events and getters that provide information about the requirements of a redemption campaign +- onchain: token mints with context of items spent +- offchain: the ability to associate with ecommerce orders (through `redemptionHash`) +- trait redemptions: improving the burn-to-redeem experience with [ERC-7496](./eip-7496.md) Dynamic Traits. + +## Specification + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174. + +The token MUST have the following interface and MUST return `true` for [ERC-165](./eip-165.md) supportsInterface for `0x1ac61e13`, the 4 byte interfaceId of the below. + +```solidity +interface IERC7498 { + /* Events */ + event CampaignUpdated(uint256 indexed campaignId, Campaign campaign, string metadataURI); + event Redemption(uint256 indexed campaignId, uint256 requirementsIndex, bytes32 redemptionHash, uint256[] considerationTokenIds, uint256[] traitRedemptionTokenIds, address redeemedBy); + + /* Structs */ + struct Campaign { + CampaignParams params; + CampaignRequirements[] requirements; // one requirement must be fully satisfied for a successful redemption + } + struct CampaignParams { + uint32 startTime; + uint32 endTime; + uint32 maxCampaignRedemptions; + address manager; // the address that can modify the campaign + address signer; // null address means no EIP-712 signature required + } + struct CampaignRequirements { + OfferItem[] offer; + ConsiderationItem[] consideration; + TraitRedemption[] traitRedemptions; + } + struct TraitRedemption { + uint8 substandard; + address token; + bytes32 traitKey; + bytes32 traitValue; + bytes32 substandardValue; + } + + /* Getters */ + function getCampaign(uint256 campaignId) external view returns (Campaign memory campaign, string memory metadataURI, uint256 totalRedemptions); + + /* Setters */ + function createCampaign(Campaign calldata campaign, string calldata metadataURI) external returns (uint256 campaignId); + function updateCampaign(uint256 campaignId, Campaign calldata campaign, string calldata metadataURI) external; + function redeem(uint256[] calldata considerationTokenIds, address recipient, bytes calldata extraData) external payable; +} + +--- + +/* Seaport structs, for reference, used in offer/consideration above */ +enum ItemType { + NATIVE, + ERC20, + ERC721, + ERC1155 +} +struct OfferItem { + ItemType itemType; + address token; + uint256 identifierOrCriteria; + uint256 startAmount; + uint256 endAmount; +} +struct ConsiderationItem extends OfferItem { + address payable recipient; + // (note: psuedocode above, as of this writing can't extend structs in solidity) +} +struct SpentItem { + ItemType itemType; + address token; + uint256 identifier; + uint256 amount; +} +``` + +### Creating campaigns + +When creating a new campaign, `createCampaign` MUST be used and MUST return the newly created `campaignId` along with the `CampaignUpdated` event. The `campaignId` MUST be a counter incremented with each new campaign. The first campaign MUST have an id of `1`. + +### Updating campaigns + +Updates to campaigns MAY use `updateCampaign` and MUST emit the `CampaignUpdated` event. If an address other than the `manager` tries to update the campaign, it MUST revert with `NotManager()`. If the manager wishes to make the campaign immutable, the `manager` MAY be set to the null address. + +### Offer + +If tokens are set in the params `offer`, the tokens MUST implement the `IRedemptionMintable` interface in order to support minting new items. The implementation SHOULD be however the token mechanics are desired. The implementing token MUST return true for ERC-165 `supportsInterface` for the interfaceId of `IRedemptionMintable`, `0x81fe13c2`. + +```solidity +interface IRedemptionMintable { + function mintRedemption( + uint256 campaignId, + address recipient, + OfferItem calldata offer, + ConsiderationItem[] calldata consideration, + TraitRedemption[] calldata traitRedemptions + ) external; +} +``` + +When `mintRedemption` is called, it is RECOMMENDED to replace the token identifiers in the consideration items and trait redemptions with the items actually being redeemed. + +### Consideration + +Any token may be specified in the campaign requirement `consideration`. This will ensure the token is transferred to the `recipient`. If the token is meant to be burned, the recipient SHOULD be `0x000000000000000000000000000000000000dEaD`. If the token can internally handle burning its own tokens and reducing totalSupply, the token MAY burn the token instead of transferring to the recipient `0x000000000000000000000000000000000000dEaD`. + +### Dynamic traits + +Including trait redemptions is optional, but if the token would like to enable trait redemptions the token MUST include [ERC-7496](./eip-7496.md) Dynamic Traits. + +### Signer + +A signer MAY be specified to provide a signature to process the redemption. If the signer is not the null address, the signature MUST recover to the signer address via [EIP-712](./eip-712.md) or [ERC-1271](./eip-1271.md). + +The EIP-712 struct for signing MUST be as follows: `SignedRedeem(address owner,uint256[] considerationTokenIds,uint256[] traitRedemptionTokenIds,uint256 campaignId,uint256 requirementsIndex, bytes32 redemptionHash, uint256 salt)"` + +### Redeem function + +The `redeem` function MUST use the `consideration`, `offer`, and `traitRedemptions` specified by the `requirements` determined by the `campaignId` and `requirementsIndex`: + +- Execute the transfers in the `consideration` +- Mutate the traits specified by `traitRedemptions` according to ERC-7496 Dynamic Traits +- Call `mintRedemption()` on every `offer` item + +The `Redemption` event MUST be emitted for every valid redemption that occurs. + +#### Redemption extraData + +The extraData layout MUST conform to the below: + +| bytes | value | description / notes | +| -------- | --------------------------------- | ------------------------------------------------------------------------------------ | +| 0-32 | campaignId | | +| 32-64 | requirementsIndex | index of the campaign requirements met | +| 64-96 | redemptionHash | hash of offchain order ids | +| 96-\* | uint256[] traitRedemptionTokenIds | token ids for trait redemptions, MUST be in same order of campaign TraitRedemption[] | +| \*-(+32) | salt | if signer != address(0) | +| \*-(+\*) | signature | if signer != address(0). can be for EIP-712 or ERC-1271 | + +The `requirementsIndex` MUST be the index in the `requirements` array that satisfies the redemption. This helps reduce gas to find the requirement met. + +The `traitRedemptionTokenIds` specifies the token IDs required for the trait redemptions in the requirements array. The order MUST be the same order of the token addresses expected in the array of `TraitRedemption` structs in the campaign requirement used. + +If the campaign `signer` is the null address the `salt` and `signature` MUST be omitted. + +The `redemptionHash` is designated for offchain redemptions to reference offchain order identifiers to track the redemption to. + +The function MUST check that the campaign is active (using the same boundary check as Seaport, `startTime <= block.timestamp < endTime`). If it is not active, it MUST revert with `NotActive()`. + +### Trait redemptions + +The token MUST respect the TraitRedemption substandards as follows: + +| substandard ID | description | substandard value | +| -------------- | ------------------------------- | ------------------------------------------------------------------ | +| 1 | set value to `traitValue` | prior required value. if blank, cannot be the `traitValue` already | +| 2 | increment trait by `traitValue` | max value | +| 3 | decrement trait by `traitValue` | min value | +| 4 | check value is `traitValue` | n/a | + +### Max campaign redemptions + +The token MUST check that the `maxCampaignRedemptions` is not exceeded. If the redemption does exceed `maxCampaignRedemptions`, it MUST revert with `MaxCampaignRedemptionsReached(uint256 total, uint256 max)` + +### Metadata URI + +The metadata URI MUST conform to the below JSON schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "campaigns": { + "type": "array", + "items": { + "type": "object", + "properties": { + "campaignId": { + "type": "number" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string", + "description": "A one-line summary of the redeemable. Markdown is not supported." + }, + "details": { + "type": "string", + "description": "A multi-line or multi-paragraph description of the details of the redeemable. Markdown is supported." + }, + "imageUrls": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A list of image URLs for the redeemable. The first image will be used as the thumbnail. Will rotate in a carousel if multiple images are provided. Maximum 5 images." + }, + "bannerUrl": { + "type": "string", + "description": "The banner image for the redeemable." + }, + "faq": { + "type": "array", + "items": { + "type": "object", + "properties": { + "question": { + "type": "string" + }, + "answer": { + "type": "string" + }, + "required": ["question", "answer"] + } + } + }, + "contentLocale": { + "type": "string", + "description": "The language tag for the content provided by this metadata. https://www.rfc-editor.org/rfc/rfc9110.html#name-language-tags" + }, + "maxRedemptionsPerToken": { + "type": "string", + "description": "The maximum number of redemptions per token. When isBurn is true should be 1, else can be a number based on the trait redemptions limit." + }, + "isBurn": { + "type": "string", + "description": "If the redemption burns the token." + }, + "uuid": { + "type": "string", + "description": "An optional unique identifier for the campaign, for backends to identify when draft campaigns are published onchain." + }, + "productLimitForRedemption": { + "type": "number", + "description": "The number of products which are able to be chosen from the products array for a single redemption." + }, + "products": { + "type": "object", + "properties": "https://schema.org/Product", + "required": ["name", "url", "description"] + } + }, + "required": ["campaignId", "name", "description", "imageUrls", "isBurn"] + } + } + } +} +``` + +Future EIPs MAY inherit this one and add to the above metadata to add more features and functionality. + +### ERC-1155 (Semi-fungibles) + +This standard MAY be applied to ERC-1155 but the redemptions would apply to all token amounts for specific token identifiers. If the ERC-1155 contract only has tokens with amount of 1, then this specification MAY be used as written. + +## Rationale + +The "offer" and "consideration" structs from Seaport were used to create a similar language for redeemable campaigns. The "offer" is what is being offered, e.g. a new onchain token, and the "consideration" is what must be satisfied to complete the redemption. The "consideration" field has a "recipient", who the token should be transferred to. For trait updates that do not require moving of a token, `traitRedemptionTokenIds` is specified instead. + +The "salt" and "signature" fields are provided primarily for offchain redemptions where a provider would want to sign approval for a redemption before it is conducted onchain, to prevent the need for irregular state changes. For example, if a user lives outside a region supported by the shipping of an offchain redeemable, during the offchain order creation process the signature would not be provided for the onchain redemption when seeing that the user's shipping country is unsupported. This prevents the user from redeeming the NFT, then later finding out the shipping isn't supported after their NFT is already burned or trait is mutated. + +[ERC-7496](./eip-7496.md) Dynamic Traits is used for trait redemptions to support onchain enforcement of trait values for secondary market orders. + +## Backwards Compatibility + +As a new EIP, no backwards compatibility issues are present. + +## Test Cases + +Authors have included Foundry tests covering functionality of the specification in the [assets folder](../assets/eip-7498/ERC721ShipyardRedeemable.t.sol). + +## Reference Implementation + +Authors have included reference implementations of the specification in the [assets folder](../assets/eip-7498/ERC7498NFTRedeemables.sol). + +## Security Considerations + +If trait redemptions are desired, tokens implementing this EIP must properly implement [ERC-7496](./eip-7496.md) Dynamic Traits. + +For tokens to be minted as part of the params `offer`, the `mintRedemption` function contained as part of `IRedemptionMintable` MUST be permissioned and ONLY allowed to be called by specified addresses. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/ERCS/erc-7506.md b/ERCS/erc-7506.md new file mode 100644 index 0000000000..7b28407568 --- /dev/null +++ b/ERCS/erc-7506.md @@ -0,0 +1,467 @@ +--- +eip: 7506 +title: Trusted Hint Registry +description: A system for managing on-chain metadata, enabling verification of ecosystem claims. +author: Philipp Bolte (@strumswell), Dennis von der Bey (@DennisVonDerBey), Lauritz Leifermann (@lleifermann) +discussions-to: https://ethereum-magicians.org/t/eip-trusted-hint-registry/15615 +status: Draft +type: Standards Track +category: ERC +created: 2023-08-31 +requires: 712 +--- + +## Abstract + +This EIP standardizes a system for managing on-chain metadata (hints), enabling claim interpretation, reliability, +and verification. It structures these hints within defined namespaces and lists, enabling structured organization and +retrieval, as well as permissioned write access. The system permits namespace owners to delegate hint management tasks, +enhancing operational flexibility. It incorporates secure meta transactions via [EIP-712](./eip-712.md)-enabled +signatures and offers optional ENS integration for trust verification and discoverability. The interface is equipped to +emit specific events for activities like hint modifications, facilitating easy traceability of changes to hints. This +setup aims to provide a robust, standardized framework for managing claim- and ecosystem-related metadata, essential for +maintaining integrity and trustworthiness in decentralized environments. + +## Motivation + +In an increasingly interconnected and decentralized landscape, the formation of trust among entities remains a critical +concern. Ecosystems, both on-chain and off-chain—spanning across businesses, social initiatives, and other organized +frameworks—frequently issue claims for or about entities within their networks. These claims serve as the foundational +elements of trust, facilitating interactions and transactions in environments that are essentially untrustworthy by +nature. While the decentralization movement has brought about significant improvements around trustless technologies, +many ecosystems building on top of these are in need of technologies that build trust in their realm. Real-world +applications have shown that verifiable claims alone are not enough for this purpose. Moreover, a supporting layer of +on-chain metadata is needed to support a reliable exchange and verification of those claims. + +The absence of a structured mechanism to manage claim metadata on-chain poses a significant hurdle to the formation and +maintenance of trust among participating entities in an ecosystem. This necessitates the introduction of a layer of +on-chain metadata, which can assist in the reliable verification and interpretation of these claims. Termed "hints" in +this specification, this metadata can be used in numerous ways, each serving to bolster the integrity and reliability +of the ecosystem's claims. Hints can perform various tasks, such as providing revocation details, identifying trusted +issuers, or offering timestamping hashes. These are just a few examples that enable ecosystems to validate and +authenticate claims, as well as verify data integrity over time. + +The proposed "Trusted Hint Registry" aims to provide a robust, flexible, and standardized interface for managing such +hints. The registry allows any address to manage multiple lists of hints, with a set of features that not only make it +easier to create and manage these hints but also offer the flexibility of delegating these capabilities to trusted +entities. In practice, this turns the hint lists into dynamic tools adaptable to varying requirements and use cases. +Moreover, an interface has been designed with a keen focus on interoperability, taking into consideration existing W3C +specifications around Decentralized Identifiers and Verifiable Credentials, as well as aligning with on-chain projects +like the Ethereum Attestation Service. + +By providing a standardized smart contract interface for hint management, this specification plays an integral role in +enabling and scaling trust in decentralized ecosystems. It offers a foundational layer upon which claims — both on-chain +and off-chain — can be reliably issued, verified, and interpreted, thus serving as an essential building block for the +credible operation of any decentralized ecosystem. Therefore, the Trusted Hint Registry is not just an addition to the +ecosystem but a necessary evolution in the complex topology of decentralized trust. + +## Specification + +The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and +“OPTIONAL” in this document are to be interpreted as described in RFC 2119. + +This EIP specifies a contract called `TrustedHintRegistry` and standardizes a set of **REQUIRED** core hint functions, +while also providing a common set of **OPTIONAL** management functions, enabling various ways for collaborative hint +management. Ecosystems **MAY** use this specification to build their own hint registry contracts with ecosystem-specific, +non-standardized features. Governance is deliberately excluded from this ERC and **MAY** be implemented according to an +ecosystem's need. + +### Definitions + +- `claim`: A claim is a statement about an entity made by another entity. +- `hint`: A "hint" refers to a small piece of information that provides insights, aiding in the interpretation, + reliability, or verifiability of decentralized ecosystem data. +- `namespace`: A namespace is a representation of an Ethereum address inside the registry that corresponds to its + owner’s address. A namespace contains hint lists for different use cases. +- `hint list`: A hint list is identified by a unique value that contains a number of hint keys that resolve to hint + values. An example of this is a revocation key that resolves to a revocation state. +- `hint key`: A hint key is a unique value that resolves to a hint value. An example of this is a trusted issuer + identifier, which resolves to the trust status of that identifier. +- `hint value`: A hint value expresses data about an entity in an ecosystem. +- `delegate`: An Ethereum address that has been granted writing permissions to a hint list by its owner. + +### Interface + +#### Hint Management + +##### getHint + +A method with the following signature **MUST** be implemented that returns the hint value in a hint list of a namespace. + +```solidity +function getHint(address _namespace, bytes32 _list, bytes32 _key) external view returns (bytes32); +``` + +##### setHint + +A method with the following signature **MUST** be implemented that changes the hint value in a hint list of a namespace. +An overloaded method with an additional `bytes calldata _metadata` parameter **MAY** be implemented to set metadata +together with the hint value. + +```solidity +function setHint(address _namespace, bytes32 _list, bytes32 _key, bytes32 _value) public; +``` + +##### setHintSigned + +A method with the following signature **MAY** be implemented that changes the hint value in a hint list of a namespace +with a raw signature. The raw signature **MUST** be generated following the Meta Transactions section. An overloaded +method with an additional `bytes calldata _metadata` parameter **MAY** be implemented to set metadata together with the +hint value. + +```solidity +function setHintSigned(address _namespace, bytes32 _list, bytes32 _key, bytes32 _value, address _signer, bytes calldata _signature) public; +``` + +##### setHints + +A method with the following signature **MUST** be implemented that changes multiple hint values in a hint list of a +namespace. An overloaded method with an additional `bytes calldata _metadata` parameter **MAY** be implemented to set +metadata together with the hint value. + +```solidity +function setHints(address _namespace, bytes32 _list, bytes32[] calldata _keys, bytes32[] calldata _values) public; +``` + +##### setHintsSigned + +A method with the following signature **MUST** be implemented that multiple hint values in a hint list of a namespace +with a raw signature. The raw signature **MUST** be generated following the Meta Transactions section. An overloaded +method with an additional `bytes calldata _metadata` parameter **MAY** be implemented to set metadata together with the +hint value. + +```solidity +function setHintsSigned(address _namespace, bytes32 _list, bytes32[] calldata _keys, bytes32[] calldata _values, address _signer, bytes calldata _signature) public; +``` + +#### Delegated Hint Management + +A namespace owner can add delegate addresses to specific hint lists in their namespace. These delegates **SHALL** have +write access to the specific lists via a specific set of methods. + +##### setHintDelegated + +A method with the following signature **MAY** be implemented that changes the hint value in a hint list of a namespace +for pre-approved delegates. An overloaded method with an additional `bytes calldata _metadata` parameter **MAY** be +implemented to set metadata together with the hint value. + +```solidity +function setHintDelegated(address _namespace, bytes32 _list, bytes32 _key, bytes32 _value) public; +``` + +##### setHintDelegatedSigned + +A method with the following signature **MAY** be implemented that changes the hint value in a hint list of a namespace +for pre-approved delegates with a raw signature. The raw signature **MUST** be generated following the Meta Transactions +section. An overloaded method with an additional `bytes calldata _metadata` parameter **MAY** be implemented to set +metadata together with the hint value. + +```solidity +function setHintDelegatedSigned(address _namespace, bytes32 _list, bytes32 _key, bytes32 _value, address _signer, bytes calldata _signature) public; +``` + +##### setHintsDelegated + +A method with the following signature **MAY** be implemented that changes multiple hint values in a hint list of a +namespace for pre-approved delegates. An overloaded method with an additional `bytes calldata _metadata` parameter +**MAY** be implemented to set metadata together with the hint value. + +```solidity +function setHintsDelegated(address _namespace, bytes32 _list, bytes32[] calldata _keys, bytes32[] calldata _values) public; +``` + +##### setHintsDelegatedSigned + +A method with the following signature **MAY** be implemented that has multiple hint values in a hint list of a namespace +for pre-approved delegates with a raw signature. The raw signature **MUST** be generated following the Meta Transactions +section. An overloaded method with an additional `bytes calldata _metadata` parameter **MAY** be implemented to set +metadata together with the hint value. + +```solidity +function setHintsDelegatedSigned(address _namespace, bytes32 _list, bytes32[] calldata _keys, bytes32[] calldata _values, address _signer, bytes calldata _signature) public; +``` + +#### Hint List Management + +##### setListStatus + +A method with the following signature **MAY** be implemented that changes the validity state of a hint list. This +enables one to (un)-revoke a whole list of hint values. + +```solidity +function setListStatus(address _namespace, bytes32 _list, bool _revoked) public; +``` + +##### setListStatusSigned + +A method with the following signature **MAY** be implemented that changes the validity state of a hint list with a raw +signature. This enables one to (un)-revoke a whole list of hint values. + +```solidity +function setListStatusSigned(address _namespace, bytes32 _list, bool _revoked, address _signer, bytes calldata _signature) public; +``` + +##### setListOwner + +A method with the following signature **MAY** be implemented that transfers the ownership of a trust list to another +address. Changing the owner of a list **SHALL NOT** change the namespace the hint list resides in, to retain references +of paths to a hint value. + +```solidity +function setListOwner(address _namespace, bytes32 _list, address _newOwner) public; +``` + +##### setListOwnerSigned + +A method with the following signature **MAY** be implemented that transfers the ownership of a trust list to another +address with a raw signature. The raw signature **MUST** be generated following the Meta Transactions section. Changing +the owner of a list **SHALL NOT** change the namespace the hint list resides in, to retain references to paths to a hint +value. + +```solidity +function setListOwnerSigned(address _namespace, bytes32 _list, address _newOwner, address _signer, bytes calldata _signature) public; +``` + +##### addListDelegate + +A method with the following signature **MAY** be implemented to add a delegate to an owner’s hint list in a namespace. + +```solidity +function addListDelegate(address _namespace, bytes32 _list, address _delegate, uint256 _untilTimestamp) public; +``` + +##### addListDelegateSigned + +A method with the following signature **MAY** be implemented to add a delegate to an owner’s hint list in a namespace +with a raw signature. The raw signature **MUST** be generated following the Meta Transactions section. + +```solidity +function addListDelegateSigned(address _namespace, bytes32 _list, address _delegate, uint256 _untilTimestamp, address _signer, bytes calldata _signature) public; +``` + +##### removeListDelegate + +A method with the following signature **MAY** be implemented to remove a delegate from an owner’s revocation hint list +in a namespace. + +```solidity +function removeListDelegate(address _namespace, bytes32 _list, address _delegate) public; +``` + +##### removeListDelegateSigned + +A method with the following signature **MAY** be implemented to remove a delegate from an owner’s revocation hint list +in a namespace with a raw signature. The raw signature **MUST** be generated following the Meta Transactions section. + +```solidity +function removeListDelegateSigned(address _namespace, bytes32 _list, address _delegate, address _signer, bytes calldata _signature) public; +``` + +#### Metadata Management + +##### getMetadata + +A method with the following signature **MAY** be implemented to retrieve metadata for a hint. + +```solidity +function getMetadata(address _namespace, bytes32 _list, bytes32 _key, bytes32 _value) external view returns (bytes memory); +``` + +##### setMetadata + +A method with the following signature **MAY** be implemented to set metadata for a hint. + +```solidity +function setMetadata(address _namespace, bytes32 _list, bytes32 _key, bytes32 _value, bytes calldata _metadata) public; +``` + +##### setMetadataSigned + +A method with the following signature **MAY** be implemented to set metadata for a hint with a raw signature. The raw +signature **MUST** be generated following the Meta Transactions section. + +```solidity +function setMetadataSigned(address _namespace, bytes32 _list, bytes32 _key, bytes32 _value, bytes calldata _metadata, address _signer, bytes calldata _signature) public; +``` + +#### setMetadataDelegated + +A method with the following signature **MAY** be implemented to set metadata for a hint as a pre-approved delegate of +the hint list. + +```solidity +function setMetadataDelegated(address _namespace, bytes32 _list, bytes32 _key, bytes32 _value, bytes calldata _metadata) public; +``` + +##### setMetadataDelegatedSigned + +A method with the following signature **MAY** be implemented to set metadata for a hint as a pre-approved delegate of +the hint list with a raw signature. The raw signature **MUST** be generated following the Meta Transactions section. + +```solidity +function setMetadataDelegatedSigned(address _namespace, bytes32 _list, bytes32 _key, bytes32 _value, bytes calldata _metadata, address _signer, bytes calldata _signature) public; +``` + +#### Events + +##### HintValueChanged + +**MUST** be emitted when a hint value has changed. + +```solidity +event HintValueChanged( + address indexed namespace, + bytes32 indexed list, + bytes32 indexed key, + bytes32 value +); +``` + +##### HintListOwnerChanged + +**MUST** be emitted when the owner of a list has changed. + +```solidity +event HintListOwnerChanged( + address indexed namespace, + bytes32 indexed list, + address indexed newOwner +); +``` + +##### HintListDelegateAdded + +**MUST** be emitted when a delegate has been added to a hint list. + +```solidity +event HintListDelegateAdded( + address indexed namespace, + bytes32 indexed list, + address indexed newDelegate +); +``` + +##### HintListDelegateRemoved + +**MUST** be emitted when a delegate has been removed from a hint list. + +```solidity +event HintListDelegateRemoved( + address indexed namespace, + bytes32 indexed list, + address indexed oldDelegate +); +``` + +##### HintListStatusChanged + +**MUST** be emitted when the validity status of the hint list has been changed. + +```solidity +event HintListStatusChanged( + address indexed namespace, + bytes32 indexed list, + bool indexed revoked +); +``` + +### Meta Transactions + +This section uses the following terms: + +- **`transaction signer`**: An Ethereum address that signs arbitrary data for the contract to execute **BUT** does not + commit the transaction. +- **`transaction sender`**: An Ethereum address that takes signed data from a **transaction signer** and commits it + wrapped in a transaction to the smart contract. + +A **transaction signer** **MAY** be able to deliver a signed payload off-band to a **transaction sender** that initiates +the Ethereum interaction with the smart contract. The signed payload **MUST** be limited to being used only +once (see Signed Hash and Nonce). + +#### Signed Hash + +The signature of the **transaction signer** **MUST** conform to [EIP-712](./eip-712.md). This helps users understand +what the payload they are signing consists of, and it provides protection against replay attacks. + +#### Nonce + +This EIP **RECOMMENDS** the use of a **dedicated nonce mapping** for meta transactions. If the signature of the +**transaction sender** and its meta-contents are verified, the contract increases a nonce for this +**transaction signer**. This effectively removes the possibility for any other sender to execute the same transaction +again with another wallet. + +### Trust Anchor via ENS + +Ecosystems that use an Ethereum Name Service (ENS) domain can increase trust by using ENS entries to share information +about a hint list registry. This method takes advantage of the ENS domain's established credibility to make it easier to +find a reliable hint registry contract, as well as the appropriate namespace and hint list customized for particular +ecosystem needs. Implementing a trust anchor through ENS is **OPTIONAL**. + +For each use case, a specific ENS subdomain **SHALL** be created only used for a specific hint list, e.g., +“trusted-issuers.ens.eth”. The following records **SHALL** be set: + +- ADDRESS ETH - address of the trusted hint registry contract +- TEXT - key: “hint.namespace”; value: owner address of namespace + +The following records **MAY** be set: + +- TEXT - key: “hint.list”; value: bytes32 key of hint list +- TEXT - key: “hint.key”; value: bytes32 key of hint key +- TEXT - key: “hint.value”; value: bytes32 key of hint value +- ABI - ABI of trusted hint registry contract + +To create a two-way connection, a namespace owner **SHALL** set metadata referencing the ENS subdomain hash for the hint +list. Metadata **SHALL** be set in the owners namespace, hint list `0x0`, and hint key `0x0` where the value is the +ENS subdomain keccak256 hash. + +By establishing this connection, a robust foundation for trust and discovery within an ecosystem is created. + +## Rationale + +Examining the method signatures reveals a deliberate architecture and data hierarchy within this ERC: A namespace +address maps to a hint list, which in turn maps to a hint key, which then reveals the hint value. + +```solidity +// namespace hint list hint key hint value +mapping(address => mapping(bytes32 => mapping(bytes32 => bytes32))) hints; +``` + +This structure is designed to implicitly establish the initial ownership of all lists under a given namespace, +eliminating the need for subsequent claiming actions. As a result, it simplifies the process of verifying and enforcing +write permissions, thereby reducing potential attack surfaces. Additional data structures must be established and +validated for features like delegate management and ownership transfer of hint lists. These structures won't affect the +main namespace layout; rather, they serve as a secondary mechanism for permission checks. + +One of the primary objectives of this ERC is to include management features, as these significantly influence the ease +of collaboration and maintainability of hint lists. These features also enable platforms to hide complexities while +offering user-friendly interfaces. Specifically, the use of meta-transactions allows users to maintain control over +their private keys while outsourcing the technical heavy lifting to platforms, which is achieved simply by signing an +[EIP-712](./eip-712.md) payload. + +## Backwards Compatibility + +No backward compatibility issues found. + +## Security Considerations + +### Meta Transactions + +The signature of signed transactions could potentially be replayed on different chains or deployed versions of the +registry implementing this ERC. This security consideration is addressed by the usage +of [EIP-712](./eip-712.md). + +### Rights Management + +The different roles and their inherent permissions are meant to prevent changes from unauthorized entities. The hint +list owner should always be in complete control over its hint list and who has writing access to it. + +### Governance + +It is recognized that ecosystems might have processes in place that might also apply to changes in hint lists. This ERC +explicitly leaves room for implementers or users of the registry to apply a process that fits the requirements of their +ecosystem. Possible solutions can be an extension of the contract with governance features around specific methods, the +usage of multi-sig wallets, or off-chain processes enforced by an entity. + +## Copyright + +Copyright and related rights waived via [CC0](../LICENSE.md). diff --git a/assets/erc-7410/ERC7410.sol b/assets/erc-7410/ERC7410.sol new file mode 100644 index 0000000000..bd030b6d9f --- /dev/null +++ b/assets/erc-7410/ERC7410.sol @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity 0.8.17; + +import "openzeppelin-contracts/token/ERC20/ERC20.sol"; +import "./IERC7410.sol"; + +contract ERC7410 is ERC20, IERC7410 { + + constructor( + string memory name_, + string memory symbol_ + ) ERC20(name_, symbol_) {} + + function decreaseAllowanceBySpender( + address _owner, + uint256 _value + ) public override(ERC20, IERC7410) returns (bool success) { + address spender = _msgSender(); + if (allowance(_owner, spender) > _value) { + _spendAllowance(_owner, spender, _value); + } else { + _approve(_owner, spender, 0); + } + + return true; + } + + function supportsInterface( + bytes4 interfaceId + ) public view virtual returns (bool) { + return interfaceId == type(IERC7410).interfaceId; + } +} diff --git a/assets/erc-7410/IERC7410.sol b/assets/erc-7410/IERC7410.sol new file mode 100644 index 0000000000..0a57943c6b --- /dev/null +++ b/assets/erc-7410/IERC7410.sol @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.17; + +import "openzeppelin-contracts/interfaces/IERC20.sol"; +import "openzeppelin-contracts/interfaces/IERC165.sol"; + +/** + * @title ERC-7410 Update Allowance By Spender Extension + * Note: the ERC-165 identifier for this interface is 0x12860fba + */ +interface IERC7410 is IERC20, IERC165 { + + /** + * @notice Decreases any allowance by `owner` address for caller. + * Emits an {IERC20-Approval} event. + * + * Requirements: + * - when `subtractedValue` is equal or higher than current allowance of spender the new allowance is set to 0. + * Nullification also MUST be reflected for current allowance being type(uint256).max. + */ + function decreaseAllowanceBySpender(address owner, uint256 subtractedValue) external; + +} diff --git a/assets/erc-7496/DynamicTraits.sol b/assets/erc-7496/DynamicTraits.sol new file mode 100644 index 0000000000..edeb0a5a4d --- /dev/null +++ b/assets/erc-7496/DynamicTraits.sol @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import {IERC7496} from "./interfaces/IERC7496.sol"; + +library DynamicTraitsStorage { + struct Layout { + /// @dev A mapping of token ID to a mapping of trait key to trait value. + mapping(uint256 tokenId => mapping(bytes32 traitKey => bytes32 traitValue)) _traits; + /// @dev An offchain string URI that points to a JSON file containing trait metadata. + string _traitMetadataURI; + } + + bytes32 internal constant STORAGE_SLOT = keccak256("contracts.storage.erc7496-dynamictraits"); + + function layout() internal pure returns (Layout storage l) { + bytes32 slot = STORAGE_SLOT; + assembly { + l.slot := slot + } + } +} + +/** + * @title DynamicTraits + * + * @dev Implementation of [ERC-7496](https://eips.ethereum.org/EIPS/eip-7496) Dynamic Traits. + * Uses a storage layout pattern for upgradeable contracts. + * + * Requirements: + * - Overwrite `setTrait` with access role restriction. + * - Expose a function for `setTraitMetadataURI` with access role restriction if desired. + */ +contract DynamicTraits is IERC7496 { + using DynamicTraitsStorage for DynamicTraitsStorage.Layout; + + /** + * @notice Get the value of a trait for a given token ID. + * @param tokenId The token ID to get the trait value for + * @param traitKey The trait key to get the value of + */ + function getTraitValue(uint256 tokenId, bytes32 traitKey) public view virtual returns (bytes32 traitValue) { + // Return the trait value. + return DynamicTraitsStorage.layout()._traits[tokenId][traitKey]; + } + + /** + * @notice Get the values of traits for a given token ID. + * @param tokenId The token ID to get the trait values for + * @param traitKeys The trait keys to get the values of + */ + function getTraitValues(uint256 tokenId, bytes32[] calldata traitKeys) + public + view + virtual + returns (bytes32[] memory traitValues) + { + // Set the length of the traitValues return array. + uint256 length = traitKeys.length; + traitValues = new bytes32[](length); + + // Assign each trait value to the corresopnding key. + for (uint256 i = 0; i < length;) { + bytes32 traitKey = traitKeys[i]; + traitValues[i] = getTraitValue(tokenId, traitKey); + unchecked { + ++i; + } + } + } + + /** + * @notice Get the URI for the trait metadata + */ + function getTraitMetadataURI() external view virtual returns (string memory labelsURI) { + // Return the trait metadata URI. + return DynamicTraitsStorage.layout()._traitMetadataURI; + } + + /** + * @notice Set the value of a trait for a given token ID. + * Reverts if the trait value is unchanged. + * @dev IMPORTANT: Override this method with access role restriction. + * @param tokenId The token ID to set the trait value for + * @param traitKey The trait key to set the value of + * @param newValue The new trait value to set + */ + function setTrait(uint256 tokenId, bytes32 traitKey, bytes32 newValue) public virtual { + // Revert if the new value is the same as the existing value. + bytes32 existingValue = DynamicTraitsStorage.layout()._traits[tokenId][traitKey]; + if (existingValue == newValue) { + revert TraitValueUnchanged(); + } + + // Set the new trait value. + _setTrait(tokenId, traitKey, newValue); + + // Emit the event noting the update. + emit TraitUpdated(traitKey, tokenId, newValue); + } + + /** + * @notice Set the trait value (without emitting an event). + * @param tokenId The token ID to set the trait value for + * @param traitKey The trait key to set the value of + * @param newValue The new trait value to set + */ + function _setTrait(uint256 tokenId, bytes32 traitKey, bytes32 newValue) internal virtual { + // Set the new trait value. + DynamicTraitsStorage.layout()._traits[tokenId][traitKey] = newValue; + } + + /** + * @notice Set the URI for the trait metadata. + * @param uri The new URI to set. + */ + function _setTraitMetadataURI(string memory uri) internal virtual { + // Set the new trait metadata URI. + DynamicTraitsStorage.layout()._traitMetadataURI = uri; + + // Emit the event noting the update. + emit TraitMetadataURIUpdated(); + } + + /** + * @dev See {IERC165-supportsInterface}. + */ + function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { + return interfaceId == type(IERC7496).interfaceId; + } +} diff --git a/assets/erc-7496/DynamicTraitsSchema.json b/assets/erc-7496/DynamicTraitsSchema.json new file mode 100644 index 0000000000..14ff7f63dd --- /dev/null +++ b/assets/erc-7496/DynamicTraitsSchema.json @@ -0,0 +1,156 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "required": ["traits"], + "properties": { + "traits": { + "type": "object", + "additionalProperties": { + "type": "object", + "required": ["dataType"], + "properties": { + "displayName": { + "type": ["string"], + "description": "The user-facing display name for the trait." + }, + "validateOnSale": { + "enum": ["none", "requireEq", "requireUintGte", "requireUintLte"], + "description": "Whether the trait value should be validated when the token is sold. If this isn't specified, it is assumed to be `none`." + }, + "tokenOwnerCanUpdateValue": { + "type": "boolean", + "description": "Whether the token owner is able to set the trait value directly by calling `setTrait`. If this isn't specified, it is assumed to be false." + }, + "dataType": { + "oneOf": [ + { + "type": "object", + "required": ["type"], + "properties": { + "type": { "const": "string" }, + "acceptableValues": { + "type": "array", + "description": "An exclusive list of possible string values that can be set for the trait. If this is not specified, the trait can be set to any reasonable string value. If `valueMappings` is specified, this list must be the `mappedValue`s.", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "maxLength": { + "type": "number", + "description": "The maximum length of the string value that can be set for the trait (inclusive). If this is not specified, the trait can be set to any reasonable string length." + }, + "minLength": { + "type": "number", + "description": "The minimum length of the string value that can be set for the trait (inclusive). If this is not specified, it is assumed to be 0." + }, + "valueMappings": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "description": "A dictionary mapping of `traitValue`s returned from the contract to values that an offchain indexer should display. The keys to the dictionary are the onchain values and the dictionary values are the offchain values. Useful when longer than the 32 ASCII characters that bytes32 allows for." + } + } + }, + { + "type": "object", + "required": ["type"], + "properties": { + "type": { "const": "decimal" }, + "signed": { + "type": "boolean", + "description": "Whether the trait value being returned is signed. If this is not specified, it is assumed to be false." + }, + "decimals": { + "type": "integer", + "description": "The number of decimal places that the trait value is returned with onchain. If this is not specified, it is assumed to be 0 (i.e. an integer value)." + }, + "minValue": { + "type": "number", + "description": "The minimum value that the trait value can be set to (inclusive). If this is not specified, it is assumed to be the minimum value of the `signed` and `decimals`." + }, + "maxValue": { + "type": "number", + "description": "The maximum value that the trait value can be set to (inclusive). If this is not specified, it is assumed to be the maximum value of the `signed` and `decimals`." + }, + "valueMappings": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "description": "A dictionary mapping of `traitValue`s returned from the contract to values that an offchain indexer should display. The keys to the dictionary are the onchain values and the dictionary values are the offchain values. Useful for default values of 0x0 and large or magic numbers." + } + } + }, + { + "type": "object", + "required": ["type"], + "properties": { + "type": { "const": "boolean" }, + "valueMappings": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ] + }, + "description": "A dictionary mapping of `traitValue`s returned from the contract to values that an offchain indexer should display. The keys to the dictionary are the onchain values and the dictionary values are the offchain values. Useful for default values of 0x0 and magic numbers." + } + } + }, + { + "type": "object", + "required": ["type"], + "properties": { + "type": { "const": "epochSeconds" }, + "valueMappings": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ] + }, + "description": "A dictionary mapping of `traitValue`s returned from the contract to values that an offchain indexer should display. The keys to the dictionary are the onchain values and the dictionary values are the offchain values. Useful for default values of 0x0 and magic numbers." + } + }, + "description": "A datetime type that is the number of seconds since the Unix epoch (January 1, 1970 00:00:00 UTC). Must return an integer value." + } + ], + "description": "The data type definition of the trait." + } + } + } + } + } +} diff --git a/assets/erc-7496/ERC721DynamicTraits.sol b/assets/erc-7496/ERC721DynamicTraits.sol new file mode 100644 index 0000000000..9b22705a08 --- /dev/null +++ b/assets/erc-7496/ERC721DynamicTraits.sol @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import {ERC721} from "openzeppelin-contracts/contracts/token/ERC721/ERC721.sol"; +import {Ownable} from "openzeppelin-contracts/access/Ownable.sol"; +import {DynamicTraits} from "src/dynamic-traits/DynamicTraits.sol"; + +contract ERC721DynamicTraits is DynamicTraits, Ownable, ERC721 { + constructor() Ownable(msg.sender) ERC721("ERC721DynamicTraits", "ERC721DT") { + _setTraitMetadataURI("https://example.com"); + } + + function setTrait(uint256 tokenId, bytes32 traitKey, bytes32 value) public virtual override onlyOwner { + // Revert if the token doesn't exist. + _requireOwned(tokenId); + + // Call the internal function to set the trait. + DynamicTraits.setTrait(tokenId, traitKey, value); + } + + function getTraitValue(uint256 tokenId, bytes32 traitKey) + public + view + virtual + override + returns (bytes32 traitValue) + { + // Revert if the token doesn't exist. + _requireOwned(tokenId); + + // Call the internal function to get the trait value. + return DynamicTraits.getTraitValue(tokenId, traitKey); + } + + function getTraitValues(uint256 tokenId, bytes32[] calldata traitKeys) + public + view + virtual + override + returns (bytes32[] memory traitValues) + { + // Revert if the token doesn't exist. + _requireOwned(tokenId); + + // Call the internal function to get the trait values. + return DynamicTraits.getTraitValues(tokenId, traitKeys); + } + + function setTraitMetadataURI(string calldata uri) external onlyOwner { + // Set the new metadata URI. + _setTraitMetadataURI(uri); + } + + function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, DynamicTraits) returns (bool) { + return ERC721.supportsInterface(interfaceId) || DynamicTraits.supportsInterface(interfaceId); + } +} diff --git a/assets/erc-7496/ERC721DynamicTraits.t.sol b/assets/erc-7496/ERC721DynamicTraits.t.sol new file mode 100644 index 0000000000..33febdafa3 --- /dev/null +++ b/assets/erc-7496/ERC721DynamicTraits.t.sol @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import "forge-std/Test.sol"; +import {IERC721Errors} from "openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol"; +import {ERC721} from "openzeppelin-contracts/contracts/token/ERC721/ERC721.sol"; +import {Ownable} from "openzeppelin-contracts/contracts/access/Ownable.sol"; +import {IERC7496} from "src/dynamic-traits/interfaces/IERC7496.sol"; +import {ERC721DynamicTraits} from "src/dynamic-traits/ERC721DynamicTraits.sol"; +import {Solarray} from "solarray/Solarray.sol"; + +contract ERC721DynamicTraitsMintable is ERC721DynamicTraits { + constructor() ERC721DynamicTraits() {} + + function mint(address to, uint256 tokenId) public onlyOwner { + _mint(to, tokenId); + } +} + +contract ERC721DynamicTraitsTest is Test { + ERC721DynamicTraitsMintable token; + + /* Events */ + event TraitUpdated(bytes32 indexed traitKey, uint256 tokenId, bytes32 trait); + event TraitMetadataURIUpdated(); + + function setUp() public { + token = new ERC721DynamicTraitsMintable(); + } + + function testSupportsInterfaceId() public { + assertTrue(token.supportsInterface(type(IERC7496).interfaceId)); + } + + function testReturnsValueSet() public { + bytes32 key = bytes32("testKey"); + bytes32 value = bytes32("foo"); + uint256 tokenId = 12345; + token.mint(address(this), tokenId); + + vm.expectEmit(true, true, true, true); + emit TraitUpdated(key, tokenId, value); + + token.setTrait(tokenId, key, value); + + assertEq(token.getTraitValue(tokenId, key), value); + } + + function testOnlyOwnerCanSetValues() public { + address alice = makeAddr("alice"); + vm.prank(alice); + vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, alice)); + token.setTrait(0, bytes32("test"), bytes32("test")); + } + + function testSetTrait_Unchanged() public { + bytes32 key = bytes32("testKey"); + bytes32 value = bytes32("foo"); + uint256 tokenId = 1; + token.mint(address(this), tokenId); + + token.setTrait(tokenId, key, value); + vm.expectRevert(IERC7496.TraitValueUnchanged.selector); + token.setTrait(tokenId, key, value); + } + + function testGetTraitValues() public { + bytes32 key1 = bytes32("testKeyOne"); + bytes32 key2 = bytes32("testKeyTwo"); + bytes32 value1 = bytes32("foo"); + bytes32 value2 = bytes32("bar"); + uint256 tokenId = 1; + token.mint(address(this), tokenId); + + token.setTrait(tokenId, key1, value1); + token.setTrait(tokenId, key2, value2); + + bytes32[] memory values = token.getTraitValues(tokenId, Solarray.bytes32s(key1, key2)); + assertEq(values[0], value1); + assertEq(values[1], value2); + } + + function testGetAndSetTraitMetadataURI() public { + string memory uri = "https://example.com/labels.json"; + + vm.expectEmit(true, true, true, true); + emit TraitMetadataURIUpdated(); + token.setTraitMetadataURI(uri); + + assertEq(token.getTraitMetadataURI(), uri); + + vm.prank(address(0x1234)); + vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(0x1234))); + token.setTraitMetadataURI(uri); + } + + function testGetAndSetTraitValue_NonexistantToken() public { + bytes32 key = bytes32("testKey"); + bytes32 value = bytes32(uint256(1)); + uint256 tokenId = 1; + + vm.expectRevert(abi.encodeWithSelector(IERC721Errors.ERC721NonexistentToken.selector, tokenId)); + token.setTrait(tokenId, key, value); + + vm.expectRevert(abi.encodeWithSelector(IERC721Errors.ERC721NonexistentToken.selector, tokenId)); + token.getTraitValue(tokenId, key); + + vm.expectRevert(abi.encodeWithSelector(IERC721Errors.ERC721NonexistentToken.selector, tokenId)); + token.getTraitValues(tokenId, Solarray.bytes32s(key)); + } + + function testGetTraitValue_DefaultZeroValue() public { + bytes32 key = bytes32("testKey"); + uint256 tokenId = 1; + token.mint(address(this), tokenId); + + bytes32 value = token.getTraitValue(tokenId, key); + assertEq(value, bytes32(0), "should return bytes32(0)"); + + bytes32[] memory values = token.getTraitValues(tokenId, Solarray.bytes32s(key)); + assertEq(values[0], bytes32(0), "should return bytes32(0)"); + } +} diff --git a/assets/erc-7498/ERC721ShipyardRedeemable.sol b/assets/erc-7498/ERC721ShipyardRedeemable.sol new file mode 100644 index 0000000000..96b4fd734a --- /dev/null +++ b/assets/erc-7498/ERC721ShipyardRedeemable.sol @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import {ERC721ConduitPreapproved_Solady} from "shipyard-core/src/tokens/erc721/ERC721ConduitPreapproved_Solady.sol"; +import {ERC721} from "solady/src/tokens/ERC721.sol"; +import {Ownable} from "solady/src/auth/Ownable.sol"; +import {ERC7498NFTRedeemables} from "./lib/ERC7498NFTRedeemables.sol"; +import {CampaignParams} from "./lib/RedeemablesStructs.sol"; + +contract ERC721ShipyardRedeemable is ERC721ConduitPreapproved_Solady, ERC7498NFTRedeemables, Ownable { + constructor() ERC721ConduitPreapproved_Solady() { + _initializeOwner(msg.sender); + } + + function name() public pure override returns (string memory) { + return "ERC721ShipyardRedeemable"; + } + + function symbol() public pure override returns (string memory) { + return "SY-RDM"; + } + + function tokenURI(uint256 /* tokenId */ ) public pure override returns (string memory) { + return "https://example.com/"; + } + + function createCampaign(CampaignParams calldata params, string calldata uri) + public + override + onlyOwner + returns (uint256 campaignId) + { + campaignId = ERC7498NFTRedeemables.createCampaign(params, uri); + } + + function _useInternalBurn() internal pure virtual override returns (bool) { + return true; + } + + function _internalBurn(uint256 id, uint256 /* amount */ ) internal virtual override { + _burn(id); + } + + function supportsInterface(bytes4 interfaceId) + public + view + virtual + override(ERC721, ERC7498NFTRedeemables) + returns (bool) + { + return ERC721.supportsInterface(interfaceId) || ERC7498NFTRedeemables.supportsInterface(interfaceId); + } +} diff --git a/assets/erc-7498/ERC721ShipyardRedeemable.t.sol b/assets/erc-7498/ERC721ShipyardRedeemable.t.sol new file mode 100644 index 0000000000..a589b983d7 --- /dev/null +++ b/assets/erc-7498/ERC721ShipyardRedeemable.t.sol @@ -0,0 +1,499 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import {Test} from "forge-std/Test.sol"; +import {Solarray} from "solarray/Solarray.sol"; +import {ERC721} from "solady/src/tokens/ERC721.sol"; +import {TestERC721} from "./utils/mocks/TestERC721.sol"; +import {OfferItem, ConsiderationItem} from "seaport-types/src/lib/ConsiderationStructs.sol"; +import {ItemType, OrderType, Side} from "seaport-sol/src/SeaportEnums.sol"; +import {CampaignParams, CampaignRequirements, TraitRedemption} from "../src/lib/RedeemablesStructs.sol"; +import {RedeemablesErrors} from "../src/lib/RedeemablesErrors.sol"; +import {ERC721RedemptionMintable} from "../src/extensions/ERC721RedemptionMintable.sol"; +import {ERC721ShipyardRedeemableOwnerMintable} from "../src/test/ERC721ShipyardRedeemableOwnerMintable.sol"; + +contract TestERC721ShipyardRedeemable is RedeemablesErrors, Test { + event Redemption( + uint256 indexed campaignId, + uint256 requirementsIndex, + bytes32 redemptionHash, + uint256[] considerationTokenIds, + uint256[] traitRedemptionTokenIds, + address redeemedBy + ); + + ERC721ShipyardRedeemableOwnerMintable redeemToken; + ERC721RedemptionMintable receiveToken; + address alice; + + address constant _BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; + + function setUp() public { + redeemToken = new ERC721ShipyardRedeemableOwnerMintable(); + receiveToken = new ERC721RedemptionMintable(address(redeemToken)); + alice = makeAddr("alice"); + + vm.label(address(redeemToken), "redeemToken"); + vm.label(address(receiveToken), "receiveToken"); + vm.label(alice, "alice"); + } + + function testBurnInternalToken() public { + uint256 tokenId = 2; + redeemToken.mint(address(this), tokenId); + + OfferItem[] memory offer = new OfferItem[](1); + offer[0] = OfferItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(receiveToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1 + }); + + ConsiderationItem[] memory consideration = new ConsiderationItem[](1); + consideration[0] = ConsiderationItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(redeemToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + CampaignRequirements[] memory requirements = new CampaignRequirements[]( + 1 + ); + requirements[0].offer = offer; + requirements[0].consideration = consideration; + + { + CampaignParams memory params = CampaignParams({ + requirements: requirements, + signer: address(0), + startTime: uint32(block.timestamp), + endTime: uint32(block.timestamp + 1000), + maxCampaignRedemptions: 5, + manager: address(this) + }); + + redeemToken.createCampaign(params, ""); + } + + { + OfferItem[] memory offerFromEvent = new OfferItem[](1); + offerFromEvent[0] = OfferItem({ + itemType: ItemType.ERC721, + token: address(receiveToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1 + }); + ConsiderationItem[] memory considerationFromEvent = new ConsiderationItem[](1); + considerationFromEvent[0] = ConsiderationItem({ + itemType: ItemType.ERC721, + token: address(redeemToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + assertGt(uint256(consideration[0].itemType), uint256(considerationFromEvent[0].itemType)); + + // campaignId: 1 + // requirementsIndex: 0 + // redemptionHash: bytes32(0) + bytes memory extraData = abi.encode(1, 0, bytes32(0)); + consideration[0].identifierOrCriteria = tokenId; + + uint256[] memory considerationTokenIds = Solarray.uint256s(tokenId); + uint256[] memory traitRedemptionTokenIds; + + vm.expectEmit(true, true, true, true); + emit Redemption(1, 0, bytes32(0), considerationTokenIds, traitRedemptionTokenIds, address(this)); + redeemToken.redeem(considerationTokenIds, address(this), extraData); + + vm.expectRevert(ERC721.TokenDoesNotExist.selector); + redeemToken.ownerOf(tokenId); + + assertEq(receiveToken.ownerOf(1), address(this)); + } + } + + function testRevert721ConsiderationItemInsufficientBalance() public { + uint256 tokenId = 2; + uint256 invalidTokenId = tokenId + 1; + redeemToken.mint(address(this), tokenId); + redeemToken.mint(alice, invalidTokenId); + + OfferItem[] memory offer = new OfferItem[](1); + offer[0] = OfferItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(receiveToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1 + }); + + ConsiderationItem[] memory consideration = new ConsiderationItem[](1); + consideration[0] = ConsiderationItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(redeemToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + CampaignRequirements[] memory requirements = new CampaignRequirements[]( + 1 + ); + requirements[0].offer = offer; + requirements[0].consideration = consideration; + + { + CampaignParams memory params = CampaignParams({ + requirements: requirements, + signer: address(0), + startTime: uint32(block.timestamp), + endTime: uint32(block.timestamp + 1000), + maxCampaignRedemptions: 5, + manager: address(this) + }); + + redeemToken.createCampaign(params, ""); + } + + { + OfferItem[] memory offerFromEvent = new OfferItem[](1); + offerFromEvent[0] = OfferItem({ + itemType: ItemType.ERC721, + token: address(receiveToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1 + }); + ConsiderationItem[] memory considerationFromEvent = new ConsiderationItem[](1); + considerationFromEvent[0] = ConsiderationItem({ + itemType: ItemType.ERC721, + token: address(redeemToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + assertGt(uint256(consideration[0].itemType), uint256(considerationFromEvent[0].itemType)); + + // campaignId: 1 + // requirementsIndex: 0 + // redemptionHash: bytes32(0) + bytes memory extraData = abi.encode(1, 0, bytes32(0)); + consideration[0].identifierOrCriteria = tokenId; + + uint256[] memory tokenIds = Solarray.uint256s(invalidTokenId); + + vm.expectRevert( + abi.encodeWithSelector( + ConsiderationItemInsufficientBalance.selector, + requirements[0].consideration[0].token, + 0, + requirements[0].consideration[0].startAmount + ) + ); + redeemToken.redeem(tokenIds, address(this), extraData); + + assertEq(redeemToken.ownerOf(tokenId), address(this)); + + vm.expectRevert(ERC721.TokenDoesNotExist.selector); + receiveToken.ownerOf(1); + } + } + + function testRevertConsiderationLengthNotMet() public { + ERC721ShipyardRedeemableOwnerMintable secondRedeemToken = new ERC721ShipyardRedeemableOwnerMintable(); + + uint256 tokenId = 2; + redeemToken.mint(address(this), tokenId); + + OfferItem[] memory offer = new OfferItem[](1); + offer[0] = OfferItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(receiveToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1 + }); + + ConsiderationItem[] memory consideration = new ConsiderationItem[](2); + consideration[0] = ConsiderationItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(redeemToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + consideration[1] = ConsiderationItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(secondRedeemToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + CampaignRequirements[] memory requirements = new CampaignRequirements[]( + 1 + ); + requirements[0].offer = offer; + requirements[0].consideration = consideration; + + { + CampaignParams memory params = CampaignParams({ + requirements: requirements, + signer: address(0), + startTime: uint32(block.timestamp), + endTime: uint32(block.timestamp + 1000), + maxCampaignRedemptions: 5, + manager: address(this) + }); + + redeemToken.createCampaign(params, ""); + } + + { + OfferItem[] memory offerFromEvent = new OfferItem[](1); + offerFromEvent[0] = OfferItem({ + itemType: ItemType.ERC721, + token: address(receiveToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1 + }); + ConsiderationItem[] memory considerationFromEvent = new ConsiderationItem[](1); + considerationFromEvent[0] = ConsiderationItem({ + itemType: ItemType.ERC721, + token: address(redeemToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + assertGt(uint256(consideration[0].itemType), uint256(considerationFromEvent[0].itemType)); + + // campaignId: 1 + // requirementsIndex: 0 + // redemptionHash: bytes32(0) + bytes memory extraData = abi.encode(1, 0, bytes32(0)); + consideration[0].identifierOrCriteria = tokenId; + + uint256[] memory tokenIds = Solarray.uint256s(tokenId); + + vm.expectRevert(abi.encodeWithSelector(TokenIdsDontMatchConsiderationLength.selector, 2, 1)); + + redeemToken.redeem(tokenIds, address(this), extraData); + + assertEq(redeemToken.ownerOf(tokenId), address(this)); + + vm.expectRevert(ERC721.TokenDoesNotExist.selector); + receiveToken.ownerOf(1); + } + } + + function testBurnWithSecondConsiderationItem() public { + ERC721ShipyardRedeemableOwnerMintable secondRedeemToken = new ERC721ShipyardRedeemableOwnerMintable(); + vm.label(address(secondRedeemToken), "secondRedeemToken"); + secondRedeemToken.setApprovalForAll(address(redeemToken), true); + + uint256 tokenId = 2; + redeemToken.mint(address(this), tokenId); + secondRedeemToken.mint(address(this), tokenId); + + OfferItem[] memory offer = new OfferItem[](1); + offer[0] = OfferItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(receiveToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1 + }); + + ConsiderationItem[] memory consideration = new ConsiderationItem[](2); + consideration[0] = ConsiderationItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(redeemToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + consideration[1] = ConsiderationItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(secondRedeemToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + CampaignRequirements[] memory requirements = new CampaignRequirements[]( + 1 + ); + requirements[0].offer = offer; + requirements[0].consideration = consideration; + + { + CampaignParams memory params = CampaignParams({ + requirements: requirements, + signer: address(0), + startTime: uint32(block.timestamp), + endTime: uint32(block.timestamp + 1000), + maxCampaignRedemptions: 5, + manager: address(this) + }); + + redeemToken.createCampaign(params, ""); + } + + { + OfferItem[] memory offerFromEvent = new OfferItem[](1); + offerFromEvent[0] = OfferItem({ + itemType: ItemType.ERC721, + token: address(receiveToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1 + }); + ConsiderationItem[] memory considerationFromEvent = new ConsiderationItem[](1); + considerationFromEvent[0] = ConsiderationItem({ + itemType: ItemType.ERC721, + token: address(redeemToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + assertGt(uint256(consideration[0].itemType), uint256(considerationFromEvent[0].itemType)); + + // campaignId: 1 + // requirementsIndex: 0 + // redemptionHash: bytes32(0) + bytes memory extraData = abi.encode(1, 0, bytes32(0)); + consideration[0].identifierOrCriteria = tokenId; + + uint256[] memory tokenIds = Solarray.uint256s(tokenId, tokenId); + + redeemToken.redeem(tokenIds, address(this), extraData); + + vm.expectRevert(ERC721.TokenDoesNotExist.selector); + redeemToken.ownerOf(tokenId); + + assertEq(secondRedeemToken.ownerOf(tokenId), _BURN_ADDRESS); + + assertEq(receiveToken.ownerOf(1), address(this)); + } + } + + function testBurnWithSecondRequirementsIndex() public { + ERC721ShipyardRedeemableOwnerMintable secondRedeemToken = new ERC721ShipyardRedeemableOwnerMintable(); + vm.label(address(secondRedeemToken), "secondRedeemToken"); + secondRedeemToken.setApprovalForAll(address(redeemToken), true); + + uint256 tokenId = 2; + redeemToken.mint(address(this), tokenId); + secondRedeemToken.mint(address(this), tokenId); + + OfferItem[] memory offer = new OfferItem[](1); + offer[0] = OfferItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(receiveToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1 + }); + + ConsiderationItem[] memory consideration = new ConsiderationItem[](1); + consideration[0] = ConsiderationItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(redeemToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + ConsiderationItem[] memory secondRequirementConsideration = new ConsiderationItem[](1); + secondRequirementConsideration[0] = ConsiderationItem({ + itemType: ItemType.ERC721_WITH_CRITERIA, + token: address(secondRedeemToken), + identifierOrCriteria: 0, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + CampaignRequirements[] memory requirements = new CampaignRequirements[]( + 2 + ); + requirements[0].offer = offer; + requirements[0].consideration = consideration; + + requirements[1].offer = offer; + requirements[1].consideration = secondRequirementConsideration; + + { + CampaignParams memory params = CampaignParams({ + requirements: requirements, + signer: address(0), + startTime: uint32(block.timestamp), + endTime: uint32(block.timestamp + 1000), + maxCampaignRedemptions: 5, + manager: address(this) + }); + + redeemToken.createCampaign(params, ""); + } + + { + OfferItem[] memory offerFromEvent = new OfferItem[](1); + offerFromEvent[0] = OfferItem({ + itemType: ItemType.ERC721, + token: address(receiveToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1 + }); + ConsiderationItem[] memory considerationFromEvent = new ConsiderationItem[](1); + considerationFromEvent[0] = ConsiderationItem({ + itemType: ItemType.ERC721, + token: address(redeemToken), + identifierOrCriteria: tokenId, + startAmount: 1, + endAmount: 1, + recipient: payable(_BURN_ADDRESS) + }); + + assertGt(uint256(consideration[0].itemType), uint256(considerationFromEvent[0].itemType)); + + // campaignId: 1 + // requirementsIndex: 0 + // redemptionHash: bytes32(0) + bytes memory extraData = abi.encode(1, 1, bytes32(0)); + consideration[0].identifierOrCriteria = tokenId; + + uint256[] memory tokenIds = Solarray.uint256s(tokenId); + + redeemToken.redeem(tokenIds, address(this), extraData); + + assertEq(redeemToken.ownerOf(tokenId), address(this)); + + assertEq(secondRedeemToken.ownerOf(tokenId), _BURN_ADDRESS); + + assertEq(receiveToken.ownerOf(1), address(this)); + } + } +} diff --git a/assets/erc-7498/ERC7498NFTRedeemables.sol b/assets/erc-7498/ERC7498NFTRedeemables.sol new file mode 100644 index 0000000000..fb854b3b19 --- /dev/null +++ b/assets/erc-7498/ERC7498NFTRedeemables.sol @@ -0,0 +1,394 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import {IERC20} from "openzeppelin-contracts/contracts/interfaces/IERC20.sol"; +import {IERC721} from "openzeppelin-contracts/contracts/interfaces/IERC721.sol"; +import {IERC1155} from "openzeppelin-contracts/contracts/interfaces/IERC1155.sol"; +import {OfferItem, ConsiderationItem, SpentItem} from "seaport-types/src/lib/ConsiderationStructs.sol"; +import {ItemType} from "seaport-types/src/lib/ConsiderationEnums.sol"; +import {DynamicTraits} from "shipyard-core/src/dynamic-traits/DynamicTraits.sol"; +import {IERC7498} from "./IERC7498.sol"; +import {IRedemptionMintable} from "./IRedemptionMintable.sol"; +import {RedeemablesErrors} from "./RedeemablesErrors.sol"; +import {CampaignParams, CampaignRequirements, TraitRedemption} from "./RedeemablesStructs.sol"; + +contract ERC7498NFTRedeemables is IERC7498, RedeemablesErrors { + /// @dev Counter for next campaign id. + uint256 private _nextCampaignId = 1; + + /// @dev The campaign parameters by campaign id. + mapping(uint256 campaignId => CampaignParams params) private _campaignParams; + + /// @dev The campaign URIs by campaign id. + mapping(uint256 campaignId => string campaignURI) private _campaignURIs; + + /// @dev The total current redemptions by campaign id. + mapping(uint256 campaignId => uint256 count) private _totalRedemptions; + + /// @dev The burn address. + address constant _BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; + + struct RedemptionParams { + uint256[] considerationTokenIds; + address recipient; + bytes extraData; + } + + function multiRedeem(RedemptionParams[] calldata params) external payable { + for (uint256 i; i < params.length;) { + redeem(params[i].considerationTokenIds, params[i].recipient, params[i].extraData); + unchecked { + ++i; + } + } + } + + function redeem(uint256[] calldata considerationTokenIds, address recipient, bytes calldata extraData) + public + payable + { + // Get the campaign id and requirementsIndex from extraData. + uint256 campaignId = uint256(bytes32(extraData[0:32])); + uint256 requirementsIndex = uint256(bytes32(extraData[32:64])); + + // Get the campaign params. + CampaignParams storage params = _campaignParams[campaignId]; + + // Validate the campaign time and total redemptions. + _validateRedemption(campaignId, params); + + // Increment totalRedemptions. + ++_totalRedemptions[campaignId]; + + // Get the campaign requirements. + if (requirementsIndex >= params.requirements.length) { + revert RequirementsIndexOutOfBounds(); + } + CampaignRequirements storage requirements = params.requirements[requirementsIndex]; + + // Process the redemption. + _processRedemption(campaignId, requirements, considerationTokenIds, recipient); + + // TODO: decode traitRedemptionTokenIds from extraData. + uint256[] memory traitRedemptionTokenIds; + + // Emit the Redemption event. + emit Redemption( + campaignId, requirementsIndex, bytes32(0), considerationTokenIds, traitRedemptionTokenIds, msg.sender + ); + } + + function getCampaign(uint256 campaignId) + external + view + override + returns (CampaignParams memory params, string memory uri, uint256 totalRedemptions) + { + // Revert if campaign id is invalid. + if (campaignId >= _nextCampaignId) revert InvalidCampaignId(); + + // Get the campaign params. + params = _campaignParams[campaignId]; + + // Get the campaign URI. + uri = _campaignURIs[campaignId]; + + // Get the total redemptions. + totalRedemptions = _totalRedemptions[campaignId]; + } + + function createCampaign(CampaignParams calldata params, string calldata uri) + public + virtual + returns (uint256 campaignId) + { + // Validate the campaign params, reverts if invalid. + _validateCampaignParams(params); + + // Set the campaignId and increment the next one. + campaignId = _nextCampaignId; + ++_nextCampaignId; + + // Set the campaign params. + _campaignParams[campaignId] = params; + + // Set the campaign URI. + _campaignURIs[campaignId] = uri; + + emit CampaignUpdated(campaignId, params, uri); + } + + function updateCampaign(uint256 campaignId, CampaignParams calldata params, string calldata uri) external { + // Revert if the campaign id is invalid. + if (campaignId == 0 || campaignId >= _nextCampaignId) { + revert InvalidCampaignId(); + } + + // Revert if msg.sender is not the manager. + address existingManager = _campaignParams[campaignId].manager; + if (params.manager != msg.sender && (existingManager != address(0) && existingManager != params.manager)) { + revert NotManager(); + } + + // Validate the campaign params and revert if invalid. + _validateCampaignParams(params); + + // Set the campaign params. + _campaignParams[campaignId] = params; + + // Update the campaign uri if it was provided. + if (bytes(uri).length != 0) { + _campaignURIs[campaignId] = uri; + } + + emit CampaignUpdated(campaignId, params, _campaignURIs[campaignId]); + } + + function _validateCampaignParams(CampaignParams memory params) internal pure { + // Revert if startTime is past endTime. + if (params.startTime > params.endTime) { + revert InvalidTime(); + } + + // Iterate over the requirements. + for (uint256 i = 0; i < params.requirements.length;) { + CampaignRequirements memory requirements = params.requirements[i]; + + // Validate each consideration item. + for (uint256 j = 0; j < requirements.consideration.length;) { + ConsiderationItem memory c = requirements.consideration[j]; + + // Revert if any of the consideration item recipients is the zero address. + // 0xdead address should be used instead. + // For internal burn, override _internalBurn and set _useInternalBurn to true. + if (c.recipient == address(0)) { + revert ConsiderationItemRecipientCannotBeZeroAddress(); + } + + if (c.startAmount == 0) { + revert ConsiderationItemAmountCannotBeZero(); + } + + // Revert if startAmount != endAmount, as this requires more complex logic. + if (c.startAmount != c.endAmount) { + revert NonMatchingConsiderationItemAmounts(i, c.startAmount, c.endAmount); + } + + unchecked { + ++j; + } + } + + unchecked { + ++i; + } + } + } + + function _validateRedemption(uint256 campaignId, CampaignParams memory params) internal view { + if (_isInactive(params.startTime, params.endTime)) { + revert NotActive_(block.timestamp, params.startTime, params.endTime); + } + + // Revert if max total redemptions would be exceeded. + if (_totalRedemptions[campaignId] + 1 > params.maxCampaignRedemptions) { + revert MaxCampaignRedemptionsReached(_totalRedemptions[campaignId] + 1, params.maxCampaignRedemptions); + } + } + + function _transferConsiderationItem(uint256 id, ConsiderationItem memory c) internal { + // If consideration item is this contract, recipient is burn address, and _useInternalBurn() fn returns true, + // call the internal burn function and return. + if (c.token == address(this) && c.recipient == payable(_BURN_ADDRESS) && _useInternalBurn()) { + _internalBurn(id, c.startAmount); + return; + } + + // Transfer the token to the consideration recipient. + if (c.itemType == ItemType.ERC721 || c.itemType == ItemType.ERC721_WITH_CRITERIA) { + // ERC721_WITH_CRITERIA with identifier 0 is wildcard: any id is valid. + // Criteria is not yet implemented, for that functionality use the contract offerer. + if (c.itemType == ItemType.ERC721 && id != c.identifierOrCriteria) { + revert InvalidConsiderationTokenIdSupplied(c.token, id, c.identifierOrCriteria); + } + IERC721(c.token).safeTransferFrom(msg.sender, c.recipient, id); + } else if ((c.itemType == ItemType.ERC1155 || c.itemType == ItemType.ERC1155_WITH_CRITERIA)) { + // ERC1155_WITH_CRITERIA with identifier 0 is wildcard: any id is valid. + // Criteria is not yet implemented, for that functionality use the contract offerer. + if (c.itemType == ItemType.ERC1155 && id != c.identifierOrCriteria) { + revert InvalidConsiderationTokenIdSupplied(c.token, id, c.identifierOrCriteria); + } + IERC1155(c.token).safeTransferFrom(msg.sender, c.recipient, id, c.startAmount, ""); + } else if (c.itemType == ItemType.ERC20) { + IERC20(c.token).transferFrom(msg.sender, c.recipient, c.startAmount); + } else { + // ItemType.NATIVE + (bool success,) = c.recipient.call{value: msg.value}(""); + if (!success) revert EtherTransferFailed(); + } + } + + /// @dev Override this function to return true if `_internalBurn` is used. + function _useInternalBurn() internal pure virtual returns (bool) { + return false; + } + + /// @dev Function that is called to burn amounts of a token internal to this inherited contract. + /// Override with token implementation calling internal burn. + function _internalBurn(uint256 id, uint256 amount) internal virtual { + // Override with your token implementation calling internal burn. + } + + function _isInactive(uint256 startTime, uint256 endTime) internal view returns (bool inactive) { + // Using the same check for time boundary from Seaport. + // startTime <= block.timestamp < endTime + assembly { + inactive := or(iszero(gt(endTime, timestamp())), gt(startTime, timestamp())) + } + } + + function _processRedemption( + uint256 campaignId, + CampaignRequirements memory requirements, + uint256[] memory tokenIds, + address recipient + ) internal { + // Get the campaign consideration. + ConsiderationItem[] memory consideration = requirements.consideration; + + // Revert if the tokenIds length does not match the consideration length. + if (consideration.length != tokenIds.length) { + revert TokenIdsDontMatchConsiderationLength(consideration.length, tokenIds.length); + } + + // Keep track of the total native value to validate. + uint256 totalNativeValue; + + // Iterate over the consideration items. + for (uint256 j; j < consideration.length;) { + // Get the consideration item. + ConsiderationItem memory c = consideration[j]; + + // Get the identifier. + uint256 id = tokenIds[j]; + + // Get the token balance. + uint256 balance; + if (c.itemType == ItemType.ERC721 || c.itemType == ItemType.ERC721_WITH_CRITERIA) { + balance = IERC721(c.token).ownerOf(id) == msg.sender ? 1 : 0; + } else if (c.itemType == ItemType.ERC1155 || c.itemType == ItemType.ERC1155_WITH_CRITERIA) { + balance = IERC1155(c.token).balanceOf(msg.sender, id); + } else if (c.itemType == ItemType.ERC20) { + balance = IERC20(c.token).balanceOf(msg.sender); + } else { + // ItemType.NATIVE + totalNativeValue += c.startAmount; + // Total native value is validated after the loop. + } + + // Ensure the balance is sufficient. + if (balance < c.startAmount) { + revert ConsiderationItemInsufficientBalance(c.token, balance, c.startAmount); + } + + // Transfer the consideration item. + _transferConsiderationItem(id, c); + + // Get the campaign offer. + OfferItem[] memory offer = requirements.offer; + + // Mint the new tokens. + for (uint256 k; k < offer.length;) { + IRedemptionMintable(offer[k].token).mintRedemption( + campaignId, recipient, requirements.consideration, requirements.traitRedemptions + ); + + unchecked { + ++k; + } + } + + unchecked { + ++j; + } + } + + // Validate the correct native value is sent with the transaction. + if (msg.value != totalNativeValue) { + revert InvalidTxValue(msg.value, totalNativeValue); + } + + // Process trait redemptions. + // TraitRedemption[] memory traitRedemptions = requirements.traitRedemptions; + // _setTraits(traitRedemptions); + } + + function _setTraits(TraitRedemption[] calldata traitRedemptions) internal { + /* + // Iterate over the trait redemptions and set traits on the tokens. + for (uint256 i; i < traitRedemptions.length;) { + // Get the trait redemption token address and place on the stack. + address token = traitRedemptions[i].token; + + uint256 identifier = traitRedemptions[i].identifier; + + // Declare a new block to manage stack depth. + { + // Get the substandard and place on the stack. + uint8 substandard = traitRedemptions[i].substandard; + + // Get the substandard value and place on the stack. + bytes32 substandardValue = traitRedemptions[i].substandardValue; + + // Get the trait key and place on the stack. + bytes32 traitKey = traitRedemptions[i].traitKey; + + bytes32 traitValue = traitRedemptions[i].traitValue; + + // Get the current trait value and place on the stack. + bytes32 currentTraitValue = getTraitValue(traitKey, identifier); + + // If substandard is 1, set trait to traitValue. + if (substandard == 1) { + // Revert if the current trait value does not match the substandard value. + if (currentTraitValue != substandardValue) { + revert InvalidRequiredValue(currentTraitValue, substandardValue); + } + + // Set the trait to the trait value. + _setTrait(traitRedemptions[i].traitKey, identifier, traitValue); + // If substandard is 2, increment trait by traitValue. + } else if (substandard == 2) { + // Revert if the current trait value is greater than the substandard value. + if (currentTraitValue > substandardValue) { + revert InvalidRequiredValue(currentTraitValue, substandardValue); + } + + // Increment the trait by the trait value. + uint256 newTraitValue = uint256(currentTraitValue) + uint256(traitValue); + + _setTrait(traitRedemptions[i].traitKey, identifier, bytes32(newTraitValue)); + } else if (substandard == 3) { + // Revert if the current trait value is less than the substandard value. + if (currentTraitValue < substandardValue) { + revert InvalidRequiredValue(currentTraitValue, substandardValue); + } + + uint256 newTraitValue = uint256(currentTraitValue) - uint256(traitValue); + + // Decrement the trait by the trait value. + _setTrait(traitRedemptions[i].traitKey, traitRedemptions[i].identifier, bytes32(newTraitValue)); + } + } + + unchecked { + ++i; + } + } + */ + } + + function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { + return interfaceId == type(IERC7498).interfaceId; + } +} diff --git a/assets/erc-7498/IERC7498.sol b/assets/erc-7498/IERC7498.sol new file mode 100644 index 0000000000..e8bfbe8565 --- /dev/null +++ b/assets/erc-7498/IERC7498.sol @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import {OfferItem, ConsiderationItem, SpentItem} from "seaport-types/src/lib/ConsiderationStructs.sol"; +import {CampaignParams, TraitRedemption} from "./RedeemablesStructs.sol"; + +interface IERC7498 { + event CampaignUpdated(uint256 indexed campaignId, CampaignParams params, string uri); + event Redemption( + uint256 indexed campaignId, + uint256 requirementsIndex, + bytes32 redemptionHash, + uint256[] considerationTokenIds, + uint256[] traitRedemptionTokenIds, + address redeemedBy + ); + + function createCampaign(CampaignParams calldata params, string calldata uri) + external + returns (uint256 campaignId); + + function updateCampaign(uint256 campaignId, CampaignParams calldata params, string calldata uri) external; + + function getCampaign(uint256 campaignId) + external + view + returns (CampaignParams memory params, string memory uri, uint256 totalRedemptions); + + function redeem(uint256[] calldata considerationTokenIds, address recipient, bytes calldata extraData) + external + payable; +} diff --git a/assets/erc-7498/IRedemptionMintable.sol b/assets/erc-7498/IRedemptionMintable.sol new file mode 100644 index 0000000000..f79bf5caae --- /dev/null +++ b/assets/erc-7498/IRedemptionMintable.sol @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import {ConsiderationItem} from "seaport-types/src/lib/ConsiderationStructs.sol"; +import {TraitRedemption} from "./RedeemablesStructs.sol"; + +interface IRedemptionMintable { + function mintRedemption( + uint256 campaignId, + address recipient, + ConsiderationItem[] calldata consideration, + TraitRedemption[] calldata traitRedemptions + ) external; +} diff --git a/assets/erc-7498/RedeemablesErrors.sol b/assets/erc-7498/RedeemablesErrors.sol new file mode 100644 index 0000000000..653db7486c --- /dev/null +++ b/assets/erc-7498/RedeemablesErrors.sol @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import {SpentItem} from "seaport-types/src/lib/ConsiderationStructs.sol"; +import {CampaignParams} from "./RedeemablesStructs.sol"; + +interface RedeemablesErrors { + /// Configuration errors + error NotManager(); + error InvalidTime(); + error ConsiderationItemRecipientCannotBeZeroAddress(); + error ConsiderationItemAmountCannotBeZero(); + error NonMatchingConsiderationItemAmounts(uint256 itemIndex, uint256 startAmount, uint256 endAmount); + + /// Redemption errors + error InvalidCampaignId(); + error CampaignAlreadyExists(); + error InvalidCaller(address caller); + error NotActive_(uint256 currentTimestamp, uint256 startTime, uint256 endTime); + error MaxRedemptionsReached(uint256 total, uint256 max); + error MaxCampaignRedemptionsReached(uint256 total, uint256 max); + error NativeTransferFailed(); + error InvalidOfferLength(uint256 got, uint256 want); + error InvalidNativeOfferItem(); + error InvalidOwner(); + error InvalidRequiredValue(bytes32 got, bytes32 want); + //error InvalidSubstandard(uint256 substandard); + error InvalidTraitRedemption(); + error InvalidTraitRedemptionToken(address token); + error ConsiderationRecipientNotFound(address token); + error RedemptionValuesAreImmutable(); + error RequirementsIndexOutOfBounds(); + error ConsiderationItemInsufficientBalance(address token, uint256 balance, uint256 amount); + error EtherTransferFailed(); + error InvalidTxValue(uint256 got, uint256 want); + error InvalidConsiderationTokenIdSupplied(address token, uint256 got, uint256 want); + error TokenIdsDontMatchConsiderationLength(uint256 considerationLength, uint256 tokenIdsLength); +} diff --git a/assets/erc-7498/RedeemablesStructs.sol b/assets/erc-7498/RedeemablesStructs.sol new file mode 100644 index 0000000000..4b43223c59 --- /dev/null +++ b/assets/erc-7498/RedeemablesStructs.sol @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: CC0-1.0 +pragma solidity ^0.8.19; + +import {OfferItem, ConsiderationItem, SpentItem} from "seaport-types/src/lib/ConsiderationStructs.sol"; + +struct CampaignParams { + uint32 startTime; + uint32 endTime; + uint32 maxCampaignRedemptions; + address manager; + address signer; + CampaignRequirements[] requirements; +} + +struct CampaignRequirements { + OfferItem[] offer; + ConsiderationItem[] consideration; + TraitRedemption[] traitRedemptions; +} + +struct TraitRedemption { + uint8 substandard; + address token; + uint256 identifier; + bytes32 traitKey; + bytes32 traitValue; + bytes32 substandardValue; +}