ethereum / EIPs

The Ethereum Improvement Proposal repository

Home Page:https://eips.ethereum.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ERC: Multi Token Standard

coinfork opened this issue · comments

commented
---
eip: 1155
title: ERC-1155 Multi Token Standard
author: Witek Radomski <witek@enjin.io>, Andrew Cooke <ac0dem0nk3y@gmail.com>, Philippe Castonguay <pc@horizongames.net>, James Therien <james@turing-complete.com>, Eric Binet <eric@enjin.io>, Ronan Sandford <wighawag@gmail.com>
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.

Suggestion: Add in some detail of how to encode extra information into the _itemId to facilitate the mixing of different item/token standards.

An example strategy to mix Fungible and Non-Fungible items together in the same contract for example may be to pass the base item ID in the top 128 bits of the uint256 _itemID parameter and then use the bottom 128 bits for any extra data you wish to pass to the contract.

In the ERC-721 case individual NFTs are interacted with using an index based accessor into the contract/item data set. Therefore to access a particular item set within a mixed data contract and particular NFT within that set, _itemID could be passed as "<uint128: base item id><uint128: index of NFT>".

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

commented

Added the split bits strategy to the description, thanks :)

Transfer made using this standard, 2 FTs (10k + 500) and 100 NFTs (100):

https://ropsten.etherscan.io/tx/0xfc924192fb068a6326bc28a2f5762be3a4b1fb6a1ef801bf6bf02c06af929d53

FT "ENJ" ID: 0x54e8b965cee12ac713ee58508b0d07300000000000000000000000000000000
FT "Gold" ID: 0x3bf7ded270a4ab1d5e170cc79deb931800000000000000000000000000000000
NFT "Lots of NFTs" ID: 0x4362b8ce48bee741861f523a3b91803c00000000000000000000000000000000

10000, 500 and 100*1 sent in one transaction costing 5480196 gas (~$2.42 at time of tx).

Note, this was done in an advanced solution with a lot more features than a basic impl. Basic/ref impl and gas as compared to current standards in basic form will be added soon.

Hyperbridge is interested in potentially supporting this standard in our upcoming marketplace. We'd like to see where other organizations stand on this as it's an obvious problem, and if the proposed solution works for you. @coinfork I don't see source code, so I'm going to take to take it that it's currently proprietary. Is there any examples in the wild as of yet?

commented

Hey @ericmuyser thanks for your interest! We currently have a deployed contract on Ropsten (please see AC0DEM0NK3Y's post above) that is specifically tailored to our gaming use-case. We'll consider adding a reference implementation to the standard.

I hope you didn't announce this like "Biggest innovation in the manking". 5480196 gas is unacceptably high.

"I hope you didn't announce this like "Biggest innovation in the manking". 5480196 gas is unacceptably high."

I think you need to look at the gas cost relative to the alternatives and how this differs from them. If you average this down (even without the fungible transfers that went with it) the above transfer cost ~55K per NFT sent, which compared to many other ERC721 implementations for eg. (seeing numbers 250K+ each) this offers significant savings. A simple ETH transfer costs 21K and ERC20 tokens look to cost anywhere from 35k to 130k each tx after some quick explorer checks in the top 100. So I would say the above cost is quite reasonable.

On top of that there is also the reduction of number of contracts necessary to be deployed to the network, the transaction numbers being reduced (in this case 102 : 1) and also the possible features this would bring that wouldn't be possible with separate contracts and incompatible NFT & FT standards.

I don't have strong opinions yet, but did y'all explore the option of composing ERC721 and 20/721 to get similar functionality? As in, creating a AllItems contract that is 721 but fully controlled by whatever governance mechanism you'd prefer. Then, owners can create a new item set like createNonFungible(...) to deploy a 721 contract and add that new contract address as one of the tokens tracked by the contract (owned by the AllItems contract itself). Similar for fungible assets. Then clients can get the set of all items via iterating the 721 interface, ERC165 detect fungibility or non-fungibility, and either 1) directly interface with those sub-contracts to manage their items or 2) you could provide similar multi-send features by proxying transfer requests through the AllItems contract that's either an approved operator of the sub-contract or is just an all-seeing authority (deferring the access-control logic to the AllItems contract to verify who owns what before transferring).

Anyway, it might be a little roundabout, but it does avoid the creation of a new standard by extending and composing existing ones, which is neat.

Hi @shrugs while not getting too far into the implementation details of a system that uses this standard, in the above example where two different fungible types and one non-fungible set were operated on what a user/creator could do is call a "deployERCAdapter" function on the particular type if they so wish which will deploy an adapter contract that is either fully ERC721 or ERC20 compatible depending on the base type. This means the individual set is now backwards compatible with those standards and can therefore be used in any current system that supports them.
So we get the best of both worlds, full compatibility with ERC20 and ERC721 (as an option) but also the ability to mix these two standards together by operating at the 1155 "main level" and so can transfer/operate on these together and on multiple of the types, in the same transaction.

Extending ERC721 rather than making a new standard that can mix different fungibility (and then supporting ERC721 with backwards compatibility) wouldn't have quite worked as ERC721 mandatory standard has certain functions that only make it suitable for a single data set in a single contract such as "balanceOf(address _owner)" and "isApprovedForAll(address _owner, address _operator)" for example.

@AC0DEM0NK3Y the ERC adaptor is interesting, yeah.

The fungible/non-fungible tokens would not be tracked in a single 721; their contract addresses would be.

AllItems (ERC721, tracking contract addresses)
  |__ Sword contract (ERC20)
  |
  |__ Legendary Armor contract (ERC721)

so each individual contract still fulfills 721 and 20 to the best of their ability, and you add additional features like multi-send and factory methods to the AllItems parent contract.

That is a way to track perhaps, but is much less user/network friendly. If I want to send you an NFT A and and NFT B and do that through your tracking contract I'd have to call approve on contract A and B separately to give the tracking contract the allowance, then call the tracking contract to do the transfer.
That is 3 individual transactions (4 if your tracking contract doesn't support arrays for transfer API).

By allowing things to be mixed together and stored in a single contract I can transfer A and B to you in a single tx.

A and B contract also have to be deployed. It's more data on the chain than is needed and that is not sustainable and/or limiting imho.
If you consider use cases like a videogames that have lots of different types of NFTs and how many games there are in the market now and will be in the future, having to deploy an ERC20/ERC721 contract to support those types every time is not good for the ETH network as a whole going forward and that is just one use case.

I mentioned that above as well, perhaps I wasn't clear enough; you can implement multi-send functionality by making the AllItems contract a designated operator (or a super user of sorts) for transferring tokens/items and then implement access control at the AllItems layer, allowing you to skip approvals and send multiple items with a single transaction exactly as you do in 1155. Nothing has changed here.

I agree that composability does come with gas costs, and these should be measured. You can also separate logic and data using proxy patterns and cut down on duplicate logic deployments. (and before someone references the parity wallet, this is very much the same approach that 1155 uses by consolidating the logic and data into a single contract; it's still a single point of failure if there is a show-stopping bug).

It sounds like it could work, but it doesn't fix the wastage/management issue. Deploying a contract for every NFT is not future proof imho.

Your pattern seems like it would work with 1155 though. The register function that you are proposing could be something someone implements and then this returns an ID to match the contract address when calling the function. The call to transfer A and B in that case would might be to call:

uint aID = 1155.register(ContractOfA);
uint aIndex = 12345; // NFT index I want to send from contract A
uint bID = 1155.register(ContractOfB);
uint bIndex = 888; // NFT index I want to send from contract B
ContractOfA.makeSuperUser(1155);
ContractOfB.makeSuperUser(1155);
1155.transfer([aID, aIndex, bID, bIndex], [yourAddr,yourAddr],[1,1]);

This now needs an extension to ERC721 to append "makeSuperUser" function.

((an aside: using an existing standard is the definition of futureproof))

superuser would need to be added, yes. you could also get away with operator functionality that already exists; simply default to setting the approved operator of every token to the AllItems contract. users could revoke, but 1) why would they and 2) to restore previous behavior, they can simply re-approve the operator. compatible with both 20 and 721.

The data/logic separation via proxy is a well-known pattern and does indeed work. The only unknown is the gas implications, which could be measured. Having your sub-items be compatible with 20/721 by default is a very powerful effect. We've only just started the whole NFT thing, and fracturing into another standard instead of leveraging existing ones isn't really a strong move, imo. Existing indexers (Toshi, Trust Wallet, etc) would need to have extra logic to monitor this standard as well. And deploying ERC adaptors for every token just gets you back to the point I'm making; it should just be compatible with the existing standard by default.

Anyway, give it a think and see if it solves the problem you're interested in solving. I'm very familiar with the space and the problems you're facing, specifically around gaming, and have thought about this at length as well. A next step would be profiling the gas costs of a composable approach, which I may mind time to do within the next week or two, but can't guarantee.

an aside: using an existing standard is the definition of futureproof

I would call that backwards compatible but hey :)

The data/logic separation via proxy is a well-known pattern and does indeed work.

Yes, we do this or sorts in our implementation. Storage contract holds all the data, then the rest is an API over the top of it. Many reasons to do this.
So in the above test, consider that a test of gas costs perhaps.

Thanks for the discussion @shrugs looking forward to more.

Hello!

Happy to see other people working on something like this. I personally recommend the following changes ;

  1. Remove transfer(...). It's a special case of transferFrom() and is less explicit, which isn't great.

  2. Add safeTransferFrom(...) instead of passing data in second 128 bits. Explicit > implicit should be favored in standards imo.

  3. Change arguments order of transferFrom(uint256[] _itemId, address[] _from, address[] _to, uint256[] _value)nt ordering from transferFrom(uint256[] _itemId, address[] _from, address[] _to, uint256[] _value) to transferFrom(address[] _from, address[] _to, uint256[] _itemId, uint256[] _value) which seems more consistent with current standards.

  4. Change the current approval logic to something like setApprovalForAll() or setOperator() instead of using specific approvals. Approvals are almost exclusively used to give access to your tokens to a trusted/vetted contract. I have yet to see an example of a specific approval value. Even with erc-721, I have yet to see a use case where giving approval to a single ID is useful.

When it comes to transfer() and transferFrom(), is the reason for "not" throwing and return a bool instead to prevent a single transfer from breaking the entire transfer? What does it mean to return false? That at least one of them was unsuccessful? All of them? Not sure I understand the logic here and would love some extra info.

Thanks for putting this together!

A few folks (@petejkim (Cipher/Toshi), @lsankar4033 (PepeDapp), @pkieltyka (Horizon Games), and myself (Rare Bits/Fan Bits)) were actually bouncing around a Semi Fungible Token standard that may make sense to combine efforts on given the similarities. I've put it below for posterity. That being said, a couple ideological things that may be worth considering:

  1. ERC721 was just approved after a lot of deliberation and it seems like maintaining this as an evolution/superset of ERC721/ERC20 in terms of nomenclature / API compatibility will help with adoption / building to consensus quickly. We took the approach of starting with the ERC721 spec and then evolving from there to ensure we captured all of the hard work and thought that went into that standard.

  2. This is bigger than games and the ecosystem for NFTs is already spreading well beyond virtual items. Switching from Items to Tokens doesn't make a whole lot of sense given the existing ecosystem that exists around these standards already.

  3. We all agreed that having indexing/metadata functions are required versus optional makes life a lot easier for wallet providers and other indexers trying to display the data and interoperate with these contracts.

pragma solidity ^0.4.20;

/// The goal of this spec is to handle a now-common case of having different
/// token types with fungibility within each type.

/// Many DApps are either using ERC721 with multiple-tokens of the same type or deploying 
/// multiple ERC20 contracts to create fungible tokens within a set non-fungible token types.
/// An example would be a trading card game with different types but where 
/// each card of a given type is indistinguishable from the other. Or an art 
/// token where each print of an art piece is indistinguishable from any other print.

/// This is a *VERY* draft spec that is modified from the (near) final
/// ERC721-spec. We should evolve it as necessary from here.

/// @title ERC->>>TBD<<< Semi-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-TBD.md
///  Note: the ERC-165 identifier for this interface is >>>TBD<<<
interface ERCTBD /* is ERC165 */ {
    /// @dev This emits when ownership of any SFT changes by any mechanism.
    ///  This event emits when SFTs are created (from == 0) and destroyed
    ///  (to == 0). Exception: during contract creation, any number of SFTs
    ///  may be created and assigned without emitting Transfer. At the time of
    ///  any transfer, the approved address for that SFT (if any) is reset to none.
    event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenType, uint256 indexed _value);

    /// @dev This emits when the approved address for an SFT is changed or
    ///  reaffirmed. The zero address indicates there is no approved address.
    ///  When a Transfer event emits, this also indicates that the approved
    ///  address for that SFT (if any) is reset to none.
    event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenType, uint256 indexed _value);

    /// @dev This emits when an operator is enabled or disabled for an owner.
    ///  The operator can manage all SFTs of the owner.
    event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);

    /// @notice Returns the total token supply.
    /// @dev Throws if '_tokenType' is not a valid SFT
    /// @param _tokenType The type of SFT to get the totalSupply of. Must be less than the return value of totalTokenTypes
    /// @return The total supply of the given SFT
    function totalSupply(uint256 _tokenType) external view returns (uint256 totalSupply);

    /// @notice Count all SFTs of a given type owned by _owner
    /// @dev Throws if '_tokenType' is not a valid SFT or if _owner is set to the zero-address
    /// @param _owner An address for whom to query the balance
    /// @param _tokenType The type of SFT to get the balance of. Must be less than the return value of totalTokenTypes
    function balanceOf(address _owner, uint256 _tokenType) external view returns (uint256 balance);
    
    /// @notice Return all token types for a given _owner
    /// @param _owner An address for whom to return token types for
    function tokenTypesOf(address _owner) external view returns (uint256[] tokenTypes);

    /// @notice Returns the total number of token types for this contract
    /// @dev Can possibly be zero
    /// @return The total number of token types
    function totalTokenTypes() external view returns (uint256 totalTokenTypes);

    /// @notice Returns the total number of distinct owners who own _tokenType
    /// @dev Can possibly be zero
    /// @return The total number of distinct owners owning _tokenType
    function totalOwners(uint256 _tokenType) external view returns (uint256 totalOwners);

    /// @notice Returns the owner of _tokenType specified by _ownerIndex
    /// @param _ownerIndex Unique identifier of an owner of _tokenType
    /// @return The address of the ownner of _tokenType specified by _ownerIndex
    function ownerOf(uint256 _tokenType, uint256 _ownerIndex) external view returns (address owner);

    /// @notice Transfers the ownership of some SFTs from one address to another address
    /// @dev Throws unless 'msg.sender' is the current owner, an authorized
    ///  operator, or the approved address for the SFTs. Throws if '_from' is
    ///  not the current owner. Throws if '_to' is the zero address. Throws if
    ///  '_tokenType' is not a valid SFT type. When transfer is complete, this function
    ///  checks if '_to' is a smart contract (code size > 0). If so, it calls
    ///  'onERCTBDReceived' on '_to' and throws if the return value is not
    ///  'bytes4(keccak256("onERCTBDReceived(address,address,uint256,bytes)"))'.
    /// @param _from The current owner of the SFTs
    /// @param _to The new owner
    /// @param _tokenType The SFT type to transfer. Must be less than the return value of totalTokenTypes
    /// @param _value Amount of SFT to transfer
    /// @param data Additional data with no specified format, sent in call to '_to'
    function safeTransferFrom(address _from, address _to, uint256 _tokenType, uint256 _value, bytes data) external payable;

    /// @notice Transfers the ownership of some SFTs from one address to another address
    /// @dev This works identically to the other function with an extra data parameter,
    ///  except this function just sets data to "".
    /// @param _from The current owner of the SFTs
    /// @param _to The new owner
    /// @param _tokenType The SFT type to transfer. Must be less than the return value of totalTokenTypes
    /// @param _value Amount of SFT to transfer
    function safeTransferFrom(address _from, address _to, uint256 _tokenType, uint256 _value) external payable;

    /// @notice Transfer ownership of some SFT -- THE CALLER IS RESPONSIBLE
    ///  TO CONFIRM THAT '_to' IS CAPABLE OF RECEIVING SFTS OR ELSE
    ///  THEY MAY BE PERMANENTLY LOST
    /// @dev Throws unless 'msg.sender' is the current owner, an authorized
    ///  operator, or the approved address for this SFT. Throws if '_from' is
    ///  not the current owner. Throws if '_to' is the zero address. Throws if
    ///  '_tokenType' is not a valid SFT.
    /// @param _from The current owner of the SFT
    /// @param _to The new owner
    /// @param _tokenType The SFT type to transfer. Must be less than the return value of totalTokenTypes
    function transferFrom(address _from, address _to, uint256 _tokenType, uint256 _value) external payable;

    /// @notice Change or reaffirm the approved address for some SFTs
    /// @dev The zero address indicates there is no approved address.
    ///  Throws unless 'msg.sender' is the current owner of the SFTs, or an authorized
    ///  operator of the current owner.
    /// @param _approved The new approved SFT controller
    /// @param _tokenType The SFT type to approve. Must be less than the return value of totalTokenTypes
    /// @param _value The amount of SFT able to be withdrawn
    function approve(address _approved, uint256 _tokenType, uint256 _value) external payable;

    /// @notice Enable or disable approval for a third party ("operator") to manage
    ///  all of msg.sender's assets
    /// @dev Emits the ApprovalForAll event. The contract MUST allow
    ///  multiple operators per owner.
    /// @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 Get the amount of allowance a spender has for a given owner and SFT type
    /// @param _owner The address that owns the SFTs
    /// @param _spender The address that is operating on behalf of the owner
    /// @param _tokenType The type of SFT to find the approved address for. Must be less than the return value of totalTokenTypes
    /// @return The amount able to be spent by the spender for a given owner and type
    function allowance(address _owner, address _spender, uint256 _tokenType) external view returns (uint256);

    /// @notice Query if an address is an authorized operator for another address
    /// @param _owner The address that owns the SFTs
    /// @param _operator The address that acts on behalf of the owner
    /// @return True if '_operator' is an approved operator for '_owner', false otherwise
    function isApprovedForAll(address _owner, address _operator) external view returns (bool);

    /// @notice A descriptive name for a collection of SFTs in this contract
    function name() external view returns (string _name);

    /// @notice An abbreviated name for SFTs of a given type
    function symbol(uint256 _tokenType) external view returns (string _symbol);

    /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
    /// @dev Throws if '_tokenType' is not a valid SFT. URIs are defined in RFC
    ///  3986. The URI may point to a JSON file that conforms to the "ERC721
    ///  Metadata JSON Schema".
    function tokenURI(uint256 _tokenType) external view returns (string);    
}

interface ERC165 {
    /// @notice Query if a contract implements an interface
    /// @param interfaceID The interface identifier, as specified in ERC-165
    /// @dev Interface identification is specified in ERC-165. This function
    ///  uses less than 30,000 gas.
    /// @return 'true' if the contract implements 'interfaceID' and
    ///  'interfaceID' is not 0xffffffff, 'false' otherwise
    function supportsInterface(bytes4 interfaceID) external view returns (bool);
}

@amittmahajan Could you explain what ownerOf and totalOwners are referring to? It's not clear to me what the intentions are with these functions.

@PhABC totalOwners is referring to the number of unique addresses that hold a given tokenType. ownerOf is one element of that "owners" array of a given tokenType. it allows you to enumerate every owner of a given tokenType.

Thanks for adding that @amittmahajan and we'll discuss it internally. What first springs to mind however is that your proposal standard does not allow for approving/transferring etc. on multiple things in one shot as they do not take array arguments.

Also the functions such as @PhABC is talking about like totalOwners sound immediately to me like they would need more storage and so gas costs to maintain. I would advocate for as little as possible on chain storage and this sort of "metadata" instead recorded off-chain.
You could find the owners/track balance via transfer log events for eg. and store that info elsewhere. It isn't necessary for the users to have that info stored and the developers can get this info from a local node.
The less we bloat ETH while providing great features for the users the better imho.

@amittmahajan Ah I see. How do you keep track of all the owners? I can understand iterating over all token types an user owns if the totsl number of token types is somewhat low, but I can't really see a way to iterate over the owners unless you keep a big array of owners for each token types. Any insights?

Good to see this proposal.

Our use case is for ERC-20 tokens. We want to 'color' tokens by community while allowing them to be fungible on exchanges as a 'clear' token. Within communities transfer of colored tokens will be allowed in the community color only, but outside of communities the rest of the world will see the tokens as a single ERC-20 type token. This looks like a similar solution I came up with to solve this.

A standard will encourage the creation of tools and potentially wallets will that can deal with this paradigm. My question: is this EIP just for NFTs or is it intended to be used for ERC-20 tokens as well?

@PhABC @AC0DEM0NK3Y re: totalOwners, ownerOf. not married to including these because we've built out the infra already to support it but I included it with the intent of spurring the discussion if there was a more clever way to implement it / see what the community demand for such a feature would be.

re: multiple token transfer, i think it's a good idea and has a lot of use cases. That being said, I wouldn't be surprised if that function is mostly called with a single type. Perhaps it makes sense to implement that as a new function (multiTransfer) to reduce complexity for the most basic use case of transfer. If I were to vote right now, i'd say stick with the current version (one func transfer that takes multiple types) but wanted to raise the topic of two funcs to be diligent.

@amittmahajan batch transfer is critical for these types of tokens, imo, it's really what makes such an interface interesting. I personally vote for batchTransferFrom(..) to follow naming conventions. I do agree that some applications might favor single type transfer while others might utilize the batch transfer functionality more often.Convince me :).

I personally would not include totalOwners & ownerOf as they add significant gas cost and their on-chain utility seems limited.

We originally had a transfer (single) and multiTransfer (array) in the standard but after testing gas differences and usability we decided it better to just use the array version and name it transfer for simplicity.

If you pass in MEW for eg. as well as other methods, the difference in array vs non-array method is almost identical (it is identical in MEW) and the gas difference is negligible and the power of the feature is huge for gas savings and for functionaility.

With my implementation, it costs around 400k gas to send 100 token types, but single transfer is about 2k gas more expensive using the batchTransferFrom function compared to the transferFrom().

@AC0DEM0NK3Y one downside of a single transfer method (vs. separate transfer and multiTransfer methods) is that there's an additional burden on 3rd parties integrating with all standards, as they have to remember that transfer has different argument lists (address vs. address[]) for ERC721/20/1155.

I think the simplicity cost of having two methods is worth the integration win of cleaner unification with existing standards.

@lsankar4033 We'll talk/test about that internally and come back on it.

My first thought is that transfer has to change even in singular form to include the token/item type:

function transfer(address _to, uint256 _value)

vs

function transfer(uint256 _itemId, address _to, uint256 _value)
or
function transfer(uint256[] _itemId, address[] _to, uint256[] _value)

so if it has to change signature anyway, why not go for the most powerful version if it is just as easy to call, almost as cheap and provides the opportunity for much more functionality?

A standard will encourage the creation of tools and potentially wallets will that can deal with this paradigm. My question: is this EIP just for NFTs or is it intended to be used for ERC-20 tokens as well?

@dwking2000 we intend it for both. In our implementation we mix erc20 and erc721 style, can transfer (and lots of other ops) both types in the same tx and can deploy an adapter for each type that fully supports ERC20 and ERC721 API on the tokens if the user wishes.

We've tried to plan for the future while supporting current standards whilst also trying to keep the on-chain storage as low as possible.

@AC0DEM0NK3Y When you say you tested the gas cost difference of using arrays by default, would you mind sharing the numbers?

@PhABC I didn't personally complete those tests. I've pinged the person who did for exact numbers (it's a stat holiday here so won't be answered until tomorrow at the earliest) but from the figure I have at hand from chat logs it looks like it was ~500 gas more for a single transfer and then ~9% less overall on larger multi transfers due to less need to call the function itself, the potential to reduce checks per transfer and to reduce cross library/contract calls. Of course this is in our particular implementation, this would be variable by use case.

As mentioned we'll talk it through here with community and take feedback into the final standard for both signatures and naming conventions. This is to benefit us all as a community after all.

@AC0DEM0NK3Y

Great to hear.

One thing I would like to note, however, is that the standard should not be rushed to be finalized and should definitely not be made internally. As you can see, many people are implementing interfaces that are practically identical (from, to, type, amount) and a concensus should be reached among various groups for it to be a successful standard. I fear people will otherwise propose other too similar standards, as I and many other people in this tread were planning to.

Absolutely. Keep the comments and concerns coming in this thread and lets all try to come together to an agreed solution.

@AC0DEM0NK3Y the address vs. address[] is particularly confusing because how the same semantic item (an address) is passed in changes b/w 20/721 and 1155. so even though the whole signature is changing, it might cause some errors

I agree with @lsankar4033 and I would also argue that_from[] and _to[] are somewhat niche functionalities that seem to better suit custom implementations. I would prefer to not include this as a standard as I suspect it's unnecessary for most use cases (especially the current format, where you send the same amounts from same IDs from different sources to different recipients). This is like minting related functions not being part of most token standards because it's usually only useful to contract owner and not third parties (where standardization is needed).

Maybe erc20 adapters can be deployed on demand by anyone.

A user would simply call deployAdapter(itemId)

And the erc1155 contract would deploy a contract thats the adapter for a certain item.

Calling getAdapter(itemId) would get them a adapter contract address if one exists.

Edit: Someone proposed the exact same thing earlier.

I'm wondering if the totalSupply is really necessary. Afaik, the only third parties using total supplies are blockchain explorers, who already track events anyway. Updating the supply of each minted tokenID can be quite expensive, especially when batch minting. Supply can easily be calculated off-chain for anyone with a full-node. Any examples where on-chain access to totalSupply is important?

Maybe erc20 adapters can be deployed on demand by anyone.
@MickdeGraaf It's already done in our implementation (and for erc721), works well.

@PhABC I think totalSupply is necessary for the user to asses rarity of item but I see in the future the possibility of people using supply model mechanics for their item distribution which would need this info on chain to do so trustlessly. Exchanges may also want to quickly pull this without having to run through events. It seems like this value would not need to be altered often to me?
I suppose there is the possibility of adding these types things as erc-165 interface extensions.

Also we are testing the gas costs of array vs non-array atm and it seems that you are right at 2k cost for array pass (was originally measured against our impl with opts and not a simple case), so we are looking like we all agree with your idea to move back to a transfer + multi/batchTransfer set.

I see in the future the possibility of people using supply model mechanics for their item distribution which would need this info on chain to do so trustlessly.

That's possible, but that would be implemented by the owner of the contract, not third parties imo, or it would be quite specific to a given supply model.

Exchanges may also want to quickly pull this without having to run through events.

I don't recall seing an exchange that lists the token total supply to users. Do you have examples?

It seems like this value would not need to be altered often to me?

Perhaps I am misunderstanding some of the specs. How does the total supply work for NFTs and fungible tokens? From my understanding, each ID is either a balance of 1 for NFTs and whatever balance for fungibles. Is this correct? If so, you have totalSupply[anyNFT] == 1 which kinds of seems like useless info.

I don't recall seing an exchange that lists the token total supply to users. Do you have examples?

I don't. But it seems to me that this is something (total and circulating perhaps) that may be wanted by exchanges/browsers like CMC going forward. We don't have good examples for anything like this, yet.

Perhaps I am misunderstanding some of the specs. How does the total supply work for NFTs and fungible tokens?

If you have a token 0x1234 and that is fungible, you can return the totalSupply for that just fine. For NFT when we are storing multiple definitions in a single contract, to get that info I would have a "base token" that represents that type, i.e. the ID we are talking about adding to all the functions here. You could then easily store the total of all NFTs of that classification.

So I could have totalSupply of "Tesla Roadster" for eg. as the number manufactured but then also have the ownership of the individual cars manufactured under that SKU.
A balanceOf(baseTokenID) may return 1000 for number of total cars manufactured/minted to date, a balanceOf(baseTokenID + index of car #5345) might return 1, balanceOf(baseTokenID + index of car not yet manufactured) might return 0.

I'm just thinking that for every NFT created, you have at least 3 SSTORE operations ; balance[to,NFT_family + index] , totalSupply[NFT_family], totalSupply[NFT_family + index], which would cost 45k gas minimum instead of 25k (or 20k without any supply).

If you implement it with reduced storage in mind from the start, you don't need to alter balance on creation just increase total.

Btw, @coinfork is working on a bare impl that he will attach to the EIP.

I am not sure I understand. Clearly if NFT_family + index does not exist yet, the supply will be 0?

I am not sure I understand. Clearly if NFT_family + index does not exist yet, the supply will be 0?

True, but if 0 < index <= totalSupply you can assume the owner is the "creator/manager" in that case.

ERC-165 signatures (correct me if I'm wrong)

    /*
        ERC-1155 API Signature
        bytes4(keccak256('transfer(uint256[], address[], uint256[])')) ^
        bytes4(keccak256('transferFrom(uint256[], address[], address[], uint256[])')) ^
        bytes4(keccak256('approve(uint256[], address[], uint256[])')) ^
        bytes4(keccak256('increaseApproval(uint256[], address[], uint256[])')) ^
        bytes4(keccak256('decreaseApproval(uint256[], address[], uint256[])')) ^
        bytes4(keccak256('totalSupply(uint256)')) ^
        bytes4(keccak256('balanceOf(uint256, address)')) ^
        bytes4(keccak256('allowance(uint256, address, address)'));
    */
    bytes4 constant INTERFACE_SIGNATURE_ERC1155 = 0x004e32b8;

    /*
        ERC-1155 Metadata Signature
        bytes4(keccak256('name(uint256)')) ^
        bytes4(keccak256('symbol(uint256)')) ^
        bytes4(keccak256('decimals(uint256)'));
    */
    bytes4 constant INTERFACE_SIGNATURE_ERC1155_METADATA = 0x71abc795;

    /*
        ERC-1155 Non-Fungible Signature
        bytes4(keccak256('ownerOf(uint256)')) ^
        bytes4(keccak256('itemURI(uint256)')) ^
        bytes4(keccak256('itemByIndex(uint256, uint256)')) ^
        bytes4(keccak256('itemOfOwnerByIndex(uint256, address, uint256)'));
    */
    bytes4 constant INTERFACE_SIGNATURE_ERC1155_NON_FUNGIBLE = 0x78246fe0;

@ericbinet to summarize what I think has been said so far...

It's looking like from conversations above and after tests that the transfer will break out into transfer and batchTransfer and the array option would be in the batch version to save gas for single transfers, but those seem like the basic categories to me yeah.
Possibly dropping transfer and only having transferFrom if further tests show gas diff is negligible to simplify things down.

As @PhABC and @lsankar4033 suggest, the sig would change to "function transferFrom(address _from, address _to, uint256 _itemId, uint256 _value)" for example also, as this seems to match what others were thinking/wanting. It's just param order it makes no difference to function but if people have preferences no harm in that.

Should get some community consensus on whether the extra functions @amittmahajan mentioned are useful in an extension to add as an optional signature too. I'd like to see more comments on those ideas myself.
The thoughts so far from what I can see is that they perhaps necessitate extra storage, users don't need to know that info and the info could be gotten off-chain in other ways by the people who do want to see it. I think both @PhABC and myself were thinking along those lines.

Great summary @AC0DEM0NK3Y!

To comment on the extra functions @amittmahajan brought up (below from his original comment):

    /// @notice Returns the total number of distinct owners who own _tokenType
    /// @dev Can possibly be zero
    /// @return The total number of distinct owners owning _tokenType
    function totalOwners(uint256 _tokenType) external view returns (uint256 totalOwners);

    /// @notice Returns the owner of _tokenType specified by _ownerIndex
    /// @param _ownerIndex Unique identifier of an owner of _tokenType
    /// @return The address of the ownner of _tokenType specified by _ownerIndex
    function ownerOf(uint256 _tokenType, uint256 _ownerIndex) external view returns (address owner);

These functions would certainly add untenable storage requirements in some cases, but in others (in my app, for example), the storage requirement isn't untenable and the benefit of having a standard way for exchanges, etc. to enumerate all of my assets would be really powerful.

I'm in favor of adding them as optional methods.

@AC0DEM0NK3Y

Why do we need try to distinguish NFT from fungible tokens in the standard itself? A NFT is simply a tokenID with a totalSupply of 1, where fungible IDs have a totalSupply > 1. Why not make two contract, one for fungible and one for NFTs? What is the advantage of having both NFTs and fungibles in the same contract? It seems like otherwise you need to keep track of which ID is NFT and which is fungible. Looking at total supply doesn't seem entirely satisfactory as a determining factor.

A NFT is simply a tokenID with a totalSupply of 1, where fungible IDs have a totalSupply > 1

That is one way of doing it.

A better way imo that this standard allows would be to have NFTs as an ID and supply of totalSupply. In that way it can be X number of Y category NFTs that each have a balance of 1 and the ownership address can stay at 0 and be assumed as creator owned initially if it is within totalSupply range.

What is the advantage of having both NFTs and fungibles in the same contract?

There are absolutely huge benefits of mixing fungible and non-fungilble in the same contract. For video games an example might be to have very unique weapons but have special ammunition that is rare but fungible and/or a currency for trading them.

So a very specific example could be in Destiny (1) perhaps, a game I loved and played a lot of, where you can get rocket launchers that are given to the player that have unique/random rolls on them so that item is potentially completely unique out of all the other weapons in the ecosystem. However all rocket launchers use a particular ammo type that is a semi-rare item, but fungible.
Then there is a very commonly gained currency called "glimmer" that is more a time/grind based earnable and another premium paid one called "silver" along with plenty of other types.
A user could be lucky and get a special rocket launcher but that isn't their particularly favorite type of weapon so they want to trade it with others.
If your contract has mixed fungibility items in the same contract that player could do a very simple, on chain escrowed trade with another player simply by posting "I am offering this RL and 100 RL ammo and want to receive 100 silver, 10000 glimmer, 15 strange coins and a unique shotgun of legendary rarity" to an exchange and another player could offer that trade up in a single simple tx and the swap occurs for a relatively tiny amount of gas.

If a publisher put their items from all their games in the same contract their users could also have cross-game swaps in this same contract for any NFT and FT type they have in any of their games.
The publisher could also have a singular premium currency that is used across all their games very easily.

You could have players loaning each other cross game items, trading/swapping them, transferring them and if you have a currency backing on these items also people could earn/trade them and melt them down into a common backing currency, so you could start to see some players even playing games and making a living from it perhaps.

But this goes beyond games. Perhaps I have a stock management system for my enterprise, I sell wine and spirits for eg.
In my store I have 1000 bottles of 2015 vintage of popular shiraz, but I also stock some extremely rare vintages of a particular Scotch. Maybe I have singular bottles of the 1965, 67 and 69 batches that were signed by the master distiller before his retirement and want to track these individually but also categorized.
Perhaps I also have a voucher system for gift cards for people to purchase my stock, perhaps I allow people to swap ETH or any type of currency for my fungible voucher system or pay directly into a "tokenised" version of those currencies in my contract.

There are obviously many more examples than just those two that I thought of off the top of my head.

IMHO mixed fungibility is absolutely crucial for mass adoption to occur in many industries and this isn't just a tech problem and a slight difference in gas perhaps it's an essential feature that we sorely lack in other standards and limits their use case significantly...but those standards are still available, they will still be out there to use and this new standard is just a way of bridging the two major ones in use today.

I think this is a good idea for the same reason I thought the 821 asset repository was a great idea. I'm still wrapping my head around issuance for ERC-20 but think this solves problems we are approaching. I'm excited to give it a try and wanted to voice tentative support.

Will respond with any findings when I start swapping out 721/20 in our current contracts.

Our team at Playfold is interested in developing this standard to alleviate the redundancy and complexity weighing on the blockchain. As a decentralised media company I am working on the language to translate the use case where an ERC721 may have value over a 721/20 token if not for the sake of existing as its own individual asset rather than a "mass produced" item.

@AC0DEM0NK3Y

an essential feature that we sorely lack in other standards and limits their use case significantly...but those standards are still available, they will still be out there to use and this new standard is just a way of bridging the two major ones in use today.

The most obvious difference is the use case of IoT sensors vs assets in a supply chain. Trustless systems would function best though with some level of redundancy. In a mature ecosystem interoperability of standards could provide the ability to clone or fork those items from a list as a form of a privately decentralized Github for instance.

At Fieldcoin, the agriculture land project (exchange and manage farmland with mobile app), we were projecting to use the ERC721 token for our land physical land exchange. I just got to be aware of the new protocol today. ERC1155 provides many advantages so as delays alleviation by grouping multiple items together during swaps, but also reduced transaction costs, less steps process... I will review in details and please do not hesitate to comment.

commented

Thank you for the feedback everyone. We've created a repository with a reference implementation (work-in-progress) of ERC-1155. The standard is also updated with single and batch functions that were suggested.

The basic implementation is here: https://github.com/enjin/erc-1155

We'd love to hear your feedback on this latest version. My own thoughts are that there are now too many required functions (with both single and batch versions) and it should be trimmed down as much as possible to the core ideal set of features.

Technically the absolute minimal spec could be: [transferFrom, approve, balanceOf, allowance]. Right now we have 13 required functions which seems like a bit of overkill for a standard. Thoughts?

Help me understand this code from the implementation:

    // Use a split bit implementation.
    // Store the metaid in the upper 128 bits..
    uint256 constant TYPE_MASK = uint256(uint128(~0)) << 128;
    // ..and the index in the lower 128
    uint256 constant NFI_INDEX_MASK = uint128(~0);
    require(_nfiType & TYPE_MASK == 0 && _nfiType & NFI_BIT  != 0);

If _nfiType & TYPE_MASK == 0 then how could _nfiType & NFI_BIT != 0?

Because this code checks to see if any of the 128 high bits of _nfiType are 1 and throws if so. Then it checks if the highest bit of _nfiType is 1 and throws if it is not. This doesn't make sense to me. This code will always throw.

commented

@mudgen you're right it was a bug, and it's fixed now. Tests are being written at the moment so there may be some bugs - please consider this a beta implementation to show the general idea until the unit tests are in place :)

@coinfork I understand. Thanks for your answer.

Hi, I would have a question. How do you group all the items in one transaction? If they can be grouped, it means they can be separated. One of the key advantage of ERC1155 is to create one and not multiple tokens. This is where I would need more insight. If you group items, it also means they can be sent separately. In this case, they should be linked and represented by a unique token. Is there some kind of mechanism inside the ERC1155 that enables to distinguish and separate specific tokens. This is certainly obvious to most here on this threat :) but I would be very glad if you could enlighten me on this one. Thanks a lot.

I'd like to re-raise the issue of naming. I think Item is too specific of a naming convention and we should revert to the word Token when describing the assets that this contract represents.

Especially since we keep describing the functionality of this contract in terms of erc721 and erc20 tokens. It seems like an unnecessary departure and would require re-education of an entire ecosystem of developers without any real upside.

@MCouzic Hi, I would have a question. How do you group all the items in one transaction? If they can be grouped, it means they can be separated. One of the key advantage of ERC1155 is to create one and not multiple tokens. This is where I would need more insight. If you group items, it also means they can be sent separately. In this case, they should be linked and represented by a unique token. Is there some kind of mechanism inside the ERC1155 that enables to distinguish and separate specific tokens.

Hi MCouzic. This as with other standards is not an implementation, but you can see an example implementation @coinfork posted earlier here.
Our internal implementation for our particular use case for instance has some ideas that inspired that example but isn't identical at all.

@jlwaugh #888 is more generalized

Hi jlwaugh. I believe we discussed an idea around this too but decided while something like that is generic on the chain (although at a cost in multiple ways) it makes off-chain interaction more complex and less predictable if using a dynamic key.
One example off-chain might be in a wallet, with a uint256 the UI designer can work with integrating that into their display with guarantee. If they can have any number of characters thrown at them via such an open nature (that is potentially overkill, you can fit a lot in 256 bits) then they no longer have this.
Also, you cannot pass an array of strings to Solidity currently and have to resort to tricks.

@amittmahajan I'd like to re-raise the issue of naming. I think Item is too specific of a naming convention and we should revert to the word Token when describing the assets that this contract represents.

It's a topic worth discussing for sure and one that we've discussed quite a bit ourselves and decided to go with "item" for what it is, rather than just pick "token" because that has been what has gone before. We knew this would be a contentious topic as we couldn't all agree on it either :)

It should be be noted, the only place where "item" is enforced is in the function names for gathering information for non-fungible items. For the standard functions, there is nothing in the name that says either item or token and you can call the parameters whatever you like and the signature stays the same.

One of the reasons for the name is when you think of the future, outside of our little developers box and hopefully towards users who currently know nothing about crypto today sending each other stuff on a daily or minute-to-minute basis; When those users talk to each other about sending "things" will they likely edge towards talking about sending/lending/trading tokens or items (and as an extension, perhaps the specifics of the items themselves)?

So the idea behind naming things items instead of tokens is to be forward thinking about the people who are hopefully mainstream users of these "things in the IoT" and if we are to have them (and us) think about these things as real world, almost and sometimes actual representation of physical items then I'm not sure tying ourselves to names that went in the past just to make developers lives a tiny fraction easier is serving them more than it is us (which is debatable, when I say token what am I talking about erc20, 721 or 1155 now?).

But...perhaps we are coming at this from too much of an angle, where what we think will be represented in the vast majority in the future with this standard would be an item i.e. something separate and distinct within the overall list that represents a thing.
Maybe the main use case would be something other than that?

Hey @AC0DEM0NK3Y, @coinfork & others, we just released publicly our implementation with a very similar interface as proposed here. We want to collaborate and do not wish to create a separate standard proposal. We think the interface could be improved and you can find the rationale of our interface design choices in the rationale section.

@AC0DEM0NK3Y We knew this would be a contentious topic as we couldn't all agree on it either :)

Appreciate the difficulty in naming things!

@AC0DEM0NK3Y So the idea behind naming things items instead of tokens is to be forward thinking about the people who are hopefully mainstream users of these "things in the IoT" and if we are to have them (and us) think about these things as real world, almost and sometimes actual representation of physical items

1/ Those distinctions can still be (and should be) made at the UI/App layer where more context is known. For example, we've already made that distinction on our properties. We call tokens "Collectibles" on Fan Bits and "Assets" on Rare Bits.

2/ The consumers of the word "token" with regards to this spec will be almost entirely devs. Given that we have so much existing infrastructure (wallets, existing DApps, etherscan, etc.) and momentum around the word Token, it seems like we should keep going with what the dev community has already adopted and latched on to.

@PhABC Hey @AC0DEM0NK3Y, @coinfork & others, we just released publicly our implementation with a very similar interface as proposed here. We want to collaborate and do not wish to create a separate standard proposal. We think the interface could be improved and you can find the rationale of our interface design choices in the rationale section.

Good stuff. I had a quick glance and will make a more in-depth look when I get some time (very busy atm).
My first thoughts on the interface are it seems like we are pretty close on the main standard and I don't see anything that really jumps out as radically different that we can't fit together. The totalSupply dropping to optional for eg. I think is probably fine.
Also if you take a look at the ref impl. @coinfork posted I think we renamed things like transfer to batchTransfer in there for example.

I also like in the impl the idea to pack more info into your arguments, although that isn't the standard interface as such but the standard does allow. I do have concerns somewhat of how implementers will go for that and some of the limiting factors for the future in doing it that way to get gas savings (something that may not be need in L2) but can talk about that later. It's definitely something that could be very prone to error, and if you are going to unlock all funds for users rather than explicit number approval to save gas...
Btw I think we originally had setApprovalForAll in the standard and dropped it but I think it could maybe go back. It is much more of a security risk for the sake of a few cents gas saving though.

One thing I don't get that I'd like you to expand on is the two standards in one, one for fungible and one for mixed.
Not entirely sure what you have in mind here but given people seem to be suggesting reducing complexity even to the point that renaming a variable or function is concerning them that is "confusing" to developers then having two separate standards in one seems like it is adding a lot of confusion that might not be warranted?

@amittmahajan 2/ The consumers of the word "token" with regards to this spec will be almost entirely devs. Given that we have so much existing infrastructure (wallets, existing DApps, etherscan, etc.) and momentum around the word Token, it seems like we should keep going with what the dev community has already adopted and latched on to.

That's fair. But I think you should give devs a little more credit, the better ones are some of the most adaptable to change I find rather than just aim for the status quo, and altering a name isn't exactly earth shattering, especially if we want to push a narrative about what these represent outside of the dev community.
For adoption I don't think it is particularly great for mainsteam news like nasdaq to be talking of tokens vs items to people outside of the crypto space. Token is like some trinket you get to pay for some other service. I think mainstream adoption is hurt (to what extent, not sure) by having a token economy talked about all the time vs "real" items. Hopefully we can change mainstream mindset that they truly own something and what they own is a real thing to be bartered and acquired. Token doesn't speak to that in the same way but it's true that at the app/dapp layer maybe it will be spoken of differently (although as you say, current infrastructure does not because the mindset is biased towards the word token!).

But if the dev community is absolutely sold on calling everything tokens I suppose that's what we should go for, to help adoption of this standard in the short term and get it off the ground.

I wish github had a public voting system as standard so we could just put a poll up that signed in github users could vote on either way and just put this to bed :)

How about this, vote on this post: Heart for "Items" / Hooray for "tokens" / Confused for "either way is fine with me""

@PhABC wrote:

[...] we just released publicly our implementation with a very similar interface as proposed here. [...] We think the interface could be improved and you can find the rationale of our interface design choices in the rationale section.

Your reference implementation is interesting. I like the proposal of a safeTransferFrom function. However, to save on gas, I would keep the basic transfer function.

I tested the cost of adding a parameter to a function here:

contract C {
    uint256 public data;
    function fct1(address to, uint256 item, uint256 value) public {
        data = uint256(msg.sender) ^ uint256(to) ^ item ^ value;
    }
    function fct2(address from, address to, uint256 item, uint256 value) public {
        data = uint256(from) ^ uint256(to) ^ item ^ value;
    }
}

fct1 costs 28534 gas and fct2 costs 29956 gas.

commented

We have opted to remove the increase/decreaseApproval functions in favor of a more concise implementation that simply requires the current approval value, when calling approve().

This idea is found in the Secure Token Development and Deployment document by Dmitry Khovratovich and Mikhail Vladimirov. ( https://drive.google.com/file/d/0ByMtMw2hul0EN3NCaVFHSFdxRzA/view )

I've updated the ref. implementation accordingly, though it's still work-in-progress :) the "batch" functions are now the default ones, while singleTransfer are named such and have become optional. totalSupply is now optional as well as suggested.

For the standard to become successful it needs to be light yet functional. I think we're starting to approach this! Now for the Item vs Token naming debate =)

hey all, I just want to give a bit of background and thoughts on the above MFT interface / contract impl above posted by @PhABC. @PhABC and the team here at Horizon Blockchain Games developed the contract over the course of a few months during our work on SkyWeaver, a blockchain powered CCG, where we had a need for a batched ERC20 contract that consisted of multi fungible card types. We were just in the process to submit our work when we came across the 1155, which was very cool to see another team solving similar problems for blockchain games settle on very similar solutions, it means we're doing something right :)

To weigh in on some of the points above:

  1. Although the CIS or MFT interfaces can have implementations that support multi-fungible tokens and non-fungible tokens (NFTs), I'm in favour of focusing the CIS/MFT specs to just batching fungible tokens, and letting NFTs focus on non-fungibles. Two arguments for this: first, a specific purpose/design of a contract is easier to build with and adopt, and second, the 721 NFT contract has been iterated for months with established consensus and it does quite good job for non-fungibles as its specific purpose is to do so, and more importantly I don't see the ecosystem adopting anything beyond 721 in the short term unless there are real material reasons to do so. Therefore, I suggest, leave the NFT to 721, and have 1155 focus on multi-fungibles. Let me know what you guys think or if there are material reasons to simultaneously try to design for both here.

  2. It's important to get the thumbs up from groups like Rarebits and OpenSea as the benefits of blockchain video games is that gamers will see network effects with the tokens they acquire.

  3. As for the naming, I asked some other friends / colleagues their opinion on the "Crypto Item Standard" name too, and someone's feedback to me is that it sounds like a specification for a single item, which is exactly the opposite of its intention. Personally I think "Crypto Item" is a neat term, and to the gamer audience I think it works too, but I think in the context of blockchain contract specifications, I think its more natural to speak to the qualities of what it delivers, and also better to be consistent with the natural language that has been adopted, whether we love it or not, and that is.. non-fungible tokens or NFTs will be here to stay for a while. As well for reasons mentioned above, that the interface proposed by CIS/MFT go beyond just items in a blockchain game in other DApps.

Hi,

reacting to the point number 1 in the post from @pkieltyka.

I think that leaving aside NFT in this standard would be a huge mistake. I think that the powerful idea of 1155 is to be able to build strong multi-token economies. Leaving out NFTs would weaken that concept considerably. Yes, 721 does a good job for NFT, but so does 20 fo Fungibles. That is not the point. 1155 brings them all together into one echosystem.

@JamesTherien, @pkieltyka, I am envisioning on 1155 contract that could handle trading across dozens of independent games that want to enable transfers between their economies.

It would be amazing for a player to be able to trade 17 million gold in an unnamed MMO (fungible) for a unique ship in another MMO (non-fungible). All securely within the blockchain.

I see ways where an augmented 1155 contract can represent a complete, trustless exchange. This would only be possible by supporting both fungibles and non-fungibles in the same standard.

We can also picture non-fungibles as fungibles with a total supply of 1, 0 decimals, and a parent ID to group some of them together. The difference is small in terms of functionality. We're still representing simple ownership of an ID by an address.

@AC0DEM0NK3Y @amittmahajan About the thorny question of naming... Here some thoughts. Item is interesting but there might be better than item... It is a token backed by something. The name token in itself may not be enough for common users to get a clear picture at 1st: Trade back or asset back token seems to long. Why just call it "asset token" or simply "asset" or "property - token". Item of course is more relevant to gaming. And I am bias as I am in farmland management and trading of land plots. But if it works for gaming it will work for many other sectors.

@ericbinet @JamesTherien hey guys, I agree trading fungibles for non-fungibles, vice-versa, or perhaps a mix of the two are real use cases that should be supported efficiently. One idea we discussed with @PhABC is a dapp could leverage #998 (cc: @mattlockyer) in a contract that combines MFTs and NFTs to achieve those very use cases. Which leads to the important question by CIS, how you'll support composables? Btw, @amittmahajan have you guys considered these kinds of trades and how they'd work on Rarebits?

As well, we've been speaking with the 0x team for a few months about our design and going to seek their advice as they have a lot of experience building token protocols for trading, and as well, we want to make sure our MFT spec is compatible on their network.

Finally, in both cases of CIS and MFT, its very possible they won't end up becoming the same thing, or taking the same direction and that is just fine too. If Enjin has something specific in mind/built for CIS, then its totally fair that you won't take our suggestions and stick with your intended design. @PhABC and I were discussing we'd try to contribute our thoughts here first to see if they gel.

@MCouzic Why just call it "asset token" or simply "asset" or "property - token". Item of course is more relevant to gaming. And I am bias as I am in farmland management and trading of land plots. But if it works for gaming it will work for many other sectors.

Another good and valid option. "Asset" goes even further than item I would say to describing a physical or valuable thing that the standard could represent so I think it's also a very good choice for many applications.

So to summarize naming options as I understand it:

Token(s):
-Pros
The most agnostic, matches well with previous and related standards, has good momentum with dev community already.
-Cons
Weak description outside of dev community and so cheapens the value in financial and validity terms of what they represent, potentially harming adoption with mainstream consumers.

Item(s)
-Pros
More accurate/marketable description of "thing within a list of things", more able to describe an real or potentially real object it represents (like medkit for eg. in real world or fantasy world). A reasonable balance between the 3 terms.
-Cons
Doesn't match previous standards, possibly poor name for description of 100% intangibles and fungibles like a pure utility "currency".

Asset(s)
-Pros
The most physical sounding, business/financial applicable and arguably strong professional sounding name, likely very good to convey this idea to mainstream audience. Ideal for NFTs.
-Cons
Same cons as items but perhaps even more pronounced.

So I think a decision has to be made here to get this out of the way otherwise we're just going to circle and imho it's just distracting away from the real stuff. We have the vote 8 posts above above on tokens, items and any. Lets add an extra vote option to this for "Asset" and give a deadline of two weeks from when voting began and let the community speak - so voting on the naming ends on the 17th.

Hopefully the vote won't be subject to brigading, in mind of that I would urge you all to vote on the future and not on your particular use case right now and try to think about what will be important for this standard to serve best as a whole, what erc20 and erc721 is missing and why we are proposing this new standard to begin with.

Enjin will stay out of the non-neutral vote and let the community as a whole decide which I think is a fair and unbiased approach.

So to vote on "Asset" do so with a Hooray on this post. to vote on the others, look 8 comments up and pick an option there. I purposely chose Hooray and not Thumbs Up to distinguish from "I approve of this message".

@pkieltyka @ericbinet @JamesTherien hey guys, I agree trading fungibles for non-fungibles, vice-versa, or perhaps a mix of the two are real use cases that should be supported efficiently. One idea we discussed with @PhABC is a dapp could leverage #998 (cc: @mattlockyer) in a contract that combines MFTs and NFTs to achieve those very use cases. Which leads to the important question by CIS, how you'll support composables? Btw, @amittmahajan have you guys concerned these kinds of trades and how they'd work on Rarebits?

1155 makes such "bundling" very easy, 998 is a very nice solution but imho is also showing up some of the problems that have been imposed by the 721 standard.

In our articular implementation of 1155 we have had "composibles" of multiple NFT's and FT's running with unit tests with various features such as transfer fees and crypto currency backing for quite some time. We have decided to take a look at it further though as we feel that our standard is too open and would like to give the developers some composition rules such as "can only have X of type Y" or "X cannot bundle with Y" for example which has lots of implications for games but likely just as much for other things also (off the top of my head, cooked meat cannot go with raw meat).

Finally, in both cases of CIS and MFT, its very possible they won't end up becoming the same thing, or taking the same direction and that is just fine too. If Enjin has something specific in mind/built for CIS, then its totally fair that you won't take our suggestions and stick with your intended design. @PhABC and I were discussing we'd try to contribute our thoughts here first to see if they gel.

While true I think that would be a shame, we are very very close and I wish we could convince you more that not including NFT support in your particular standard is very likely limiting you for the future. As you can see we already have others commenting that have NFT use cases in mind.

You are in the gaming sector, for what it's worth something that I myself have been in for a very long time as have a number of my colleagues and we are all in agreement that we need to offer that option in order to future proof the standard.
If you could go into more detail of how you expect to support something like individual rare weapon skins that may be offered as promo items (with descriptions) whilst also offering the ability to purchase/trade those with either a premium or earnable in-game currency then maybe we can understand what you are thinking a little more and edge towards your direction?

Re: Naming, let's see where the voting lands out. one last point on this: if you look at the conversations and the terms people are using in this thread, it gravitates towards "Token". The point being that the word token (or NFT or MFT) is already being used to describe and ground what these things are, leading me to believe we have the descriptive word we need already.

@pkieltyka Btw, @amittmahajan have you guys concerned these kinds of trades and how they'd work on Rarebits?

We have, I think drawing inspiration from what already exists in MMOs is likely where we'll net out on UX (our backgrounds are also in gaming). Tech wise, we're evaluating all options on the best (cheapest while balancing against ux) way to implement, obviously a standard like this will help a lot.

hey @AC0DEM0NK3Y thanks for the response, see below too

1155 makes such "bundling" very easy, 998 is a very nice solution but imho is also showing up some of the problems that have been imposed by the 721 standard.

I agree 998 is still a WIP, but which problems do you speak of specifically that are similar to 721? As well, how do you define "bundling"? when I think about compos(ai)bles, I think about how in the physical world we turn steel into a sword or sand into glass, or glass into a bottle, an element of immutable change, or a unique/rare vehicle with wheels and a gun on it (Carmageddon style) -- do you see a way for supporting this in 1155? in order to do this, would there have to be some relation between items into some root, or is it enough to have a grouping (array) of unique items that take on a root id?

If you could go into more detail of how you expect to support something like individual rare weapon skins that may be offered as promo items (with descriptions) whilst also offering the ability to purchase/trade those with either a premium or earnable in-game currency then maybe we can understand what you are thinking a little more and edge towards your direction?

Great question, and I agree this is important and the final question for me as well. Our initial thinking (but certainly still open to other ideas), is to use existing inventions/standards like NFT-721 for non-fungibles and MFT for fungibles -- this would mean for a given dapp/dgame we'd have two different token contracts, one for fungibles and one for non-fungibles. If you consider Ethereum as just a single large instance of a slow database with BZFT consensus and stored procedures, then, its like having two different database tables, one for the FTs and one for NFTs -- and two tables could make sense to optimize to the specific query/persistence uses. The downside here is that a user couldn't make a single transaction call across contracts (unless there was a contract above that, which adds cost/complexity), to transfer FTs and NFTs. But, I think most trades will occur through some kind of third party contract, which I can see being possible to make such trades in a single transaction call. I'll work through this with @PhABC and discuss with others to see if there is a design that works within reasonable gas. As well, we'll do some prototyping with 1155's NFT design as well, and mention to other DEX devs both designs to get their feedback and hopefully get them to weigh in here too.

Finally, I think its great that you guys specified the NonFungible interface as an extension on 1155, which makes it very versatile and friendly to both directions depending what developers adopt / use in their implementation.

OK I see where you are headed now.

I think at least in the short term as 721 has quite a bit of traction right now that strategy will work well. It will work for what people are currently calling "blockchain games" which I suppose sits in the realm of collectibles, turn based strategy/card games and other such things that lend themselves to low bandwidth interactions between users and certain async games and such and such.

The two data set strategy essentially limits each app to that data set though and that data set alone. It becomes trickier to add more data sets and types and I think as time goes on, this will become untenable for more mainstream style games I/we believe.

I think this is also tricky for 721/blockchain games that we will and are starting to see in these early days too, let me give an example:

Lets say I have a collectible card battle game where you can assume that everything that is an NFT in that game is a card type, and then you have multiple fungibles that are for "gold" and then a premium currency perhaps. This is pretty much perfect for your approach.

Say now I want to introduce an expansion to my game, lets call it The Purse of Raxxnamas. Now if I want to expand the card set I could increase the supply in the NFT contract and plug in all the URIs etc , perhaps on demand.
Then after I also want to increase the common base card set and do the same.
I now (if I want to categorize) have to track this information off chain that says for eg. indexes 1 to 1000 are the base set, 1001 to 1200 are the expansion and then 1201 to 1500 are the extensions to the base.
If I am a wallet or exchange I could pull the URI for the items and grab the categories but I'd have to go through 1500 uri's to find that information and tally it or you have to provide some other standard way in that contract to pull this info and display it to the user or they have to hardcode it in.

Alternatively what you could do instead when you want to deploy an expansion is you deploy a brand new contract and do that for all the expansions and new types in the future (nice and easy for this example, less so for other game types).
If I'm a user and have a card from each of those sets I want to trade in one go, I can't do it myself so I am forced through multiple approvals to allow a third party to control this for me and/or I have to give a contract or non-decentralized exchange I imagine complete access to all my balance with the boolean method * number of expansions/item sets I'm sending from. Then there there are the calls through all those contracts for the balance change when the trade occurs.
Multi-NFT trades or bundles/composibles can only be controlled with a third party contract (see 998).
It also means now the off-chain server that interacts with these contracts needs to be updated every time you add a new type/contract.

If a publisher or developer has multiple games and has to go through this each time it's going to become a logistical nightmare very quickly imho and it's not much fun for users either. Basically, adoption is hitting hard friction at a certain point.

What we are proposing is that adding a new type would essentially be doing "ID = ++numberOfTypes" and that ID represents the category and that category is of either of a set of particular NFTs or a fungible type. Under that category you could have a balance that says either how many fungible balance there is or how many NFTs there are in this category.
When you send a fungible you are subtracting a balance and adding it, when you send a non-fungible you are assigning a new address and balance could be untouched if you like (you can assume if you own that, your balance is 1).

Getting the category information out is pulling a URI on the ID and operating on a fungible is sending with that ID. Getting info or operating on an individual NFT is done by ID + index.
To store how many of a particular category one user has you could store that under balances[user, ID] and to know if a particular ID is an NFT or not you can just store it in a reserved bit inside the ID itself, no need to touch storage.

For a wallet or exchange to know how many particular things there are under a category they could just ask totalSupply(ID). This could be sub categorized for circulating supply also if desired.

As everything for this particular game or publisher is under one contract trades and any other multi-token/item/asset operation can all happen in that single contract and the off-chain logs are all tracked through that one contract also.
A user themselves can tell the contract to put a set of bundled items up for trade and then an exchange could watch that one contract for ALL trades, they do not need to rely on a third party contract to do this for them. For users and I would argue exchanges too, this is a huge power feature. The user has complete control of what goes up for a trade securely and the exchange can either be an intermediary and take fees on the trade completion (probably in their own currency) or they could be sent the items to auction in one go and then send them out in one go.
The exchange's backend is massively simplified and so easier to maintain and operate, instead of having to deal with game == at least two contracts they could potentially be dealing with one contract == multiple games (which also give users even more power features).

Was thinking about the naming a bit and what could be done here given the voting is looking like it is leaning mildly towards tokens, a good compromise might be to name all the underlying function signatures etc. with token but for the standard's non erc numbered name we have some marketable easy to remember name that speaks to both.

This way we can keep close to the old standards by having token still be the thing we reference in the dev community but we also have something that can be talked about as a kind of base "brand name" of the standard in the mainstream world.

So what I think could be a great descriptive name for erc-1155 is the CRypto Items Token Standard or Crits for short.

It speaks to games a little bit as in Crits==Critical Hits but it isn't so game oriented as to be unusable for most other use cases.

commented

Third draft of the standard (interface IERC1155) posted. The ERC-1155 reference repository is now updated to reflect this, with unit tests nearly ready.

Has anyone started work on how an exchange and or/ an explorer would interact with the contract?

An explorer would likely import the data into a SQL database base and that is something we are looking into for the Akroma project.

@detroitpro I've been thinking about this in relation to other token standards.

In the off-chain world, I don't see too many difficulties in mapping tokens to databases and / or mapping to a standard interface for DEXs to call functions. i.e. each new token implementation on-chain has a JS library that maps something like ERC-20 function calls to the new token's underlying function calls in order to achieve the fungible scarcity of e.g. a wallet to wallet transfer.

However, on-chain we lose the protocol interoperability. For example, how would I credit someone tokens from a particular project within my contract / protocol, if that project had a non-standard token implementation / interface? I would need to code in specific functionality for that token on-chain in order to support interop.

This could be alleviated potentially with safe on-chain singleton proxy / adapter contracts, though historically the community has had issues and trouble with these.

My 2 cents and the slashes are because we don't have the nomenclature 100% down yet.

@AC0DEM0NK3Y One example off-chain might be in a wallet, with a uint256 the UI designer can work with integrating that into their display with guarantee. If they can have any number of characters thrown at them via such an open nature (that is potentially overkill, you can fit a lot in 256 bits) then they no longer have this.

∞ > Earth's population > 4,294,967,295

Has anyone started work on how an exchange and or/ an explorer would interact with the contract?

Hi @detroitpro. Yes we have a backend that interacts with such contracts among other things.

As @mattlockyer states it is certainly doable with current toolset for event subscriptions etc. and then however you would like to implement your DB solution on top of that.

I've not looked into this too much myself as yet but different standards within contracts to pass between, yes it would seem that having a proxy/adapter/conversion contract/layer would be the way to go. It's a similar although much simpler problem that you would have with cross chain communication.

I'm not as familiar with the community opinion around the dislike for proxy contracts @mattlockyer could you give a quick rundown of the reasons? Aside from the clumsiness of it (something I mentioned that having multiple types per contract helps), if the code is open it would sound safe at least on the face of it.

@AC0DEM0NK3Y

I also like in the impl the idea to pack more info into your arguments, although that isn't the standard interface as such but the standard does allow.

Packing balances does not changes the interface, all is handled within the functions.

. It's definitely something that could be very prone to error, and if you are going to unlock all funds for users rather than explicit number approval to save gas...

This is not just for gas saving, but drastic UX improvement. If a user needs to make a transaction for every approval, it will both be a burden on the users and the rest of the network. Imo, we need to move towards a future that minimizes as much as possible on-chain transactions in order to reach mainstream adoption. Regardless, approving should only be done to trusted contracts anyway. The intermediate solution is to have your tokens in two accounts, one that has the approvals set on and the other that does not.

It is much more of a security risk for the sake of a few cents gas saving though.

Just to put emphasis on this, it's much more than just gas saving, especially when it comes to NFTs. The UX burden of always having to approve is gigantic. Ask the 0x team and other projects that need to deal with approvals, they will tell you it really impairs adoption.

I've updated the ref. implementation accordingly, though it's still work-in-progress :) the "batch" functions are now the default ones, while singleTransfer are named such and have become optional. totalSupply is now optional as well as suggested.

I am personally OK with this.

One thing I don't get that I'd like you to expand on is the two standards in one, one for fungible and one for

Will respond to NFT stuff in next answer. ⇩⇩⇩

@AC0DEM0NK3Y

As everything for this particular game or publisher is under one contract trades and any other multi-token/item/asset operation can all happen in that single contract and the off-chain logs are all tracked through that one contract also.

According to this comment and others, it is under my impression that you are arguing for this specific mixed design for convenience of third parties? Making it easier for them to track?

A user themselves can tell the contract to put a set of bundled items up for trade and then an exchange could watch that one contract for ALL trades, they do not need to rely on a third party contract to do this for them.

All decentralized exchanges either use a custodial contract or exchange tokens in two function calls. It doesn't make it more efficient / simple for the exchange contracts to call one contract or two since they are called in two separate token.transferFrom(from, to, amount) calls. Unless I am missing something?

For users and I would argue exchanges too, this is a huge power feature. The user has complete control of what goes up for a trade securely and the exchange can either be an intermediary and take fees on the trade completion (probably in their own currency) or they could be sent the items to auction in one go and then send them out in one go.

I'm not entirely sure I understand how having both NFTs and FTs in the same contract gives better control / security. Could you explain a bit more in detail?

@PhABC All decentralized exchanges either use a custodial contract or exchange tokens in two function calls. It doesn't make it more efficient / simple for the exchange contracts to call one contract or two since they are called in two separate token.transferFrom(from, to, amount) calls. Unless I am missing something?

I could be wrong but I believe you're thinking about this in terms of the exchange, and possibly in "how do we make this work for erc721" terms whereas I am (always) trying to come at this from a user perspective, for the future. I do worry as a community we're jumping down a sunken cost fallacy direction when it comes to erc721.

If I have 15 categories of items for eg. I want to bundle into a trade that are stored in one contract 1155 style I can do something like this (as a user direct to the main contract):

createTrade(_askingIds[], uint128[] _askingValues, uint256[] _offeringIds, uint128[] _offeringValues, address _secondParty);

and that trade can be cancelled or modified by the user in the original owning contract if they wish. I don't need to approve anything else. The "exchange" can simply be a presentation of the event that occurred when the user created that trade with possible escrow. When another use wants to complete that trade they call it n the original owning contract and the exchange happens in there. No external exchange needs to be involved in the transaction it's just a window into the trade logs. Although you could enforce this if you want with whitelisting etc.

If you want to trade something like that with 721s (after you've hacked a bundle together perhaps with #998 style composible) you have to give up ownership or approval to a third party i.e. the exchange. Isn't this more centralized therefore less secure for the user and also less simple / efficient for gas and UX?

Btw on the subject of "global operators" we already had this in our impl but didn't put into the standard:

function setPermanentApproval(address _operator, uint256 _id, bool _approved) external;
function isPermanentlyApproved(address _owner, address _operator, uint256 _id)  external view returns (bool); 

given we have that (and are possibly putting in a true global in) and others also seem to want it, it's going into the standard too. Fixing up some things first and arguing about naming :) before that goes into next draft.

"global operators"

Have been bouncing and issue around in my head the past week to do with ERC721 setApprovalForAll/isApprovedForAll where I'd really like to either block removing approval, have some kind of stake escrow associated with it to motivate re-approval or simply code a certain address to always have approval.

Such a "permanent" approval would meet my use-case for a token which has controller/operators contract that can transfer ownership of specific tokens.

How this then fits with trust and decentralisation becomes an issue for the operator contract and whatever DAO or token curation mechanisms it may implement.

If I have 15 categories of items for eg. I want to bundle into a trade that are stored in one contract 1155 style I can do something like this (as a user direct to the main contract):
createTrade(_askingIds[], uint128[] _askingValues, uint256[] _offeringIds, uint128[] _offeringValues, address _secondParty);

Are you saying the trading / exchanging functionality will be directly in the token contract? I am personally strongly against this, but as far I am concerned, that's not part of the standard so that's ok.

If you want to trade something like that with 721s (after you've hacked a bundle together perhaps with #998 style composible) you have to give up ownership or approval to a third party i.e. the exchange. Isn't this more centralized therefore less secure for the user and also less simple / efficient for gas and UX?

It's not more centralized and less secure if the exchange is decentralized, that's the same as having the functionality within the contract, it's just potentially more expensive.

I'm not strongly against having both NFTs and FTs in the same contract and I can see some projects benefiting from this, it's just that the logic in NFTs and FTs is quite different and who ever will be interacting with ERC-1155 token contracts will most likely need to know whether a given token is fungible or not. If there is no easy way to know, then perhaps it's easier to keep them separated.

That's my primary concern. How would an exchange / dapp know which token ID is fungible and which one is not?

Are you saying the trading / exchanging functionality will be directly in the token contract? I am personally strongly against this, but as far I am concerned, that's not part of the standard so that's ok.

Yes that's what I said, although even with that it could be controlled with whitelisting. Whether any of us devs are strongly for or against these things I suppose does not matter in the long run, if the users prefer it (and money and time are great motivators) then that's what will be adopted.

It's not more centralized and less secure if the exchange is decentralized, that's the same as having the functionality within the contract, it's just potentially more expensive.

That's assuming the decentralized exchange isn't up-gradable but sure. See recent examples of this.
Btw not just potentially more expensive, but potentially much more unwieldy for users and for backend services.

That's my primary concern. How would an exchange / dapp know which token ID is fungible and which one is not?

How's this?

function isNonFungible(uint256 _id) external view returns (bool);

Yes that's what I said, although even with that it could be controlled with whitelisting. Whether any of us devs are strongly for or against these things I suppose does not matter in the long run, if the users prefer it (and money and time are great motivators) then that's what will be adopted.

Fair enough!

Btw not just potentially more expensive, but potentially much more unwieldy for users and for backend services.

In what way?

function isNonFungible(uint256 _id) external view returns (bool);

Right, so third parties would need to keep track of all token IDs within a game to see if they are fungible or not. That's personally OK with me, but it seems like having an easier way to differentiate fungible vs non-fungible would make this better. A silly example would be to have odd ids (1,3,5, ...) be fungible tokens and even ids would be non-fungibles. So a DAPP can directly know whether a given ID for any game is fungible or not without needing to store they own mapping. Having both fungible and NFTs in separate contracts also makes this easier, since the contract informs the nature of the tokens, but I do think it might be possible to have a standard way of differentiating NFTs from fungibles stored in a same contract like you suggest.

Btw not just potentially more expensive, but potentially much more unwieldy for users and for backend services.
In what way?

The most obvious one I would think immediately is for the 15 types mentioned it's likely a user or backend will have to interact with 15 separate contracts from a sea of ever expanding contracts probably offering various implementations of different standards.

Scenario:
**I want to trade my CryptoDog, which (after an interaction for each one to create a composible) owns a hat, a ball, a skateboard, a pair of glasses, a hair trimmer, and 100 fungible gold pieces.

How would a user trade this with another user for the price of 500 (ft) silver pieces, another CryptoDog, a (nft) yacht and 25 (ft) cats with your third party method where NFTs seem to all have separate contracts?**

It seems like you would absolutely need a composible, for both users, for this to be workable for them. This means they have to create one for every trade or give up approval on their items to some potentially untrustworthy or buggy third party.
If they cancel the trade, they may have to now unmake the composible or then revoke all the approvals.

Here's how you do that with how I suggested it (you could also bundle then trade that instead of individually) with 1155 on the owned contract:

User 1:
tradeID = createTrade([Silver,CD,yacht,cat],[500,1,1,25], [CD,hat,ball,skateboard,glasses,hair trimmer,gold],[1,1,1,1,1,1,100], null);

The exchange would see event for tradeID creation and query it for contents.

User2:
completeTrade(tradeID);

Right, so third parties would need to keep track of all token IDs within a game to see if they are fungible or not.

No, if they get sent an ID then they'll have the ID. Plus there could be view functions outside of the standard that can be used for querying such detail (or even just through logs), or you could even reserve a bit in the ID to say NF T/F.

How would a user would trade this with another user for the price of 500 (ft) silver pieces, another CryptoDog, a (nft) yacht and 25 (ft) cats with your third party method where NFTs seem to all have separate contracts?**

The idea was to have 2 contracts, one for NFTs and one for FTs, not 15 contracts.

No, if they get sent an ID then they'll have the ID. Plus there could be view functions outside of the standard that can be used for querying such detail (or even just through logs).

Well, if am I a Dapp / exchange / wallet and want to present the objects differently if they are NFTs or FTs, then I need to know which ID is an NFT and which ID is an FT. Since I would have 100,000 users, I need to keep locally a mapping of which ID is NFT and which is not for efficiency reason (RPC calls are slower than local database query). I would need this for all different ERC-1155 contracts as well. Having a simple way to distinguish between IDs that are NFT and FT would be great. Doesn't need to be in two contracts, could be pair vs odd for example, or numbers ID < 2**128 for FTs and ID >= 2**128 for NFTs, something like that.

The idea was to have 2 contracts, one for NFTs and one for FTs, not 15 contracts.

So in simple terms like above with createTrade() how would you do that with the FT and NFT split? Maybe I'm not seeing the user flow for this as you are as it seems like it would be complicated on the face of it, and complicated means users will walk.

You missed this part on the NF identifying:

or you could even reserve a bit in the ID to say NF T/F.

It's an interesting idea to do a split by ID nonce too, will have to consider that for our impl.

I would be ok with using a bit as an identifier! Although using a bit makes the devs job a bit messier, since you would always need to append a 1 or 0 somewhere (e.g. the first/last bit), then extract this bit in contracts, etc.

Here are some options for distinguishing FTs from NFTs.

  • Using a bit
  • Odd / even
  • ID: FT < 2**128 <= NFT

I personally don't like odd/even as it's redundant with 3rd option and harder to verify. Using a bit can be nice, but adds complexity to devs. Splitting IDs in two is easy, but then you limit your NFTs to 2**128 (which is probably fine, but hey).

Any other ideas to distinguish FT from NFTs? Pros and cons?

So in simple terms like above with createTrade() how would you do that with the FT and NFT split? Maybe I'm not seeing the user flow for this as you are as it seems like it would be complicated on the face of it, and complicated means users will walk.

Yes, I agree if you want to implement trading functionality within the token contract itself, then having all under the same contract is more efficient both in cost and UX.

@PhABC We actually implemented your 3rd option. ID: FT < X <= NFT. Using a bit is pretty much the same thing as your other option... depending on where you put the bit. Doing (id & Bit) is no more difficult than doing (Id > X) or (id & 1).

I think 2**128 is unnecessary large however. There are all kinds of nice things you can do with the id bits :-)

Hate to put a damper on an innovative solution re: using an extra bit, but flexibility of how token ids (and potentially token type ids) are mapped are important to certain applications.

1/ We have seen some ERC721 apps that use token_id to map to a given date or object hash. I'd imagine apps will be doing similar things with the type_id

2/ This implementation detail will make it pretty difficult for devs to track archetypes in their DB (due to default auto-increment behavior on id columns) without explicitly enforcing NFT/FT logic. You'd have to have either: odd number only id columns, or ids that start at 2**128 and go from there. Both potentially add a lot of complexity overhead to anyone tracking these asset types in their own local db.

Is there a reason you can't use totalSupply(type) == 1 to determine NFT-ness? I think we may have cut into bone w/ the move of totalSupply to optional.

@amittmahajan I agree that you should have some flexibility in implementing your id how you want. I was just sharing what we did for the type id. We put more than just the type indexes in our implementation.

re: NFT-ness, there is so much more to it than totalSupply(type) == 1. I truly think they are worth the effort. But what you support beyond the required interface is pretty much up to you.

Could a view be used to do a translation of parameters into whatever ID packing schema a contract might use?

Something along the lines of getId(bool _fungible, uint256 _base, uint256 _index).

Perhaps with something more flexible than two uint256? A bytes32 parameter or two?

edit: With another method to go back the other way and determine fungibility or similar properties without needing to parse on the client end.

Perhaps @mryellow have been thinking about that sort of thing myself too. Working on other stuff atm though to really put proper thought into it in a general case.

Please brainstorm away!

I think @JamesTherien also may have ideas here.