The Ethereum Improvement Proposal repository

Related tags

Cryptography EIPs
Overview

Ethereum Improvement Proposals (EIPs)

Gitter

Ethereum Improvement Proposals (EIPs) describe standards for the Ethereum platform, including core protocol specifications, client APIs, and contract standards. Browse all current and draft EIPs on the official EIP site.

Before you initiate a pull request, please read the EIP-1 process document.

Once your first PR is merged, we have a bot that helps out by automatically merging PRs to draft EIPs. For this to work, it has to be able to tell that you own the draft being edited. Make sure that the 'author' line of your EIP contains either your GitHub username or your email address inside <triangular brackets>. If you use your email address, that address must be the one publicly shown on your GitHub profile.

Project Goal

The Ethereum Improvement Proposals repository exists as a place to share concrete proposals with potential users of the proposal and the Ethereum community at large.

Preferred Citation Format

The canonical URL for a EIP that has achieved draft status at any point is at https://eips.ethereum.org/. For example, the canonical URL for EIP-1 is https://eips.ethereum.org/EIPS/eip-1.

Please consider anything which is not published on https://eips.ethereum.org/ as a working paper.

And please consider anything published at https://eips.ethereum.org/ with a status of "draft" as an incomplete draft.

Validation

EIPs must pass some validation tests. The EIP repository ensures this by running tests using html-proofer and eipv.

It is possible to run the EIP validator locally:

cargo install eipv
eipv <INPUT FILE / DIRECTORY>

Automerger

The EIP repository contains an "auto merge" feature to ease the workload for EIP editors. If a change is made via a PR to a draft EIP, then the authors of the EIP can GitHub approve the change to have it auto-merged. This is handled by the EIP-Bot.

Local development

Prerequisites

  1. Open Terminal.

  2. Check whether you have Ruby 2.1.0 or higher installed:

$ ruby --version
  1. If you don't have Ruby installed, install Ruby 2.1.0 or higher.

  2. Install Bundler:

$ gem install bundler
  1. Install dependencies:
$ bundle install

Build your local Jekyll site

  1. Bundle assets and start the server:
$ bundle exec jekyll serve
  1. Preview your local Jekyll site in your web browser at http://localhost:4000.

More information on Jekyll and GitHub pages here.

Comments
  • Discussion for EIP-2981: NFT Royalty Standard

    Discussion for EIP-2981: NFT Royalty Standard

    TL;DR - ERC721s have a ton of creators and a few marketplaces, but no accepted means for transferring royalties from items being sold multiple times on secondary sales. This EIP is proposing a standard method that can be implemented by all marketplaces easily.

    // SPDX-License-Identifier: MIT
    
    pragma solidity ^0.6.0;
    
    /**
     * @dev Interface of the ERC165 standard, as defined in the
     * https://eips.ethereum.org/EIPS/eip-165[EIP].
     *
     * Implementers can declare support of contract interfaces, which can then be
     * queried by others ({ERC165Checker}).
     *
     * For an implementation, see {ERC165}.
     */
    interface IERC721Royalties {
        
        
        /**
        @notice This event is emitted when royalties are received.
    
        @dev The marketplace would call royaltiesRecieved() function so that the NFT contracts emits this event.
    
        @param creator The original creator of the NFT entitled to the royalties
        @param buyer The person buying the NFT on a secondary sale
        @param amount The amount being paid to the creator
      */
        event RecievedRoyalties (address indexed creator, address indexed buyer, uint256 indexed amount);
        
        /**
         * @dev Returns true if this contract implements the interface defined by
         * `interfaceId`. See the corresponding
         * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
         * to learn more about how these ids are created.
         *
         * This function call must use less than 30 000 gas.
         */
        function supportsInterface(bytes4 interfaceId) external view returns (bool);
        
         /**
         * @dev Returns true if implemented
         * 
         * @dev this is how the marketplace can see if the contract has royalties, other than using the supportsInterface() call.
         */
        function hasRoyalties() external view returns (bool);
    
         /**
         * @dev Returns uint256 of the amount of percentage the royalty is set to. For example, if 1%, would return "1", if 50%, would return "50"
         * 
         * @dev Marketplaces would need to call this during the purchase function of their marketplace - and then implement the transfer of that amount on their end
         */
        function royaltyAmount() external view returns (uint256);
        
          /**
         * @dev Returns royalty amount as uint256 and address where royalties should go. 
         * 
         * @dev Marketplaces would need to call this during the purchase function of their marketplace - and then implement the transfer of that amount on their end
         */
        function royaltyInfo() external view returns (uint256, address);
        
          /**
         * @dev Called by the marketplace after the transfer of royalties has happened, so that the contract has a record 
         * @dev emits RecievedRoyalties event;
         * 
         * @param _creator The original creator of the NFT entitled to the royalties
         * @param _buyer The person buying the NFT on a secondary sale
         * @param _amount The amount being paid to the creator
         */
        function royaltiesRecieved(address _creator, address _buyer, uint256 _amount) external view;
    }
    

    Flow: (just suggestions, can be implemented however you like)

    Constructor/deployment

    Creator - the person who gets the royalties for secondary sales is set. Royalty Amount - the percentage amount that the creator gets on each sale, is set.

    NFT sold on marketplace

    Marketplace checks if the NFT being sold has royalties implemented - if so, call royaltyInfo() to get the amount and the creator's address.

    Calculates the amount needed to be transferred and then executes that transfer.

    Calls royaltiesRecieved() so that the NFT contract has a record of receiving the funds during a sale.


    Thoughts? Anything that should be added or removed to make it easier to be implemented?

    The logical code looks something like this:

    abstract contract Royalties {
        /*
         * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
         */
        uint256 private royalty_amount;
        address private creator;
     
        /**
        @notice This event is emitted when royalties are transfered.
    
        @dev The marketplace would emit this event from their contracts. Or they would call royaltiesRecieved() function.
    
        @param creator The original creator of the NFT entitled to the royalties
        @param buyer The person buying the NFT on a secondary sale
        @param amount The amount being paid to the creator
      */
     
      event RecievedRoyalties (address indexed creator, address indexed buyer, uint256 indexed amount);
        constructor (uint256 _amount, address _creator) internal {
            royalty_amount = _amount;
            creator = _creator;
        }
    
        
        function hasRoyalties() public pure returns (bool) {
            return true;
        }
    
    
        function royaltyAmount() public view returns (uint256) {
            return royalty_amount;
        }
        
        function royaltyInfo() external view returns (uint256, address){
            return (royalty_amount, creator);
        }
        
        function royaltiesRecieved(address _creator, address _buyer, uint256 _amount) external {
            emit RecievedRoyalties(_creator, _buyer, _amount);
        }
    }
    
    opened by VexyCats 662
  • ERC223 token standard

    ERC223 token standard


    ERC: 223 Title: Token standard Author: Dexaran, [email protected] Status: Draft Type: ERC Created: 5-03.2017 Reference implementation: https://github.com/Dexaran/ERC223-token-standard


    Abstract

    The following describes standard functions a token contract and contract working with specified token can implement to prevent accidentally sends of tokens to contracts and make token transactions behave like ether transactions.

    Motivation

    Here is a description of the ERC20 token standard problem that is solved by ERC223:

    ERC20 token standard is leading to money losses for end users. The main problem is lack of possibility to handle incoming ERC20 transactions, that were performed via transfer function of ERC20 token.

    If you send 100 ETH to a contract that is not intended to work with Ether, then it will reject a transaction and nothing bad will happen. If you will send 100 ERC20 tokens to a contract that is not intended to work with ERC20 tokens, then it will not reject tokens because it cant recognize an incoming transaction. As the result, your tokens will get stuck at the contracts balance.

    How much ERC20 tokens are currently lost (27 Dec, 2017):

    1. QTUM, $1,204,273 lost. watch on Etherscan

    2. EOS, $1,015,131 lost. watch on Etherscan

    3. GNT, $249,627 lost. watch on Etherscan

    4. STORJ, $217,477 lost. watch on Etherscan

    5. Tronix , $201,232 lost. watch on Etherscan

    6. DGD, $151,826 lost. watch on Etherscan

    7. OMG, $149,941 lost. watch on Etherscan

    NOTE: These are only 8 token contracts that I know. Each Ethereum contract is a potential token trap for ERC20 tokens, thus, there are much more losses than I showed at this example.

    Another disadvantages of ERC20 that ERC223 will solve:

    1. Lack of transfer handling possibility.
    2. Loss of tokens.
    3. Token-transactions should match Ethereum ideology of uniformity. When a user wants to transfer tokens, he should always call transfer. It doesn't matter if the user is depositing to a contract or sending to an externally owned account.

    Those will allow contracts to handle incoming token transactions and prevent accidentally sent tokens from being accepted by contracts (and stuck at contract's balance).

    For example decentralized exchange will no more need to require users to call approve then call deposit (which is internally calling transferFrom to withdraw approved tokens). Token transaction will automatically be handled at the exchange contract.

    The most important here is a call of tokenReceived when performing a transaction to a contract.

    Specification

    Token Contracts that works with tokens

    Methods

    NOTE: An important point is that contract developers must implement tokenReceived if they want their contracts to work with the specified tokens.

    If the receiver does not implement the tokenReceived function, consider the contract is not designed to work with tokens, then the transaction must fail and no tokens will be transferred. An analogy with an Ether transaction that is failing when trying to send Ether to a contract that did not implement function() payable.

    totalSupply

    function totalSupply() constant returns (uint256 totalSupply)
    

    Get the total token supply

    name

    function name() constant returns (string _name)
    

    Get the name of token

    symbol

    function symbol() constant returns (bytes32 _symbol)
    

    Get the symbol of token

    decimals

    function decimals() constant returns (uint8 _decimals)
    

    Get decimals of token

    standard

    function standard() constant returns (string _standard)
    

    Get the standard of token contract. For some services it is important to know how to treat this particular token. If token supports ERC223 standard then it must explicitly tell that it does.

    This function MUST return "erc223" for this token standard. If no "standard()" function is implemented in the contract then the contract must be considered to be ERC20.

    balanceOf

    function balanceOf(address _owner) constant returns (uint256 balance)
    

    Get the account balance of another account with address _owner

    transfer(address, uint)

    function transfer(address _to, uint _value) returns (bool)
    

    Needed due to backwards compatibility reasons because of ERC20 transfer function doesn't have bytes parameter. This function must transfer tokens and invoke the function tokenReceived(address, uint256, bytes calldata) in _to, if _to is a contract. If the tokenReceived function is not implemented in _to (receiver contract), then the transaction must fail and the transfer of tokens should be reverted.

    transfer(address, uint, bytes)

    function transfer(address _to, uint _value, bytes calldata _data) returns (bool)
    

    function that is always called when someone wants to transfer tokens. This function must transfer tokens and invoke the function tokenReceived (address, uint256, bytes) in _to, if _to is a contract. If the tokenReceived function is not implemented in _to (receiver contract), then the transaction must fail and the transfer of tokens should not occur. If _to is an externally owned address, then the transaction must be sent without trying to execute tokenReceived in _to. _data can be attached to this token transaction and it will stay in blockchain forever (requires more gas). _data can be empty.

    NOTE: The recommended way to check whether the _to is a contract or an address is to assemble the code of _to. If there is no code in _to, then this is an externally owned address, otherwise it's a contract.

    Events

    Transfer

    event Transfer(address indexed _from, address indexed _to, uint256 _value)
    

    Triggered when tokens are transferred. Compatible with ERC20 Transfer event.

    TransferData

    event TransferData(bytes _data)
    

    Triggered when tokens are transferred and logs transaction metadata. This is implemented as a separate event to keep Transfer(address, address, uint256) ERC20-compatible.

    Contract to work with tokens

    function tokenReceived(address _from, uint _value, bytes calldata _data)
    

    A function for handling token transfers, which is called from the token contract, when a token holder sends tokens. _from is the address of the sender of the token,_value is the amount of incoming tokens, and _data is attached data similar tomsg.data of Ether transactions. It works by analogy with the fallback function of Ether transactions and returns nothing.

    NOTE: since solidity version 0.6.0+ there is a new reveive() function to handle plain Ether transfers - therefore the function tokenFallback was renamed to tokenReceived to keep the token behavior more intuitive and compatible with Ether behavior.

    NOTE: msg.sender will be a token-contract inside the tokenReceived function. It may be important to filter which tokens are sent (by token-contract address). The token sender (the person who initiated the token transaction) will be _from inside thetokenReceived function.

    IMPORTANT: This function must be named tokenReceived and take parametersaddress, uint256,bytes to match the function signature 0xc0ee0b8a.

    Recommended implementation

    This is highly recommended implementation of ERC 223 token: https://github.com/Dexaran/ERC223-token-standard/tree/development/token/ERC223

    opened by Dexaran 651
  • ERC: Multi Token Standard

    ERC: Multi Token Standard

    ---
    eip: 1155
    title: ERC-1155 Multi Token Standard
    author: Witek Radomski <[email protected]>, Andrew Cooke <[email protected]>, Philippe Castonguay <[email protected]>, James Therien <[email protected]>, Eric Binet <[email protected]>, Ronan Sandford <[email protected]>
    type: Standards Track
    category: ERC
    status: Final
    created: 2018-06-17
    discussions-to: https://github.com/ethereum/EIPs/issues/1155
    requires: 165
    ---
    

    Simple Summary

    A standard interface for contracts that manage multiple token types. A single deployed contract may include any combination of fungible tokens, non-fungible tokens or other configurations (e.g. semi-fungible tokens).

    Abstract

    This standard outlines a smart contract interface that can represent any number of fungible and non-fungible token types. Existing standards such as ERC-20 require deployment of separate contracts per token type. The ERC-721 standard's token ID is a single non-fungible index and the group of these non-fungibles is deployed as a single contract with settings for the entire collection. In contrast, the ERC-1155 Multi Token Standard allows for each token ID to represent a new configurable token type, which may have its own metadata, supply and other attributes.

    The _id argument contained in each function's argument set indicates a specific token or token type in a transaction.

    Motivation

    Tokens standards like ERC-20 and ERC-721 require a separate contract to be deployed for each token type or collection. This places a lot of redundant bytecode on the Ethereum blockchain and limits certain functionality by the nature of separating each token contract into its own permissioned address. With the rise of blockchain games and platforms like Enjin Coin, game developers may be creating thousands of token types, and a new type of token standard is needed to support them. However, ERC-1155 is not specific to games and many other applications can benefit from this flexibility.

    New functionality is possible with this design such as transferring multiple token types at once, saving on transaction costs. Trading (escrow / atomic swaps) of multiple tokens can be built on top of this standard and it removes the need to "approve" individual token contracts separately. It is also easy to describe and mix multiple fungible or non-fungible token types in a single contract.

    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.

    Smart contracts implementing the ERC-1155 standard MUST implement all of the functions in the ERC1155 interface.

    Smart contracts implementing the ERC-1155 standard MUST implement the ERC-165 supportsInterface function and MUST return the constant value true if 0xd9b67a26 is passed through the interfaceID argument.

    pragma solidity ^0.5.9;
    
    /**
        @title ERC-1155 Multi Token Standard
        @dev See https://eips.ethereum.org/EIPS/eip-1155
        Note: The ERC-165 identifier for this interface is 0xd9b67a26.
     */
    interface ERC1155 /* is ERC165 */ {
        /**
            @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
            The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
            The `_from` argument MUST be the address of the holder whose balance is decreased.
            The `_to` argument MUST be the address of the recipient whose balance is increased.
            The `_id` argument MUST be the token type being transferred.
            The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
            When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
            When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).        
        */
        event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
    
        /**
            @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).      
            The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
            The `_from` argument MUST be the address of the holder whose balance is decreased.
            The `_to` argument MUST be the address of the recipient whose balance is increased.
            The `_ids` argument MUST be the list of tokens being transferred.
            The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
            When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
            When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).                
        */
        event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
    
        /**
            @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absence of an event assumes disabled).        
        */
        event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
    
        /**
            @dev MUST emit when the URI is updated for a token ID.
            URIs are defined in RFC 3986.
            The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
        */
        event URI(string _value, uint256 indexed _id);
    
        /**
            @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
            @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
            MUST revert if `_to` is the zero address.
            MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
            MUST revert on any other error.
            MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
            After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).        
            @param _from    Source address
            @param _to      Target address
            @param _id      ID of the token type
            @param _value   Transfer amount
            @param _data    Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
        */
        function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
    
        /**
            @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
            @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
            MUST revert if `_to` is the zero address.
            MUST revert if length of `_ids` is not the same as length of `_values`.
            MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
            MUST revert on any other error.        
            MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
            Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
            After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).                      
            @param _from    Source address
            @param _to      Target address
            @param _ids     IDs of each token type (order and length must match _values array)
            @param _values  Transfer amounts per token type (order and length must match _ids array)
            @param _data    Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
        */
        function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;
    
        /**
            @notice Get the balance of an account's tokens.
            @param _owner  The address of the token holder
            @param _id     ID of the token
            @return        The _owner's balance of the token type requested
         */
        function balanceOf(address _owner, uint256 _id) external view returns (uint256);
    
        /**
            @notice Get the balance of multiple account/token pairs
            @param _owners The addresses of the token holders
            @param _ids    ID of the tokens
            @return        The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair)
         */
        function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
    
        /**
            @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
            @dev MUST emit the ApprovalForAll event on success.
            @param _operator  Address to add to the set of authorized operators
            @param _approved  True if the operator is approved, false to revoke approval
        */
        function setApprovalForAll(address _operator, bool _approved) external;
    
        /**
            @notice Queries the approval status of an operator for a given owner.
            @param _owner     The owner of the tokens
            @param _operator  Address of authorized operator
            @return           True if the operator is approved, false if not
        */
        function isApprovedForAll(address _owner, address _operator) external view returns (bool);
    }
    

    ERC-1155 Token Receiver

    Smart contracts MUST implement all of the functions in the ERC1155TokenReceiver interface to accept transfers. See "Safe Transfer Rules" for further detail.

    Smart contracts MUST implement the ERC-165 supportsInterface function and signify support for the ERC1155TokenReceiver interface to accept transfers. See "ERC1155TokenReceiver ERC-165 rules" for further detail.

    pragma solidity ^0.5.9;
    
    /**
        Note: The ERC-165 identifier for this interface is 0x4e2312e0.
    */
    interface ERC1155TokenReceiver {
        /**
            @notice Handle the receipt of a single ERC1155 token type.
            @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.        
            This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
            This function MUST revert if it rejects the transfer.
            Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
            @param _operator  The address which initiated the transfer (i.e. msg.sender)
            @param _from      The address which previously owned the token
            @param _id        The ID of the token being transferred
            @param _value     The amount of tokens being transferred
            @param _data      Additional data with no specified format
            @return           `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
        */
        function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4);
    
        /**
            @notice Handle the receipt of multiple ERC1155 token types.
            @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.        
            This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
            This function MUST revert if it rejects the transfer(s).
            Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
            @param _operator  The address which initiated the batch transfer (i.e. msg.sender)
            @param _from      The address which previously owned the token
            @param _ids       An array containing ids of each token being transferred (order and length must match _values array)
            @param _values    An array containing amounts of each token being transferred (order and length must match _ids array)
            @param _data      Additional data with no specified format
            @return           `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
        */
        function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4);       
    }
    

    Safe Transfer Rules

    To be more explicit about how the standard safeTransferFrom and safeBatchTransferFrom functions MUST operate with respect to the ERC1155TokenReceiver hook functions, a list of scenarios and rules follows.

    Scenarios

    Scenario#1 : The recipient is not a contract.

    • onERC1155Received and onERC1155BatchReceived MUST NOT be called on an EOA (Externally Owned Account).

    Scenario#2 : The transaction is not a mint/transfer of a token.

    • onERC1155Received and onERC1155BatchReceived MUST NOT be called outside of a mint or transfer process.

    Scenario#3 : The receiver does not implement the necessary ERC1155TokenReceiver interface function(s).

    • The transfer MUST be reverted with the one caveat below.
      • If the token(s) being sent are part of a hybrid implementation of another standard, that particular standard's rules on sending to a contract MAY now be followed instead. See "Compatibility with other standards" section.

    Scenario#4 : The receiver implements the necessary ERC1155TokenReceiver interface function(s) but returns an unknown value.

    • The transfer MUST be reverted.

    Scenario#5 : The receiver implements the necessary ERC1155TokenReceiver interface function(s) but throws an error.

    • The transfer MUST be reverted.

    Scenario#6 : The receiver implements the ERC1155TokenReceiver interface and is the recipient of one and only one balance change (e.g. safeTransferFrom called).

    • The balances for the transfer MUST have been updated before the ERC1155TokenReceiver hook is called on a recipient contract.
    • The transfer event MUST have been emitted to reflect the balance changes before the ERC1155TokenReceiver hook is called on the recipient contract.
    • One of onERC1155Received or onERC1155BatchReceived MUST be called on the recipient contract.
    • The onERC1155Received hook SHOULD be called on the recipient contract and its rules followed.
      • See "onERC1155Received rules" for further rules that MUST be followed.
    • The onERC1155BatchReceived hook MAY be called on the recipient contract and its rules followed.
      • See "onERC1155BatchReceived rules" for further rules that MUST be followed.

    Scenario#7 : The receiver implements the ERC1155TokenReceiver interface and is the recipient of more than one balance change (e.g. safeBatchTransferFrom called).

    • All balance transfers that are referenced in a call to an ERC1155TokenReceiver hook MUST be updated before the ERC1155TokenReceiver hook is called on the recipient contract.
    • All transfer events MUST have been emitted to reflect current balance changes before an ERC1155TokenReceiver hook is called on the recipient contract.
    • onERC1155Received or onERC1155BatchReceived MUST be called on the recipient as many times as necessary such that every balance change for the recipient in the scenario is accounted for.
      • The return magic value for every hook call MUST be checked and acted upon as per "onERC1155Received rules" and "onERC1155BatchReceived rules".
    • The onERC1155BatchReceived hook SHOULD be called on the recipient contract and its rules followed.
      • See "onERC1155BatchReceived rules" for further rules that MUST be followed.
    • The onERC1155Received hook MAY be called on the recipient contract and its rules followed.
      • See "onERC1155Received rules" for further rules that MUST be followed.

    Scenario#8 : You are the creator of a contract that implements the ERC1155TokenReceiver interface and you forward the token(s) onto another address in one or both of onERC1155Received and onERC1155BatchReceived.

    • Forwarding should be considered acceptance and then initiating a new safeTransferFrom or safeBatchTransferFrom in a new context.
      • The prescribed keccak256 acceptance value magic for the receiver hook being called MUST be returned after forwarding is successful.
    • The _data argument MAY be re-purposed for the new context.
    • If forwarding fails the transaction MAY be reverted.
      • If the contract logic wishes to keep the ownership of the token(s) itself in this case it MAY do so.

    Scenario#9 : You are transferring tokens via a non-standard API call i.e. an implementation specific API and NOT safeTransferFrom or safeBatchTransferFrom.

    • In this scenario all balance updates and events output rules are the same as if a standard transfer function had been called.
      • i.e. an external viewer MUST still be able to query the balance via a standard function and it MUST be identical to the balance as determined by TransferSingle and TransferBatch events alone.
    • If the receiver is a contract the ERC1155TokenReceiver hooks still need to be called on it and the return values respected the same as if a standard transfer function had been called.
      • However while the safeTransferFrom or safeBatchTransferFrom functions MUST revert if a receiving contract does not implement the ERC1155TokenReceiver interface, a non-standard function MAY proceed with the transfer.
      • See "Implementation specific transfer API rules".

    Rules

    safeTransferFrom rules:

    • Caller must be approved to manage the tokens being transferred out of the _from account (see "Approval" section).
    • MUST revert if _to is the zero address.
    • MUST revert if balance of holder for token _id is lower than the _value sent to the recipient.
    • MUST revert on any other error.
    • MUST emit the TransferSingle event to reflect the balance change (see "TransferSingle and TransferBatch event rules" section).
    • After the above conditions are met, this function MUST check if _to is a smart contract (e.g. code size > 0). If so, it MUST call onERC1155Received on _to and act appropriately (see "onERC1155Received rules" section).
      • The _data argument provided by the sender for the transfer MUST be passed with its contents unaltered to the onERC1155Received hook function via its _data argument.

    safeBatchTransferFrom rules:

    • Caller must be approved to manage all the tokens being transferred out of the _from account (see "Approval" section).
    • MUST revert if _to is the zero address.
    • MUST revert if length of _ids is not the same as length of _values.
    • MUST revert if any of the balance(s) of the holder(s) for token(s) in _ids is lower than the respective amount(s) in _values sent to the recipient.
    • MUST revert on any other error.
    • MUST emit TransferSingle or TransferBatch event(s) such that all the balance changes are reflected (see "TransferSingle and TransferBatch event rules" section).
    • The balance changes and events MUST occur in the array order they were submitted (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
    • After the above conditions are met, this function MUST check if _to is a smart contract (e.g. code size > 0). If so, it MUST call onERC1155Received or onERC1155BatchReceived on _to and act appropriately (see "onERC1155Received and onERC1155BatchReceived rules" section).
      • The _data argument provided by the sender for the transfer MUST be passed with its contents unaltered to the ERC1155TokenReceiver hook function(s) via their _data argument.

    TransferSingle and TransferBatch event rules:

    • TransferSingle SHOULD be used to indicate a single balance transfer has occurred between a _from and _to pair.
      • It MAY be emitted multiple times to indicate multiple balance changes in the transaction, but note that TransferBatch is designed for this to reduce gas consumption.
      • The _operator argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
      • The _from argument MUST be the address of the holder whose balance is decreased.
      • The _to argument MUST be the address of the recipient whose balance is increased.
      • The _id argument MUST be the token type being transferred.
      • The _value argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
      • When minting/creating tokens, the _from argument MUST be set to 0x0 (i.e. zero address). See "Minting/creating and burning/destroying rules".
      • When burning/destroying tokens, the _to argument MUST be set to 0x0 (i.e. zero address). See "Minting/creating and burning/destroying rules".
    • TransferBatch SHOULD be used to indicate multiple balance transfers have occurred between a _from and _to pair.
      • It MAY be emitted with a single element in the list to indicate a singular balance change in the transaction, but note that TransferSingle is designed for this to reduce gas consumption.
      • The _operator argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
      • The _from argument MUST be the address of the holder whose balance is decreased for each entry pair in _ids and _values.
      • The _to argument MUST be the address of the recipient whose balance is increased for each entry pair in _ids and _values.
      • The _ids array argument MUST contain the ids of the tokens being transferred.
      • The _values array argument MUST contain the number of token to be transferred for each corresponding entry in _ids.
      • _ids and _values MUST have the same length.
      • When minting/creating tokens, the _from argument MUST be set to 0x0 (i.e. zero address). See "Minting/creating and burning/destroying rules".
      • When burning/destroying tokens, the _to argument MUST be set to 0x0 (i.e. zero address). See "Minting/creating and burning/destroying rules".
    • The total value transferred from address 0x0 minus the total value transferred to 0x0 observed via the TransferSingle and TransferBatch events MAY be used by clients and exchanges to determine the "circulating supply" for a given token ID.
    • To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from 0x0 to 0x0, with the token creator as _operator, and a _value of 0.
    • All TransferSingle and TransferBatch events MUST be emitted to reflect all the balance changes that have occurred before any call(s) to onERC1155Received or onERC1155BatchReceived.
      • To make sure event order is correct in the case of valid re-entry (e.g. if a receiver contract forwards tokens on receipt) state balance and events balance MUST match before calling an external contract.

    onERC1155Received rules:

    • The _operator argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
    • The _from argument MUST be the address of the holder whose balance is decreased.
      • _from MUST be 0x0 for a mint.
    • The _id argument MUST be the token type being transferred.
    • The _value argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
    • The _data argument MUST contain the information provided by the sender for the transfer with its contents unaltered.
      • i.e. it MUST pass on the unaltered _data argument sent via the safeTransferFrom or safeBatchTransferFrom call for this transfer.
    • The recipient contract MAY accept an increase of its balance by returning the acceptance magic value bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
      • If the return value is bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) the transfer MUST be completed or MUST revert if any other conditions are not met for success.
    • The recipient contract MAY reject an increase of its balance by calling revert.
      • If the recipient contract throws/reverts the transaction MUST be reverted.
    • If the return value is anything other than bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) the transaction MUST be reverted.
    • onERC1155Received (and/or onERC1155BatchReceived) MAY be called multiple times in a single transaction and the following requirements must be met:
      • All callbacks represent mutually exclusive balance changes.
      • The set of all calls to onERC1155Received and onERC1155BatchReceived describes all balance changes that occurred during the transaction in the order submitted.
    • A contract MAY skip calling the onERC1155Received hook function if the transfer operation is transferring the token to itself.

    onERC1155BatchReceived rules:

    • The _operator argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
    • The _from argument MUST be the address of the holder whose balance is decreased.
      • _from MUST be 0x0 for a mint.
    • The _ids argument MUST be the list of tokens being transferred.
    • The _values argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
    • The _data argument MUST contain the information provided by the sender for the transfer with its contents unaltered.
      • i.e. it MUST pass on the unaltered _data argument sent via the safeBatchTransferFrom call for this transfer.
    • The recipient contract MAY accept an increase of its balance by returning the acceptance magic value bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
      • If the return value is bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) the transfer MUST be completed or MUST revert if any other conditions are not met for success.
    • The recipient contract MAY reject an increase of its balance by calling revert.
      • If the recipient contract throws/reverts the transaction MUST be reverted.
    • If the return value is anything other than bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) the transaction MUST be reverted.
    • onERC1155BatchReceived (and/or onERC1155Received) MAY be called multiple times in a single transaction and the following requirements must be met:
      • All callbacks represent mutually exclusive balance changes.
      • The set of all calls to onERC1155Received and onERC1155BatchReceived describes all balance changes that occurred during the transaction in the order submitted.
    • A contract MAY skip calling the onERC1155BatchReceived hook function if the transfer operation is transferring the token(s) to itself.

    ERC1155TokenReceiver ERC-165 rules:

    • The implementation of the ERC-165 supportsInterface function SHOULD be as follows:
      function supportsInterface(bytes4 interfaceID) external view returns (bool) {
          return  interfaceID == 0x01ffc9a7 ||    // ERC-165 support (i.e. `bytes4(keccak256('supportsInterface(bytes4)'))`).
                  interfaceID == 0x4e2312e0;      // ERC-1155 `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`).
      }
      
    • The implementation MAY differ from the above but:
      • It MUST return the constant value true if 0x01ffc9a7 is passed through the interfaceID argument. This signifies ERC-165 support.
      • It MUST return the constant value true if 0x4e2312e0 is passed through the interfaceID argument. This signifies ERC-1155 ERC1155TokenReceiver support.
      • It MUST NOT consume more than 10,000 gas.
        • This keeps it below the ERC-165 requirement of 30,000 gas, reduces the gas reserve needs and minimises possible side-effects of gas exhaustion during the call.

    Implementation specific transfer API rules:

    • If an implementation specific API function is used to transfer ERC-1155 token(s) to a contract, the safeTransferFrom or safeBatchTransferFrom (as appropriate) rules MUST still be followed if the receiver implements the ERC1155TokenReceiver interface. If it does not the non-standard implementation SHOULD revert but MAY proceed.
    • An example:
      1. An approved user calls a function such as function myTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values);.
      2. myTransferFrom updates the balances for _from and _to addresses for all _ids and _values.
      3. myTransferFrom emits TransferBatch with the details of what was transferred from address _from to address _to.
      4. myTransferFrom checks if _to is a contract address and determines that it is so (if not, then the transfer can be considered successful).
      5. myTransferFrom calls onERC1155BatchReceived on _to and it reverts or returns an unknown value (if it had returned bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) the transfer can be considered successful).
      6. At this point myTransferFrom SHOULD revert the transaction immediately as receipt of the token(s) was not explicitly accepted by the onERC1155BatchReceived function.
      7. If however myTransferFrom wishes to continue it MUST call supportsInterface(0x4e2312e0) on _to and if it returns the constant value true the transaction MUST be reverted, as it is now known to be a valid receiver and the previous acceptance step failed.
        • NOTE: You could have called supportsInterface(0x4e2312e0) at a previous step if you wanted to gather and act upon that information earlier, such as in a hybrid standards scenario.
      8. If the above call to supportsInterface(0x4e2312e0) on _to reverts or returns a value other than the constant value true the myTransferFrom function MAY consider this transfer successful.
        • NOTE: this MAY result in unrecoverable tokens if sent to an address that does not expect to receive ERC-1155 tokens.
    • The above example is not exhaustive but illustrates the major points (and shows that most are shared with safeTransferFrom and safeBatchTransferFrom):
      • Balances that are updated MUST have equivalent transfer events emitted.
      • A receiver address has to be checked if it is a contract and if so relevant ERC1155TokenReceiver hook function(s) have to be called on it.
      • Balances (and events associated) that are referenced in a call to an ERC1155TokenReceiver hook MUST be updated (and emitted) before the ERC1155TokenReceiver hook is called.
      • The return values of the ERC1155TokenReceiver hook functions that are called MUST be respected if they are implemented.
      • Only non-standard transfer functions MAY allow tokens to be sent to a recipient contract that does NOT implement the necessary ERC1155TokenReceiver hook functions. safeTransferFrom and safeBatchTransferFrom MUST revert in that case (unless it is a hybrid standards implementation see "Compatibility with other standards").

    Minting/creating and burning/destroying rules:

    • A mint/create operation is essentially a specialized transfer and MUST follow these rules:
      • To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from 0x0 to 0x0, with the token creator as _operator, and a _value of 0.
      • The "TransferSingle and TransferBatch event rules" MUST be followed as appropriate for the mint(s) (i.e. singles or batches) however the _from argument MUST be set to 0x0 (i.e. zero address) to flag the transfer as a mint to contract observers.
        • NOTE: This includes tokens that are given an initial balance in the contract. The balance of the contract MUST also be able to be determined by events alone meaning initial contract balances (for eg. in construction) MUST emit events to reflect those balances too.
    • A burn/destroy operation is essentially a specialized transfer and MUST follow these rules:
      • The "TransferSingle and TransferBatch event rules" MUST be followed as appropriate for the burn(s) (i.e. singles or batches) however the _to argument MUST be set to 0x0 (i.e. zero address) to flag the transfer as a burn to contract observers.
      • When burning/destroying you do not have to actually transfer to 0x0 (that is impl specific), only the _to argument in the event MUST be set to 0x0 as above.
    • The total value transferred from address 0x0 minus the total value transferred to 0x0 observed via the TransferSingle and TransferBatch events MAY be used by clients and exchanges to determine the "circulating supply" for a given token ID.
    • As mentioned above mint/create and burn/destroy operations are specialized transfers and so will likely be accomplished with custom transfer functions rather than safeTransferFrom or safeBatchTransferFrom. If so the "Implementation specific transfer API rules" section would be appropriate.
      • Even in a non-safe API and/or hybrid standards case the above event rules MUST still be adhered to when minting/creating or burning/destroying.
    • A contract MAY skip calling the ERC1155TokenReceiver hook function(s) if the mint operation is transferring the token(s) to itself. In all other cases the ERC1155TokenReceiver rules MUST be followed as appropriate for the implementation (i.e. safe, custom and/or hybrid).
    A solidity example of the keccak256 generated constants for the various magic values (these MAY be used by implementation):
    bytes4 constant public ERC1155_ERC165 = 0xd9b67a26; // ERC-165 identifier for the main token standard.
    bytes4 constant public ERC1155_ERC165_TOKENRECEIVER = 0x4e2312e0; // ERC-165 identifier for the `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`).
    bytes4 constant public ERC1155_ACCEPTED = 0xf23a6e61; // Return value from `onERC1155Received` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`).
    bytes4 constant public ERC1155_BATCH_ACCEPTED = 0xbc197c81; // Return value from `onERC1155BatchReceived` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`).
    

    Compatibility with other standards

    There have been requirements during the design discussions to have this standard be compatible with existing standards when sending to contract addresses, specifically ERC-721 at time of writing. To cater for this scenario, there is some leeway with the revert logic should a contract not implement the ERC1155TokenReceiver as per "Safe Transfer Rules" section above, specifically "Scenario#3 : The receiver does not implement the necessary ERC1155TokenReceiver interface function(s)".

    Hence in a hybrid ERC-1155 contract implementation an extra call MUST be made on the recipient contract and checked before any hook calls to onERC1155Received or onERC1155BatchReceived are made. Order of operation MUST therefore be:

    1. The implementation MUST call the function supportsInterface(0x4e2312e0) on the recipient contract, providing at least 10,000 gas.
    2. If the function call succeeds and the return value is the constant value true the implementation proceeds as a regular ERC-1155 implementation, with the call(s) to the onERC1155Received or onERC1155BatchReceived hooks and rules associated.
    3. If the function call fails or the return value is NOT the constant value true the implementation can assume the recipient contract is not an ERC1155TokenReceiver and follow its other standard's rules for transfers.

    Note that a pure implementation of a single standard is recommended rather than a hybrid solution, but an example of a hybrid ERC-1155/ERC-721 contract is linked in the references section under implementations.

    An important consideration is that even if the tokens are sent with another standard's rules the ERC-1155 transfer events MUST still be emitted. This is so the balances can still be determined via events alone as per ERC-1155 standard rules.

    Metadata

    The URI value allows for ID substitution by clients. If the string {id} exists in any URI, clients MUST replace this with the actual token ID in hexadecimal form. This allows for a large number of tokens to use the same on-chain string by defining a URI once, for that large number of tokens.

    • The string format of the substituted hexadecimal ID MUST be lowercase alphanumeric: [0-9a-f] with no 0x prefix.
    • The string format of the substituted hexadecimal ID MUST be leading zero padded to 64 hex characters length if necessary.

    Example of such a URI: https://token-cdn-domain/{id}.json would be replaced with https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json if the client is referring to token ID 314592/0x4CCE0.

    Metadata Extensions

    The optional ERC1155Metadata_URI extension can be identified with the (ERC-165 Standard Interface Detection)[https://eips.ethereum.org/EIPS/eip-165].

    If the optional ERC1155Metadata_URI extension is included:

    • The ERC-165 supportsInterface function MUST return the constant value true if 0x0e89341c is passed through the interfaceID argument.
    • Changes to the URI MUST emit the URI event if the change can be expressed with an event (i.e. it isn't dynamic/programmatic).
      • An implementation MAY emit the URI event during a mint operation but it is NOT mandatory. An observer MAY fetch the metadata uri at mint time from the uri function if it was not emitted.
    • The uri function SHOULD be used to retrieve values if no event was emitted.
    • The uri function MUST return the same value as the latest event for an _id if it was emitted.
    • The uri function MUST NOT be used to check for the existence of a token as it is possible for an implementation to return a valid string even if the token does not exist.
    pragma solidity ^0.5.9;
    
    /**
        Note: The ERC-165 identifier for this interface is 0x0e89341c.
    */
    interface ERC1155Metadata_URI {
        /**
            @notice A distinct Uniform Resource Identifier (URI) for a given token.
            @dev URIs are defined in RFC 3986.
            The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".        
            @return URI string
        */
        function uri(uint256 _id) external view returns (string memory);
    }
    

    ERC-1155 Metadata URI JSON Schema

    This JSON schema is loosely based on the "ERC721 Metadata JSON Schema", but includes optional formatting to allow for ID substitution by clients. If the string {id} exists in any JSON value, it MUST be replaced with the actual token ID, by all client software that follows this standard.

    • The string format of the substituted hexadecimal ID MUST be lowercase alphanumeric: [0-9a-f] with no 0x prefix.
    • The string format of the substituted hexadecimal ID MUST be leading zero padded to 64 hex characters length if necessary.
    {
        "title": "Token Metadata",
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "description": "Identifies the asset to which this token represents",
            },
            "decimals": {
                "type": "integer",
                "description": "The number of decimal places that the token amount should display - e.g. 18, means to divide the token amount by 1000000000000000000 to get its user representation.",
            },
            "description": {
                "type": "string",
                "description": "Describes the asset to which this token represents",
            },
            "image": {
                "type": "string",
                "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.",
            },
            "properties": {
                "type": "object",
                "description": "Arbitrary properties. Values may be strings, numbers, object or arrays.",
            },
        }
    }
    

    An example of an ERC-1155 Metadata JSON file follows. The properties array proposes some SUGGESTED formatting for token-specific display properties and metadata.

    {
    	"name": "Asset Name",
    	"description": "Lorem ipsum...",
    	"image": "https:\/\/s3.amazonaws.com\/your-bucket\/images\/{id}.png",
    	"properties": {
    		"simple_property": "example value",
    		"rich_property": {
    			"name": "Name",
    			"value": "123",
    			"display_value": "123 Example Value",
    			"class": "emphasis",
    			"css": {
    				"color": "#ffffff",
    				"font-weight": "bold",
    				"text-decoration": "underline"
    			}
    		},
    		"array_property": {
    			"name": "Name",
    			"value": [1,2,3,4],
    			"class": "emphasis"
    		}
    	}
    }
    
    Localization

    Metadata localization should be standardized to increase presentation uniformity across all languages. As such, a simple overlay method is proposed to enable localization. If the metadata JSON file contains a localization attribute, its content MAY be used to provide localized values for fields that need it. The localization attribute should be a sub-object with three attributes: uri, default and locales. If the string {locale} exists in any URI, it MUST be replaced with the chosen locale by all client software.

    JSON Schema
    {
        "title": "Token Metadata",
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "description": "Identifies the asset to which this token represents",
            },
            "decimals": {
                "type": "integer",
                "description": "The number of decimal places that the token amount should display - e.g. 18, means to divide the token amount by 1000000000000000000 to get its user representation.",
            },
            "description": {
                "type": "string",
                "description": "Describes the asset to which this token represents",
            },
            "image": {
                "type": "string",
                "description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.",
            },
            "properties": {
                "type": "object",
                "description": "Arbitrary properties. Values may be strings, numbers, object or arrays.",
            },
            "localization": {
                "type": "object",
                "required": ["uri", "default", "locales"],
                "properties": {
                    "uri": {
                        "type": "string",
                        "description": "The URI pattern to fetch localized data from. This URI should contain the substring `{locale}` which will be replaced with the appropriate locale value before sending the request."
                    },
                    "default": {
                        "type": "string",
                        "description": "The locale of the default data within the base JSON"
                    },
                    "locales": {
                        "type": "array",
                        "description": "The list of locales for which data is available. These locales should conform to those defined in the Unicode Common Locale Data Repository (http://cldr.unicode.org/)."
                    }
                }
            },
        }
    }
    
    Localized Sample

    Base URI:

    {
      "name": "Advertising Space",
      "description": "Each token represents a unique Ad space in the city.",
      "localization": {
        "uri": "ipfs://QmWS1VAdMD353A6SDk9wNyvkT14kyCiZrNDYAad4w1tKqT/{locale}.json",
        "default": "en",
        "locales": ["en", "es", "fr"]
      }
    }
    

    es.json:

    {
      "name": "Espacio Publicitario",
      "description": "Cada token representa un espacio publicitario único en la ciudad."
    }
    

    fr.json:

    {
      "name": "Espace Publicitaire",
      "description": "Chaque jeton représente un espace publicitaire unique dans la ville."
    }
    

    Approval

    The function setApprovalForAll allows an operator to manage one's entire set of tokens on behalf of the approver. To permit approval of a subset of token IDs, an interface such as ERC-1761 Scoped Approval Interface is suggested. The counterpart isApprovedForAll provides introspection into any status set by setApprovalForAll.

    An owner SHOULD be assumed to always be able to operate on their own tokens regardless of approval status, so should SHOULD NOT have to call setApprovalForAll to approve themselves as an operator before they can operate on them.

    Rationale

    Metadata Choices

    The symbol function (found in the ERC-20 and ERC-721 standards) was not included as we do not believe this is a globally useful piece of data to identify a generic virtual item / asset and are also prone to collisions. Short-hand symbols are used in tickers and currency trading, but they aren't as useful outside of that space.

    The name function (for human-readable asset names, on-chain) was removed from the standard to allow the Metadata JSON to be the definitive asset name and reduce duplication of data. This also allows localization for names, which would otherwise be prohibitively expensive if each language string was stored on-chain, not to mention bloating the standard interface. While this decision may add a small burden on implementers to host a JSON file containing metadata, we believe any serious implementation of ERC-1155 will already utilize JSON Metadata.

    Upgrades

    The requirement to emit TransferSingle or TransferBatch on balance change implies that a valid implementation of ERC-1155 redeploying to a new contract address MUST emit events from the new contract address to replicate the deprecated contract final state. It is valid to only emit a minimal number of events to reflect only the final balance and omit all the transactions that led to that state. The event emit requirement is to ensure that the current state of the contract can always be traced only through events. To alleviate the need to emit events when changing contract address, consider using the proxy pattern, such as described in ERC-1538. This will also have the added benefit of providing a stable contract address for users.

    Design decision: Supporting non-batch

    The standard supports safeTransferFrom and onERC1155Received functions because they are significantly cheaper for single token-type transfers, which is arguably a common use case.

    Design decision: Safe transfers only

    The standard only supports safe-style transfers, making it possible for receiver contracts to depend on onERC1155Received or onERC1155BatchReceived function to be always called at the end of a transfer.

    Guaranteed log trace

    As the Ethereum ecosystem continues to grow, many dapps are relying on traditional databases and explorer API services to retrieve and categorize data. The ERC-1155 standard guarantees that event logs emitted by the smart contract will provide enough data to create an accurate record of all current token balances. A database or explorer may listen to events and be able to provide indexed and categorized searches of every ERC-1155 token in the contract.

    Approval

    The function setApprovalForAll allows an operator to manage one's entire set of tokens on behalf of the approver. It enables frictionless interaction with exchange and trade contracts.

    Restricting approval to a certain set of token IDs, quantities or other rules MAY be done with an additional interface or an external contract. The rationale is to keep the ERC-1155 standard as generic as possible for all use-cases without imposing a specific approval scheme on implementations that may not need it. Standard token approval interfaces can be used, such as the suggested ERC-1761 Scoped Approval Interface which is compatible with ERC-1155.

    Usage

    This standard can be used to represent multiple token types for an entire domain. Both fungible and non-fungible tokens can be stored in the same smart-contract.

    Batch Transfers

    The safeBatchTransferFrom function allows for batch transfers of multiple token IDs and values. The design of ERC-1155 makes batch transfers possible without the need for a wrapper contract, as with existing token standards. This reduces gas costs when more than one token type is included in a batch transfer, as compared to single transfers with multiple transactions.

    Another advantage of standardized batch transfers is the ability for a smart contract to respond to the batch transfer in a single operation using onERC1155BatchReceived.

    It is RECOMMENDED that clients and wallets sort the token IDs and associated values (in ascending order) when posting a batch transfer, as some ERC-1155 implementations offer significant gas cost savings when IDs are sorted. See Horizon Games - Multi-Token Standard "packed balance" implementation for an example of this.

    Batch Balance

    The balanceOfBatch function allows clients to retrieve balances of multiple owners and token IDs with a single call.

    Enumerating from events

    In order to keep storage requirements light for contracts implementing ERC-1155, enumeration (discovering the IDs and values of tokens) must be done using event logs. It is RECOMMENDED that clients such as exchanges and blockchain explorers maintain a local database containing the token ID, Supply, and URI at the minimum. This can be built from each TransferSingle, TransferBatch, and URI event, starting from the block the smart contract was deployed until the latest block.

    ERC-1155 contracts must therefore carefully emit TransferSingle or TransferBatch events in any instance where tokens are created, minted, transferred or destroyed.

    Non-Fungible Tokens

    The following strategies are examples of how you MAY mix fungible and non-fungible tokens together in the same contract. The standard does NOT mandate how an implementation must do this.

    Split ID bits

    The top 128 bits of the uint256 _id parameter in any ERC-1155 function MAY represent the base token ID, while the bottom 128 bits MAY represent the index of the non-fungible to make it unique.

    Non-fungible tokens can be interacted with using an index based accessor into the contract/token data set. Therefore to access a particular token set within a mixed data contract and a particular non-fungible within that set, _id could be passed as <uint128: base token id><uint128: index of non-fungible>.

    To identify a non-fungible set/category as a whole (or a fungible) you COULD just pass in the base id via the _id argument as <uint128: base token id><uint128: zero>. If your implementation uses this technique this naturally means the index of a non-fungible SHOULD be 1-based.

    Inside the contract code the two pieces of data needed to access the individual non-fungible can be extracted with uint128(~0) and the same mask shifted by 128.

    uint256 baseTokenNFT = 12345 << 128;
    uint128 indexNFT = 50;
    
    uint256 baseTokenFT = 54321 << 128;
    
    balanceOf(baseTokenNFT, msg.sender); // Get balance of the base token for non-fungible set 12345 (this MAY be used to get balance of the user for all of this token set if the implementation wishes as a convenience).
    balanceOf(baseTokenNFT + indexNFT, msg.sender); // Get balance of the token at index 50 for non-fungible set 12345 (should be 1 if user owns the individual non-fungible token or 0 if they do not).
    balanceOf(baseTokenFT, msg.sender); // Get balance of the fungible base token 54321.
    

    Note that 128 is an arbitrary number, an implementation MAY choose how they would like this split to occur as suitable for their use case. An observer of the contract would simply see events showing balance transfers and mints happening and MAY track the balances using that information alone. For an observer to be able to determine type (non-fungible or fungible) from an ID alone they would have to know the split ID bits format on a implementation by implementation basis.

    The ERC-1155 Reference Implementation is an example of the split ID bits strategy.

    Natural Non-Fungible tokens

    Another simple way to represent non-fungibles is to allow a maximum value of 1 for each non-fungible token. This would naturally mirror the real world, where unique items have a quantity of 1 and fungible items have a quantity greater than 1.

    References

    Standards

    Implementations

    Articles & Discussions

    Copyright

    Copyright and related rights waived via CC0.

    opened by coinfork 470
  • ERC: Non-fungible Token Standard

    ERC: Non-fungible Token Standard

    This proposal has been accepted and merged as a draft standard, please see the officially tracked version for the current draft.

    Please see PR #841 for the discussions leading up to this draft, and use this thread (#721) for further discussion. (Or, if you have a concrete proposal, consider opening a new PR with your proposed changes.)

    Original Draft (Sep 20, 2017)

    Preamble

    EIP: <to be assigned>
    Title: Non-fungible Token Standard
    Author: Dieter Shirley <[email protected]>
    Type: Standard
    Category: ERC
    Status: Draft
    Created: 2017-09-20
    

    Simple Summary

    A standard interface for non-fungible tokens.

    Abstract

    The following standard allows for the implementation of a standard API for non-fungible tokens (henceforth referred to as "NFTs") within smart contracts. This standard provides basic functionality to track and transfer ownership of NFTs.

    Motivation

    A standard interface allows any NFTs on Ethereum to be handled by general-purpose applications. In particular, it will allow for NFTs to be tracked in standardized wallets and traded on exchanges.

    Specification

    I wanted to get the community's "first impression" before spending a bunch of time detailing out these end-points; expect this section to be significantly expanded after the first round of feedback. I've left out "obvious" return values for skimmability, and included a few notes where the functionality warrants special interest.

    • ERC-20 compatibility:
      • name() optional
      • symbol() optional
      • totalSupply() - Number of NFTs tracked by this contract
      • balanceOf(address _owner) - Number of NFTs owned by a particular address
    • Basic ownership:
      • tokensOfOwnerByIndex(address _owner, uint _index) constant returns (uint tokenId) - There's really no good way to return a list of NFTs by owner, but it's valuable functionality. You should strenuously avoid calling this method "on-chain" (i.e. from a non-constant contract function).
      • ownerOf(uint _tokenId) constant returns (address owner)
      • transfer(address _to, uint _tokenId)
      • approve(address _to, uint _tokenId) – SHOULD be cleared by any transfer() operation
      • transferFrom(address _from, address _to, unit _tokenId) - the sender must have been previously authorized by approve(). (Note: Technically, the _from address here can be inferred by calling ownerOf(_tokenId). I've left it in for symmetry with the corresponding ERC-20 method, and to forestall the (somewhat subtle) bug that could result from not clearing the approve authorization inside a successful transfer call.)
    • NFT metadata (optional):
      • tokenMetadata(uint _tokenId) returns (string infoUrl) - recommended format is IPFS or HTTP multiaddress with name, image, and description sub-paths. IPFS is the preferred mechanism (immutable and more durable). Example: If tokenMetadata() returns /ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG, the object description would be accessible via ipfs cat /ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG/description.

    Rationale

    There are many proposed uses of Ethereum smart contracts that depend on tracking individual, non-fungible tokens (NFTs). Examples of existing or planned NFTs are LAND in Decentraland, the eponymous punks in CryptoPunks, and in-game items using systems like Dmarket or EnjinCoin. Future uses include tracking real-world non-fungible assets, like real-estate (as envisioned by companies like Ubitquity or Propy). It is critical in each of these cases that these items are not "lumped together" as numbers in a ledger, but instead each token must have its ownership individually and atomically tracked. Regardless of the nature of these items, the ecosystem will be stronger if we create a standardized interface that allows for cross-functional non-fungible token management and sales platforms.

    The basis of this standard is that every NFT is identified by a unique, 256-bit unsigned integer within its tracking contract. The pair (contract address, asset ID) will then be globally unique within the Ethereum ecosystem.

    This standard has followed the model of ERC-20 as much as possible to minimize the effort required for wallets (in particular) to track non-fungible tokens, while echoing a well-understood standard.

    Backwards Compatibility

    This standard follows the semantics of ERC-20 as closely as possible, but can't be entirely compatible with it due to the fundamental differences between fungible and non-fungible tokens.

    Example non-fungible implementations as of September, 2017:

    • CryptoPunks - Partially ERC-20 compatible, but not easily generalizable because it includes auction functionality directly in the contract and uses function names that explicitly refer to the NFTs as "punks".
    • Auctionhouse Asset Interface - @dob needed a generic interface for his Auctionhouse dapp (currently ice-boxed). His "Asset" contract is very simple, but is missing ERC-20 compatiblity, approve() functionality, and metadata. This effort is referenced in the discussion for EIP-173.

    (It should be noted that "limited edition, collectable tokens" like Curio Cards and Rare Pepe are not non-fungible tokens. They're actually a collection of individual fungible tokens, each of which is tracked by its own smart contract with its own total supply (which may be 1 in extreme cases).)

    Implementation

    Reference implementation forthcoming...

    Copyright

    Copyright and related rights waived via CC0.

    Second Draft (Nov 9, 2017)

    Preamble

    EIP: <to be assigned>
    Title: Non-fungible Token Standard
    Author: Dieter Shirley <[email protected]>
    Type: Standard
    Category: ERC
    Status: Draft
    Created: 2017-09-20
    

    Simple Summary

    A standard interface for non-fungible tokens.

    Abstract

    This standard allows for the implementation of a standard API for non-fungible tokens (henceforth referred to as "NFTs") within smart contracts. This standard provides basic functionality to track and transfer ownership of NFTs.

    Motivation

    A standard interface allows any NFTs on Ethereum to be handled by general-purpose applications. In particular, it will allow for NFTs to be tracked in standardized wallets and traded on exchanges.

    Specification

    ERC-20 Compatibility

    name

    function name() constant returns (string name)
    

    OPTIONAL - It is recommend that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.

    Returns the name of the collection of NFTs managed by this contract. - e.g. "My Non-Fungibles".

    symbol

    function symbol() constant returns (string symbol)
    

    OPTIONAL - It is recommend that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.

    Returns a short string symbol referencing the entire collection of NFTs managed in this contract. e.g. "MNFT". This symbol SHOULD be short (3-8 characters is recommended), with no whitespace characters or new-lines and SHOULD be limited to the uppercase latin alphabet (i.e. the 26 letters used in English).

    totalSupply

    function totalSupply() constant returns (uint256 totalSupply)
    

    Returns the total number of NFTs currently tracked by this contract.

    balanceOf

    function balanceOf(address _owner) constant returns (uint256 balance)
    

    Returns the number of NFTs assigned to address _owner.

    Basic Ownership

    ownerOf

    function ownerOf(uint256 _tokenId) constant returns (address owner)
    

    Returns the address currently marked as the owner of _tokenID. This method MUST throw if _tokenID does not represent an NFT currently tracked by this contract. This method MUST NOT return 0 (NFTs assigned to the zero address are considered destroyed, and queries about them should throw).

    approve

    function approve(address _to, uint256 _tokenId)
    

    Grants approval for address _to to take possession of the NFT with ID _tokenId. This method MUST throw if msg.sender != ownerOf(_tokenId), or if _tokenID does not represent an NFT currently tracked by this contract, or if msg.sender == _to.

    Only one address can "have approval" at any given time; calling approveTransfer with a new address revokes approval for the previous address. Calling this method with 0 as the _to argument clears approval for any address.

    Successful completion of this method MUST emit an Approval event (defined below) unless the caller is attempting to clear approval when there is no pending approval. In particular, an Approval event MUST be fired if the _to address is zero and there is some outstanding approval. Additionally, an Approval event MUST be fired if _to is already the currently approved address and this call otherwise has no effect. (i.e. An approve() call that "reaffirms" an existing approval MUST fire an event.)

    Action | Prior State | _to address | New State | Event -- | -- | -- | -- | -- Clear unset approval | Clear | 0 | Clear | None Set new approval | Clear | X | Set to X | Approval(owner, X, tokenID) Change approval | Set to X | Y | Set to Y | Approval(owner, Y, tokenID) Reaffirm approval | Set to X | X | Set to X | Approval(owner, X, tokenID) Clear approval | Set to X | 0 | Clear | Approval(owner, 0, tokenID)

    Note: ANY change of ownership of an NFT – whether directly through the transfer and transferFrom methods defined in this interface, or through any other mechanism defined in the conforming contract – MUST clear any and all approvals for the transferred NFT. The implicit clearing of approval via ownership transfer MUST also fire the event Approval(0, _tokenId) if there was an outstanding approval. (i.e. All actions that transfer ownership must emit the same Approval event, if any, as would emitted by calling approve(0, _tokenID).)

    takeOwnership

    function takeOwnership(uint256 _tokenId)
    

    Assigns the ownership of the NFT with ID _tokenId to msg.sender if and only if msg.sender currently has approval (via a previous call to approveTransfer). A successful transfer MUST fire the Transfer event (defined below).

    This method MUST transfer ownership to msg.sender or throw, no other outcomes can be possible. Reasons for failure include (but are not limited to):

    • msg.sender does not have approval for _tokenId
    • _tokenID does not represent an NFT currently tracked by this contract
    • msg.sender already has ownership of _tokenId

    Important: Please refer to the Note in the approveTransfer method description; a successful transfer MUST clear pending approval.

    transfer

    function transfer(address _to, uint256 _tokenId)
    

    Assigns the ownership of the NFT with ID _tokenId to _to if and only if msg.sender == ownerOf(_tokenId). A successful transfer MUST fire the Transfer event (defined below).

    This method MUST transfer ownership to _to or throw, no other outcomes can be possible. Reasons for failure include (but are not limited to):

    • msg.sender is not the owner of _tokenId
    • _tokenID does not represent an NFT currently tracked by this contract
    • _to is 0 (Conforming contracts MAY have other methods to destroy or burn NFTs, which are conceptually "transfers to 0" and will emit Transfer events reflecting this. However, transfer(0, tokenID) MUST be treated as an error.)

    A conforming contract MUST allow the current owner to "transfer" a token to themselves, as a way of affirming ownership in the event stream. (i.e. it is valid for _to == ownerOf(_tokenID).) This "no-op transfer" MUST be considered a successful transfer, and therefore MUST fire a Transfer event (with the same address for _from and _to).

    Important: Please refer to the Note in the approveTransfer method description; a successful transfer MUST clear pending approval. This includes no-op transfers to the current owner!

    tokenOfOwnerByIndex

    function tokenOfOwnerByIndex(address _owner, uint256 _index) constant returns (uint tokenId)
    

    OPTIONAL - It is recommend that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.

    Returns the nth NFT assigned to the address _owner, with n specified by the _index argument. This method MUST throw if _index >= balanceOf(_owner).

    Recommended usage is as follows:

    uint256 ownerBalance = nonFungibleContract.balanceOf(owner);
    
    uint256[] memory ownerTokens = new uint256[](ownerBalance);
    
    for (uint256 i = 0; i < ownerBalance; i++) {
        ownerTokens[i] = nonFungibleContract.tokenOfOwnerByIndex(owner, i);
    }
    

    Implementations MUST NOT assume that NFTs are accessed in any particular order by their callers (In particular, don't assume this method is called in a monotonically ascending loop.), and MUST ensure that calls to tokenOfOwnerByIndex are fully idempotent unless and until some non-constant function is called on this contract.

    Callers of tokenOfOwnerByIndex MUST never assume that the order of NFTs is maintained outside of a single operation, or through the invocation (direct or indirect) of any non-constant contract method.

    NOTE: Current limitations in Solidity mean that there is no efficient way to return a complete list of an address's NFTs with a single function call. Callers should not assume this method is implemented efficiently (from a gas standpoint) and should strenuously avoid calling this method "on-chain" (i.e. from any non-constant contract function, or from any constant contract function that is likely to be called on-chain).

    NFT Metadata

    tokenMetadata

    function tokenMetadata(uint256 _tokenId) constant returns (string infoUrl)
    

    OPTIONAL - It is recommend that this method is implemented for enhanced usability with wallets and exchanges, but interfaces and other contracts MUST NOT depend on the existence of this method.

    Returns a multiaddress string referencing an external resource bundle that contains (optionally localized) metadata about the NFT associated with _tokenId. The string MUST be an IPFS or HTTP(S) base path (without a trailing slash) to which specific subpaths are obtained through concatenation. (IPFS is the preferred format due to better scalability, persistence, and immutability.)

    Standard sub-paths:

    • name (required) - The name sub-path MUST contain the UTF-8 encoded name of the specific NFT (i.e. distinct from the name of the collection, as returned by the contract's name method). A name SHOULD be 50 characters or less, and unique amongst all NFTs tracked by this contract. A name MAY contain white space characters, but MUST NOT include new-line or carriage-return characters. A name MAY include a numeric component to differentiate from similar NFTs in the same contract. For example: "Happy Token #157".
    • image (optional) - If the image sub-path exists, it MUST contain a PNG, JPEG, or SVG image with at least 300 pixels of detail in each dimension. The image aspect ratio SHOULD be between 16:9 (landscape mode) and 2:3 (portrait mode). The image SHOULD be structured with a "safe zone" such that cropping the image to a maximal, central square doesn't remove any critical information. (The easiest way to meet this requirement is simply to use a 1:1 image aspect ratio.)
    • description (optional) - If the description sub-path exists, it MUST contain a UTF-8 encoded textual description of the asset. This description MAY contain multiple lines and SHOULD use a single new-line character to delimit explicit line-breaks, and two new-line characters to delimit paragraphs. The description MAY include CommonMark-compatible Markdown annotations for styling. The description SHOULD be 1500 characters or less.
    • other metadata (optional) - A contract MAY choose to include any number of additional subpaths, where they are deemed useful. There may be future formal and informal standards for additional metadata fields independent of this standard.

    Each metadata subpath (including subpaths not defined in this standard) MUST contain a sub-path default leading to a file containing the default (i.e. unlocalized) version of the data for that metadata element. For example, an NFT with the metadata path /ipfs/QmZU8bKEG8fhcQwKoLHfjtJoKBzvUT5LFR3f8dEz86WdVe MUST contain the NFT's name as a UTF-8 encoded string available at the full path /ipfs/QmZU8bKEG8fhcQwKoLHfjtJoKBzvUT5LFR3f8dEz86WdVe/name/default. Additionally, each metadata subpath MAY have one or more localizations at a subpath of an ISO 639-1 language code (the same language codes used for HTML). For example, /ipfs/QmZU8bKEG8fhcQwKoLHfjtJoKBzvUT5LFR3f8dEz86WdVe/name/en would have the name in English, and /ipfs/QmZU8bKEG8fhcQwKoLHfjtJoKBzvUT5LFR3f8dEz86WdVe/name/fr would have the name in French (note that even localized values need to have a default entry). Consumers of NFT metadata SHOULD look for a localized value before falling back to the default value. Consumers MUST NOT assume that all metadata subpaths for a particular NFT are localized similarly. For example, it will be common for the name and image objects to not be localized even when the description is.

    You can explore the metadata package referenced in this example here.

    Events

    Transfer

    This event MUST trigger when NFT ownership is transferred via any mechanism.

    Additionally, the creation of new NFTs MUST trigger a Transfer event for each newly created NFTs, with a _from address of 0 and a _to address matching the owner of the new NFT (possibly the smart contract itself). The deletion (or burn) of any NFT MUST trigger a Transfer event with a _to address of 0 and a _from address of the owner of the NFT (now former owner!).

    NOTE: A Transfer event with _from == _to is valid. See the transfer() documentation for details.

    event Transfer(address indexed _from, address indexed _to, uint256 _tokenId)
    

    Approval

    This event MUST trigger on any successful call to approve(address _spender, uint256 _value) (unless the caller is attempting to clear approval when there is no pending approval).

    See the documentation for the approve() method above for further detail.

    event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId)
    

    Rationale

    Utility

    There are many proposed uses of Ethereum smart contracts that depend on tracking individual, non-fungible tokens (NFTs). Examples of existing or planned NFTs are LAND in Decentraland, the eponymous punks in CryptoPunks, and in-game items using systems like Dmarket or EnjinCoin. Future uses include tracking real-world non-fungible assets, like real-estate (as envisioned by companies like Ubitquity or Propy). It is critical in each of these cases that these items are not "lumped together" as numbers in a ledger, but instead, each token must have its ownership individually and atomically tracked. Regardless of the nature of these items, the ecosystem will be stronger if we have a standardized interface that allows for cross-functional non-fungible token management and sales platforms.

    NTF IDs

    The basis of this standard is that every NFT is identified by a unique, 256-bit unsigned integer within its tracking contract. This ID number MUST NOT change for the life of the contract. The pair (contract address, asset ID) will then be a globally unique and fully-qualified identifier for a specific NFT within the Ethereum ecosystem. While some contracts may find it convenient to start with ID 0 and simply increment by one for each new NFT, callers MUST NOT assume that ID numbers have any specific pattern to them, and should treat the ID as a "black box".

    Backwards Compatibility

    This standard follows the semantics of ERC-20 as closely as possible, but can't be entirely compatible with it due to the fundamental differences between fungible and non-fungible tokens.

    Example non-fungible implementations as of September 2017:

    • CryptoPunks - Partially ERC-20 compatible, but not easily generalizable because it includes auction functionality directly in the contract and uses function names that explicitly refer to the NFTs as "punks".
    • Auctionhouse Asset Interface - @dob needed a generic interface for his Auctionhouse dapp (currently ice-boxed). His "Asset" contract is very simple, but is missing ERC-20 compatibility, approve() functionality, and metadata. This effort is referenced in the discussion for EIP-173.

    (It should be noted that "limited edition, collectable tokens" like Curio Cards and Rare Pepe are not non-fungible tokens. They're actually a collection of individual fungible tokens, each of which is tracked by its own smart contract with its own total supply (which may be 1 in extreme cases).)

    Implementation

    Reference implementation forthcoming...

    Copyright

    Copyright and related rights waived via CC0.

    opened by dete 397
  • ERC: Token standard

    ERC: Token standard

    The final standard can be found here: https://eips.ethereum.org/EIPS/eip-20


    ERC: 20
    Title: Token standard
    Status: Draft
    Type: Informational
    Created: 19-11.2015
    Resolution: https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs
    

    Abstract

    The following describes standard functions a token contract can implement.

    Motivation

    Those will allow dapps and wallets to handle tokens across multiple interfaces/dapps.

    The most important here are, transfer, balanceOf and the Transfer event.

    Specification

    Token

    Methods

    NOTE: An important point is that callers should handle false from returns (bool success). Callers should not assume that false is never returned!

    totalSupply

    function totalSupply() constant returns (uint256 totalSupply)
    

    Get the total token supply

    balanceOf

    function balanceOf(address _owner) constant returns (uint256 balance)
    

    Get the account balance of another account with address _owner

    transfer

    function transfer(address _to, uint256 _value) returns (bool success)
    

    Send _value amount of tokens to address _to

    transferFrom

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
    

    Send _value amount of tokens from address _from to address _to

    The transferFrom method is used for a withdraw workflow, allowing contracts to send tokens on your behalf, for example to "deposit" to a contract address and/or to charge fees in sub-currencies; the command should fail unless the _from account has deliberately authorized the sender of the message via some mechanism; we propose these standardized APIs for approval:

    approve

    function approve(address _spender, uint256 _value) returns (bool success)
    

    Allow _spender to withdraw from your account, multiple times, up to the _value amount. If this function is called again it overwrites the current allowance with _value.

    allowance

    function allowance(address _owner, address _spender) constant returns (uint256 remaining)
    

    Returns the amount which _spender is still allowed to withdraw from _owner

    Events

    Transfer

    event Transfer(address indexed _from, address indexed _to, uint256 _value)
    

    Triggered when tokens are transferred.

    Approval

    event Approval(address indexed _owner, address indexed _spender, uint256 _value)
    

    Triggered whenever approve(address _spender, uint256 _value) is called.

    opened by frozeman 362
  • ERC: Proxy Account

    ERC: Proxy Account

    eip: <to be assigned>
    title: ERC-725 Smart Contract Based Account
    author: Fabian Vogelsteller <[email protected]>, Tyler Yasaka (@tyleryasaka)
    discussions-to: https://github.com/ethereum/EIPs/issues/725
    status: Draft
    type: Standards Track
    category: ERC
    requires: ERC165, ERC173, ERC1271 (optional)
    created: 2017-10-02
    updated: 2020-07-02
    

    This is the new 725 v2 standard, that is radically different from ERC 725 v1. ERC 725 v1 is be moved to #734 as a new key manager standard.

    Simple Summary

    A standard interface for a smart contract based account with attachable key value store.

    Abstract

    The following describes standard functions for a unique smart contract based account that can be used by humans, groups, organisations, objects and machines.

    The standard is divided into two sub standards:

    ERC725X: Can execute arbitrary smart contracts using and deploy other smart contracts.

    ERC725Y: Can hold arbitrary data through a generic key/value store.

    Motivation

    Standardizing a minimal interface for a smart contract based account allows any interface to operate through these account types. Smart contact based accounts following this standard have the following advantages:

    • can hold any asset (native token, e.g. ERC20 like tokens)
    • can execute any smart contract and deploy smart contracts
    • have upgradeable security (through owner change, e.g. to a gnosis safe)
    • are basic enough to work for for a long time
    • are extensible though additional standardisation of the key/value data.
    • can function as an owner/controller or proxy of other smart contracts

    Specification

    ERC725X

    ERC165 identifier: 0x44c028fe

    execute

    Executes a call on any other smart contracts, transfers the blockchains native token, or deploys a new smart contract. MUST only be called by the current owner of the contract.

    function execute(uint256 operationType, address to, uint256 value, bytes data)
    

    The operationType can execute the following operations:

    • 0 for call
    • 1 for delegatecall
    • 2 for create2
    • 3 for create

    Others may be added in the future.

    Triggers Event: ContractCreated if a contract was created

    Events

    ContractCreated

    MUST be triggered when execute creates a new contract using the _operationType 1.

    event ContractCreated(address indexed contractAddress)
    

    ERC725Y

    ERC165 identifier: 0x2bd57b73

    getData

    Returns the data at the specified key.

    function getData(bytes32 key) external view returns(bytes value)
    

    setData

    Sets the data at a specific key. MUST only be called by the current owner of the contract.

    Triggers Event: DataChanged

    function setData(bytes32 _key, bytes memory _value) external
    

    Events

    DataChanged

    MUST be triggered when setData was successfully called.

    event DataChanged(bytes32 indexed key, bytes value)
    

    Ownership

    This contract is controlled by an owner. The owner can be a smart contract or an external account. This standard requires ERC173 and should implement the functions:

    • owner() view
    • transferOwnership(address newOwner)
    • and the Event event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)

    Data keys

    Data keys, should be the keccak256 hash of a type name. e.g. keccak256('ERCXXXMyNewKeyType') is 0x6935a24ea384927f250ee0b954ed498cd9203fc5d2bf95c735e52e6ca675e047

    Multiple keys of the same type

    If you require multiple keys of the same key type they MUST be defined as follows:

    • The keytype name MUST have a [] add and then hashed
    • The key hash MUST contain the number of all elements, and is required to be updated when a new key element is added.

    For all other elements:

    • The first 16 bytes are the first 16 bytes of the key hash
    • The second 16 bytes is a uint128 of the number of the element
    • Elements start at number 0
    Example

    This would looks as follows for ERCXXXMyNewKeyType[] (keccak256: 0x4f876465dbe22c8495f4e4f823d846957ddb8ce6006afe66ddc5bac4f0626767):

    • element number: key: 0x4f876465dbe22c8495f4e4f823d846957ddb8ce6006afe66ddc5bac4f0626767, value: 0x0000000000000000000000000000000000000000000000000000000000000002 (2 elements)
    • element 1: key: 0x4f876465dbe22c8495f4e4f823d8469500000000000000000000000000000000, value: 0x123... (element 0)
    • element 2: key: 0x4f876465dbe22c8495f4e4f823d8469500000000000000000000000000000001, value: 0x321... (element 1) ...

    Default key values

    ERC725 key standards need to be defined within new standards, we suggest the following defaults:

    | Name | Description | Key | value | | --- | --- | --- | --- | | SupportedStandards | Allows to determine standards supported by this contract | 0xeafec4d89fa9619884b6b89135626455000000000000000000000000xxxxxxxx, where xxxxxxxx is the 4 bytes identifier of the standard supported | Value can be defined by the standard, by default it should be the 4 bytes identifier e.g. 0x7a30e6fc | | SupportedStandards > ERC725Account | Allows to determine standards supported by this contract | 0xeafec4d89fa9619884b6b89135626455000000000000000000000000afdeb5d6, where afdeb5d6 is the 4 bytes part of the hash of keccak256('ERC725Account') | Value is the 4 bytes identifier 0xafdeb5d6 |

    ERC725Account

    An ERC725Account is an ERC725 smart contract based account for storing of assets and execution of other smart contracts.

    • ERC173 to be controllable by an owner, that could be am external account, or smart contract
    • ERC725X to interact with other smart contracts
    • ERC725Y to attach data to the account for future extensibility
    • COULD have ERC1271 to be able to verify signatures from owners.
    • Should fire the event ValueReceived(address indexed sender, uint256 indexed value) if ETH is received.

    A full implementation of an ERC725Account can be found found here.

    Rationale

    The purpose of an smart contract account is to allow an entity to exist as a first-class citizen with the ability to execute arbitrary contract calls.

    Implementation

    Solidity Interfaces

    // SPDX-License-Identifier: CC0-1.0
    pragma solidity >=0.5.0 <0.7.0;
    
    //ERC165 identifier: `0x44c028fe`
    interface IERC725X  /* is ERC165, ERC173 */ {
        event ContractCreated(address indexed contractAddress);
        event Executed(uint256 indexed operation, address indexed to, uint256 indexed  value, bytes data);
    
        function execute(uint256 operationType, address to, uint256 value, bytes memory data) external;
    }
    
    //ERC165 identifier: `0x2bd57b73`
    interface IERC725Y /* is ERC165, ERC173 */ {
        event DataChanged(bytes32 indexed key, bytes value);
    
        function getData(bytes32 key) external view returns (bytes memory value);
        function setData(bytes32 key, bytes memory value) external;
    }
    
    interface IERC725 /* is IERC725X, IERC725Y */ {
    
    }
    
    interface IERC725Account /* is IERC725, IERC725Y, IERC1271 */ {
        event ValueReceived(address indexed sender, uint256 indexed value);
    }
    

    Flow chart

    ERC725v2-flow

    Additional References

    Copyright

    Copyright and related rights waived via CC0.

    stale 
    opened by frozeman 274
  • EIP: Modify block mining to be ASIC resistant.

    EIP: Modify block mining to be ASIC resistant.

    Disclaimer: My area of expertise does not lend well to me suggesting how to make things ASIC resistant. I hope there are some informed opinions floating around out there who can help fill in the how.

    According to "the internet" there is an ASIC based ethereum miner on the horizon.

    this may be the original source of that news

    If you believe the analysis in the comments on this reddit thread BitMain may already running these miners.

    I believe it is the accepted wisdom that ASIC based mining leads to increases centralization when compared to GPU mining.

    This leads us to two questions:

    1. Should we hard fork to make ASIC mining harder and to demonstrate a willingness to hard fork any future ASIC based ethereum mining.
    2. What specifically changes do we make to implement this increased ASIC resistance.

    Should we fork?

    I propose that people indicate support/opposition with a simple 👍 / 👎 on this main issue. I would prefer this conversation not devolve into deep discussions around this subjective topic so my request is that people refrain from commenting on that specific question here.

    How do we implement improved ASIC resistance

    This is the primary issue that I think needs to be addressed, after which we can have an informed discussion about whether we should actually do it.

    opened by pipermerriam 262
  • Standardized Ethereum Recovery Proposals (ERPs)

    Standardized Ethereum Recovery Proposals (ERPs)

    Provide a standardized format for Ethereum Recovery Proposals (ERPs), which relate to recovery of certain classes of lost funds.

    Closes https://github.com/ethereum/EIPs/issues/866

    opened by phiferd 254
  • EIP-721 Non-Fungible Token Standard

    EIP-721 Non-Fungible Token Standard

    STATUS: DRAFT STANDARD PUBLISHED, SEE https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md

    Thanks for all your help and hard work!


    How to discuss

    If you... | Then please discuss at... -- | -- Want to discuss YOUR application | https://gitter.im/ETH-NFT/Lobby Have general thoughts/questions on NFT/deed standardization | https://github.com/ethereum/eips/issues/721 Reviewed this pull request and have implementation feedback or can help improve the wording in the standard | Comment here, scroll down ⬇

    And you can always reach out to me directly.

    • Please introduce yourself 😃
    • If you express an opinion, are you speaking individually or do you represent an organization?
    • If you provide feedback, what level of review you have performed (creative thinking/test code/deployed contract)?

    TO DO:

    • [x] Write rationale section
    • [x] Finalize ERC721Metadata interface
    • [x] Finalize ERC165 compliance
    • [x] Reconsider the "deed" word choice -- https://github.com/fulldecent/EIPs/pull/2
    • [x] Demonstrate sufficient consensus for standardization
    • [x] Launch bug bounty program (bounty ended 2018-03-04)
    • [x] Review which event parameters are indexed
    • [x] **Submit to EIP reviewer for DRAFT ACCEPTED
    • [x] OPEN ITEM -- should setApprovedForAll allow the zero address?
    • [x] Get implementation into OpenZeppelin
    • [x] Write test cases / Truffle
    • [x] Post on Reddit, wider forum promote adoption
    • [x] Requires ERC-165 (currently in DRAFT ACCEPTED status)
    • [x] Get to DRAFT APPROVED status

    What is this?

    This pull request is the ERC-721 standardization document.

    This PR is represents the contributions of dozens of people imagining a future where smart contracts will manage ownership of important things in the real world and online. Thanks for your help and support!

    Please react with party emoji 🎉 if you believe this EIP should be accepted. Acceptance is NOT final. The significance of acceptance is detailed in EIP-1:

    If the EIP collaborators approve, the EIP editor will assign the EIP a number (generally the issue or PR number related to the EIP), label it as Standards Track, Informational, or Meta, give it status “Draft”, and add it to the git repository.

    When this is accepted, then we can begin the work of writing test cases and implementations. We can still discuss and change things. Another benefit is that it gets listed on the EIP homepage, this increases the audience of this EIP and will get more people involved and scrutinizing this standard.

    You are the collaborators.

    opened by fulldecent 230
  • EIP-649: Byzantium Difficulty Bomb Delay and Block Reward Reduction

    EIP-649: Byzantium Difficulty Bomb Delay and Block Reward Reduction

    Meta #609 (Byzantium).

    Closes #186 (Replaced).

    Closes #649 (Implemented).

    Please use the according issues to discuss the proposals and use this pull request to discuss the specification.

    opened by 5chdn 200
  • Meta: cap total ether supply at ~120 million

    Meta: cap total ether supply at ~120 million

    Author: Vitalik Buterin Category: Meta Published: 2018 Apr 1

    In order to ensure the economic sustainability of the platform under the widest possible variety of circumstances, and in light of the fact that issuing new coins to proof of work miners is no longer an effective way of promoting an egalitarian coin distribution or any other significant policy goal, I propose that we agree on a hard cap for the total quantity of ETH.

    During the next hard fork that alters reward distributions (likely phase 1 Casper), this proposal requires redenominating all in-protocol rewards, including mining rewards, staking interest, staking rewards in the sharding system and any other future rewards that may be devised, in "reward units", where the definition of reward units is:

    1 RU = (1 - CURRENT_SUPPLY / MAX_SUPPLY) ETH
    

    I recommend setting MAX_SUPPLY = 120,204,432, or exactly 2x the amount of ETH sold in the original ether sale.

    Assuming MAX_SUPPLY = 120 million, and given the current supply of 98.5 million, that means that 1 RU is now equal to 1 - 98.5m/120m ~= 0.1792 ETH, so if a hard fork were to be implemented today, the 3 ETH block reward would become 16.74 RU. In one month, the ETH supply will grow to ~99.1 million, so 1 RU will reduce to 0.1742 ETH, and so the block reward in ETH would be 16.74 * 0.1742 = 2.91555.

    In the longer term, the supply would exponentially approach the max cap and the rewards would exponentially approach zero, so if hypothetically Ethereum stays with proof of work forever, this would halve rewards every 744 days. In reality, however, rewards will decrease greatly with the switch to proof of stake, and fees such as rent (as well as slashed validators) will decrease the ETH supply, so the actual ETH supply will reach some equilibrium below MAX_SUPPLY where rewards and penalties/fees cancel out, and so rewards will always remain at some positive level above zero.

    If for some reason this EIP is adopted at a point where it is too late to set a max cap at 120 million, it is also possible to set a higher max cap. I would recommend 144,052,828 ETH, or exactly 2x the total amount released in the genesis block including both the sale and premines.

    stale 
    opened by vbuterin 187
  • [EIP-4844] Fee Market Update

    [EIP-4844] Fee Market Update

    Update to the EIP-4844 fee market design. List of changes:

    • [x] introduce data gas
    • [x] add max_fee_per_data_gas tx field
    • [x] change fake exponential function to taylor expansion
    • [x] add min data gasprice of 10,000 Gwei
    • [x] remove max blobs per tx restriction
    • [x] align tx field naming with EIP-1559

    Potential remaining todos:

    • [ ] make excess blobs calculation slot-based instead of block-based
    • [ ] mention option for mempool to enforce a max blobs per tx restriction
    • [ ] change data gas name to something more unique (oil? mana?)
    • [ ] change DATA_GAS_PER_BLOB to make it easier to add calldata pricing later
    c-update t-core s-draft 
    opened by adietrichs 2
  • Add EIP-5700: Bindable Token Standard

    Add EIP-5700: Bindable Token Standard

    When opening a pull request to submit a new EIP, please use the suggested template: https://github.com/ethereum/EIPs/blob/master/eip-template.md

    We have a GitHub bot that automatically merges some PRs. It will merge yours immediately if certain criteria are met:

    • The PR edits only existing draft PRs.
    • The build passes.
    • Your GitHub username or email address is listed in the 'author' header of all affected PRs, inside .
    • If matching on email address, the email address is the one publicly listed on your GitHub profile.
    c-new t-erc s-draft 
    opened by leeren 1
  • Update EIP Template: Add EIP patent waiver

    Update EIP Template: Add EIP patent waiver

    Obviously IANAL.

    Pandapip1 IS NOT A LAW FIRM OR EVEN A LAWYER AND DOES NOT PROVIDE
    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
    ATTORNEY-CLIENT RELATIONSHIP. Pandapip1 PROVIDES THIS
    INFORMATION ON AN "AS-IS" BASIS. Pandapip1 MAKES NO WARRANTIES
    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
    HEREUNDER.
    
    c-update t-process e-number s-draft e-consensus 
    opened by Pandapip1 1
Bitcoin Improvement Proposals

People wishing to submit BIPs, first should propose their idea or document to the [email protected] mailing list (do not assign a

Bitcoin 7.1k Sep 14, 2022
ConsenSys Software 8 Jan 18, 2022
LEO (Low Ethereum Orbit) is an Ethereum Portal Network client.

LEO LEO (Low Ethereum Orbit) is an Ethereum Portal Network client. What makes LEO different from other Portal Network clients is that it uses libp2p f

Valist, Inc. 10 Apr 19, 2022
Ethereum-vanity-wallet - A fork of https://github.com/meehow/ethereum-vanity-wallet but the key can be exported to a JSON keystore file

ethereum-vanity-wallet See https://github.com/meehow/ethereum-vanity-wallet This version: doesn't display the private key let's you interactively expo

null 0 Jan 2, 2022
Go-ethereum - Official Golang implementation of the Ethereum protocol

Go Ethereum Official Golang implementation of the Ethereum protocol. Automated b

i06 0 Jan 4, 2022
This library aims to make it easier to interact with Ethereum through de Go programming language by adding a layer of abstraction through a new client on top of the go-ethereum library.

Simple ethereum client Simple ethereum client aims to make it easier for the developers to interact with Ethereum through a new layer of abstraction t

Jero 3 May 1, 2022
Accompanying repository for the "Build Ethereum From Scratch - Smart Contracts and More" course by David Katz

Build Ethereum From Scratch - Smart Contracts and More This repository accompanies the "Build Ethereum From Scratch - Smart Contracts and More" course

David Katz 43 Jul 28, 2022
This is the repository I made while learning Go Programming Language & You can follow this repository to learn it

Golang Arena ?? Hey Folks! Welcome to Golang Arena . This is the repository I made while learning Go Programming Language & You can follow this reposi

Anukul Pandey 1 Jan 31, 2022
Huobi Eco Chain client based on the go-ethereum fork

The Huobi Open Platform is a unified infrastructure platform based on the technical, traffic and ecological resources of the Huobi Group, and will be gradually open to the blockchain industry.

null 236 Sep 10, 2022
Streaming Fast on Ethereum

Stream Ethereum data like there's no tomorrow

StreamingFast 69 Jul 9, 2022
a Golang sdk for working with DeFi protocols, and ethereum compatible blockchains

A golang sdk for working with DeFi protocols and general utilities for working with ethereum-compatible blockchains. packages bclient bindings cli con

bonedaddy 70 Sep 13, 2022
run ABI encoded data against the ethereum blockchain

Run EVM code against a database at a certain block height - Note You can't run this against a running geth node - because that would share the db and

Edgar Aroutiounian 60 Nov 11, 2021
Go implementation of Ethereum proof of stake

Prysm: An Ethereum Consensus Implementation Written in Go This is the core repository for Prysm, a Golang implementation of the Ethereum Consensus spe

Prysmatic Labs 2.8k Sep 25, 2022
Ethereum Dapp Go API

Web3 Go Ethereum Dapp Go API, inspired by web3.js. Report Bug · Pull Request Introduction This is the Ethereum Golang API which connects to the Generi

Kyle Liu 16 Sep 5, 2022
A phoenix Chain client based on the go-ethereum fork,the new PoA consensus engine is based on the VRF algorithm.

Phoenix Official Golang implementation of the Phoenix protocol. !!!The current version is for testing and developing purposes only!!! Building the sou

g_master 14 Apr 28, 2022
Ethereum on StreamingFast

Ethereum on StreamingFast Requirements (clone repos, build stuff...) Install Geth git clone [email protected]:streamingfast/go-ethereum.git cd go-ethereu

StreamingFast 32 Sep 9, 2022
Evmos is a scalable, high-throughput Proof-of-Stake blockchain that is fully compatible and interoperable with Ethereum.

Evmos Evmos is a scalable, high-throughput Proof-of-Stake blockchain that is fully compatible and interoperable with Ethereum. It's built using the Co

Tharsis 1.3k Sep 26, 2022
Monorepo implementing the Optimistic Ethereum protocol

The Optimism Monorepo TL;DR This is the primary place where Optimism works on stuff related to Optimistic Ethereum. Documentation Extensive documentat

OMG Network 38 Jul 22, 2022
Tool for monitoring your Ethereum clients. Client-agnostic as it queries the standardized JSON-RPC APIs

e7mon Tool for monitoring your Ethereum clients. Client-agnostic as it queries the standardized JSON-RPC APIs. However, the execution client should be

null 25 Jul 7, 2022